browser.c 286 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090
  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 (512u * 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_ARENA_MAX (24u * 1024u * 1024u)
  43. #define BR_IMG_LAYOUT_W 1000
  44. /* An image job may hold a fetch helper this long. The page/script
  45. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  46. * must not starve the other images of all four helpers that long. */
  47. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  48. #define BR_CSS_MAX (832u * 1024u)
  49. #define BR_CSS_COMP_MAX (192u * 1024u)
  50. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  51. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  52. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  53. #define FETCH_ABORT (-2)
  54. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  55. #define CSS_CACHE_MAX 16
  56. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  57. #define CSS_CACHE_PREFIX "bcss-"
  58. #define SCRIPT_CACHE_MAX 24
  59. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  60. #define SCRIPT_CACHE_PREFIX "bjs-"
  61. #define BR_MAX_SHEETS 6
  62. #define BR_HISTORY 16
  63. #define BR_URL_MAX 512
  64. #define BR_STATUS_MAX 200
  65. #define BR_IMG_RGB565(r, g, b) \
  66. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  67. #define BR_GRAY 0x8410
  68. enum {
  69. ID_URL = 1,
  70. ID_GO,
  71. ID_BACK,
  72. ID_FORWARD,
  73. ID_RELOAD,
  74. ID_HOME
  75. };
  76. #define ACT_NAV (1u << 0)
  77. #define ACT_BACK (1u << 1)
  78. #define ACT_FORWARD (1u << 2)
  79. #define ACT_RELOAD (1u << 3)
  80. #define ACT_HOME (1u << 4)
  81. #define ACT_CLOSE (1u << 5)
  82. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  83. ACT_HOME | ACT_CLOSE)
  84. struct br_image {
  85. int state; /* 0 empty, 1 ready */
  86. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  87. int native_w, native_h;
  88. unsigned int url_hash; /* <img> source, 0 = not shareable */
  89. char err[32];
  90. };
  91. static struct ngui ui;
  92. static struct ngui_input url_in;
  93. static struct ngui_scroll page_scroll;
  94. static struct br_doc doc;
  95. static struct br_image images[BR_MAX_IMAGES];
  96. static int image_count;
  97. static unsigned int image_pixels;
  98. /* Painted border boxes, in page/screen coordinates (layout starts at
  99. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  100. struct br_layout_box {
  101. int x, y;
  102. int w, h;
  103. unsigned char valid;
  104. };
  105. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  106. /* Images are loaded one per main-loop iteration so the parsed page stays
  107. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  108. static int preload_active;
  109. static int preload_max_jobs;
  110. static int preload_pending;
  111. static int preload_wait;
  112. static unsigned int preload_node;
  113. static int preload_loaded;
  114. static int preload_scroll;
  115. static int preload_rescan;
  116. static char post_status_text[BR_STATUS_MAX];
  117. static int post_status_error;
  118. static unsigned int post_status_ttl;
  119. /* Content-relative position/height of each <img>, recorded by the measure
  120. * pass so image loading can be deferred until it is near the viewport. */
  121. static unsigned short img_top[BR_MAX_NODES];
  122. static unsigned short img_h[BR_MAX_NODES];
  123. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  124. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  125. * body. Decode arenas are allocated per image instead of living here. */
  126. static unsigned char *image_io_buf;
  127. static struct ufont_face *font_faces[BR_MAX_FACES];
  128. #define image_file_buf (image_io_buf)
  129. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  130. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  131. static struct inflate image_inflate_ws;
  132. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  133. #error "CSS scratch must fit in image_io_buf"
  134. #endif
  135. static char page_url[BR_URL_MAX];
  136. static char page_title[BR_TITLE_MAX];
  137. static char cwd[64];
  138. static int page_is_local;
  139. static int page_loading;
  140. static char status_text[BR_STATUS_MAX];
  141. static unsigned int status_until;
  142. static int status_error;
  143. static char history[BR_HISTORY][BR_URL_MAX];
  144. static int hist_len, hist_pos;
  145. static char click_url[BR_URL_MAX];
  146. static char pending_url[BR_URL_MAX];
  147. #define BR_POST_MAX 4096
  148. static char pending_post[BR_POST_MAX];
  149. static unsigned int pending_post_len;
  150. /* The pending navigation is a POST even when its body is empty (a form
  151. * without fields, e.g. the OIDC consent auto-submit). */
  152. static int pending_post_is;
  153. /* window "resize" bookkeeping: the page width the last event was for. */
  154. static int resize_sent_w = -1;
  155. static int resize_pending;
  156. static unsigned int pending_action;
  157. static int cancel_fetch;
  158. static int quit;
  159. static struct ngui_rect page_rect;
  160. static unsigned short *page_backbuf;
  161. static int pagebuf_w, pagebuf_h;
  162. static int page_cache_valid;
  163. static int page_cache_scroll;
  164. static unsigned int page_cache_nnode;
  165. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  166. static int layout_valid, layout_left, layout_right;
  167. /* Height of the page viewport: what html/body height:100% resolves to. */
  168. static int layout_view_h;
  169. static unsigned int layout_nnode;
  170. static int layout_content_h;
  171. /* layout output */
  172. struct lay_run {
  173. unsigned int off;
  174. unsigned short len;
  175. unsigned short gap;
  176. unsigned short color;
  177. unsigned short href;
  178. char lit[28];
  179. short img;
  180. signed short dy; /* inline image vertical offset */
  181. unsigned short iw, ih;
  182. unsigned short w;
  183. unsigned char font_px, bold, italic, mono, underline, strike;
  184. unsigned char overline, font_face;
  185. unsigned char transform_scale;
  186. unsigned char origin_x_kind, origin_y_kind;
  187. signed short scale_x, scale_y, rotate_x100;
  188. signed short origin_x, origin_y;
  189. unsigned char has_lit;
  190. unsigned int form; /* node + 1, 0 = not a control */
  191. unsigned char form_kind;
  192. unsigned char form_disabled;
  193. };
  194. struct lay {
  195. int draw;
  196. struct ngui *ui;
  197. int left, right;
  198. int y;
  199. int line_x, line_y, line_h;
  200. int line_left, line_right;
  201. int parent_top;
  202. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  203. int cb_h; /* definite content height of the containing block for
  204. * percentage heights; 0 = indefinite (auto) */
  205. int run_x;
  206. int align;
  207. int depth;
  208. int space_pending;
  209. unsigned char float_active;
  210. int float_left, float_right, float_bottom;
  211. struct lay_run runs[96];
  212. int nruns;
  213. };
  214. struct hit {
  215. int x, y, w, h;
  216. unsigned short node;
  217. };
  218. /* Live form state; the DOM attributes stay the initial/default value. */
  219. #define FORM_MAX 64
  220. #define FORM_VALUE_MAX 63
  221. enum {
  222. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  223. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  224. };
  225. struct form_state {
  226. unsigned int node;
  227. char value[FORM_VALUE_MAX + 1];
  228. unsigned char len, caret, checked, selected, used;
  229. };
  230. static struct form_state form_states[FORM_MAX];
  231. static unsigned int form_focus;
  232. static unsigned int form_dirty;
  233. static int form_descendant(unsigned int node, unsigned int form);
  234. static int form_submit_form(unsigned int node, int fire_event);
  235. static int link_fragment_nav(unsigned int node);
  236. static void history_push(const char *url);
  237. static void form_reset_event(unsigned int form);
  238. static unsigned int s_len(const char *s);
  239. static int s_eq(const char *a, const char *b);
  240. static void form_key(int k);
  241. static void form_click(unsigned int node);
  242. static void style_for_node(unsigned int node, struct br_style *out);
  243. static int form_disabled(unsigned int node)
  244. {
  245. struct br_node *n = &doc.nodes[node];
  246. if (n->attr_flags & BR_ATTR_DISABLED)
  247. return 1;
  248. return br_find_attr(&doc, node, "disabled") != 0;
  249. }
  250. static int form_kind_of(unsigned int node)
  251. {
  252. const char *type = br_type(&doc, node);
  253. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  254. return FORM_TEXTAREA;
  255. if (doc.nodes[node].tag == BR_TAG_SELECT)
  256. return FORM_SELECT;
  257. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  258. if (s_eq(type, "reset"))
  259. return FORM_RESET;
  260. if (s_eq(type, "button"))
  261. return FORM_BUTTON;
  262. return FORM_SUBMIT;
  263. }
  264. if (s_eq(type, "password"))
  265. return FORM_PASSWORD;
  266. if (s_eq(type, "checkbox"))
  267. return FORM_CHECKBOX;
  268. if (s_eq(type, "radio"))
  269. return FORM_RADIO;
  270. if (s_eq(type, "submit"))
  271. return FORM_SUBMIT;
  272. if (s_eq(type, "reset"))
  273. return FORM_RESET;
  274. if (s_eq(type, "button"))
  275. return FORM_BUTTON;
  276. return FORM_TEXT;
  277. }
  278. static unsigned int form_option_count(unsigned int node)
  279. {
  280. unsigned int c, n = 0;
  281. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  282. if (doc.nodes[c].type == BR_NODE_ELEM &&
  283. doc.nodes[c].tag == BR_TAG_OPTION)
  284. n++;
  285. return n;
  286. }
  287. static unsigned int form_option_selected(unsigned int node)
  288. {
  289. unsigned int c, i = 0;
  290. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  291. if (doc.nodes[c].type != BR_NODE_ELEM ||
  292. doc.nodes[c].tag != BR_TAG_OPTION)
  293. continue;
  294. if (br_find_attr(&doc, c, "selected"))
  295. return i;
  296. i++;
  297. }
  298. return 0;
  299. }
  300. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  301. char *out, unsigned int cap)
  302. {
  303. unsigned int c, i = 0;
  304. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  305. if (doc.nodes[c].type != BR_NODE_ELEM ||
  306. doc.nodes[c].tag != BR_TAG_OPTION)
  307. continue;
  308. if (i == idx)
  309. return br_text_content(&doc, c, out, cap);
  310. i++;
  311. }
  312. return 0;
  313. }
  314. static struct form_state *form_get(unsigned int node, int create)
  315. {
  316. struct form_state *slot = 0;
  317. unsigned int i;
  318. for (i = 0; i < FORM_MAX; i++) {
  319. if (form_states[i].used) {
  320. if (form_states[i].node == node)
  321. return &form_states[i];
  322. } else if (!slot) {
  323. slot = &form_states[i];
  324. }
  325. }
  326. if (!create || !slot)
  327. return 0;
  328. slot->node = node;
  329. slot->len = 0;
  330. slot->caret = 0;
  331. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  332. slot->selected = form_option_selected(node);
  333. slot->used = 1;
  334. {
  335. unsigned int n = 0;
  336. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  337. n = br_text_content(&doc, node, slot->value,
  338. FORM_VALUE_MAX + 1);
  339. } else {
  340. const char *v = br_value(&doc, node);
  341. if (v) {
  342. n = s_len(v);
  343. if (n > FORM_VALUE_MAX)
  344. n = FORM_VALUE_MAX;
  345. for (unsigned int j = 0; j < n; j++)
  346. slot->value[j] = v[j];
  347. }
  348. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  349. n = br_text_content(&doc, node, slot->value,
  350. FORM_VALUE_MAX + 1);
  351. }
  352. if (n > FORM_VALUE_MAX)
  353. n = FORM_VALUE_MAX;
  354. slot->value[n] = '\0';
  355. slot->len = (unsigned char)n;
  356. slot->caret = (unsigned char)n;
  357. }
  358. return slot;
  359. }
  360. static void form_reset_state(void)
  361. {
  362. unsigned int i;
  363. for (i = 0; i < FORM_MAX; i++)
  364. form_states[i].used = 0;
  365. form_focus = 0;
  366. }
  367. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  368. * is laid out like a normal element so that content shows; only a text or
  369. * empty button is drawn as a native control. Clicks still reach it
  370. * through the box hit test. */
  371. static int button_has_elements(unsigned int node)
  372. {
  373. unsigned int c;
  374. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  375. return 0;
  376. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  377. if (doc.nodes[c].type == BR_NODE_ELEM)
  378. return 1;
  379. return 0;
  380. }
  381. static int form_is_control(unsigned int node)
  382. {
  383. unsigned int tag;
  384. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  385. return 0;
  386. tag = doc.nodes[node].tag;
  387. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  388. tag == BR_TAG_SELECT ||
  389. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  390. }
  391. #define HIT_MAX 96
  392. static struct hit hits[HIT_MAX];
  393. static int nhits;
  394. static unsigned short block_h[BR_MAX_NODES];
  395. /* Measure-pass top of each block, in the same document coordinates as
  396. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  397. * paint, so it cannot drive the lazy background loader). */
  398. static unsigned short block_top[BR_MAX_NODES];
  399. static char li_marker[BR_MAX_NODES][12];
  400. /* one connection object; the browser fetches one resource at a time */
  401. /* ---- tiny strings ---- */
  402. static unsigned int s_len(const char *s)
  403. {
  404. unsigned int n = 0;
  405. while (s && s[n])
  406. n++;
  407. return n;
  408. }
  409. static void s_copy(char *d, const char *s, unsigned int cap)
  410. {
  411. unsigned int i = 0;
  412. if (!cap)
  413. return;
  414. while (s && s[i] && i + 1 < cap) {
  415. d[i] = s[i];
  416. i++;
  417. }
  418. d[i] = '\0';
  419. }
  420. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  421. {
  422. while (s && *s && *n + 1 < cap)
  423. d[(*n)++] = *s++;
  424. d[*n] = '\0';
  425. }
  426. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  427. unsigned int cap)
  428. {
  429. char tmp[12];
  430. unsigned int i = 0, j;
  431. do {
  432. tmp[i++] = (char)('0' + v % 10);
  433. v /= 10;
  434. } while (v && i < sizeof(tmp));
  435. for (j = 0; j < i && *n + 1 < cap; j++)
  436. d[(*n)++] = tmp[i - 1 - j];
  437. d[*n] = '\0';
  438. }
  439. static int s_eq(const char *a, const char *b)
  440. {
  441. while (*a && *b) {
  442. if (*a != *b)
  443. return 0;
  444. a++;
  445. b++;
  446. }
  447. return *a == *b;
  448. }
  449. static int starts_with(const char *s, const char *p)
  450. {
  451. unsigned int i = 0;
  452. while (p[i]) {
  453. if (s[i] != p[i])
  454. return 0;
  455. i++;
  456. }
  457. return 1;
  458. }
  459. static int contains_ci(const char *s, const char *p)
  460. {
  461. unsigned int i, j;
  462. for (i = 0; s[i]; i++) {
  463. for (j = 0; p[j]; j++) {
  464. char a = s[i + j];
  465. if (a >= 'A' && a <= 'Z')
  466. a = (char)(a - 'A' + 'a');
  467. if (a != p[j])
  468. break;
  469. }
  470. if (!p[j])
  471. return 1;
  472. }
  473. return 0;
  474. }
  475. static char *trim(char *s)
  476. {
  477. unsigned int n;
  478. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  479. s++;
  480. n = s_len(s);
  481. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  482. s[n - 1] == '\r' || s[n - 1] == '\n'))
  483. s[--n] = '\0';
  484. return s;
  485. }
  486. /* ---- per-process heap ---- */
  487. static int heap_start(void)
  488. {
  489. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  490. if (!image_io_buf)
  491. return -1;
  492. page_backbuf = (unsigned short *)malloc(
  493. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  494. pagebuf_w = page_backbuf ? ui.w : 0;
  495. pagebuf_h = page_backbuf ? ui.h : 0;
  496. page_cache_valid = 0;
  497. return 0;
  498. }
  499. static void heap_clear(void)
  500. {
  501. memset(font_faces, 0, sizeof(font_faces));
  502. ngui_font_detach(&ui);
  503. svg_cache_clear();
  504. decode_arena = 0; /* lives in the page heap too */
  505. decode_arena_size = 0;
  506. heap_reset();
  507. /* The document arenas live in that heap; drop the stale pointers so
  508. * the next br_parse_plain() allocates fresh ones. */
  509. doc.nodes = 0;
  510. doc.text = 0;
  511. doc.attrs = 0;
  512. image_io_buf = 0;
  513. page_backbuf = 0;
  514. pagebuf_w = pagebuf_h = 0;
  515. page_cache_valid = 0;
  516. }
  517. static void browser_rules_alloc(void)
  518. {
  519. struct br_rule *rules;
  520. rules = (struct br_rule *)malloc(
  521. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  522. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  523. }
  524. /* ---- status ---- */
  525. static void set_status(const char *s, int err, unsigned int ttl_ms)
  526. {
  527. s_copy(status_text, s, sizeof(status_text));
  528. status_error = err;
  529. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  530. ngui_invalidate(&ui);
  531. }
  532. /* ---- JavaScript ---- */
  533. static int resolve_link(const char *base, const char *href, char *out,
  534. unsigned int cap);
  535. static char js_last_status[BR_STATUS_MAX];
  536. static int js_last_error;
  537. static void js_host_status(const char *msg, int error)
  538. {
  539. s_copy(js_last_status, msg, sizeof(js_last_status));
  540. js_last_error = error;
  541. set_status(msg, error, 6000);
  542. }
  543. static void js_host_report(const char *msg)
  544. {
  545. u_puts("[js] ");
  546. u_puts(msg);
  547. u_putc('\n');
  548. s_copy(js_last_status, msg, sizeof(js_last_status));
  549. js_last_error = 1;
  550. set_status(msg, 1, 8000);
  551. }
  552. static void js_host_navigate(const char *url)
  553. {
  554. char resolved[BR_URL_MAX];
  555. if (!url || !url[0])
  556. return;
  557. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  558. return;
  559. s_copy(pending_url, resolved, sizeof(pending_url));
  560. pending_action |= ACT_NAV;
  561. cancel_fetch = 1;
  562. }
  563. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  564. * back/forward between fragments): the page URL, address bar and history
  565. * follow, nothing is reloaded. `push` adds a history entry. */
  566. static int page_set_fragment(const char *url, int push)
  567. {
  568. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  569. return -1;
  570. s_copy(page_url, url, sizeof(page_url));
  571. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  572. url_in.len = s_len(url_in.text);
  573. url_in.cursor = url_in.len;
  574. url_in.scroll = 0;
  575. if (push)
  576. history_push(page_url);
  577. ngui_invalidate(&ui);
  578. return 0;
  579. }
  580. static int js_host_set_hash(const char *url)
  581. {
  582. return page_set_fragment(url, 1);
  583. }
  584. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  585. * the page, so a hash router can react). */
  586. static int same_doc_fragment(const char *url)
  587. {
  588. unsigned int a = 0, b = 0;
  589. if (!js_browser_active() || !url)
  590. return 0;
  591. while (url[a] && url[a] != '#')
  592. a++;
  593. while (page_url[b] && page_url[b] != '#')
  594. b++;
  595. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  596. !s_eq(url, page_url);
  597. }
  598. static void js_host_changed(void)
  599. {
  600. /* Class/style/attribute mutations change computed styles, not just the
  601. * text: drop the per-node style cache before the next layout. */
  602. br_reset_styles(&doc);
  603. layout_valid = 0;
  604. /* Script-built content (Angular's ng-repeat cards) brings new images
  605. * and inline background styles: rescan once the main loop is idle. */
  606. preload_rescan = 1;
  607. ngui_invalidate(&ui);
  608. }
  609. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  610. {
  611. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  612. return 0;
  613. *x = layout_boxes[node].x - page_rect.x;
  614. *y = layout_boxes[node].y - page_rect.y;
  615. *w = layout_boxes[node].w;
  616. *h = layout_boxes[node].h;
  617. return 1;
  618. }
  619. static void form_copy_out(const char *s, char *buf, int cap)
  620. {
  621. int i = 0;
  622. if (!buf || cap <= 0)
  623. return;
  624. while (s && s[i] && i + 1 < cap) {
  625. buf[i] = s[i];
  626. i++;
  627. }
  628. buf[i] = '\0';
  629. }
  630. static int js_host_form_value(unsigned int node, char *buf, int cap)
  631. {
  632. struct form_state *fs;
  633. int kind;
  634. if (!form_is_control(node))
  635. return 0;
  636. kind = form_kind_of(node);
  637. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  638. return 0;
  639. if (kind == FORM_SELECT) {
  640. char opt[64] = "";
  641. unsigned int c, i = 0;
  642. fs = form_get(node, 1);
  643. if (!fs)
  644. return 0;
  645. form_option_text(node, fs->selected, opt, sizeof(opt));
  646. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  647. if (doc.nodes[c].type != BR_NODE_ELEM ||
  648. doc.nodes[c].tag != BR_TAG_OPTION)
  649. continue;
  650. if (i == fs->selected) {
  651. const char *v = br_value(&doc, c);
  652. if (v && v[0])
  653. form_copy_out(v, buf, cap);
  654. else
  655. form_copy_out(opt, buf, cap);
  656. return 1;
  657. }
  658. i++;
  659. }
  660. form_copy_out(opt, buf, cap);
  661. return 1;
  662. }
  663. fs = form_get(node, 1);
  664. if (!fs)
  665. return 0;
  666. form_copy_out(fs->value, buf, cap);
  667. return 1;
  668. }
  669. static int js_host_form_checked(unsigned int node)
  670. {
  671. struct form_state *fs;
  672. int kind;
  673. if (!form_is_control(node))
  674. return -1;
  675. kind = form_kind_of(node);
  676. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  677. return -1;
  678. fs = form_get(node, 1);
  679. return fs ? fs->checked : 0;
  680. }
  681. static int js_host_form_selected(unsigned int node)
  682. {
  683. struct form_state *fs;
  684. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  685. return -1;
  686. fs = form_get(node, 1);
  687. return fs ? fs->selected : 0;
  688. }
  689. static int js_host_form_set_value(unsigned int node, const char *value)
  690. {
  691. struct form_state *fs;
  692. unsigned int n;
  693. if (!form_is_control(node))
  694. return 0;
  695. fs = form_get(node, 1);
  696. if (!fs)
  697. return 0;
  698. n = s_len(value ? value : "");
  699. if (n > FORM_VALUE_MAX)
  700. n = FORM_VALUE_MAX;
  701. for (unsigned int i = 0; i < n; i++)
  702. fs->value[i] = value[i];
  703. fs->value[n] = '\0';
  704. fs->len = (unsigned char)n;
  705. fs->caret = (unsigned char)n;
  706. layout_valid = 0;
  707. ngui_invalidate(&ui);
  708. return 1;
  709. }
  710. static int js_host_form_set_checked(unsigned int node, int checked)
  711. {
  712. struct form_state *fs;
  713. int kind;
  714. if (!form_is_control(node))
  715. return 0;
  716. kind = form_kind_of(node);
  717. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  718. return 0;
  719. fs = form_get(node, 1);
  720. if (!fs)
  721. return 0;
  722. fs->checked = (unsigned char)(checked != 0);
  723. layout_valid = 0;
  724. ngui_invalidate(&ui);
  725. return 1;
  726. }
  727. static int js_host_form_set_selected(unsigned int node, int index)
  728. {
  729. struct form_state *fs;
  730. unsigned int n;
  731. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  732. return 0;
  733. fs = form_get(node, 1);
  734. if (!fs)
  735. return 0;
  736. n = form_option_count(node);
  737. if (index < 0)
  738. index = 0;
  739. if (n && (unsigned int)index >= n)
  740. index = (int)n - 1;
  741. fs->selected = (unsigned char)index;
  742. layout_valid = 0;
  743. ngui_invalidate(&ui);
  744. return 1;
  745. }
  746. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  747. {
  748. unsigned int i;
  749. int n = 0;
  750. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  751. doc.nodes[form].tag != BR_TAG_FORM)
  752. return 0;
  753. for (i = 0; i < doc.nnode && n < cap; i++) {
  754. struct br_node *nd = &doc.nodes[i];
  755. if (i == form || nd->type != BR_NODE_ELEM)
  756. continue;
  757. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  758. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  759. continue;
  760. if (!form_descendant(i, form))
  761. continue;
  762. out[n++] = i;
  763. }
  764. return n;
  765. }
  766. static int js_host_form_submit(unsigned int form)
  767. {
  768. form_submit_form(form, 0);
  769. return 1;
  770. }
  771. static int js_host_form_reset(unsigned int form)
  772. {
  773. form_reset_event(form);
  774. return 1;
  775. }
  776. static void css_computed_name(const char *p, char *out, int cap)
  777. {
  778. int n = 0;
  779. for (; p && *p && n + 2 < cap; p++) {
  780. char c = *p;
  781. if (c >= 'A' && c <= 'Z') {
  782. out[n++] = '-';
  783. c = (char)(c - 'A' + 'a');
  784. } else if (c == '_') {
  785. c = '-';
  786. } else if (c >= 'a' && c <= 'z') {
  787. /* keep */
  788. }
  789. out[n++] = c;
  790. }
  791. out[n] = '\0';
  792. if (!strcmp(out, "css-float"))
  793. strcpy(out, "float");
  794. }
  795. static void css_rgb(unsigned short c, char *buf, int cap)
  796. {
  797. int r = ((c >> 11) & 31) * 255 / 31;
  798. int g = ((c >> 5) & 63) * 255 / 63;
  799. int b = (c & 31) * 255 / 31;
  800. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  801. }
  802. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  803. int font_px)
  804. {
  805. if (unit == 4) {
  806. snprintf(buf, cap, "auto");
  807. } else if (unit == 0) {
  808. snprintf(buf, cap, "%dpx", raw);
  809. } else if (unit == 1) {
  810. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  811. } else if (unit == 2) {
  812. /* Chrome's getComputedStyle() reports used pixel values. */
  813. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  814. } else if (unit == 3) {
  815. snprintf(buf, cap, "%dpx",
  816. (int)br_root_font_px() * raw / 100);
  817. } else {
  818. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  819. raw / 100, raw % 100, px);
  820. }
  821. }
  822. static int js_host_computed(unsigned int node, const char *property,
  823. char *buf, int cap)
  824. {
  825. struct br_style st;
  826. char name[40];
  827. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  828. return 0;
  829. buf[0] = '\0';
  830. css_computed_name(property, name, sizeof(name));
  831. style_for_node(node, &st);
  832. if (!strcmp(name, "display")) {
  833. const char *v = "inline";
  834. if (st.display == BR_DISPLAY_BLOCK)
  835. v = "block";
  836. else if (st.display == BR_DISPLAY_NONE)
  837. v = "none";
  838. else if (st.display == BR_DISPLAY_FLEX)
  839. v = "flex";
  840. else if (st.display == BR_DISPLAY_GRID)
  841. v = "grid";
  842. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  843. v = "inline-block";
  844. snprintf(buf, cap, "%s", v);
  845. } else if (!strcmp(name, "position")) {
  846. static const char *pos[] = {
  847. "static", "absolute", "fixed", "relative", "sticky"
  848. };
  849. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  850. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  851. int is_w = name[0] == 'w';
  852. int kind = is_w ? st.width_kind : st.height_kind;
  853. int val = is_w ? st.width : st.height;
  854. if (kind == 3) {
  855. if (is_w)
  856. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  857. st.width_calc_pct / 100,
  858. st.width_calc_pct % 100,
  859. st.width_calc_px);
  860. else
  861. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  862. st.height_calc_pct / 100,
  863. st.height_calc_pct % 100,
  864. st.height_calc_px);
  865. } else if (kind == 1) {
  866. snprintf(buf, cap, "%dpx", val);
  867. } else if (kind == 2) {
  868. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  869. } else {
  870. snprintf(buf, cap, "auto");
  871. }
  872. } else if (!strcmp(name, "color") ||
  873. !strcmp(name, "background-color")) {
  874. if (!strcmp(name, "background-color") && !st.has_bg)
  875. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  876. else
  877. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  878. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  879. int is_fill = name[0] == 'f';
  880. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  881. if (mode == BR_PAINT_COLOR)
  882. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  883. else if (mode == BR_PAINT_CURRENT)
  884. css_rgb(st.color, buf, cap);
  885. else if (mode == BR_PAINT_UNSET && is_fill)
  886. snprintf(buf, cap, "rgb(0, 0, 0)");
  887. else if (mode == BR_PAINT_URL)
  888. snprintf(buf, cap, "url()");
  889. else
  890. snprintf(buf, cap, "none");
  891. } else if (!strcmp(name, "font-size")) {
  892. snprintf(buf, cap, "%dpx", st.font_px);
  893. } else if (!strcmp(name, "font-weight")) {
  894. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  895. } else if (!strcmp(name, "font-style")) {
  896. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  897. } else if (!strcmp(name, "font-family")) {
  898. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  899. br_font_face_family(st.font_face)[0])
  900. snprintf(buf, cap, "%s",
  901. br_font_face_family(st.font_face));
  902. else
  903. snprintf(buf, cap, "%s",
  904. st.mono ? "monospace" : "sans-serif");
  905. } else if (!strcmp(name, "text-align")) {
  906. static const char *al[] = { "left", "center", "right", "justify" };
  907. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  908. } else if (!strcmp(name, "float")) {
  909. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  910. st.float_left == 2 ? "right" : "none");
  911. } else if (!strcmp(name, "clear")) {
  912. static const char *cl[] = { "none", "left", "right", "both" };
  913. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  914. } else if (!strcmp(name, "opacity")) {
  915. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  916. } else if (!strcmp(name, "visibility")) {
  917. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  918. } else if (!strcmp(name, "overflow")) {
  919. snprintf(buf, cap, "%s",
  920. st.overflow_hidden ? "hidden" : "visible");
  921. } else if (!strcmp(name, "white-space")) {
  922. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  923. } else if (!strcmp(name, "text-transform")) {
  924. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  925. } else if (!strcmp(name, "box-sizing")) {
  926. snprintf(buf, cap, "%s",
  927. st.box_sizing ? "border-box" : "content-box");
  928. } else if (!strcmp(name, "line-height")) {
  929. if (st.line_h_px)
  930. snprintf(buf, cap, "%dpx", st.line_h_px);
  931. else if (st.line_h_pct)
  932. snprintf(buf, cap, "%d%%", st.line_h_pct);
  933. else
  934. snprintf(buf, cap, "normal");
  935. } else if (!strcmp(name, "z-index")) {
  936. if (st.z_set)
  937. snprintf(buf, cap, "%d", st.z_index);
  938. else
  939. snprintf(buf, cap, "auto");
  940. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  941. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  942. int set = name[0] == 't' ? st.top_set :
  943. name[0] == 'l' ? st.left_set :
  944. name[0] == 'r' ? st.right_set : st.bottom_set;
  945. int v = name[0] == 't' ? st.top :
  946. name[0] == 'l' ? st.left :
  947. name[0] == 'r' ? st.right : st.bottom;
  948. if (set)
  949. snprintf(buf, cap, "%dpx", v);
  950. else
  951. snprintf(buf, cap, "auto");
  952. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  953. !strcmp(name, "margin-bottom") ||
  954. !strcmp(name, "margin-left") ||
  955. !strcmp(name, "padding-top") ||
  956. !strcmp(name, "padding-right") ||
  957. !strcmp(name, "padding-bottom") ||
  958. !strcmp(name, "padding-left")) {
  959. int is_pad = name[0] == 'p';
  960. int side = name[strlen(name) - 1] == 'p' ? 0 :
  961. name[strlen(name) - 1] == 't' ? 1 :
  962. name[strlen(name) - 1] == 'm' ? 2 : 3;
  963. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  964. if (!strcmp(name, "margin-right") ||
  965. !strcmp(name, "padding-right"))
  966. side = 1;
  967. else if (!strcmp(name, "margin-bottom") ||
  968. !strcmp(name, "padding-bottom"))
  969. side = 2;
  970. else if (!strcmp(name, "margin-left") ||
  971. !strcmp(name, "padding-left"))
  972. side = 3;
  973. else
  974. side = 0;
  975. side += is_pad ? 4 : 0;
  976. css_mp_value(buf, cap,
  977. side == 0 ? st.mt : side == 1 ? st.mr :
  978. side == 2 ? st.mb : side == 3 ? st.ml :
  979. side == 4 ? st.pt : side == 5 ? st.pr :
  980. side == 6 ? st.pb : st.pl,
  981. st.mp_unit[side], st.mp_calc_px[side],
  982. st.font_px);
  983. } else if (!strcmp(name, "border-top-width") ||
  984. !strcmp(name, "border-right-width") ||
  985. !strcmp(name, "border-bottom-width") ||
  986. !strcmp(name, "border-left-width")) {
  987. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  988. name[7] == 'b' ? 2 : 3;
  989. snprintf(buf, cap, "%dpx", st.border_w[side]);
  990. } else if (!strcmp(name, "border-top-color") ||
  991. !strcmp(name, "border-right-color") ||
  992. !strcmp(name, "border-bottom-color") ||
  993. !strcmp(name, "border-left-color")) {
  994. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  995. name[7] == 'b' ? 2 : 3;
  996. if (st.border_w[side] && !st.border_t[side])
  997. css_rgb(st.border_c[side], buf, cap);
  998. else
  999. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1000. } else if (!strcmp(name, "background-image")) {
  1001. if (st.bg_image)
  1002. snprintf(buf, cap, "url(\"%s\")",
  1003. br_bg_image_url(st.bg_image - 1));
  1004. else
  1005. snprintf(buf, cap, "none");
  1006. } else if (!strcmp(name, "background-repeat")) {
  1007. static const char *rp[] = {
  1008. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1009. };
  1010. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1011. st.bg_repeat : 0]);
  1012. } else if (!strcmp(name, "background-position")) {
  1013. if (st.bg_pos_x_kind == 1)
  1014. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1015. st.bg_pos_y);
  1016. else
  1017. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1018. st.bg_pos_y);
  1019. } else if (!strcmp(name, "background-size")) {
  1020. if (st.bg_size_kind == 3)
  1021. snprintf(buf, cap, "cover");
  1022. else if (st.bg_size_kind == 4)
  1023. snprintf(buf, cap, "contain");
  1024. else if (st.bg_size_kind == 1)
  1025. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1026. st.bg_size_h);
  1027. else if (st.bg_size_kind == 2)
  1028. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1029. st.bg_size_h);
  1030. else
  1031. snprintf(buf, cap, "auto");
  1032. } else if (!strcmp(name, "transform")) {
  1033. char tmp[128];
  1034. unsigned int n = 0;
  1035. if (!st.transform_set) {
  1036. snprintf(buf, cap, "none");
  1037. } else {
  1038. tmp[0] = '\0';
  1039. if (st.tx || st.ty) {
  1040. snprintf(tmp + n, sizeof(tmp) - n,
  1041. "translate(%dpx, %dpx)", st.tx, st.ty);
  1042. n = (unsigned int)strlen(tmp);
  1043. }
  1044. if (st.transform_scale) {
  1045. snprintf(tmp + n, sizeof(tmp) - n,
  1046. "%sscale(%d.%02d, %d.%02d)",
  1047. n ? " " : "", st.scale_x / 100,
  1048. st.scale_x % 100, st.scale_y / 100,
  1049. st.scale_y % 100);
  1050. n = (unsigned int)strlen(tmp);
  1051. if (st.rotate_x100) {
  1052. snprintf(tmp + n, sizeof(tmp) - n,
  1053. " rotate(%d.%02ddeg)",
  1054. st.rotate_x100 / 100,
  1055. st.rotate_x100 % 100);
  1056. }
  1057. } else if (st.rotate_x100) {
  1058. snprintf(tmp + n, sizeof(tmp) - n,
  1059. "%srotate(%d.%02ddeg)",
  1060. n ? " " : "", st.rotate_x100 / 100,
  1061. st.rotate_x100 % 100);
  1062. }
  1063. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1064. }
  1065. } else {
  1066. return 0;
  1067. }
  1068. return buf[0] != '\0';
  1069. }
  1070. static int js_host_click(unsigned int node)
  1071. {
  1072. char url[BR_URL_MAX];
  1073. const char *href;
  1074. if (node >= doc.nnode)
  1075. return 0;
  1076. if (form_is_control(node)) {
  1077. form_click(node); /* dispatches its own click event */
  1078. return 1;
  1079. }
  1080. /* element.click() fires a bubbling, cancelable click before the
  1081. * default action, like a real click (delegated list handlers). */
  1082. if (!js_browser_event(node, "click", 1, 1))
  1083. return 1;
  1084. if (link_fragment_nav(node))
  1085. return 1;
  1086. href = br_href(&doc, node);
  1087. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1088. return 0;
  1089. s_copy(pending_url, url, sizeof(pending_url));
  1090. pending_action |= ACT_NAV;
  1091. cancel_fetch = 1;
  1092. ngui_invalidate(&ui);
  1093. return 1;
  1094. }
  1095. static int fetch_script_text(const char *url, unsigned char **out,
  1096. unsigned int *outlen, char *err,
  1097. unsigned int errcap);
  1098. struct fetch_worker;
  1099. static struct fetch_worker *fetch_worker_alloc(void);
  1100. static void fetch_worker_release(struct fetch_worker *w);
  1101. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1102. unsigned int cap, const char *post,
  1103. unsigned int post_len, unsigned int node,
  1104. int bg, char *err, unsigned int errcap);
  1105. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1106. unsigned int errcap);
  1107. static int fetch_worker_read_body(struct fetch_worker *w,
  1108. unsigned char *plain,
  1109. unsigned int plaincap,
  1110. unsigned char *comp,
  1111. unsigned int compcap,
  1112. int *truncated, char *err,
  1113. unsigned int errcap);
  1114. static void fetch_workers_stop_all(void);
  1115. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1116. unsigned int cap, const char *method,
  1117. const char *ctype, const char *post,
  1118. unsigned int post_len, unsigned int node,
  1119. int bg, char *err, unsigned int errcap);
  1120. static int script_cache_has(const char *url);
  1121. static void script_cache_put(const char *url, const unsigned char *data,
  1122. unsigned int len);
  1123. static unsigned int script_cache_hash(const char *s);
  1124. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1125. unsigned int errcap);
  1126. static void fetch_workers_cancel_busy(void);
  1127. static void worker_wait_ui(void);
  1128. static int fetch_worker_status(const struct fetch_worker *w);
  1129. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1130. * module load: the wait must not pump input, or a click would dispatch DOM
  1131. * events into the middle of the running script. */
  1132. static int fetch_wait_passive;
  1133. static void script_error(const char *what, const char *url, const char *why)
  1134. {
  1135. char msg[192];
  1136. unsigned int n = 0;
  1137. s_append(msg, &n, what, sizeof(msg));
  1138. if (url && url[0]) {
  1139. s_append(msg, &n, " ", sizeof(msg));
  1140. s_append(msg, &n, url, sizeof(msg));
  1141. }
  1142. if (why && why[0]) {
  1143. s_append(msg, &n, ": ", sizeof(msg));
  1144. s_append(msg, &n, why, sizeof(msg));
  1145. }
  1146. js_host_report(msg);
  1147. }
  1148. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1149. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1150. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1151. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1152. #define JS_HTTP_POST_MAX (16u * 1024u)
  1153. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1154. static int js_worker_http(const char *method, const char *url,
  1155. const char *ctype, const char *body,
  1156. unsigned int body_len, struct js_http_resp *r,
  1157. char *err, int errcap);
  1158. static int js_host_http(const char *method, const char *url,
  1159. const char *ctype, const char *body,
  1160. unsigned int body_len, struct js_http_resp *r,
  1161. char *err, int errcap)
  1162. {
  1163. if (pending_action) {
  1164. s_copy(err, "page is navigating", (unsigned int)errcap);
  1165. return -1;
  1166. }
  1167. if (url[0] == '/') {
  1168. /* Local file: GET only. */
  1169. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1170. int rv;
  1171. if (!buf) {
  1172. s_copy(err, "out of memory", (unsigned int)errcap);
  1173. return -1;
  1174. }
  1175. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1176. (int)JS_HTTP_MAX);
  1177. r->status = rv < 0 ? 404 : 200;
  1178. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1179. buf[r->len] = '\0';
  1180. r->body = (char *)buf;
  1181. s_copy(r->url, url, sizeof(r->url));
  1182. if (contains_ci(url, ".json"))
  1183. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1184. return 0;
  1185. }
  1186. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1187. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1188. return -1;
  1189. }
  1190. if (body_len > JS_HTTP_POST_MAX) {
  1191. s_copy(err, "request body too large", (unsigned int)errcap);
  1192. return -1;
  1193. }
  1194. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1195. errcap);
  1196. }
  1197. /* Module source for the engine's loader: the boot script cache first, then
  1198. * one blocking fetch with input pumping disabled (the loader runs inside
  1199. * JavaScript). */
  1200. static char *js_host_load_script(const char *url, unsigned int *len)
  1201. {
  1202. unsigned char *data = 0;
  1203. char err[64];
  1204. int rv;
  1205. fetch_wait_passive++;
  1206. set_status("Loading module...", 0, 0);
  1207. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1208. fetch_wait_passive--;
  1209. if (rv != 0) {
  1210. script_error("Cannot load module", url,
  1211. rv == FETCH_ABORT ? "navigation" : err);
  1212. return 0;
  1213. }
  1214. return (char *)data;
  1215. }
  1216. /* Web Storage lives in /share, outside the page heap that every navigation
  1217. * resets: localStorage per origin for the boot, sessionStorage per origin
  1218. * and browser window. */
  1219. #define JS_ORIGIN_MAX 160
  1220. /* scheme://host[:port] of the page (a local page's whole path). */
  1221. static void js_page_origin(char *origin, unsigned int cap)
  1222. {
  1223. unsigned int i = 0, slashes = 0;
  1224. while (page_url[i] && i + 1 < cap) {
  1225. if (page_url[i] == '/' && ++slashes == 3)
  1226. break;
  1227. origin[i] = page_url[i];
  1228. i++;
  1229. }
  1230. origin[i] = '\0';
  1231. }
  1232. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1233. {
  1234. unsigned int n = 0;
  1235. s_append(out, &n, "/share/bls", cap);
  1236. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1237. }
  1238. static void js_storage_path(int kind, char *out, unsigned int cap)
  1239. {
  1240. char origin[JS_ORIGIN_MAX];
  1241. unsigned int n = 0;
  1242. js_page_origin(origin, sizeof(origin));
  1243. if (!kind) {
  1244. js_origin_path(origin, out, cap);
  1245. return;
  1246. }
  1247. s_append(out, &n, "/share/bss", cap);
  1248. if (kind) {
  1249. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1250. s_append(out, &n, "-", cap);
  1251. }
  1252. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1253. }
  1254. static void persist_mark_origin(const char *origin);
  1255. static int persist_store_lookup(const char *origin, char *out, int cap);
  1256. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1257. {
  1258. char path[48], origin[JS_ORIGIN_MAX];
  1259. int rv;
  1260. js_storage_path(kind, path, sizeof(path));
  1261. if (set) {
  1262. if (kind) {
  1263. if (!set[0] || !strcmp(set, "{}")) {
  1264. u_syscall1(SYS_UNLINK, (int)path);
  1265. return 0;
  1266. }
  1267. } else {
  1268. /* localStorage keeps an explicit "{}" rather than no
  1269. * file: a missing /share file means "not loaded from
  1270. * /data yet", and a cleared store must not come back
  1271. * from the disk copy before it is flushed. */
  1272. if (!set[0])
  1273. set = "{}";
  1274. js_page_origin(origin, sizeof(origin));
  1275. persist_mark_origin(origin);
  1276. }
  1277. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1278. (int)strlen(set)) < 0 ? -1 : 0;
  1279. }
  1280. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1281. if (rv < 0 && !kind) {
  1282. /* First use this boot: the persistent copy on /data. */
  1283. js_page_origin(origin, sizeof(origin));
  1284. rv = persist_store_lookup(origin, out, cap);
  1285. if (rv >= 0)
  1286. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1287. }
  1288. if (rv < 0)
  1289. return -1;
  1290. out[rv] = '\0';
  1291. return rv;
  1292. }
  1293. /* ---- persistence on /data ----
  1294. *
  1295. * /share is the working copy (RAM, shared by every helper and window); the
  1296. * installed disk's /data volume keeps the cookie jar and localStorage
  1297. * across reboots when it is mounted. The browser owns the disk copies: at
  1298. * start it restores the jar into /share, and its main loop writes back
  1299. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1300. * setItem updates costs one FAT write. The helpers only touch /share (they
  1301. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1302. * /data mount every disk access simply fails. Both files are plaintext
  1303. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1304. #define PERSIST_MS 3000u
  1305. #define SHARE_COOKIES "/share/bcookies"
  1306. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1307. #define DATA_STORE "/data/BSTORE.DAT"
  1308. #define DATA_STORE_MAGIC "NBLS1\n"
  1309. #define DATA_STORE_MAX (192u * 1024u)
  1310. #define PERSIST_DIRTY_MAX 8
  1311. static unsigned int persist_due;
  1312. static unsigned int cookie_sum_saved;
  1313. static int cookie_sum_valid;
  1314. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1315. static int persist_ndirty;
  1316. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1317. {
  1318. unsigned int h = 2166136261u, i;
  1319. for (i = 0; i < n; i++)
  1320. h = (h ^ p[i]) * 16777619u;
  1321. return h;
  1322. }
  1323. /* Called once at startup, before any helper runs. */
  1324. static void persist_restore(void)
  1325. {
  1326. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1327. int n;
  1328. if (!jar)
  1329. return;
  1330. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1331. (int)sizeof(struct uhttp_jar));
  1332. if (n != (int)sizeof(struct uhttp_jar)) {
  1333. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1334. (int)sizeof(struct uhttp_jar));
  1335. if (n == (int)sizeof(struct uhttp_jar)) {
  1336. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1337. (int)jar, n);
  1338. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1339. cookie_sum_valid = 1;
  1340. }
  1341. }
  1342. free(jar);
  1343. persist_due = u_ticks_ms() + PERSIST_MS;
  1344. }
  1345. static void persist_mark_origin(const char *origin)
  1346. {
  1347. int i;
  1348. for (i = 0; i < persist_ndirty; i++)
  1349. if (s_eq(persist_dirty[i], origin))
  1350. return;
  1351. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1352. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1353. }
  1354. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1355. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1356. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1357. unsigned int *o_off, unsigned int *o_len,
  1358. unsigned int *d_off, unsigned int *d_len,
  1359. unsigned int *rec_end)
  1360. {
  1361. unsigned int p = *pos, v = 0;
  1362. if (p >= len)
  1363. return 0;
  1364. *o_off = p;
  1365. while (p < len && buf[p] != '\n')
  1366. p++;
  1367. if (p >= len)
  1368. return 0;
  1369. *o_len = p - *o_off;
  1370. p++;
  1371. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1372. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1373. if (p >= len || buf[p] != '\n')
  1374. return 0;
  1375. p++;
  1376. if (v > len - p)
  1377. return 0;
  1378. *d_off = p;
  1379. *d_len = v;
  1380. p += v;
  1381. if (p < len && buf[p] == '\n')
  1382. p++;
  1383. *rec_end = p;
  1384. *pos = p;
  1385. return 1;
  1386. }
  1387. static int store_load(char **out)
  1388. {
  1389. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1390. int n;
  1391. *out = buf;
  1392. if (!buf)
  1393. return -1;
  1394. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1395. (int)DATA_STORE_MAX);
  1396. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1397. !starts_with(buf, DATA_STORE_MAGIC))
  1398. return 0;
  1399. return n;
  1400. }
  1401. static int persist_store_lookup(const char *origin, char *out, int cap)
  1402. {
  1403. char *buf;
  1404. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1405. unsigned int olen = s_len(origin);
  1406. int n = store_load(&buf), rv = -1;
  1407. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1408. &dl, &e)) {
  1409. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1410. if ((int)dl < cap) {
  1411. memcpy(out, buf + d, dl);
  1412. out[dl] = '\0';
  1413. rv = (int)dl;
  1414. }
  1415. break;
  1416. }
  1417. }
  1418. free(buf);
  1419. return rv;
  1420. }
  1421. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1422. static void persist_store_flush(void)
  1423. {
  1424. char *old, *nb, path[48];
  1425. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1426. int n = store_load(&old), i, w;
  1427. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1428. if (n < 0 || !nb) {
  1429. free(old);
  1430. free(nb);
  1431. return;
  1432. }
  1433. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1434. /* Untouched origins first, in their old order. */
  1435. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1436. &dl, &e)) {
  1437. int dirty = 0;
  1438. for (i = 0; i < persist_ndirty; i++)
  1439. if (s_len(persist_dirty[i]) == ol &&
  1440. !memcmp(persist_dirty[i], old + oo, ol))
  1441. dirty = 1;
  1442. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1443. continue;
  1444. memcpy(nb + nn, old + oo, e - oo);
  1445. nn += e - oo;
  1446. }
  1447. /* Then the changed ones (an emptied store is dropped). */
  1448. for (i = 0; i < persist_ndirty; i++) {
  1449. char num[12];
  1450. unsigned int k = 0;
  1451. js_origin_path(persist_dirty[i], path, sizeof(path));
  1452. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1453. (int)DATA_STORE_MAX);
  1454. if (w <= 2) /* missing or "{}" */
  1455. continue;
  1456. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1457. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1458. DATA_STORE_MAX) {
  1459. set_status("Saved site data is full; a site's "
  1460. "localStorage was not saved", 1, 6000);
  1461. continue;
  1462. }
  1463. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1464. nb[nn++] = '\n';
  1465. s_append(nb, &nn, num, DATA_STORE_MAX);
  1466. nb[nn++] = '\n';
  1467. memcpy(nb + nn, old, (unsigned int)w);
  1468. nn += (unsigned int)w;
  1469. nb[nn++] = '\n';
  1470. }
  1471. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1472. persist_ndirty = 0;
  1473. free(old);
  1474. free(nb);
  1475. }
  1476. static void persist_cookies_flush(void)
  1477. {
  1478. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1479. unsigned int sum;
  1480. int n;
  1481. if (!jar)
  1482. return;
  1483. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1484. (int)sizeof(struct uhttp_jar));
  1485. if (n == (int)sizeof(struct uhttp_jar)) {
  1486. sum = persist_sum(jar, (unsigned int)n);
  1487. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1488. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1489. (int)jar, n) >= 0) {
  1490. cookie_sum_saved = sum;
  1491. cookie_sum_valid = 1;
  1492. }
  1493. }
  1494. }
  1495. free(jar);
  1496. }
  1497. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1498. static void persist_tick(void)
  1499. {
  1500. unsigned int now = u_ticks_ms();
  1501. if ((int)(now - persist_due) < 0)
  1502. return;
  1503. persist_due = now + PERSIST_MS;
  1504. persist_cookies_flush();
  1505. if (persist_ndirty)
  1506. persist_store_flush();
  1507. }
  1508. /* <link rel="modulepreload">: download the page's module graph on all
  1509. * helpers at once into the boot script cache, before any script runs. The
  1510. * engine's module loader is sequential (one blocking fetch per import), so
  1511. * without this a Vite app with a dozen chunks pays every round trip in a
  1512. * row. Failures are ignored; the loader fetches what is missing. */
  1513. #define MODULE_PRELOAD_MAX 24
  1514. static void prefetch_module_preloads(void)
  1515. {
  1516. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1517. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1518. unsigned int count = 0, next = 0, done = 0, i;
  1519. char err[64];
  1520. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1521. struct br_node *nd = &doc.nodes[i];
  1522. const char *rel, *href;
  1523. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1524. continue;
  1525. rel = br_rel(&doc, i);
  1526. href = br_href(&doc, i);
  1527. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1528. continue;
  1529. if (resolve_link(page_url, href, urls[count],
  1530. sizeof(urls[count])) != 0 ||
  1531. urls[count][0] == '/' || script_cache_has(urls[count]))
  1532. continue;
  1533. slot[count++] = 0;
  1534. }
  1535. if (!count)
  1536. return;
  1537. set_status("Loading modules...", 0, 0);
  1538. while (done < count) {
  1539. struct fetch_worker *w;
  1540. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1541. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1542. 0, 0, 0, err,
  1543. sizeof(err)) != 0) {
  1544. fetch_worker_release(w);
  1545. done++;
  1546. } else {
  1547. slot[next] = w;
  1548. }
  1549. next++;
  1550. }
  1551. worker_wait_ui();
  1552. if (cancel_fetch || pending_action) {
  1553. fetch_workers_cancel_busy();
  1554. return;
  1555. }
  1556. for (i = 0; i < next; i++) {
  1557. unsigned char *body;
  1558. int rv, tr = 0;
  1559. if (!slot[i])
  1560. continue;
  1561. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1562. if (rv == 0)
  1563. continue;
  1564. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1565. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1566. if (body) {
  1567. rv = fetch_worker_read_body(slot[i], body,
  1568. BR_SCRIPT_MAX, image_io_buf,
  1569. BR_PAGE_COMP_MAX, &tr, err,
  1570. sizeof(err));
  1571. if (rv > 0 && !tr)
  1572. script_cache_put(urls[i], body,
  1573. (unsigned int)rv);
  1574. free(body);
  1575. }
  1576. fetch_worker_release(slot[i]);
  1577. slot[i] = 0;
  1578. done++;
  1579. }
  1580. u_sleep_ms(10);
  1581. }
  1582. }
  1583. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1584. * submitted to helper workers ahead of time, but scripts still execute in
  1585. * document order. */
  1586. #define SCRIPT_INLINE 0
  1587. #define SCRIPT_LOCAL 1
  1588. #define SCRIPT_REMOTE 2
  1589. #define SCRIPT_ERROR 3
  1590. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1591. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1592. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1593. static void script_submit_window(unsigned int *next, char *err,
  1594. unsigned int errcap)
  1595. {
  1596. while (*next < doc.nscripts) {
  1597. struct fetch_worker *w;
  1598. if (script_kind[*next] != SCRIPT_REMOTE) {
  1599. (*next)++;
  1600. continue;
  1601. }
  1602. w = fetch_worker_alloc();
  1603. if (!w)
  1604. return;
  1605. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1606. 0, 0, 0, 0, err, errcap) != 0) {
  1607. fetch_worker_release(w);
  1608. script_kind[*next] = SCRIPT_ERROR;
  1609. (*next)++;
  1610. continue;
  1611. }
  1612. script_slot[*next] = w;
  1613. (*next)++;
  1614. }
  1615. }
  1616. /* Run the page's scripts in document order. External bodies are prefetched
  1617. * in parallel so downloading script N+1 overlaps executing script N; inline
  1618. * bodies are copied because the engine needs NUL-terminated text. */
  1619. static void run_page_scripts(void)
  1620. {
  1621. struct js_browser_host host;
  1622. unsigned int i, next = 0;
  1623. char err[64], ferr[64];
  1624. if (!doc.nscripts)
  1625. return;
  1626. host.status = js_host_status;
  1627. host.report = js_host_report;
  1628. host.navigate = js_host_navigate;
  1629. host.changed = js_host_changed;
  1630. host.rect = js_host_rect;
  1631. host.form_value = js_host_form_value;
  1632. host.form_checked = js_host_form_checked;
  1633. host.form_selected = js_host_form_selected;
  1634. host.form_set_value = js_host_form_set_value;
  1635. host.form_set_checked = js_host_form_set_checked;
  1636. host.form_set_selected = js_host_form_set_selected;
  1637. host.form_elements = js_host_form_elements;
  1638. host.form_submit = js_host_form_submit;
  1639. host.form_reset = js_host_form_reset;
  1640. host.click = js_host_click;
  1641. host.computed = js_host_computed;
  1642. host.http = js_host_http;
  1643. host.load_script = js_host_load_script;
  1644. host.storage = js_host_storage;
  1645. host.set_hash = js_host_set_hash;
  1646. host.page_url = page_url;
  1647. host.width = ui.w;
  1648. host.height = ui.h;
  1649. if (js_browser_start(&doc, &host) != 0) {
  1650. js_host_status("JavaScript: out of memory", 1);
  1651. return;
  1652. }
  1653. resize_sent_w = -1;
  1654. resize_pending = 0;
  1655. prefetch_module_preloads();
  1656. for (i = 0; i < doc.nscripts; i++) {
  1657. struct br_script *script = &doc.scripts[i];
  1658. const char *src_attr = script->src_off ?
  1659. doc.attrs + script->src_off : "";
  1660. script_slot[i] = 0;
  1661. if (!script->src_off) {
  1662. script_kind[i] = SCRIPT_INLINE;
  1663. continue;
  1664. }
  1665. if (!src_attr[0] ||
  1666. resolve_link(page_url, src_attr, script_urls[i],
  1667. sizeof(script_urls[i])) != 0) {
  1668. script_urls[i][0] = '\0';
  1669. script_kind[i] = SCRIPT_ERROR;
  1670. continue;
  1671. }
  1672. if (script_urls[i][0] == '/' ||
  1673. script_cache_has(script_urls[i]))
  1674. script_kind[i] = SCRIPT_LOCAL;
  1675. else
  1676. script_kind[i] = SCRIPT_REMOTE;
  1677. }
  1678. script_submit_window(&next, ferr, sizeof(ferr));
  1679. for (i = 0; i < doc.nscripts; i++) {
  1680. struct br_script *script = &doc.scripts[i];
  1681. /* document.currentScript for classic scripts (null for modules) */
  1682. js_browser_set_current_script(script->module ? 0 : script->node);
  1683. if (script_kind[i] == SCRIPT_INLINE) {
  1684. unsigned int off = script->off;
  1685. unsigned int len = script->len;
  1686. unsigned int k;
  1687. char *src = (char *)malloc(len + 1);
  1688. if (!src) {
  1689. js_host_status("JavaScript: out of memory", 1);
  1690. break;
  1691. }
  1692. for (k = 0; k < len; k++)
  1693. src[k] = doc.script_src[off + k];
  1694. src[len] = '\0';
  1695. if (script->module) {
  1696. /* A distinct module name per inline module
  1697. * (QuickJS registers modules by name); the
  1698. * fragment keeps relative imports resolving
  1699. * against the page. */
  1700. char mname[BR_URL_MAX + 16];
  1701. unsigned int mn = 0;
  1702. s_append(mname, &mn, page_url, sizeof(mname));
  1703. s_append(mname, &mn, "#module", sizeof(mname));
  1704. s_append_dec(mname, &mn, i, sizeof(mname));
  1705. js_browser_run_module(src, mname);
  1706. } else {
  1707. js_browser_run(src, page_url);
  1708. }
  1709. free(src);
  1710. } else if (script->src_off) {
  1711. const char *src_attr = doc.attrs + script->src_off;
  1712. if (script_kind[i] == SCRIPT_ERROR) {
  1713. script_error("Cannot load script", src_attr,
  1714. script_urls[i][0] ?
  1715. "network busy" :
  1716. "unsupported URL");
  1717. continue;
  1718. }
  1719. if (script_kind[i] == SCRIPT_LOCAL) {
  1720. unsigned char *data = 0;
  1721. unsigned int len = 0;
  1722. int rv;
  1723. set_status("Loading script...", 0, 0);
  1724. rv = fetch_script_text(script_urls[i], &data,
  1725. &len, err, sizeof(err));
  1726. if (rv == FETCH_ABORT)
  1727. break;
  1728. if (rv != 0) {
  1729. script_error("Cannot load script",
  1730. script_urls[i], err);
  1731. continue;
  1732. }
  1733. if (script->module)
  1734. js_browser_run_module(
  1735. (const char *)data,
  1736. script_urls[i]);
  1737. else
  1738. js_browser_run((const char *)data,
  1739. script_urls[i]);
  1740. free(data);
  1741. } else {
  1742. struct fetch_worker *w = script_slot[i];
  1743. unsigned char *body = 0;
  1744. int tr = 0, rv;
  1745. if (!w) {
  1746. w = fetch_worker_alloc();
  1747. if (!w)
  1748. continue;
  1749. if (fetch_worker_submit(w,
  1750. script_urls[i],
  1751. BR_SCRIPT_MAX,
  1752. 0, 0, 0, 0, err,
  1753. sizeof(err)) != 0) {
  1754. fetch_worker_release(w);
  1755. script_kind[i] = SCRIPT_ERROR;
  1756. if (i == next)
  1757. next++;
  1758. continue;
  1759. }
  1760. script_slot[i] = w;
  1761. if (i == next)
  1762. next++;
  1763. }
  1764. set_status("Loading script...", 0, 0);
  1765. rv = fetch_worker_wait(w, err, sizeof(err));
  1766. if (rv == FETCH_ABORT) {
  1767. fetch_workers_stop_all();
  1768. break;
  1769. }
  1770. /* The body gets its own buffer (scripts are up
  1771. * to 2 MB); image_io_buf takes the gzip
  1772. * stream. */
  1773. body = rv == 0 ? (unsigned char *)malloc(
  1774. BR_SCRIPT_MAX + 1) : 0;
  1775. if (body)
  1776. rv = fetch_worker_read_body(w, body,
  1777. BR_SCRIPT_MAX, image_io_buf,
  1778. BR_PAGE_COMP_MAX, &tr, err,
  1779. sizeof(err));
  1780. else {
  1781. if (rv == 0)
  1782. s_copy(err, "out of memory",
  1783. sizeof(err));
  1784. rv = -1;
  1785. }
  1786. fetch_worker_release(w);
  1787. script_slot[i] = 0;
  1788. script_submit_window(&next, ferr, sizeof(ferr));
  1789. if (rv <= 0)
  1790. script_error("Cannot load script",
  1791. script_urls[i], err);
  1792. else if (tr || (unsigned int)rv >=
  1793. BR_SCRIPT_MAX)
  1794. script_error("Cannot load script",
  1795. script_urls[i],
  1796. "script is too large");
  1797. else {
  1798. body[rv] = '\0';
  1799. script_cache_put(script_urls[i], body,
  1800. (unsigned int)rv);
  1801. if (script->module)
  1802. js_browser_run_module(
  1803. (const char *)body,
  1804. script_urls[i]);
  1805. else
  1806. js_browser_run(
  1807. (const char *)body,
  1808. script_urls[i]);
  1809. }
  1810. free(body);
  1811. }
  1812. }
  1813. if (pending_action)
  1814. break;
  1815. }
  1816. js_browser_set_current_script(0);
  1817. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1818. * load_home() stop it before the next navigation. */
  1819. if (doc.scripts_truncated && !js_last_error)
  1820. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1821. 1);
  1822. }
  1823. /* ---- images ---- */
  1824. static void image_reset(void)
  1825. {
  1826. int i;
  1827. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1828. images[i].state = 0;
  1829. images[i].native_w = images[i].native_h = 0;
  1830. images[i].err[0] = '\0';
  1831. }
  1832. image_count = 0;
  1833. image_pixels = 0;
  1834. preload_active = 0;
  1835. preload_pending = 0;
  1836. preload_wait = 0;
  1837. preload_node = 0;
  1838. preload_loaded = 0;
  1839. }
  1840. /* Decode into the shared arena, then copy/scale the result into a display
  1841. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1842. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1843. * pixels. Transparent edges are composited over white. */
  1844. /* One decode scratch arena per page, reused across images. Allocating and
  1845. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1846. * each small display bitmap landed in the hole the previous arena left, so
  1847. * the next arena no longer fit and the heap ratcheted up until an app
  1848. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1849. * still released right after their one image. */
  1850. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1851. static unsigned char *decode_arena_get(unsigned int bytes)
  1852. {
  1853. if (decode_arena && decode_arena_size >= bytes)
  1854. return decode_arena;
  1855. free(decode_arena);
  1856. decode_arena = (unsigned char *)malloc(bytes);
  1857. decode_arena_size = decode_arena ? bytes : 0;
  1858. return decode_arena;
  1859. }
  1860. static void decode_arena_put(void)
  1861. {
  1862. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1863. free(decode_arena);
  1864. decode_arena = 0;
  1865. decode_arena_size = 0;
  1866. }
  1867. }
  1868. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1869. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1870. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1871. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  1872. static int svg_decode_image(const unsigned char *data, unsigned int len,
  1873. struct br_image *bi, int box_w, int box_h);
  1874. static int decode_image_data(const unsigned char *data, unsigned int len,
  1875. struct br_image *bi, int box_w, int box_h)
  1876. {
  1877. struct img_info info;
  1878. struct img_options opt;
  1879. struct img_mem mem;
  1880. struct img_image decoded;
  1881. unsigned char *arena;
  1882. unsigned int est, bytes, i;
  1883. unsigned short *px;
  1884. unsigned char *alpha = 0;
  1885. int dw, dh, r;
  1886. bi->url_hash = 0;
  1887. if (img_sniff(data, len, &info) != 0) {
  1888. if (svg_text_sniff(data, len))
  1889. return svg_decode_image(data, len, bi, box_w, box_h);
  1890. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1891. return -1;
  1892. }
  1893. est = img_estimate(&info);
  1894. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1895. s_copy(bi->err, "image too large", sizeof(bi->err));
  1896. return -1;
  1897. }
  1898. arena = decode_arena_get(est);
  1899. if (!arena) {
  1900. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1901. return -1;
  1902. }
  1903. img_mem_init(&mem, arena, est);
  1904. opt.max_pixels = BR_IMG_PIX_MAX;
  1905. r = img_decode(data, len, &opt, &mem, &decoded);
  1906. if (r != 0) {
  1907. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1908. goto fail;
  1909. }
  1910. if (decoded.w == 0 || decoded.h == 0) {
  1911. s_copy(bi->err, "empty image", sizeof(bi->err));
  1912. goto fail;
  1913. }
  1914. bi->native_w = (int)decoded.w;
  1915. bi->native_h = (int)decoded.h;
  1916. dw = (int)decoded.w;
  1917. dh = (int)decoded.h;
  1918. if (box_w > 0 && box_h > 0) {
  1919. /* cover: scale so both box sides are filled, never up */
  1920. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1921. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1922. unsigned int sc = sw > sh ? sw : sh;
  1923. if (sc < 0x10000u) {
  1924. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1925. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1926. }
  1927. }
  1928. if (dw > BR_IMG_LAYOUT_W) {
  1929. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1930. dw = BR_IMG_LAYOUT_W;
  1931. }
  1932. if (dh < 1)
  1933. dh = 1;
  1934. if (dw < 1)
  1935. dw = 1;
  1936. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1937. BR_IMG_PIXEL_BUDGET) {
  1938. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1939. goto fail;
  1940. }
  1941. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1942. px = (unsigned short *)malloc(bytes);
  1943. if (!px) {
  1944. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1945. goto fail;
  1946. }
  1947. /* Keep the alpha plane for the scaled image so transparent logos and
  1948. * icons composite over the page instead of the browser's dark theme
  1949. * background. Very large alpha images stay flattened to bound the
  1950. * heap use. */
  1951. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1952. alpha = (unsigned char *)malloc((unsigned int)dw *
  1953. (unsigned int)dh);
  1954. if (alpha) {
  1955. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1956. alpha[i] = 255;
  1957. }
  1958. }
  1959. /* With an alpha plane the colour under transparent pixels only shows
  1960. * through partially covered edge pixels of the downscale: use white,
  1961. * as documented above, not the dark browser theme (which left a dark
  1962. * fringe around scaled app icons). */
  1963. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1964. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1965. {
  1966. struct img_blit b;
  1967. b.dst = px;
  1968. b.dst_w = dw;
  1969. b.dst_h = dh;
  1970. b.clip_x = 0;
  1971. b.clip_y = 0;
  1972. b.clip_w = dw;
  1973. b.clip_h = dh;
  1974. b.x = 0;
  1975. b.y = 0;
  1976. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1977. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1978. b.bg2 = b.bg;
  1979. b.dst_a = alpha;
  1980. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1981. img_draw(&decoded, &b);
  1982. }
  1983. bi->img.format = decoded.format;
  1984. bi->img.w = (unsigned int)dw;
  1985. bi->img.h = (unsigned int)dh;
  1986. bi->img.px = px;
  1987. bi->img.alpha = alpha;
  1988. bi->img.flags = 0;
  1989. bi->state = 1;
  1990. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1991. decode_arena_put();
  1992. return 0;
  1993. fail:
  1994. decode_arena_put();
  1995. return -1;
  1996. }
  1997. /* ---- URL / local path handling ---- */
  1998. static int is_http(const char *s)
  1999. {
  2000. return starts_with(s, "http://") || starts_with(s, "https://");
  2001. }
  2002. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2003. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2004. {
  2005. char seg[64];
  2006. unsigned int i = 0, o = 1;
  2007. int depth = 0;
  2008. int trailing;
  2009. if (!in || in[0] != '/' || cap < 2)
  2010. return -1;
  2011. trailing = 0;
  2012. {
  2013. unsigned int n = s_len(in);
  2014. if (n > 1 && in[n - 1] == '/')
  2015. trailing = 1;
  2016. }
  2017. out[0] = '/';
  2018. while (in[i]) {
  2019. unsigned int n = 0;
  2020. while (in[i] == '/')
  2021. i++;
  2022. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2023. if (n + 1 < sizeof(seg))
  2024. seg[n++] = in[i];
  2025. i++;
  2026. }
  2027. seg[n] = '\0';
  2028. if (n == 0)
  2029. break;
  2030. if (s_eq(seg, "."))
  2031. continue;
  2032. if (s_eq(seg, "..")) {
  2033. if (depth > 0) {
  2034. while (o > 1 && out[o - 1] != '/')
  2035. o--;
  2036. if (o > 1)
  2037. o--;
  2038. depth--;
  2039. }
  2040. continue;
  2041. }
  2042. if (o > 1) {
  2043. if (o + 1 >= cap)
  2044. return -1;
  2045. out[o++] = '/';
  2046. }
  2047. if (o + n + 1 >= cap)
  2048. return -1;
  2049. {
  2050. unsigned int j;
  2051. for (j = 0; j < n; j++)
  2052. out[o++] = seg[j];
  2053. }
  2054. depth++;
  2055. }
  2056. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2057. if (o + 1 >= cap)
  2058. return -1;
  2059. out[o++] = '/';
  2060. }
  2061. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2062. if (in[i] == '?' || in[i] == '#') {
  2063. while (in[i]) {
  2064. if (o + 1 >= cap)
  2065. return -1;
  2066. out[o++] = in[i++];
  2067. }
  2068. }
  2069. out[o] = '\0';
  2070. return 0;
  2071. }
  2072. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2073. {
  2074. char joined[BR_URL_MAX];
  2075. if (!in || !in[0]) {
  2076. s_copy(out, cwd[0] ? cwd : "/", cap);
  2077. return;
  2078. }
  2079. if (in[0] == '/') {
  2080. if (normalize_abs(in, out, cap) != 0)
  2081. s_copy(out, in, cap);
  2082. return;
  2083. }
  2084. {
  2085. unsigned int n = 0;
  2086. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2087. s_append(joined, &n, "/", sizeof(joined));
  2088. s_append(joined, &n, in, sizeof(joined));
  2089. }
  2090. if (normalize_abs(joined, out, cap) != 0)
  2091. s_copy(out, joined, cap);
  2092. }
  2093. /* ---- canonical origin cache ---- *
  2094. *
  2095. * Sites commonly redirect http://host to https://host and then to
  2096. * https://www.host. Remember the final scheme/host of the last navigation so
  2097. * a bare domain typed again goes straight there instead of paying for two
  2098. * more connections and TLS handshakes. Only default-port requests are
  2099. * rewritten; explicit ports are left alone. */
  2100. #define ORIGIN_CACHE_MAX 8
  2101. #define ORIGIN_FILE "/share/borigins"
  2102. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2103. UHTTP_HOST_MAX + 2))
  2104. struct origin_cache_entry {
  2105. char host[UHTTP_HOST_MAX];
  2106. char origin[UHTTP_HOST_MAX + 16];
  2107. };
  2108. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2109. static int origin_count;
  2110. static char origin_buf[ORIGIN_BUF_SIZE];
  2111. static int default_port(const struct uhttp_url *u)
  2112. {
  2113. return u->secure ? u->port == 443 : u->port == 80;
  2114. }
  2115. static void url_origin(const struct uhttp_url *u, char *out,
  2116. unsigned int cap)
  2117. {
  2118. unsigned int n = 0;
  2119. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2120. s_append(out, &n, u->host, cap);
  2121. if (!default_port(u)) {
  2122. s_append(out, &n, ":", cap);
  2123. s_append_dec(out, &n, u->port, cap);
  2124. }
  2125. }
  2126. static void origin_cache_apply(char *url, unsigned int cap)
  2127. {
  2128. struct uhttp_url u;
  2129. char out[BR_URL_MAX];
  2130. unsigned int n = 0;
  2131. int i;
  2132. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2133. return;
  2134. for (i = 0; i < origin_count; i++) {
  2135. if (!s_eq(u.host, origins[i].host))
  2136. continue;
  2137. s_append(out, &n, origins[i].origin, sizeof(out));
  2138. s_append(out, &n, u.path, sizeof(out));
  2139. s_copy(url, out, cap);
  2140. return;
  2141. }
  2142. }
  2143. static void origin_cache_save(void)
  2144. {
  2145. unsigned int n = 0;
  2146. int i;
  2147. for (i = 0; i < origin_count; i++) {
  2148. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2149. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2150. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2151. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2152. }
  2153. if (n)
  2154. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2155. (int)origin_buf, (int)n);
  2156. }
  2157. static void origin_cache_load(void)
  2158. {
  2159. char *p;
  2160. int rn;
  2161. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2162. (int)(sizeof(origin_buf) - 1));
  2163. if (rn <= 0)
  2164. return;
  2165. origin_buf[rn] = '\0';
  2166. p = origin_buf;
  2167. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2168. char *line = p, *origin;
  2169. while (*p && *p != '\n')
  2170. p++;
  2171. if (*p)
  2172. *p++ = '\0';
  2173. if (!line[0])
  2174. continue;
  2175. origin = line;
  2176. while (*origin && *origin != ' ')
  2177. origin++;
  2178. if (!*origin)
  2179. continue;
  2180. *origin++ = '\0';
  2181. if (!line[0] || !is_http(origin))
  2182. continue;
  2183. {
  2184. struct uhttp_url uo;
  2185. if (uhttp_parse_url(origin, &uo) != 0 ||
  2186. !s_eq(uo.path, "/"))
  2187. continue;
  2188. }
  2189. s_copy(origins[origin_count].host, line,
  2190. sizeof(origins[origin_count].host));
  2191. s_copy(origins[origin_count].origin, origin,
  2192. sizeof(origins[origin_count].origin));
  2193. origin_count++;
  2194. }
  2195. }
  2196. static int host_is_www_of(const char *host, const char *base)
  2197. {
  2198. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2199. host[3] == '.' && s_eq(host + 4, base);
  2200. }
  2201. static void origin_cache_learn(const char *requested, const char *final)
  2202. {
  2203. struct uhttp_url from, to;
  2204. char origin[UHTTP_HOST_MAX + 16];
  2205. int i;
  2206. if (!is_http(requested) || !is_http(final))
  2207. return;
  2208. if (uhttp_parse_url(requested, &from) != 0 ||
  2209. uhttp_parse_url(final, &to) != 0)
  2210. return;
  2211. if (!default_port(&from))
  2212. return;
  2213. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2214. from.port == to.port)
  2215. return;
  2216. /* Only remember origin-level canonicalisation: the same path, and
  2217. * either the same host or its www./apex sibling. A path- or
  2218. * host-specific redirect (a shortener, a login page) must not poison
  2219. * every request to the typed host. */
  2220. if (!s_eq(from.path, to.path))
  2221. return;
  2222. if (!s_eq(from.host, to.host) &&
  2223. !host_is_www_of(to.host, from.host) &&
  2224. !host_is_www_of(from.host, to.host))
  2225. return;
  2226. url_origin(&to, origin, sizeof(origin));
  2227. for (i = 0; i < origin_count; i++) {
  2228. if (s_eq(origins[i].host, from.host)) {
  2229. if (!s_eq(origins[i].origin, origin)) {
  2230. s_copy(origins[i].origin, origin,
  2231. sizeof(origins[i].origin));
  2232. origin_cache_save();
  2233. }
  2234. return;
  2235. }
  2236. }
  2237. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2238. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2239. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2240. origin_cache_save();
  2241. }
  2242. static int path_dir(const char *path, char *out, unsigned int cap)
  2243. {
  2244. unsigned int i, last = 0;
  2245. for (i = 0; path[i]; i++)
  2246. if (path[i] == '/')
  2247. last = i;
  2248. if (last == 0) {
  2249. if (cap < 2)
  2250. return -1;
  2251. out[0] = '/';
  2252. out[1] = '\0';
  2253. return 0;
  2254. }
  2255. if (last + 1 >= cap)
  2256. return -1;
  2257. {
  2258. unsigned int j;
  2259. for (j = 0; j < last; j++)
  2260. out[j] = path[j];
  2261. out[last] = '\0';
  2262. }
  2263. return 0;
  2264. }
  2265. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2266. static int resolve_link(const char *base, const char *href, char *out,
  2267. unsigned int cap)
  2268. {
  2269. char joined[BR_URL_MAX];
  2270. if (!href || !href[0] || href[0] == '#')
  2271. return -1;
  2272. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2273. starts_with(href, "data:") || starts_with(href, "tel:"))
  2274. return -1;
  2275. if (starts_with(href, "about:")) {
  2276. s_copy(out, href, cap);
  2277. return 0;
  2278. }
  2279. if (is_http(href)) {
  2280. s_copy(out, href, cap);
  2281. return 0;
  2282. }
  2283. if (starts_with(href, "//")) {
  2284. if (is_http(base)) {
  2285. unsigned int n = 0;
  2286. s_append(out, &n, starts_with(base, "https:") ?
  2287. "https:" : "http:", cap);
  2288. s_append(out, &n, href, cap);
  2289. return 0;
  2290. }
  2291. return -1;
  2292. }
  2293. if (is_http(base)) {
  2294. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2295. }
  2296. /* local page */
  2297. if (href[0] == '/') {
  2298. if (normalize_abs(href, out, cap) != 0)
  2299. return -1;
  2300. return 0;
  2301. }
  2302. {
  2303. char dir[BR_URL_MAX];
  2304. unsigned int n = 0;
  2305. if (s_eq(base, "about:home"))
  2306. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2307. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2308. s_copy(dir, "/", sizeof(dir));
  2309. s_append(joined, &n, dir, sizeof(joined));
  2310. if (n == 0 || joined[n - 1] != '/')
  2311. s_append(joined, &n, "/", sizeof(joined));
  2312. s_append(joined, &n, href, sizeof(joined));
  2313. }
  2314. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2315. }
  2316. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2317. * rest instead of failing when a page or stylesheet is larger than the
  2318. * buffer. The stream is still walked to the end, so a normal page is
  2319. * verified; a truncated compressed input still returns whatever was decoded
  2320. * so far. */
  2321. struct trunc_buf {
  2322. unsigned char *dst;
  2323. unsigned int cap, pos;
  2324. int full;
  2325. };
  2326. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2327. {
  2328. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2329. if (len > m->cap - m->pos) {
  2330. unsigned int room = m->cap - m->pos;
  2331. if (room) {
  2332. unsigned int i;
  2333. for (i = 0; i < room; i++)
  2334. m->dst[m->pos + i] = data[i];
  2335. m->pos += room;
  2336. }
  2337. m->full = 1;
  2338. return 0;
  2339. }
  2340. {
  2341. unsigned int i;
  2342. for (i = 0; i < len; i++)
  2343. m->dst[m->pos + i] = data[i];
  2344. }
  2345. m->pos += len;
  2346. return 0;
  2347. }
  2348. static void worker_wait_ui(void);
  2349. static void inflate_ui_pump(void *ctx)
  2350. {
  2351. static unsigned int last;
  2352. unsigned int now = u_ticks_ms();
  2353. (void)ctx;
  2354. if ((int)(now - last) >= 50) {
  2355. last = now;
  2356. worker_wait_ui();
  2357. }
  2358. }
  2359. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2360. unsigned char *dst, unsigned int cap,
  2361. unsigned int *outlen, int gzip, int *truncated)
  2362. {
  2363. struct inflate_src in;
  2364. struct inflate_sink sink;
  2365. struct trunc_buf m;
  2366. unsigned int got = 0;
  2367. int r;
  2368. in.p = src;
  2369. in.len = len;
  2370. in.more = 0;
  2371. in.ctx = 0;
  2372. m.dst = dst;
  2373. m.cap = cap;
  2374. m.pos = 0;
  2375. m.full = 0;
  2376. sink.write = trunc_write;
  2377. sink.ctx = &m;
  2378. inflate_init(&image_inflate_ws, &in, &sink);
  2379. image_inflate_ws.progress = inflate_ui_pump;
  2380. image_inflate_ws.progress_ctx = 0;
  2381. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2382. inflate_zlib(&image_inflate_ws, &got);
  2383. *outlen = m.pos;
  2384. *truncated = m.full || r != 0;
  2385. if (r != 0 && m.pos == 0)
  2386. return -1;
  2387. return 0;
  2388. }
  2389. /* ---- headless fetch workers ------------------------------------------ *
  2390. *
  2391. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2392. * writes the raw response, a small metadata file and a done marker under
  2393. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2394. * or a multi-megabyte body never freezes the UI and images download in
  2395. * parallel.
  2396. */
  2397. struct fetch_meta {
  2398. int status;
  2399. int error;
  2400. int trunc;
  2401. unsigned int len;
  2402. unsigned int open_ms;
  2403. unsigned int first_ms;
  2404. unsigned int total_ms;
  2405. char encoding[16];
  2406. char ctype[64];
  2407. char final[BR_URL_MAX];
  2408. };
  2409. static void draw(unsigned int *action);
  2410. static void handle_keys(unsigned int *action);
  2411. static void handle_page_click(unsigned int *action);
  2412. #define FETCH_WORKERS 4
  2413. #define FETCH_PATH_MAX 32
  2414. /* One long-lived curl __serve helper per worker. Each worker has its own
  2415. * request/body/meta/done files under /share so several downloads can be in
  2416. * flight at once; the keep-alive connection stays in the helper process, so
  2417. * tls.c's per-process state remains valid. */
  2418. struct fetch_worker {
  2419. int pid;
  2420. int slot;
  2421. int busy;
  2422. int ready;
  2423. int image_job;
  2424. unsigned int seq;
  2425. unsigned int deadline;
  2426. int retried;
  2427. char req[FETCH_PATH_MAX];
  2428. char body[FETCH_PATH_MAX];
  2429. char meta[FETCH_PATH_MAX];
  2430. char done[FETCH_PATH_MAX];
  2431. char post[FETCH_PATH_MAX];
  2432. /* Optional preload job attached to this worker. */
  2433. unsigned int node;
  2434. int bg;
  2435. char url[BR_URL_MAX];
  2436. struct fetch_meta m;
  2437. };
  2438. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2439. static int fetch_tty = -2;
  2440. static void fetch_tty_drain(void);
  2441. static unsigned int fetch_session;
  2442. static unsigned int fetch_seq;
  2443. static struct fetch_meta fetch_meta;
  2444. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2445. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2446. static int fetch_last_error;
  2447. static unsigned int meta_uint(char **pp)
  2448. {
  2449. char *p = *pp;
  2450. unsigned int v = 0;
  2451. while (*p >= '0' && *p <= '9') {
  2452. v = v * 10 + (unsigned int)(*p - '0');
  2453. p++;
  2454. }
  2455. while (*p && *p != '\n')
  2456. p++;
  2457. if (*p == '\n')
  2458. p++;
  2459. *pp = p;
  2460. return v;
  2461. }
  2462. static void meta_str(char **pp, char *out, unsigned int cap)
  2463. {
  2464. char *p = *pp;
  2465. unsigned int n = 0;
  2466. while (*p && *p != '\n' && n + 1 < cap)
  2467. out[n++] = *p++;
  2468. out[n] = '\0';
  2469. while (*p && *p != '\n')
  2470. p++;
  2471. if (*p == '\n')
  2472. p++;
  2473. *pp = p;
  2474. }
  2475. static void worker_wait_ui(void)
  2476. {
  2477. unsigned int action = 0;
  2478. if (!ngui_begin(&ui))
  2479. return;
  2480. draw(&action);
  2481. handle_keys(&action);
  2482. handle_page_click(&action);
  2483. if (action & ACT_WAIT_NAV) {
  2484. pending_action |= action & ACT_WAIT_NAV;
  2485. if ((action & ACT_NAV) && click_url[0])
  2486. s_copy(pending_url, click_url, sizeof(pending_url));
  2487. click_url[0] = '\0';
  2488. cancel_fetch = 1;
  2489. }
  2490. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2491. ngui_invalidate(&ui);
  2492. ngui_end(&ui);
  2493. }
  2494. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2495. unsigned int session, int slot)
  2496. {
  2497. unsigned int n = 0;
  2498. s_append(out, &n, "/share/bf", cap);
  2499. s_append_dec(out, &n, session, cap);
  2500. s_append(out, &n, "_", cap);
  2501. s_append_dec(out, &n, (unsigned int)slot, cap);
  2502. s_append(out, &n, kind, cap);
  2503. }
  2504. static void fetch_pool_init(void)
  2505. {
  2506. static int ready;
  2507. int i;
  2508. if (ready)
  2509. return;
  2510. ready = 1;
  2511. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2512. (u_ticks_ms() & 0xFFFFu);
  2513. if (!fetch_session)
  2514. fetch_session = 1;
  2515. for (i = 0; i < FETCH_WORKERS; i++) {
  2516. struct fetch_worker *w = &fetch_workers[i];
  2517. w->pid = -1;
  2518. w->slot = i;
  2519. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2520. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2521. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2522. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2523. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2524. }
  2525. }
  2526. static void fetch_worker_stop(struct fetch_worker *w)
  2527. {
  2528. int i;
  2529. /* An abandoned image job leaves its node loadable again. */
  2530. if (w->busy && w->image_job && w->node < doc.nnode) {
  2531. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2532. doc.nodes[w->node].bg_img_index = -1;
  2533. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2534. doc.nodes[w->node].img_index = -1;
  2535. }
  2536. if (w->pid > 0) {
  2537. u_kill((unsigned int)w->pid);
  2538. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2539. u_sleep_ms(5);
  2540. /* Let the reaper close the socket before we reuse the slot. */
  2541. u_sleep_ms(10);
  2542. }
  2543. w->pid = -1;
  2544. w->busy = 0;
  2545. w->ready = 0;
  2546. w->image_job = 0;
  2547. if (w->req[0]) {
  2548. u_syscall1(SYS_UNLINK, (int)w->done);
  2549. u_syscall1(SYS_UNLINK, (int)w->meta);
  2550. u_syscall1(SYS_UNLINK, (int)w->body);
  2551. u_syscall1(SYS_UNLINK, (int)w->post);
  2552. u_syscall1(SYS_UNLINK, (int)w->req);
  2553. }
  2554. }
  2555. static void fetch_workers_stop_all(void)
  2556. {
  2557. int i;
  2558. for (i = 0; i < FETCH_WORKERS; i++)
  2559. fetch_worker_stop(&fetch_workers[i]);
  2560. }
  2561. /* Abandon the transfers of the current page but keep idle helpers and their
  2562. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2563. * because its response would otherwise land in a reused /share slot. */
  2564. static void fetch_workers_cancel_busy(void)
  2565. {
  2566. int i;
  2567. for (i = 0; i < FETCH_WORKERS; i++)
  2568. if (fetch_workers[i].busy)
  2569. fetch_worker_stop(&fetch_workers[i]);
  2570. }
  2571. static void fetch_workers_prepare_nav(const char *url)
  2572. {
  2573. int i;
  2574. (void)url;
  2575. for (i = 0; i < FETCH_WORKERS; i++) {
  2576. struct fetch_worker *w = &fetch_workers[i];
  2577. if (w->pid <= 0)
  2578. continue;
  2579. /* Only an in-flight transfer must be aborted. Idle helpers
  2580. * stay warm across origins: there are just FETCH_WORKERS of
  2581. * them, and uhttp_open drops the old connection when the
  2582. * next job is for another host. Killing and respawning all
  2583. * four on every navigation churned processes and sockets
  2584. * while images were still loading. */
  2585. if (w->busy)
  2586. fetch_worker_stop(w);
  2587. }
  2588. }
  2589. /* The browser is no longer the active window and no fetch is running: give
  2590. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2591. static void fetch_workers_stop_if_unfocused(void)
  2592. {
  2593. int i;
  2594. fetch_tty_drain();
  2595. if (ui.focused || page_loading || preload_active)
  2596. return;
  2597. for (i = 0; i < FETCH_WORKERS; i++)
  2598. if (fetch_workers[i].pid > 0) {
  2599. fetch_workers_stop_all();
  2600. return;
  2601. }
  2602. }
  2603. /* The helpers (and this process, since u_tty_create() rebinds our own
  2604. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2605. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2606. * a dozen TLS connections every helper hung in its next log line, so the
  2607. * following cross-origin navigation sat at "Loading..." until it timed out.
  2608. * Drain and discard it from every wait/poll loop. */
  2609. static void fetch_tty_drain(void)
  2610. {
  2611. char sink[512];
  2612. int i;
  2613. if (fetch_tty <= 0)
  2614. return;
  2615. for (i = 0; i < 16; i++)
  2616. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2617. break;
  2618. }
  2619. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2620. unsigned int errcap)
  2621. {
  2622. char arg[40];
  2623. unsigned int n = 0;
  2624. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2625. return 0;
  2626. w->pid = -1;
  2627. fetch_pool_init();
  2628. if (fetch_tty == -2) {
  2629. int t = u_tty_create();
  2630. fetch_tty = t > 0 ? t : 0;
  2631. }
  2632. s_append(arg, &n, "__serve ", sizeof(arg));
  2633. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2634. s_append(arg, &n, " ", sizeof(arg));
  2635. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2636. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2637. if (w->pid <= 0) {
  2638. w->pid = -1;
  2639. s_copy(err, "cannot start network helper", errcap);
  2640. return -1;
  2641. }
  2642. return 0;
  2643. }
  2644. static struct fetch_worker *fetch_worker_alloc(void)
  2645. {
  2646. int i;
  2647. fetch_pool_init();
  2648. for (i = 0; i < FETCH_WORKERS; i++)
  2649. if (!fetch_workers[i].busy)
  2650. return &fetch_workers[i];
  2651. return 0;
  2652. }
  2653. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2654. unsigned int cap, const char *method,
  2655. const char *ctype, const char *post,
  2656. unsigned int post_len, unsigned int node,
  2657. int bg, char *err, unsigned int errcap);
  2658. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2659. unsigned int cap, const char *post,
  2660. unsigned int post_len, unsigned int node,
  2661. int bg, char *err, unsigned int errcap)
  2662. {
  2663. /* A body pointer with no bytes is still a POST: the classic request
  2664. * line would turn it into a GET. */
  2665. if (post && !post_len)
  2666. return fetch_worker_submit_req(w, url, cap, "POST",
  2667. "application/x-www-form-urlencoded", post, 0, node,
  2668. bg, err, errcap);
  2669. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2670. node, bg, err, errcap);
  2671. }
  2672. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2673. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2674. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2675. unsigned int cap, const char *method,
  2676. const char *ctype, const char *post,
  2677. unsigned int post_len, unsigned int node,
  2678. int bg, char *err, unsigned int errcap)
  2679. {
  2680. static char req[1024];
  2681. unsigned int n = 0;
  2682. fetch_seq++;
  2683. if (!fetch_seq)
  2684. fetch_seq = 1;
  2685. w->seq = fetch_seq;
  2686. w->ready = 0;
  2687. w->image_job = 0;
  2688. w->retried = 0;
  2689. w->m.error = 0;
  2690. w->node = node;
  2691. w->bg = bg;
  2692. s_copy(w->url, url, sizeof(w->url));
  2693. s_append_dec(req, &n, w->seq, sizeof(req));
  2694. s_append(req, &n, " ", sizeof(req));
  2695. s_append_dec(req, &n, cap, sizeof(req));
  2696. s_append(req, &n, " ", sizeof(req));
  2697. if (method) {
  2698. unsigned int k;
  2699. s_append(req, &n, "X ", sizeof(req));
  2700. s_append(req, &n, method, sizeof(req));
  2701. s_append(req, &n, " ", sizeof(req));
  2702. s_append_dec(req, &n, post_len, sizeof(req));
  2703. s_append(req, &n, " ", sizeof(req));
  2704. if (!ctype || !ctype[0])
  2705. s_append(req, &n, "-", sizeof(req));
  2706. /* One token on the request line: drop the spaces
  2707. * ("application/json; charset=utf-8" stays valid). */
  2708. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2709. if (ctype[k] != ' ')
  2710. req[n++] = ctype[k];
  2711. req[n] = '\0';
  2712. s_append(req, &n, " ", sizeof(req));
  2713. } else if (post_len) {
  2714. s_append(req, &n, "POST ", sizeof(req));
  2715. s_append_dec(req, &n, post_len, sizeof(req));
  2716. s_append(req, &n, " ", sizeof(req));
  2717. }
  2718. s_append(req, &n, url, sizeof(req));
  2719. s_append(req, &n, "\n", sizeof(req));
  2720. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2721. (int)post, (int)post_len) < 0) {
  2722. s_copy(err, "cannot queue form body", errcap);
  2723. return -1;
  2724. }
  2725. u_syscall1(SYS_UNLINK, (int)w->done);
  2726. u_syscall1(SYS_UNLINK, (int)w->meta);
  2727. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2728. s_copy(err, "cannot queue network request", errcap);
  2729. return -1;
  2730. }
  2731. if (fetch_worker_start(w, err, errcap) != 0)
  2732. return -1;
  2733. w->busy = 1;
  2734. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2735. return 0;
  2736. }
  2737. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2738. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2739. unsigned int errcap)
  2740. {
  2741. static char meta[1024];
  2742. char *p;
  2743. int rn, mseq;
  2744. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2745. (int)(sizeof(meta) - 1));
  2746. if (rn <= 0) {
  2747. s_copy(err, "network helper failed", errcap);
  2748. return -1;
  2749. }
  2750. meta[rn] = '\0';
  2751. p = meta;
  2752. mseq = (int)meta_uint(&p);
  2753. if (mseq != (int)w->seq) {
  2754. s_copy(err, "stale network response", errcap);
  2755. return -1;
  2756. }
  2757. w->m.status = (int)meta_uint(&p);
  2758. w->m.error = (int)meta_uint(&p);
  2759. w->m.trunc = (int)meta_uint(&p);
  2760. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2761. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2762. meta_str(&p, w->m.final, sizeof(w->m.final));
  2763. w->m.len = meta_uint(&p);
  2764. w->m.open_ms = 0;
  2765. w->m.first_ms = 0;
  2766. w->m.total_ms = 0;
  2767. if (*p) {
  2768. w->m.open_ms = meta_uint(&p);
  2769. w->m.first_ms = meta_uint(&p);
  2770. w->m.total_ms = meta_uint(&p);
  2771. }
  2772. if (w->m.error) {
  2773. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2774. return -1;
  2775. }
  2776. w->ready = 1;
  2777. return 0;
  2778. }
  2779. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2780. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2781. unsigned int errcap)
  2782. {
  2783. static char done[24];
  2784. char *p;
  2785. int rn, mseq;
  2786. fetch_tty_drain();
  2787. if (!w->busy)
  2788. return -1;
  2789. if (w->ready)
  2790. return 1;
  2791. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2792. (int)(sizeof(done) - 1));
  2793. if (rn > 0) {
  2794. done[rn] = '\0';
  2795. p = done;
  2796. mseq = (int)meta_uint(&p);
  2797. if (mseq == (int)w->seq) {
  2798. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2799. fetch_worker_stop(w);
  2800. return -1;
  2801. }
  2802. return 1;
  2803. }
  2804. }
  2805. if (!u_alive((unsigned int)w->pid)) {
  2806. w->pid = -1;
  2807. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2808. w->retried = 1;
  2809. return 0;
  2810. }
  2811. s_copy(err, "network helper stopped", errcap);
  2812. fetch_worker_stop(w);
  2813. return -1;
  2814. }
  2815. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2816. s_copy(err, "network request timed out", errcap);
  2817. fetch_worker_stop(w);
  2818. return -1;
  2819. }
  2820. return 0;
  2821. }
  2822. /* Copy the completed body, inflating it if the server ignored our identity
  2823. * request. Mirrors the old fetch_remote body path. */
  2824. static int fetch_worker_read_body(struct fetch_worker *w,
  2825. unsigned char *plain,
  2826. unsigned int plaincap,
  2827. unsigned char *comp,
  2828. unsigned int compcap,
  2829. int *truncated, char *err,
  2830. unsigned int errcap)
  2831. {
  2832. int rv, zr, was_trunc;
  2833. if (contains_ci(w->m.encoding, "gzip") ||
  2834. contains_ci(w->m.encoding, "deflate")) {
  2835. unsigned int comp_len = 0, plen = 0;
  2836. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2837. (int)compcap);
  2838. if (rv < 0) {
  2839. s_copy(err, "empty response", errcap);
  2840. return -1;
  2841. }
  2842. comp_len = (unsigned int)rv;
  2843. if (comp_len < w->m.len) {
  2844. s_copy(err, "compressed response is too large", errcap);
  2845. return -1;
  2846. }
  2847. if (contains_ci(w->m.encoding, "deflate"))
  2848. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2849. &plen, 0, &was_trunc);
  2850. else
  2851. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2852. &plen, 1, &was_trunc);
  2853. if (zr != 0) {
  2854. s_copy(err, "compressed response is corrupt", errcap);
  2855. return -1;
  2856. }
  2857. *truncated = w->m.trunc || was_trunc;
  2858. return (int)plen;
  2859. }
  2860. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2861. if (rv < 0) {
  2862. s_copy(err, "empty response", errcap);
  2863. return -1;
  2864. }
  2865. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2866. return rv;
  2867. }
  2868. static void fetch_worker_release(struct fetch_worker *w)
  2869. {
  2870. u_syscall1(SYS_UNLINK, (int)w->done);
  2871. u_syscall1(SYS_UNLINK, (int)w->meta);
  2872. u_syscall1(SYS_UNLINK, (int)w->body);
  2873. u_syscall1(SYS_UNLINK, (int)w->post);
  2874. u_syscall1(SYS_UNLINK, (int)w->req);
  2875. w->busy = 0;
  2876. w->ready = 0;
  2877. w->image_job = 0;
  2878. }
  2879. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2880. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2881. unsigned int errcap)
  2882. {
  2883. for (;;) {
  2884. int rv;
  2885. if (!fetch_wait_passive)
  2886. worker_wait_ui();
  2887. if (cancel_fetch || pending_action) {
  2888. fetch_workers_cancel_busy();
  2889. return FETCH_ABORT;
  2890. }
  2891. rv = fetch_worker_poll(w, err, errcap);
  2892. if (rv != 0)
  2893. return rv == 1 ? 0 : -1;
  2894. u_sleep_ms(10);
  2895. }
  2896. }
  2897. static int fetch_remote(const char *url, unsigned int cap,
  2898. const char *post, unsigned int post_len,
  2899. unsigned char *plain, unsigned int plaincap,
  2900. unsigned char *comp, unsigned int compcap,
  2901. struct fetch_meta *m, int *truncated,
  2902. char *err, unsigned int errcap)
  2903. {
  2904. struct fetch_worker *w = fetch_worker_alloc();
  2905. int rv;
  2906. fetch_last_error = 0;
  2907. if (!w) {
  2908. s_copy(err, "network busy", errcap);
  2909. return -1;
  2910. }
  2911. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2912. err, errcap) != 0) {
  2913. fetch_worker_release(w);
  2914. return -1;
  2915. }
  2916. rv = fetch_worker_wait(w, err, errcap);
  2917. if (rv == FETCH_ABORT) {
  2918. fetch_worker_release(w);
  2919. return FETCH_ABORT;
  2920. }
  2921. if (rv != 0) {
  2922. fetch_last_error = w->m.error;
  2923. fetch_worker_release(w);
  2924. return -1;
  2925. }
  2926. *m = w->m;
  2927. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2928. truncated, err, errcap);
  2929. fetch_worker_release(w);
  2930. if (rv >= 0 && (cancel_fetch || pending_action))
  2931. return FETCH_ABORT;
  2932. return rv;
  2933. }
  2934. static int fetch_worker_status(const struct fetch_worker *w)
  2935. {
  2936. return w->m.status;
  2937. }
  2938. /* fetch()/XHR through a helper: one request, the status and body come back
  2939. * whatever the HTTP status (a 401 is an answer, not a network error). */
  2940. static int js_worker_http(const char *method, const char *url,
  2941. const char *ctype, const char *body,
  2942. unsigned int body_len, struct js_http_resp *r,
  2943. char *err, int errcap)
  2944. {
  2945. struct fetch_worker *w = fetch_worker_alloc();
  2946. unsigned char *plain;
  2947. int rv, tr = 0;
  2948. if (!w) {
  2949. s_copy(err, "network busy", (unsigned int)errcap);
  2950. return -1;
  2951. }
  2952. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  2953. body_len, 0, 0, err,
  2954. (unsigned int)errcap) != 0) {
  2955. fetch_worker_release(w);
  2956. return -1;
  2957. }
  2958. fetch_wait_passive++;
  2959. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  2960. fetch_wait_passive--;
  2961. if (rv != 0) {
  2962. if (rv == FETCH_ABORT)
  2963. s_copy(err, "page is navigating", (unsigned int)errcap);
  2964. fetch_worker_release(w);
  2965. return -1;
  2966. }
  2967. r->status = w->m.status;
  2968. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  2969. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  2970. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  2971. if (!plain) {
  2972. fetch_worker_release(w);
  2973. s_copy(err, "out of memory", (unsigned int)errcap);
  2974. return -1;
  2975. }
  2976. if (w->m.len == 0) {
  2977. rv = 0; /* 204, an empty 200: no body file */
  2978. } else {
  2979. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  2980. image_io_buf, BR_PAGE_COMP_MAX,
  2981. &tr, err, (unsigned int)errcap);
  2982. }
  2983. fetch_worker_release(w);
  2984. if (rv < 0) {
  2985. free(plain);
  2986. return -1;
  2987. }
  2988. plain[rv] = '\0';
  2989. r->body = (char *)plain;
  2990. r->len = (unsigned int)rv;
  2991. return 0;
  2992. }
  2993. /* ---- HTTP / file fetch ---- */
  2994. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2995. unsigned int *outlen, int *is_local, char *ctype,
  2996. unsigned int ctcap, char *final, unsigned int finalcap,
  2997. char *err, unsigned int errcap, int *truncated,
  2998. const char *post, unsigned int post_len)
  2999. {
  3000. unsigned char *buf;
  3001. unsigned int len;
  3002. int tr = 0;
  3003. int rv;
  3004. *out = 0;
  3005. *outlen = 0;
  3006. *truncated = 0;
  3007. if (final && finalcap)
  3008. final[0] = '\0';
  3009. if (ctype && ctcap)
  3010. ctype[0] = '\0';
  3011. if (url[0] == '/') {
  3012. char pathbuf[BR_URL_MAX];
  3013. const char *open_url = url;
  3014. unsigned int i = 0;
  3015. /* A local form GET keeps ?query in the address bar but the
  3016. * file lookup uses the path alone, like a real browser. */
  3017. while (url[i] && url[i] != '?' && url[i] != '#')
  3018. i++;
  3019. if (url[i]) {
  3020. s_copy(pathbuf, url, i + 1);
  3021. open_url = pathbuf;
  3022. }
  3023. buf = (unsigned char *)malloc(cap);
  3024. if (!buf) {
  3025. s_copy(err, "out of memory", errcap);
  3026. return -1;
  3027. }
  3028. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3029. if (rv < 0) {
  3030. free(buf);
  3031. s_copy(err, "file not found", errcap);
  3032. return -1;
  3033. }
  3034. *out = buf;
  3035. *outlen = (unsigned int)rv;
  3036. *is_local = 1;
  3037. if (ctype)
  3038. s_copy(ctype, "text/html", ctcap);
  3039. if (final)
  3040. s_copy(final, url, finalcap);
  3041. if ((unsigned int)rv == cap)
  3042. *truncated = 1;
  3043. return 0;
  3044. }
  3045. buf = (unsigned char *)malloc(cap);
  3046. if (!buf) {
  3047. s_copy(err, "out of memory", errcap);
  3048. return -1;
  3049. }
  3050. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3051. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3052. if (rv == FETCH_ABORT) {
  3053. free(buf);
  3054. return FETCH_ABORT;
  3055. }
  3056. if (rv < 0) {
  3057. free(buf);
  3058. return -1;
  3059. }
  3060. len = (unsigned int)rv;
  3061. if (len == 0) {
  3062. free(buf);
  3063. s_copy(err, "empty response", errcap);
  3064. return -1;
  3065. }
  3066. if (ctype)
  3067. s_copy(ctype, fetch_meta.ctype, ctcap);
  3068. if (final && fetch_meta.final[0])
  3069. s_copy(final, fetch_meta.final, finalcap);
  3070. *is_local = 0;
  3071. *out = buf;
  3072. *outlen = len;
  3073. *truncated = tr;
  3074. return 0;
  3075. }
  3076. /* Load every @font-face the parser registered. Local files go through
  3077. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3078. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3079. * to the built-in regular/bold/italic/mono set. */
  3080. static void load_font_faces(void)
  3081. {
  3082. unsigned int i;
  3083. memset(font_faces, 0, sizeof(font_faces));
  3084. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3085. i <= BR_MAX_FACES; i++) {
  3086. const char *url = br_font_face_url((int)i);
  3087. const char *base = br_font_face_base((int)i);
  3088. char abs[BR_URL_MAX];
  3089. if (!url || !url[0])
  3090. continue;
  3091. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3092. sizeof(abs)) != 0)
  3093. continue;
  3094. if (abs[0] == '/') {
  3095. font_faces[i - 1] = ufont_face_open_path(abs);
  3096. } else if (is_http(abs)) {
  3097. unsigned char *buf;
  3098. char err[64];
  3099. int rv, tr = 0;
  3100. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3101. if (!buf)
  3102. continue;
  3103. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3104. UFONT_MAX_FILE, image_io_buf,
  3105. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3106. err, sizeof(err));
  3107. if (rv > 0)
  3108. font_faces[i - 1] = ufont_face_open_mem(buf,
  3109. rv);
  3110. free(buf);
  3111. }
  3112. }
  3113. }
  3114. /* Remote scripts are cached under /share for the current boot, like the
  3115. * stylesheet cache, so reloads and later visits skip the network. */
  3116. static int script_cache_count;
  3117. static unsigned int script_cache_hash(const char *s)
  3118. {
  3119. unsigned int h = 2166136261u;
  3120. while (*s) {
  3121. h ^= (unsigned char)*s++;
  3122. h *= 16777619u;
  3123. }
  3124. return h;
  3125. }
  3126. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3127. {
  3128. unsigned int n = 0;
  3129. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3130. s_append_dec(out, &n, script_cache_hash(url), cap);
  3131. }
  3132. static void script_cache_clear(void)
  3133. {
  3134. struct sys_dirent d;
  3135. char path[96];
  3136. for (;;) {
  3137. int i, found = 0;
  3138. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3139. (int)&d) == 1; i++) {
  3140. unsigned int n = 0;
  3141. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3142. continue;
  3143. s_append(path, &n, "/share/", sizeof(path));
  3144. s_append(path, &n, d.name, sizeof(path));
  3145. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3146. return;
  3147. found = 1;
  3148. break;
  3149. }
  3150. if (!found)
  3151. break;
  3152. }
  3153. script_cache_count = 0;
  3154. }
  3155. static void script_cache_init(void)
  3156. {
  3157. struct sys_dirent d;
  3158. int i, count = 0;
  3159. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3160. (int)&d) == 1; i++)
  3161. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3162. count++;
  3163. if (count >= SCRIPT_CACHE_MAX) {
  3164. script_cache_clear();
  3165. return;
  3166. }
  3167. script_cache_count = count;
  3168. }
  3169. static int script_cache_get(const char *url, unsigned char **out,
  3170. unsigned int *outlen)
  3171. {
  3172. char path[96];
  3173. struct sys_stat st;
  3174. unsigned char *buf;
  3175. int rn;
  3176. script_cache_path(url, path, sizeof(path));
  3177. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3178. st.size >= SCRIPT_CACHE_FILE_MAX)
  3179. return 0;
  3180. buf = (unsigned char *)malloc(st.size + 1);
  3181. if (!buf)
  3182. return 0;
  3183. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3184. if (rn != (int)st.size) {
  3185. free(buf);
  3186. return 0;
  3187. }
  3188. buf[st.size] = '\0';
  3189. *out = buf;
  3190. *outlen = st.size;
  3191. return 1;
  3192. }
  3193. static void script_cache_put(const char *url, const unsigned char *data,
  3194. unsigned int len)
  3195. {
  3196. char path[96];
  3197. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3198. len >= SCRIPT_CACHE_FILE_MAX)
  3199. return;
  3200. script_cache_path(url, path, sizeof(path));
  3201. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3202. (int)len) >= 0)
  3203. script_cache_count++;
  3204. }
  3205. static int script_cache_has(const char *url)
  3206. {
  3207. char path[96];
  3208. struct sys_stat st;
  3209. script_cache_path(url, path, sizeof(path));
  3210. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3211. st.size < SCRIPT_CACHE_FILE_MAX;
  3212. }
  3213. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3214. static int fetch_script_text(const char *url, unsigned char **out,
  3215. unsigned int *outlen, char *err,
  3216. unsigned int errcap)
  3217. {
  3218. unsigned char *buf;
  3219. unsigned int len;
  3220. int local, truncated = 0;
  3221. char ctype[64], final[BR_URL_MAX];
  3222. int rv;
  3223. *out = 0;
  3224. *outlen = 0;
  3225. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3226. return 0;
  3227. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3228. sizeof(ctype), final, sizeof(final), err, errcap,
  3229. &truncated, 0, 0);
  3230. if (rv != 0)
  3231. return rv;
  3232. if (truncated || len >= BR_SCRIPT_MAX) {
  3233. free(buf);
  3234. s_copy(err, "script is too large", errcap);
  3235. return -1;
  3236. }
  3237. buf[len] = '\0';
  3238. if (!local)
  3239. script_cache_put(url, buf, len);
  3240. *out = buf;
  3241. *outlen = len;
  3242. return 0;
  3243. }
  3244. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3245. * the heap, so images must not allocate their file body from it as well. */
  3246. static int fetch_image(const char *url, unsigned int cap,
  3247. unsigned char **out, unsigned int *outlen,
  3248. char *err, unsigned int errcap)
  3249. {
  3250. unsigned int len;
  3251. int tr = 0;
  3252. int rv;
  3253. *out = 0;
  3254. *outlen = 0;
  3255. if (cap > BR_IMG_FILE_MAX)
  3256. cap = BR_IMG_FILE_MAX;
  3257. if (url[0] == '/') {
  3258. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3259. (int)cap);
  3260. if (rv < 0) {
  3261. s_copy(err, "file not found", errcap);
  3262. return -1;
  3263. }
  3264. *out = image_file_buf;
  3265. *outlen = (unsigned int)rv;
  3266. return 0;
  3267. }
  3268. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3269. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3270. if (rv == FETCH_ABORT)
  3271. return FETCH_ABORT;
  3272. if (rv < 0)
  3273. return -1;
  3274. len = (unsigned int)rv;
  3275. if (len == 0) {
  3276. s_copy(err, "empty image", errcap);
  3277. return -1;
  3278. }
  3279. *out = image_file_buf;
  3280. *outlen = len;
  3281. return 0;
  3282. }
  3283. /* Remote stylesheets are immutable enough for the current boot: keep
  3284. * successful responses under /share so a reload, a second visit or a fresh
  3285. * browser launch does not fetch the same five sheets over the network again.
  3286. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3287. static int css_cache_count;
  3288. static unsigned int css_cache_hash(const char *s)
  3289. {
  3290. unsigned int h = 2166136261u;
  3291. while (*s) {
  3292. h ^= (unsigned char)*s++;
  3293. h *= 16777619u;
  3294. }
  3295. return h;
  3296. }
  3297. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3298. {
  3299. unsigned int n = 0;
  3300. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3301. s_append_dec(out, &n, css_cache_hash(url), cap);
  3302. }
  3303. static void css_cache_clear(void)
  3304. {
  3305. struct sys_dirent d;
  3306. char path[96];
  3307. for (;;) {
  3308. int i, found = 0;
  3309. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3310. (int)&d) == 1; i++) {
  3311. unsigned int n = 0;
  3312. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3313. continue;
  3314. s_append(path, &n, "/share/", sizeof(path));
  3315. s_append(path, &n, d.name, sizeof(path));
  3316. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3317. return;
  3318. found = 1;
  3319. break;
  3320. }
  3321. if (!found)
  3322. break;
  3323. }
  3324. css_cache_count = 0;
  3325. }
  3326. static void css_cache_init(void)
  3327. {
  3328. struct sys_dirent d;
  3329. int i, count = 0;
  3330. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3331. (int)&d) == 1; i++)
  3332. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3333. count++;
  3334. if (count >= CSS_CACHE_MAX) {
  3335. css_cache_clear();
  3336. return;
  3337. }
  3338. css_cache_count = count;
  3339. }
  3340. static int css_cache_get(const char *url, unsigned char **out,
  3341. unsigned int *outlen)
  3342. {
  3343. char path[96];
  3344. int rn;
  3345. css_cache_path(url, path, sizeof(path));
  3346. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3347. (int)CSS_CACHE_FILE_MAX);
  3348. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3349. return 0;
  3350. *out = image_io_buf;
  3351. *outlen = (unsigned int)rn;
  3352. return 1;
  3353. }
  3354. static void css_cache_put(const char *url, const unsigned char *data,
  3355. unsigned int len)
  3356. {
  3357. char path[96];
  3358. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3359. len >= CSS_CACHE_FILE_MAX)
  3360. return;
  3361. css_cache_path(url, path, sizeof(path));
  3362. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3363. (int)len) >= 0)
  3364. css_cache_count++;
  3365. }
  3366. static int css_cache_has(const char *url)
  3367. {
  3368. char path[96];
  3369. struct sys_stat st;
  3370. css_cache_path(url, path, sizeof(path));
  3371. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3372. st.size < CSS_CACHE_FILE_MAX;
  3373. }
  3374. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3375. * immediately, so it does not need the page heap; this leaves the heap for
  3376. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3377. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3378. char *err, unsigned int errcap)
  3379. {
  3380. unsigned int len;
  3381. int tr = 0;
  3382. int rv;
  3383. *out = 0;
  3384. *outlen = 0;
  3385. if (url[0] == '/') {
  3386. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3387. (int)BR_CSS_MAX);
  3388. if (rv < 0) {
  3389. s_copy(err, "stylesheet not found", errcap);
  3390. return -1;
  3391. }
  3392. *out = image_io_buf;
  3393. *outlen = (unsigned int)rv;
  3394. return 0;
  3395. }
  3396. if (css_cache_get(url, out, outlen))
  3397. return 0;
  3398. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3399. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3400. &fetch_meta, &tr, err, errcap);
  3401. if (rv == FETCH_ABORT)
  3402. return FETCH_ABORT;
  3403. if (rv < 0)
  3404. return -1;
  3405. len = (unsigned int)rv;
  3406. if (len == 0) {
  3407. s_copy(err, "empty stylesheet", errcap);
  3408. return -1;
  3409. }
  3410. *out = image_io_buf;
  3411. *outlen = len;
  3412. css_cache_put(url, image_io_buf, len);
  3413. return 0;
  3414. }
  3415. static void redraw_now(void);
  3416. static char error_page[1024];
  3417. static void show_error(const char *title, const char *detail)
  3418. {
  3419. char *page = error_page;
  3420. unsigned int n = 0;
  3421. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3422. s_append(page, &n, title, sizeof(error_page));
  3423. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3424. {
  3425. const char *p = detail;
  3426. while (*p && n + 1 < sizeof(error_page)) {
  3427. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3428. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3429. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3430. else page[n++] = *p;
  3431. p++;
  3432. }
  3433. }
  3434. page[n] = '\0';
  3435. s_append(page, &n, "</p><p>", sizeof(error_page));
  3436. s_append(page, &n, page_url, sizeof(error_page));
  3437. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3438. sizeof(error_page));
  3439. br_parse(&doc, page, n);
  3440. layout_valid = 0;
  3441. preload_active = 0;
  3442. preload_pending = 0;
  3443. preload_wait = 0;
  3444. fetch_workers_cancel_busy();
  3445. s_copy(page_title, title, sizeof(page_title));
  3446. page_loading = 0;
  3447. set_status(title, 1, 0);
  3448. ngui_invalidate(&ui);
  3449. }
  3450. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3451. unsigned int node)
  3452. {
  3453. if (image_count >= BR_MAX_IMAGES)
  3454. return -1;
  3455. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  3456. return -1;
  3457. doc.nodes[node].img_index = 0;
  3458. image_count = 1;
  3459. return 0;
  3460. }
  3461. static int ancestor_is(unsigned int node, unsigned int tag)
  3462. {
  3463. unsigned int p = doc.nodes[node].parent;
  3464. while (p) {
  3465. if (doc.nodes[p].tag == tag)
  3466. return 1;
  3467. p = doc.nodes[p].parent;
  3468. }
  3469. return 0;
  3470. }
  3471. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3472. * parallel but parsed in document order, so the cascade is unchanged. */
  3473. static int load_stylesheets(void)
  3474. {
  3475. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3476. static unsigned char remote[BR_MAX_SHEETS];
  3477. struct fetch_worker *slot[BR_MAX_SHEETS];
  3478. unsigned int i, n = 0, next = 0, k;
  3479. char err[64];
  3480. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3481. struct br_node *nd = &doc.nodes[i];
  3482. const char *rel, *href;
  3483. char url[BR_URL_MAX];
  3484. int dup = 0;
  3485. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3486. continue;
  3487. rel = br_rel(&doc, i);
  3488. if (!contains_ci(rel, "stylesheet"))
  3489. continue;
  3490. href = br_href(&doc, i);
  3491. if (!href[0])
  3492. continue;
  3493. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3494. continue;
  3495. for (k = 0; k < n; k++)
  3496. if (s_eq(urls[k], url)) {
  3497. dup = 1;
  3498. break;
  3499. }
  3500. if (dup)
  3501. continue;
  3502. s_copy(urls[n], url, BR_URL_MAX);
  3503. remote[n] = url[0] != '/' && !css_cache_has(url);
  3504. n++;
  3505. }
  3506. for (i = 0; i < BR_MAX_SHEETS; i++)
  3507. slot[i] = 0;
  3508. /* Start as many remote sheets as there are free workers. */
  3509. for (; next < n; next++) {
  3510. struct fetch_worker *w;
  3511. if (!remote[next])
  3512. continue;
  3513. w = fetch_worker_alloc();
  3514. if (!w)
  3515. break;
  3516. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3517. err, sizeof(err)) != 0) {
  3518. fetch_worker_release(w);
  3519. remote[next] = 0;
  3520. continue;
  3521. }
  3522. slot[next] = w;
  3523. }
  3524. for (i = 0; i < n; i++) {
  3525. unsigned char *data = 0;
  3526. unsigned int len = 0;
  3527. int rv;
  3528. if (!remote[i]) {
  3529. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3530. if (rv == FETCH_ABORT) {
  3531. fetch_workers_stop_all();
  3532. return FETCH_ABORT;
  3533. }
  3534. if (rv != 0 || !len)
  3535. continue;
  3536. } else {
  3537. struct fetch_worker *w = slot[i];
  3538. int tr = 0;
  3539. if (!w) {
  3540. w = fetch_worker_alloc();
  3541. if (!w) {
  3542. rv = -1;
  3543. goto css_failed;
  3544. }
  3545. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3546. 0, 0, 0, 0, err,
  3547. sizeof(err)) != 0) {
  3548. fetch_worker_release(w);
  3549. remote[i] = 0;
  3550. if (i == next)
  3551. next++;
  3552. continue;
  3553. }
  3554. slot[i] = w;
  3555. if (i == next)
  3556. next++;
  3557. }
  3558. rv = fetch_worker_wait(w, err, sizeof(err));
  3559. if (rv == FETCH_ABORT) {
  3560. fetch_workers_stop_all();
  3561. return FETCH_ABORT;
  3562. }
  3563. if (rv == 0)
  3564. rv = fetch_worker_read_body(w, image_io_buf,
  3565. BR_CSS_MAX,
  3566. image_io_buf + BR_CSS_MAX,
  3567. BR_CSS_COMP_MAX, &tr,
  3568. err, sizeof(err));
  3569. else
  3570. rv = -1;
  3571. fetch_worker_release(w);
  3572. slot[i] = 0;
  3573. /* Refill the worker window before parsing this sheet. */
  3574. for (; next < n; next++) {
  3575. struct fetch_worker *nw;
  3576. if (!remote[next])
  3577. continue;
  3578. nw = fetch_worker_alloc();
  3579. if (!nw)
  3580. break;
  3581. if (fetch_worker_submit(nw, urls[next],
  3582. BR_CSS_MAX, 0, 0, 0, 0,
  3583. err, sizeof(err)) != 0) {
  3584. fetch_worker_release(nw);
  3585. remote[next] = 0;
  3586. continue;
  3587. }
  3588. slot[next] = nw;
  3589. }
  3590. css_failed:
  3591. if (rv <= 0) {
  3592. /* One synchronous retry: a dropped sheet leaves the
  3593. * whole page unstyled (seen intermittently on
  3594. * arstechnica's CDN). */
  3595. u_puts("[css] retry ");
  3596. u_puts(urls[i]);
  3597. u_puts(": ");
  3598. u_puts(err[0] ? err : "no worker/empty body");
  3599. u_putc('\n');
  3600. err[0] = '\0';
  3601. rv = fetch_css(urls[i], &data, &len, err,
  3602. sizeof(err));
  3603. if (rv == FETCH_ABORT) {
  3604. fetch_workers_stop_all();
  3605. return FETCH_ABORT;
  3606. }
  3607. if (rv != 0 || !len) {
  3608. u_puts("[css] failed: ");
  3609. u_puts(err);
  3610. u_putc('\n');
  3611. continue;
  3612. }
  3613. } else {
  3614. len = (unsigned int)rv;
  3615. data = image_io_buf;
  3616. css_cache_put(urls[i], data, len);
  3617. }
  3618. }
  3619. if (len) {
  3620. br_set_font_base(urls[i]);
  3621. br_parse_css_text(&doc, (const char *)data, len);
  3622. }
  3623. }
  3624. br_set_font_base(page_url);
  3625. br_parse_inline_css(&doc);
  3626. load_font_faces();
  3627. br_reset_styles(&doc);
  3628. layout_valid = 0;
  3629. return 0;
  3630. }
  3631. static void preload_begin(void)
  3632. {
  3633. preload_active = 1;
  3634. preload_pending = 0;
  3635. preload_wait = 1;
  3636. preload_max_jobs = FETCH_WORKERS;
  3637. preload_node = 0;
  3638. preload_loaded = 0;
  3639. preload_scroll = 0;
  3640. }
  3641. /* Styles are computed top-down during layout, but images inside a hidden
  3642. * menu/carousel are never visited and keep img_top == 0. Without this check
  3643. * the preloader walks the DOM in node order and spends the whole image
  3644. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3645. static int node_hidden(unsigned int node)
  3646. {
  3647. unsigned int path[32], n = 0, p = node, i;
  3648. struct br_style st, parent;
  3649. while (p && n < sizeof(path) / sizeof(path[0])) {
  3650. path[n++] = p;
  3651. p = doc.nodes[p].parent;
  3652. }
  3653. parent = (struct br_style){0};
  3654. parent.font_px = 16;
  3655. parent.display = BR_DISPLAY_BLOCK;
  3656. for (i = n; i > 0; i--) {
  3657. br_style_for(&doc, path[i - 1], &parent, &st);
  3658. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3659. st.opacity_hidden)
  3660. return 1;
  3661. parent = st;
  3662. }
  3663. return 0;
  3664. }
  3665. static struct br_style base_style(void);
  3666. static void style_for_node(unsigned int node, struct br_style *out)
  3667. {
  3668. unsigned int p = doc.nodes[node].parent;
  3669. struct br_style parent;
  3670. if (p) {
  3671. style_for_node(p, &parent);
  3672. br_style_for(&doc, node, &parent, out);
  3673. } else {
  3674. parent = base_style();
  3675. br_style_for(&doc, node, &parent, out);
  3676. }
  3677. }
  3678. /* ---- parallel image preloading ---- *
  3679. *
  3680. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3681. * preload_step() only starts jobs and harvests completed ones; the browser
  3682. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3683. */
  3684. static int preload_active_jobs(void)
  3685. {
  3686. int i, n = 0;
  3687. for (i = 0; i < FETCH_WORKERS; i++)
  3688. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3689. n++;
  3690. return n;
  3691. }
  3692. static void preload_job_error(struct fetch_worker *w)
  3693. {
  3694. if (w->node < doc.nnode) {
  3695. if (w->bg)
  3696. doc.nodes[w->node].bg_img_index = -2;
  3697. else
  3698. doc.nodes[w->node].img_index = -2;
  3699. ngui_invalidate(&ui);
  3700. }
  3701. }
  3702. static void preload_decode(unsigned int node, int bg,
  3703. const unsigned char *data, unsigned int len,
  3704. const char *url)
  3705. {
  3706. if (image_count >= BR_MAX_IMAGES) {
  3707. if (bg)
  3708. doc.nodes[node].bg_img_index = -2;
  3709. else
  3710. doc.nodes[node].img_index = -2;
  3711. return;
  3712. }
  3713. if (decode_image_data(data, len, &images[image_count],
  3714. bg && node < BR_MAX_NODES &&
  3715. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3716. bg && node < BR_MAX_NODES &&
  3717. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3718. /* An <img> bitmap only depends on its URL, so the next
  3719. * <img> with the same source reuses it (heise repeats one
  3720. * comment icon 85 times). Backgrounds are scaled to their
  3721. * box and are not shared. */
  3722. images[image_count].url_hash =
  3723. !bg && url ? script_cache_hash(url) | 1u : 0;
  3724. if (bg)
  3725. doc.nodes[node].bg_img_index = (short)image_count;
  3726. else
  3727. doc.nodes[node].img_index = (short)image_count;
  3728. image_count++;
  3729. preload_loaded++;
  3730. layout_valid = 0;
  3731. } else {
  3732. if (bg)
  3733. doc.nodes[node].bg_img_index = -2;
  3734. else
  3735. doc.nodes[node].img_index = -2;
  3736. }
  3737. ngui_invalidate(&ui);
  3738. }
  3739. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3740. static int preload_finish_worker(struct fetch_worker *w)
  3741. {
  3742. char err[64];
  3743. int rv, tr = 0;
  3744. rv = fetch_worker_poll(w, err, sizeof(err));
  3745. if (rv < 0) {
  3746. preload_job_error(w);
  3747. fetch_worker_release(w);
  3748. return 1;
  3749. }
  3750. if (rv == 0)
  3751. return 0;
  3752. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3753. image_comp_buf, BR_IMG_FILE_MAX,
  3754. &tr, err, sizeof(err));
  3755. if (rv >= 0)
  3756. preload_decode(w->node, w->bg, image_file_buf,
  3757. (unsigned int)rv, w->url);
  3758. else
  3759. preload_job_error(w);
  3760. fetch_worker_release(w);
  3761. return 1;
  3762. }
  3763. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3764. * the number of jobs started. */
  3765. static int preload_fill_jobs(void)
  3766. {
  3767. int started = 0;
  3768. char err[64];
  3769. while (preload_active && preload_node < doc.nnode) {
  3770. unsigned int i = preload_node;
  3771. struct br_node *nd = &doc.nodes[i];
  3772. const char *src;
  3773. char url[BR_URL_MAX];
  3774. struct fetch_worker *w;
  3775. if (preload_active_jobs() >= preload_max_jobs)
  3776. break;
  3777. if (nd->type != BR_NODE_ELEM) {
  3778. preload_node++;
  3779. continue;
  3780. }
  3781. if (nd->tag != BR_TAG_IMG) {
  3782. if (nd->bg_img_index == -1) {
  3783. struct br_style bs;
  3784. style_for_node(i, &bs);
  3785. if (bs.display != BR_DISPLAY_NONE &&
  3786. !bs.vis_hidden && bs.bg_image) {
  3787. const char *bsrc =
  3788. br_bg_image_url(bs.bg_image - 1);
  3789. /* Lazy like <img>: a background box
  3790. * below the viewport (or not laid
  3791. * out yet) waits for the next scan. */
  3792. if (bsrc[0] &&
  3793. (!layout_boxes[i].valid ||
  3794. block_top[i] >
  3795. (unsigned int)(page_scroll.offset +
  3796. page_rect.h + 160))) {
  3797. preload_pending = 1;
  3798. preload_node++;
  3799. continue;
  3800. }
  3801. if (bsrc[0] &&
  3802. !starts_with(bsrc, "data:") &&
  3803. resolve_link(page_url, bsrc, url,
  3804. sizeof(url)) == 0) {
  3805. if (image_count +
  3806. preload_active_jobs() >=
  3807. BR_MAX_IMAGES) {
  3808. preload_node = doc.nnode;
  3809. break;
  3810. }
  3811. if (url[0] == '/') {
  3812. unsigned char *data = 0;
  3813. unsigned int len = 0;
  3814. preload_node = i + 1;
  3815. if (fetch_image(url,
  3816. BR_IMG_FILE_MAX,
  3817. &data, &len,
  3818. err,
  3819. sizeof(err)) == 0)
  3820. preload_decode(i, 1, data, len, 0);
  3821. else
  3822. nd->bg_img_index = -2;
  3823. continue;
  3824. }
  3825. w = fetch_worker_alloc();
  3826. if (!w)
  3827. return started;
  3828. preload_node = i + 1;
  3829. if (fetch_worker_submit(w, url,
  3830. BR_IMG_FILE_MAX,
  3831. 0, 0, i, 1,
  3832. err,
  3833. sizeof(err)) != 0) {
  3834. nd->bg_img_index = -2;
  3835. fetch_worker_release(w);
  3836. continue;
  3837. }
  3838. w->image_job = 1;
  3839. w->deadline = u_ticks_ms() +
  3840. BR_IMG_JOB_TIMEOUT_MS;
  3841. /* in flight: rescans skip it */
  3842. nd->bg_img_index = -3;
  3843. started++;
  3844. continue;
  3845. }
  3846. }
  3847. nd->bg_img_index = -2;
  3848. }
  3849. preload_node++;
  3850. continue;
  3851. }
  3852. if (nd->img_index != -1) {
  3853. preload_node++;
  3854. continue;
  3855. }
  3856. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3857. preload_node++;
  3858. continue;
  3859. }
  3860. src = br_src(&doc, i);
  3861. if (!src[0] || starts_with(src, "data:")) {
  3862. preload_node++;
  3863. continue;
  3864. }
  3865. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3866. preload_node++;
  3867. continue;
  3868. }
  3869. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3870. preload_node = doc.nnode;
  3871. break;
  3872. }
  3873. /* Do not stop at the first below-fold image: DOM order is
  3874. * not visual order, and a footer/ad image early in the DOM
  3875. * used to hide every later article image from the loader. */
  3876. if (img_top[i] >
  3877. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3878. preload_pending = 1;
  3879. preload_node++;
  3880. continue;
  3881. }
  3882. {
  3883. unsigned int uh = script_cache_hash(url) | 1u;
  3884. int k;
  3885. for (k = 0; k < image_count; k++)
  3886. if (images[k].state == 1 &&
  3887. images[k].url_hash == uh)
  3888. break;
  3889. if (k < image_count) {
  3890. nd->img_index = (short)k;
  3891. layout_valid = 0;
  3892. preload_node = i + 1;
  3893. ngui_invalidate(&ui);
  3894. continue;
  3895. }
  3896. }
  3897. if (url[0] == '/') {
  3898. unsigned char *data = 0;
  3899. unsigned int len = 0;
  3900. preload_node = i + 1;
  3901. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3902. err, sizeof(err)) == 0)
  3903. preload_decode(i, 0, data, len, url);
  3904. else
  3905. nd->img_index = -2;
  3906. continue;
  3907. }
  3908. w = fetch_worker_alloc();
  3909. if (!w)
  3910. return started;
  3911. preload_node = i + 1;
  3912. {
  3913. char msg[64];
  3914. unsigned int n = 0;
  3915. s_append(msg, &n, "Loading images ", sizeof(msg));
  3916. s_append_dec(msg, &n,
  3917. (unsigned int)preload_loaded + 1,
  3918. sizeof(msg));
  3919. s_append(msg, &n, "...", sizeof(msg));
  3920. set_status(msg, 0, 0);
  3921. }
  3922. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3923. err, sizeof(err)) != 0) {
  3924. nd->img_index = -2;
  3925. fetch_worker_release(w);
  3926. continue;
  3927. }
  3928. w->image_job = 1;
  3929. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3930. nd->img_index = -3; /* in flight: rescans skip it */
  3931. started++;
  3932. }
  3933. return started;
  3934. }
  3935. static void preload_step(void)
  3936. {
  3937. int i;
  3938. if (!preload_active)
  3939. return;
  3940. if (cancel_fetch || pending_action) {
  3941. preload_active = 0;
  3942. preload_pending = 0;
  3943. fetch_workers_cancel_busy();
  3944. return;
  3945. }
  3946. preload_fill_jobs();
  3947. /* Decode at most one completed image per main-loop pass. A full-size
  3948. * JPEG decode blocks this single-threaded UI for a long time, and
  3949. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3950. * every other image download) on slow CPUs: requests looked stuck
  3951. * while four decodes ran in a row. */
  3952. for (i = 0; i < FETCH_WORKERS; i++) {
  3953. if (!fetch_workers[i].busy)
  3954. continue;
  3955. if (preload_finish_worker(&fetch_workers[i]))
  3956. return;
  3957. }
  3958. if (preload_active && preload_node >= doc.nnode &&
  3959. preload_active_jobs() == 0) {
  3960. preload_active = 0;
  3961. if (preload_pending)
  3962. preload_scroll = page_scroll.offset;
  3963. else
  3964. preload_pending = 0;
  3965. /* Keep the now idle helpers and their connections; a later
  3966. * navigation reuses them. They exit after ten idle seconds,
  3967. * and losing window focus stops them at once. */
  3968. set_status(post_status_text, post_status_error, post_status_ttl);
  3969. ngui_invalidate(&ui);
  3970. }
  3971. }
  3972. /* Set by navigate() when it turned a typed bare host into https://; the next
  3973. * load_page() consumes it and may retry over http. */
  3974. static int nav_https_upgraded;
  3975. /* Errors that mean "https is not served here" rather than "the site is
  3976. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3977. static int https_fallback_error(int e)
  3978. {
  3979. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3980. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3981. e == UHTTP_ERR_RESET;
  3982. }
  3983. static void history_push(const char *url)
  3984. {
  3985. if (!url || !url[0])
  3986. return;
  3987. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3988. s_eq(history[hist_pos], url))
  3989. return;
  3990. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3991. hist_len = hist_pos + 1;
  3992. if (hist_len < BR_HISTORY) {
  3993. s_copy(history[hist_len], url, BR_URL_MAX);
  3994. hist_pos = hist_len;
  3995. hist_len++;
  3996. } else {
  3997. int i;
  3998. for (i = 1; i < BR_HISTORY; i++)
  3999. s_copy(history[i - 1], history[i], BR_URL_MAX);
  4000. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  4001. hist_pos = BR_HISTORY - 1;
  4002. }
  4003. }
  4004. static void load_page(const char *url, int local, int push)
  4005. {
  4006. unsigned char *body = 0;
  4007. unsigned int len = 0;
  4008. int truncated = 0;
  4009. struct img_info image_info;
  4010. char ctype[64];
  4011. char final[BR_URL_MAX];
  4012. char err[80];
  4013. const char *detail = 0;
  4014. const char *post = pending_post_is ? pending_post : 0;
  4015. unsigned int post_len = pending_post_len;
  4016. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  4017. /* Phase timings for the status line: where a slow load spends it. */
  4018. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  4019. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  4020. int upgraded = nav_https_upgraded;
  4021. int retried = 0;
  4022. int rv;
  4023. nav_https_upgraded = 0;
  4024. final[0] = '\0';
  4025. pending_post_len = 0;
  4026. pending_post_is = 0;
  4027. cancel_fetch = 0;
  4028. preload_active = 0;
  4029. preload_pending = 0;
  4030. fetch_workers_prepare_nav(url);
  4031. js_browser_stop();
  4032. js_last_status[0] = '\0';
  4033. js_last_error = 0;
  4034. heap_clear();
  4035. image_reset();
  4036. form_reset_state();
  4037. layout_valid = 0;
  4038. page_scroll.offset = 0;
  4039. page_scroll.dragging = 0;
  4040. page_title[0] = '\0';
  4041. page_loading = 1;
  4042. page_is_local = local;
  4043. s_copy(page_url, url, sizeof(page_url));
  4044. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4045. url_in.len = s_len(url_in.text);
  4046. url_in.cursor = url_in.len;
  4047. url_in.scroll = 0;
  4048. ngui_set_focus(&ui, 0);
  4049. if (final[0])
  4050. final[0] = '\0';
  4051. if (push)
  4052. history_push(url);
  4053. set_status("Loading...", 0, 0);
  4054. ngui_invalidate(&ui);
  4055. /* heap_clear() detaches the fonts, so attach them again before the
  4056. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4057. if (heap_start() != 0) {
  4058. show_error("Out of memory", "Cannot allocate the page buffer");
  4059. return;
  4060. }
  4061. br_parse_plain(&doc, "", 0); /* blank while loading */
  4062. ngui_font_attach(&ui);
  4063. redraw_now();
  4064. browser_rules_alloc();
  4065. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4066. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  4067. &truncated, post, post_len);
  4068. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  4069. fetch_last_error == UHTTP_ERR_DNS) {
  4070. /* A busy previous page can leave the receiver ring full just
  4071. * long enough to lose a DNS reply. Tear the old helpers down
  4072. * and try once more before giving up. */
  4073. retried = 1;
  4074. fetch_workers_stop_all();
  4075. u_sleep_ms(500);
  4076. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4077. sizeof(ctype), final, sizeof(final), err,
  4078. sizeof(err), &truncated, post, post_len);
  4079. }
  4080. if (rv == FETCH_ABORT)
  4081. return;
  4082. t_fetch = u_ticks_ms() - t_start;
  4083. /* Capture the page timing before CSS/script/image fetches overwrite the
  4084. * shared fetch_meta block. */
  4085. if (rv == 0 && !local) {
  4086. page_open_ms = fetch_meta.open_ms;
  4087. page_first_ms = fetch_meta.first_ms;
  4088. page_total_ms = fetch_meta.total_ms;
  4089. }
  4090. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  4091. https_fallback_error(fetch_last_error)) {
  4092. char http_url[BR_URL_MAX];
  4093. unsigned int n = 0;
  4094. s_append(http_url, &n, "http://", sizeof(http_url));
  4095. s_append(http_url, &n, url + 8, sizeof(http_url));
  4096. /* Replace the https entry instead of adding a second one. */
  4097. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  4098. s_eq(history[hist_pos], url))
  4099. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  4100. load_page(http_url, 0, 0);
  4101. return;
  4102. }
  4103. if (rv != 0) {
  4104. detail = err;
  4105. show_error("Cannot load this page", detail);
  4106. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4107. url_in.len = s_len(url_in.text);
  4108. url_in.cursor = url_in.len;
  4109. url_in.scroll = 0;
  4110. return;
  4111. }
  4112. if (!local)
  4113. origin_cache_learn(url, final[0] ? final : url);
  4114. page_is_local = local;
  4115. if (final[0]) {
  4116. s_copy(page_url, final, sizeof(page_url));
  4117. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4118. url_in.len = s_len(url_in.text);
  4119. url_in.cursor = url_in.len;
  4120. url_in.scroll = 0;
  4121. }
  4122. if (contains_ci(ctype, "text/plain")) {
  4123. br_parse_plain(&doc, (const char *)body, len);
  4124. } else if (contains_ci(ctype, "image/") ||
  4125. (!contains_ci(ctype, "text/html") &&
  4126. img_sniff(body, len, &image_info) == 0)) {
  4127. unsigned int node = br_parse_image_doc(&doc, page_url);
  4128. if (node)
  4129. decode_direct_image(body, len, node);
  4130. s_copy(page_title, "Image", sizeof(page_title));
  4131. } else {
  4132. br_set_viewport(ui.w);
  4133. t_mark = u_ticks_ms();
  4134. br_parse(&doc, (const char *)body, len);
  4135. t_parse = u_ticks_ms() - t_mark;
  4136. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4137. sizeof(page_title));
  4138. t_mark = u_ticks_ms();
  4139. if (load_stylesheets() == FETCH_ABORT)
  4140. return;
  4141. t_css = u_ticks_ms() - t_mark;
  4142. if (pending_action)
  4143. return;
  4144. }
  4145. preload_begin();
  4146. page_loading = 0;
  4147. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4148. url_in.len = s_len(url_in.text);
  4149. url_in.cursor = url_in.len;
  4150. url_in.scroll = 0;
  4151. ngui_set_focus(&ui, 0);
  4152. /* Paint the parsed page before fetching/running scripts. A slow
  4153. * remote <script src> then does not hide the page behind the loading
  4154. * screen; the fetch helper pumps this UI while it waits. */
  4155. set_status("Loading scripts...", 0, 0);
  4156. t_mark = u_ticks_ms();
  4157. redraw_now();
  4158. t_paint = u_ticks_ms() - t_mark;
  4159. /* Start one image download before the scripts. The other workers
  4160. * fetch the external script bodies in parallel, and the remaining
  4161. * images start as soon as the script phase ends. */
  4162. preload_max_jobs = 1;
  4163. preload_fill_jobs();
  4164. preload_wait = 0;
  4165. t_mark = u_ticks_ms();
  4166. run_page_scripts();
  4167. t_js = u_ticks_ms() - t_mark;
  4168. preload_max_jobs = FETCH_WORKERS;
  4169. if (pending_action)
  4170. return;
  4171. post_status_text[0] = '\0';
  4172. post_status_error = 0;
  4173. post_status_ttl = 0;
  4174. if (js_last_status[0]) {
  4175. s_copy(post_status_text, js_last_status,
  4176. sizeof(post_status_text));
  4177. post_status_error = js_last_error;
  4178. post_status_ttl = 8000;
  4179. } else if (truncated) {
  4180. s_copy(post_status_text, "Page truncated at the buffer limit",
  4181. sizeof(post_status_text));
  4182. post_status_ttl = 6000;
  4183. } else if (doc.truncated) {
  4184. s_copy(post_status_text, "Page truncated by the parser",
  4185. sizeof(post_status_text));
  4186. post_status_ttl = 6000;
  4187. } else if (page_total_ms) {
  4188. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4189. * paint 220, js 1750" -- the phases of this load. */
  4190. unsigned int n = 0;
  4191. static const char *const names[] = {
  4192. ", parse ", ", css ", ", paint ", ", js "
  4193. };
  4194. unsigned int vals[4];
  4195. int k;
  4196. vals[0] = t_parse;
  4197. vals[1] = t_css;
  4198. vals[2] = t_paint;
  4199. vals[3] = t_js;
  4200. (void)page_first_ms;
  4201. if (starts_with(page_url, "https://"))
  4202. s_append(post_status_text, &n,
  4203. "HTTPS (not verified), ",
  4204. sizeof(post_status_text));
  4205. s_append(post_status_text, &n, "Loaded in ",
  4206. sizeof(post_status_text));
  4207. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4208. sizeof(post_status_text));
  4209. s_append(post_status_text, &n, " ms: page ",
  4210. sizeof(post_status_text));
  4211. s_append_dec(post_status_text, &n, t_fetch,
  4212. sizeof(post_status_text));
  4213. s_append(post_status_text, &n, " (headers ",
  4214. sizeof(post_status_text));
  4215. s_append_dec(post_status_text, &n, page_open_ms,
  4216. sizeof(post_status_text));
  4217. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4218. for (k = 0; k < 4; k++) {
  4219. s_append(post_status_text, &n, names[k],
  4220. sizeof(post_status_text));
  4221. s_append_dec(post_status_text, &n, vals[k],
  4222. sizeof(post_status_text));
  4223. }
  4224. post_status_ttl = 12000;
  4225. } else if (starts_with(page_url, "https://")) {
  4226. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4227. sizeof(post_status_text));
  4228. post_status_ttl = 6000;
  4229. }
  4230. set_status(post_status_text, post_status_error, post_status_ttl);
  4231. ngui_invalidate(&ui);
  4232. }
  4233. static void load_home(int push)
  4234. {
  4235. pending_post_len = 0;
  4236. pending_post_is = 0;
  4237. cancel_fetch = 0;
  4238. preload_active = 0;
  4239. preload_pending = 0;
  4240. js_browser_stop();
  4241. js_last_status[0] = '\0';
  4242. js_last_error = 0;
  4243. heap_clear();
  4244. image_reset();
  4245. form_reset_state();
  4246. layout_valid = 0;
  4247. page_scroll.offset = 0;
  4248. page_scroll.dragging = 0;
  4249. page_loading = 1;
  4250. page_is_local = 0;
  4251. s_copy(page_url, "about:home", sizeof(page_url));
  4252. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4253. url_in.len = s_len(url_in.text);
  4254. url_in.cursor = url_in.len;
  4255. url_in.scroll = 0;
  4256. ngui_set_focus(&ui, 0);
  4257. if (push)
  4258. history_push(page_url);
  4259. ngui_invalidate(&ui);
  4260. /* See load_page(): reattach the fonts before the first redraw. */
  4261. if (heap_start() != 0) {
  4262. show_error("Out of memory", "Cannot allocate the browser heap");
  4263. return;
  4264. }
  4265. br_parse_plain(&doc, "", 0);
  4266. ngui_font_attach(&ui);
  4267. redraw_now();
  4268. browser_rules_alloc();
  4269. {
  4270. static const char home[] =
  4271. "<html><head><title>NebOS Browser</title><style>"
  4272. "body { margin: 10px; color: #e4e6f0; }"
  4273. "h1 { color: #7fb0ff; }"
  4274. ".box { background-color: #262b3a; margin: 12px; "
  4275. "padding: 10px; }"
  4276. "a { color: #7fb0ff; }"
  4277. "pre { background-color: #32384a; }"
  4278. "</style></head><body>"
  4279. "<h1>NebOS Browser</h1>"
  4280. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4281. "shared HTTP client and the image library.</p>"
  4282. "<div class=\"box\"><b>Try:</b>"
  4283. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4284. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4285. "<li><a href=\"/floppy1/JS.HTM\">/"
  4286. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4287. "<li><a href=\"http://10.0.2.2:8000/\">"
  4288. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4289. "<li><a href=\"https://example.com/\">"
  4290. "https://example.com/</a> (TLS, not verified)</li>"
  4291. "</ul></div>"
  4292. "<p>Type a URL in the bar above. Esc closes the "
  4293. "window, Ctrl+L focuses the address bar.</p>"
  4294. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4295. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4296. "</body></html>";
  4297. br_set_viewport(ui.w);
  4298. br_parse(&doc, home, sizeof(home) - 1);
  4299. br_parse_inline_css(&doc);
  4300. br_reset_styles(&doc);
  4301. s_copy(page_title, doc.title, sizeof(page_title));
  4302. }
  4303. post_status_text[0] = '\0';
  4304. post_status_error = 0;
  4305. post_status_ttl = 0;
  4306. page_loading = 0;
  4307. set_status("", 0, 0);
  4308. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4309. url_in.len = s_len(url_in.text);
  4310. url_in.cursor = url_in.len;
  4311. url_in.scroll = 0;
  4312. ngui_set_focus(&ui, 0);
  4313. ngui_invalidate(&ui);
  4314. }
  4315. /* Extensions the browser opens from the local filesystem. A dotted input
  4316. * with one of these still resolves relative to the cwd. */
  4317. static int local_file_ext(const char *s)
  4318. {
  4319. static const char *const exts[] = {
  4320. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4321. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4322. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  4323. "cfg", "conf", 0
  4324. };
  4325. unsigned int i = 0, start = 0, len = 0, e;
  4326. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  4327. s[i] != '#') {
  4328. if (s[i] == '.') {
  4329. start = i + 1;
  4330. len = 0;
  4331. } else if (start) {
  4332. len++;
  4333. }
  4334. i++;
  4335. }
  4336. if (!len)
  4337. return 0;
  4338. for (e = 0; exts[e]; e++) {
  4339. const char *x = exts[e];
  4340. unsigned int xn = s_len(x), k;
  4341. if (xn != len)
  4342. continue;
  4343. for (k = 0; k < len; k++) {
  4344. char a = s[start + k];
  4345. if (a >= 'A' && a <= 'Z')
  4346. a = (char)(a - 'A' + 'a');
  4347. if (a != x[k])
  4348. break;
  4349. }
  4350. if (k == len)
  4351. return 1;
  4352. }
  4353. return 0;
  4354. }
  4355. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  4356. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  4357. * Enter to the first network request. */
  4358. static int looks_like_host(const char *s)
  4359. {
  4360. unsigned int i = 0;
  4361. int dot = 0;
  4362. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  4363. s[i] != ':') {
  4364. char c = s[i];
  4365. if (c == '.') {
  4366. dot = 1;
  4367. } else if (!((c >= 'a' && c <= 'z') ||
  4368. (c >= 'A' && c <= 'Z') ||
  4369. (c >= '0' && c <= '9') ||
  4370. c == '-' || c == '_')) {
  4371. return 0;
  4372. }
  4373. i++;
  4374. }
  4375. return dot && i > 0 && !local_file_ext(s);
  4376. }
  4377. static void load_remote(const char *url, int push)
  4378. {
  4379. char canon[BR_URL_MAX];
  4380. s_copy(canon, url, sizeof(canon));
  4381. origin_cache_apply(canon, sizeof(canon));
  4382. load_page(canon, 0, push);
  4383. }
  4384. static void navigate(const char *input, int push)
  4385. {
  4386. char target[BR_URL_MAX];
  4387. char *t;
  4388. if (!input)
  4389. return;
  4390. s_copy(target, input, sizeof(target));
  4391. t = trim(target);
  4392. if (!t[0])
  4393. return;
  4394. if (s_eq(t, "about:home")) {
  4395. load_home(push);
  4396. return;
  4397. }
  4398. if (starts_with(t, "file://")) {
  4399. make_abs_local(t + 7, target, sizeof(target));
  4400. load_page(target, 1, push);
  4401. return;
  4402. }
  4403. if (is_http(t)) {
  4404. load_remote(t, push);
  4405. return;
  4406. }
  4407. if (t[0] == '/') {
  4408. make_abs_local(t, target, sizeof(target));
  4409. load_page(target, 1, push);
  4410. return;
  4411. }
  4412. if (!looks_like_host(t)) {
  4413. struct sys_stat st;
  4414. if (u_stat(t, &st) == 0 && !st.is_dir) {
  4415. make_abs_local(t, target, sizeof(target));
  4416. load_page(target, 1, push);
  4417. return;
  4418. }
  4419. }
  4420. {
  4421. /* A typed bare host tries https first: nearly every site
  4422. * redirects http -> https anyway, and that hop costs a whole
  4423. * extra connection. load_page() falls back to http when the
  4424. * https connection itself fails. */
  4425. char with_scheme[BR_URL_MAX];
  4426. unsigned int n = 0;
  4427. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  4428. s_append(with_scheme, &n, t, sizeof(with_scheme));
  4429. nav_https_upgraded = 1;
  4430. load_remote(with_scheme, push);
  4431. }
  4432. }
  4433. /* ---- layout ---- */
  4434. static struct ufont_face *style_face(const struct br_style *st)
  4435. {
  4436. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  4437. return font_faces[st->font_face - 1];
  4438. return 0;
  4439. }
  4440. static struct ufont_face *run_face(const struct lay_run *r)
  4441. {
  4442. if (r->font_face && r->font_face <= BR_MAX_FACES)
  4443. return font_faces[r->font_face - 1];
  4444. return 0;
  4445. }
  4446. static unsigned int face_text_width(struct ngui *gui,
  4447. const struct br_style *st,
  4448. const char *s, unsigned int n)
  4449. {
  4450. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  4451. st->bold, st->italic, st->mono);
  4452. }
  4453. static int face_line_height(struct ngui *gui, const struct br_style *st)
  4454. {
  4455. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  4456. st->mono);
  4457. }
  4458. static unsigned int run_text_width(struct ngui *gui,
  4459. const struct lay_run *r,
  4460. const char *s, unsigned int n)
  4461. {
  4462. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  4463. r->bold, r->italic, r->mono);
  4464. }
  4465. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  4466. {
  4467. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  4468. r->mono);
  4469. }
  4470. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  4471. {
  4472. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  4473. }
  4474. static struct br_style base_style(void)
  4475. {
  4476. struct br_style s = { 0 };
  4477. s.color = ui.theme.text;
  4478. s.bg = ui.theme.bg;
  4479. s.has_bg = 0;
  4480. for (int i = 0; i < 4; i++) {
  4481. s.border_c[i] = 0;
  4482. s.border_w[i] = 0;
  4483. s.border_s[i] = BR_BORDER_SOLID;
  4484. }
  4485. s.font_px = 16;
  4486. s.bold = 0;
  4487. s.italic = 0;
  4488. s.mono = 0;
  4489. s.underline = 0;
  4490. s.strike = 0;
  4491. s.overline = 0;
  4492. s.align = BR_ALIGN_LEFT;
  4493. s.display = BR_DISPLAY_BLOCK;
  4494. s.no_bullet = 0;
  4495. s.list_style = BR_LIST_AUTO;
  4496. s.uppercase = 0;
  4497. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  4498. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  4499. s.width = s.max_width = s.min_width = 0;
  4500. s.height = s.min_height = s.max_height = 0;
  4501. s.box_sizing = 0;
  4502. s.ml_auto = s.mr_auto = 0;
  4503. s.line_h_pct = 0;
  4504. s.line_h_px = 0;
  4505. s.mt = s.mb = s.ml = s.mr = 0;
  4506. s.pt = s.pb = s.pl = s.pr = 0;
  4507. return s;
  4508. }
  4509. /* Resolve a margin/padding raw value. Percentages use the containing
  4510. * block width for all four sides, as CSS specifies. */
  4511. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  4512. {
  4513. if (unit == 1)
  4514. return base * v / 10000;
  4515. if (unit == 2)
  4516. return st->font_px * v / 100;
  4517. if (unit == 3)
  4518. return (int)br_root_font_px() * v / 100;
  4519. if (unit == 4)
  4520. return 0;
  4521. return v;
  4522. }
  4523. static int mp_px(const struct br_style *st, int side, int base)
  4524. {
  4525. int raw;
  4526. switch (side) {
  4527. case 0: raw = st->mt; break;
  4528. case 1: raw = st->mr; break;
  4529. case 2: raw = st->mb; break;
  4530. case 3: raw = st->ml; break;
  4531. case 4: raw = st->pt; break;
  4532. case 5: raw = st->pr; break;
  4533. case 6: raw = st->pb; break;
  4534. default: raw = st->pl; break;
  4535. }
  4536. if (st->mp_unit[side] == 5)
  4537. return base * raw / 100 + st->mp_calc_px[side];
  4538. return css_mp_px(st, raw, st->mp_unit[side], base);
  4539. }
  4540. static int style_width_px(const struct br_style *st, int base)
  4541. {
  4542. if (st->width_kind == 1)
  4543. return st->width;
  4544. if (st->width_kind == 2)
  4545. return base * (int)st->width / 100;
  4546. if (st->width_kind == 3)
  4547. return base * st->width_calc_pct / 100 + st->width_calc_px;
  4548. return 0;
  4549. }
  4550. static int style_height_px(const struct br_style *st, int base)
  4551. {
  4552. if (st->height_kind == 1)
  4553. return st->height;
  4554. if (st->height_kind == 2)
  4555. return base * (int)st->height / 100;
  4556. if (st->height_kind == 3)
  4557. return base * st->height_calc_pct / 100 + st->height_calc_px;
  4558. return 0;
  4559. }
  4560. static int css_size(unsigned char kind, int val, int base)
  4561. {
  4562. if (kind == 1)
  4563. return val;
  4564. if (kind == 2)
  4565. return base * val / 100;
  4566. return -1;
  4567. }
  4568. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  4569. int thick, int horizontal, unsigned short color,
  4570. unsigned char style)
  4571. {
  4572. int pos;
  4573. if (len <= 0 || thick <= 0)
  4574. return;
  4575. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  4576. if (horizontal)
  4577. ngui_fill_rect(ui, (struct ngui_rect){
  4578. x, y, len, thick}, color);
  4579. else
  4580. ngui_fill_rect(ui, (struct ngui_rect){
  4581. x, y, thick, len}, color);
  4582. return;
  4583. }
  4584. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  4585. int seg = len - pos;
  4586. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  4587. seg = style == BR_BORDER_DASHED ? 4 : 2;
  4588. if (horizontal)
  4589. ngui_fill_rect(ui, (struct ngui_rect){
  4590. x + pos, y, seg, thick}, color);
  4591. else
  4592. ngui_fill_rect(ui, (struct ngui_rect){
  4593. x, y + pos, thick, seg}, color);
  4594. }
  4595. }
  4596. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  4597. const struct br_style *st)
  4598. {
  4599. int top = st->border_w[0], right = st->border_w[1];
  4600. int bottom = st->border_w[2], left = st->border_w[3];
  4601. if (r.w <= 0 || r.h <= 0)
  4602. return;
  4603. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  4604. int i;
  4605. for (i = 0; i < 4; i++)
  4606. if (st->border_w[i] && !st->border_t[i]) {
  4607. ngui_fill_rect(ui, r, st->border_c[i]);
  4608. break;
  4609. }
  4610. return;
  4611. }
  4612. if (top && !st->border_t[0])
  4613. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  4614. st->border_c[0], st->border_s[0]);
  4615. if (bottom && !st->border_t[2])
  4616. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  4617. st->border_c[2], st->border_s[2]);
  4618. if (left && !st->border_t[3])
  4619. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  4620. left, 0, st->border_c[3], st->border_s[3]);
  4621. if (right && !st->border_t[1])
  4622. draw_border_side(ui, r.x + r.w - right, r.y + top,
  4623. r.h - top - bottom, right, 0,
  4624. st->border_c[1], st->border_s[1]);
  4625. }
  4626. static void transform_origin(const struct br_style *st, int w, int h,
  4627. int *ox, int *oy)
  4628. {
  4629. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  4630. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  4631. }
  4632. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  4633. unsigned int a)
  4634. {
  4635. unsigned int dr, dg, db, sr, sg, sb;
  4636. if (a >= 255)
  4637. return s;
  4638. dr = (d >> 11) & 31;
  4639. dg = (d >> 5) & 63;
  4640. db = d & 31;
  4641. sr = (s >> 11) & 31;
  4642. sg = (s >> 5) & 63;
  4643. sb = s & 31;
  4644. dr = (dr * (255 - a) + sr * a) / 255;
  4645. dg = (dg * (255 - a) + sg * a) / 255;
  4646. db = (db * (255 - a) + sb * a) / 255;
  4647. return (unsigned short)((dr << 11) | (dg << 5) | db);
  4648. }
  4649. /* Paint a solid box through scale()/rotate() around transform-origin. This
  4650. * transforms the element's own background box; text and descendants keep
  4651. * their layout (documented approximation). */
  4652. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  4653. unsigned short color,
  4654. const struct br_style *st)
  4655. {
  4656. double sx = st->scale_x / 100.0;
  4657. double sy = st->scale_y / 100.0;
  4658. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  4659. double c = cos(th), sn = sin(th);
  4660. int ox, oy, minx, miny, maxx, maxy, x, y;
  4661. double ax, ay;
  4662. double px[4], py[4];
  4663. int cx1, cy1, cx2, cy2, i;
  4664. if (sx == 0)
  4665. sx = 0.01;
  4666. if (sy == 0)
  4667. sy = 0.01;
  4668. transform_origin(st, box.w, box.h, &ox, &oy);
  4669. ax = box.x + ox;
  4670. ay = box.y + oy;
  4671. px[0] = -ox; py[0] = -oy;
  4672. px[1] = box.w - ox; py[1] = -oy;
  4673. px[2] = box.w - ox; py[2] = box.h - oy;
  4674. px[3] = -ox; py[3] = box.h - oy;
  4675. minx = miny = 1000000;
  4676. maxx = maxy = -1000000;
  4677. for (i = 0; i < 4; i++) {
  4678. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  4679. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  4680. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4681. if (dx < minx) minx = dx;
  4682. if (dx > maxx) maxx = dx;
  4683. if (dy < miny) miny = dy;
  4684. if (dy > maxy) maxy = dy;
  4685. }
  4686. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4687. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4688. cx2 = page_rect.x + page_rect.w - 12;
  4689. cy2 = page_rect.y + page_rect.h;
  4690. if (cx2 > gui->w) cx2 = gui->w;
  4691. if (cy2 > gui->h) cy2 = gui->h;
  4692. if (minx < cx1) minx = cx1;
  4693. if (miny < cy1) miny = cy1;
  4694. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4695. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4696. for (y = miny; y <= maxy; y++) {
  4697. for (x = minx; x <= maxx; x++) {
  4698. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  4699. double rx = dx * c + dy * sn;
  4700. double ry = -dx * sn + dy * c;
  4701. double bx = rx / sx + ox;
  4702. double by = ry / sy + oy;
  4703. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  4704. gui->px[y * gui->w + x] = color;
  4705. }
  4706. }
  4707. }
  4708. static void draw_image_transformed(struct ngui *gui,
  4709. const struct img_image *im,
  4710. int x, int y, int w, int h,
  4711. int sx100, int sy100, int rot100,
  4712. int origin_x, int origin_y,
  4713. int origin_x_kind, int origin_y_kind)
  4714. {
  4715. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4716. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4717. double c = cos(th), sn = sin(th);
  4718. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4719. double ax, ay;
  4720. double bx[4], by[4];
  4721. int cx1, cy1, cx2, cy2;
  4722. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4723. return;
  4724. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4725. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4726. ax = x + ox;
  4727. ay = y + oy;
  4728. bx[0] = -ox; by[0] = -oy;
  4729. bx[1] = w - ox; by[1] = -oy;
  4730. bx[2] = w - ox; by[2] = h - oy;
  4731. bx[3] = -ox; by[3] = h - oy;
  4732. minx = miny = 1000000;
  4733. maxx = maxy = -1000000;
  4734. for (i = 0; i < 4; i++) {
  4735. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4736. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4737. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4738. if (dx < minx) minx = dx;
  4739. if (dx > maxx) maxx = dx;
  4740. if (dy < miny) miny = dy;
  4741. if (dy > maxy) maxy = dy;
  4742. }
  4743. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4744. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4745. cx2 = page_rect.x + page_rect.w - 12;
  4746. cy2 = page_rect.y + page_rect.h;
  4747. if (cx2 > gui->w) cx2 = gui->w;
  4748. if (cy2 > gui->h) cy2 = gui->h;
  4749. if (minx < cx1) minx = cx1;
  4750. if (miny < cy1) miny = cy1;
  4751. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4752. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4753. for (py = miny; py <= maxy; py++) {
  4754. for (px = minx; px <= maxx; px++) {
  4755. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4756. double rx = dx * c + dy * sn;
  4757. double ry = -dx * sn + dy * c;
  4758. double fx = rx / sx + ox;
  4759. double fy = ry / sy + oy;
  4760. int ix, iy;
  4761. unsigned int si, a;
  4762. unsigned short src;
  4763. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4764. continue;
  4765. ix = (int)(fx * (double)im->w / w);
  4766. iy = (int)(fy * (double)im->h / h);
  4767. if (ix < 0 || ix >= (int)im->w ||
  4768. iy < 0 || iy >= (int)im->h)
  4769. continue;
  4770. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4771. src = im->px[si];
  4772. a = im->alpha ? im->alpha[si] : 255;
  4773. gui->px[py * gui->w + px] =
  4774. a >= 255 ? src :
  4775. blend_rgb565(gui->px[py * gui->w + px],
  4776. src, a);
  4777. }
  4778. }
  4779. }
  4780. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4781. unsigned int node, const struct br_style *st);
  4782. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4783. * first and every pixel outside a corner's arc is restored afterwards. */
  4784. #define BG_ROUND_MAX 64
  4785. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4786. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4787. unsigned int node, const struct br_style *st,
  4788. int rtl, int rtr, int rbr, int rbl)
  4789. {
  4790. struct ngui *ui = l->ui;
  4791. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4792. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4793. if (ui->nclip > 0)
  4794. clip = ui->clip[ui->nclip - 1];
  4795. for (c = 0; c < 4; c++) {
  4796. if (r[c] > BG_ROUND_MAX)
  4797. r[c] = BG_ROUND_MAX;
  4798. if (r[c] > box.w / 2)
  4799. r[c] = box.w / 2;
  4800. if (r[c] > box.h / 2)
  4801. r[c] = box.h / 2;
  4802. }
  4803. for (c = 0; c < 4; c++) {
  4804. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4805. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4806. for (dy = 0; dy < r[c]; dy++)
  4807. for (dx = 0; dx < r[c]; dx++) {
  4808. int px = ox + dx, py = oy + dy;
  4809. if (px >= clip.x && py >= clip.y &&
  4810. px < clip.x + clip.w && py < clip.y + clip.h)
  4811. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4812. ui->px[py * ui->w + px];
  4813. }
  4814. }
  4815. draw_bg_image(l, box, node, st);
  4816. for (c = 0; c < 4; c++) {
  4817. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4818. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4819. /* arc centre, in corner-square coordinates */
  4820. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4821. int cy = (c >= 2) ? 0 : r[c];
  4822. for (dy = 0; dy < r[c]; dy++)
  4823. for (dx = 0; dx < r[c]; dx++) {
  4824. int px = ox + dx, py = oy + dy;
  4825. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4826. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4827. continue;
  4828. if (px >= clip.x && py >= clip.y &&
  4829. px < clip.x + clip.w && py < clip.y + clip.h)
  4830. ui->px[py * ui->w + px] =
  4831. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4832. }
  4833. }
  4834. }
  4835. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4836. unsigned int node, const struct br_style *st)
  4837. {
  4838. struct br_image *bi;
  4839. struct img_blit b;
  4840. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4841. unsigned int scale = 65536;
  4842. int legacy, tiles = 0, rows = 0;
  4843. int cx1, cy1, cx2, cy2;
  4844. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4845. return;
  4846. if (doc.nodes[node].bg_img_index < 0 ||
  4847. doc.nodes[node].bg_img_index >= image_count)
  4848. return;
  4849. bi = &images[doc.nodes[node].bg_img_index];
  4850. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4851. return;
  4852. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4853. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4854. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4855. if (legacy) {
  4856. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4857. tw = box.w;
  4858. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4859. x = box.x;
  4860. y = box.y;
  4861. rep_x = rep_y = 0;
  4862. } else {
  4863. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4864. unsigned int sx = ((unsigned int)box.w << 16) /
  4865. bi->img.w;
  4866. unsigned int sy = ((unsigned int)box.h << 16) /
  4867. bi->img.h;
  4868. scale = st->bg_size_kind == 3 ?
  4869. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4870. } else if (st->bg_size_kind == 1 ||
  4871. st->bg_size_kind == 2) {
  4872. int w = st->bg_size_w;
  4873. int h = st->bg_size_h;
  4874. if (st->bg_size_kind == 2) {
  4875. if (w)
  4876. w = box.w * w / 100;
  4877. if (h)
  4878. h = box.h * h / 100;
  4879. }
  4880. if (w)
  4881. scale = ((unsigned int)w << 16) / bi->img.w;
  4882. else if (h)
  4883. scale = ((unsigned int)h << 16) / bi->img.h;
  4884. }
  4885. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4886. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4887. if (tw < 1)
  4888. tw = 1;
  4889. if (th < 1)
  4890. th = 1;
  4891. posx = st->bg_pos_x_kind == 1 ?
  4892. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4893. posy = st->bg_pos_y_kind == 1 ?
  4894. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4895. x = box.x + posx;
  4896. y = box.y + posy;
  4897. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4898. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4899. if (rep_x) {
  4900. int m = (x - box.x) % tw;
  4901. if (m > 0)
  4902. m -= tw;
  4903. x = box.x + m;
  4904. }
  4905. if (rep_y) {
  4906. int m = (y - box.y) % th;
  4907. if (m > 0)
  4908. m -= th;
  4909. y = box.y + m;
  4910. }
  4911. }
  4912. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4913. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4914. cx2 = box.x + box.w;
  4915. cy2 = box.y + box.h;
  4916. if (cx2 > page_rect.x + page_rect.w - 12)
  4917. cx2 = page_rect.x + page_rect.w - 12;
  4918. if (cy2 > page_rect.y + page_rect.h)
  4919. cy2 = page_rect.y + page_rect.h;
  4920. if (cx1 >= cx2 || cy1 >= cy2)
  4921. return;
  4922. b.dst = l->ui->px;
  4923. b.dst_w = l->ui->w;
  4924. b.dst_h = l->ui->h;
  4925. b.clip_x = cx1;
  4926. b.clip_y = cy1;
  4927. b.clip_w = cx2 - cx1;
  4928. b.clip_h = cy2 - cy1;
  4929. b.scale = scale;
  4930. b.bg = ui.theme.bg;
  4931. b.bg2 = ui.theme.bg;
  4932. b.flags = IMG_BLIT_OVER_DST;
  4933. {
  4934. int row_x = x;
  4935. for (;;) {
  4936. for (;;) {
  4937. b.x = x;
  4938. b.y = y;
  4939. img_draw(&bi->img, &b);
  4940. if (!rep_x || ++tiles > 512)
  4941. break;
  4942. x += tw;
  4943. if (x >= box.x + box.w)
  4944. break;
  4945. }
  4946. if (!rep_y || ++rows > 64)
  4947. break;
  4948. y += th;
  4949. if (y >= box.y + box.h)
  4950. break;
  4951. x = row_x;
  4952. }
  4953. }
  4954. }
  4955. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  4956. int *out_w, int *out_h);
  4957. static void svg_paint_box(struct ngui *ui, unsigned int node,
  4958. const struct br_style *st, int x, int y, int w,
  4959. int h);
  4960. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  4961. * RUN_SVG an inline <svg> icon (its node in off). */
  4962. #define RUN_SVG (-3)
  4963. static int run_width(const struct lay_run *r)
  4964. {
  4965. if (r->img >= 0)
  4966. return r->iw;
  4967. if (r->img == -2 || r->img == RUN_SVG)
  4968. return r->iw;
  4969. return (int)r->w;
  4970. }
  4971. static void start_line(struct lay *l, const struct br_style *st)
  4972. {
  4973. (void)st;
  4974. if (l->nruns == 0) {
  4975. l->line_y = l->y;
  4976. l->line_h = 0;
  4977. }
  4978. l->line_left = l->left;
  4979. l->line_right = l->right;
  4980. if (l->float_active && l->line_y < l->float_bottom) {
  4981. if (l->float_left > l->line_left)
  4982. l->line_left = l->float_left;
  4983. if (l->float_right < l->line_right)
  4984. l->line_right = l->float_right;
  4985. }
  4986. if (l->line_right < l->line_left + 8)
  4987. l->line_right = l->line_left + 8;
  4988. l->line_x = l->line_left;
  4989. l->run_x = l->line_left;
  4990. }
  4991. static void flush_line(struct lay *l)
  4992. {
  4993. int total, x, i, vis;
  4994. if (!l->nruns && l->line_x == l->line_left) {
  4995. l->line_h = 0;
  4996. return;
  4997. }
  4998. total = l->line_x - l->line_left;
  4999. x = l->line_left;
  5000. vis = 1;
  5001. if (l->draw) {
  5002. int lh = l->line_h ? l->line_h : 16;
  5003. vis = l->line_y + lh >= page_rect.y &&
  5004. l->line_y <= page_rect.y + page_rect.h;
  5005. }
  5006. if (l->align == BR_ALIGN_CENTER)
  5007. x += (l->line_right - l->line_left - total) / 2;
  5008. else if (l->align == BR_ALIGN_RIGHT)
  5009. x = l->line_right - total;
  5010. if (x < l->line_left)
  5011. x = l->line_left;
  5012. for (i = 0; i < l->nruns; i++) {
  5013. struct lay_run *r = &l->runs[i];
  5014. int w = run_width(r);
  5015. int ry = l->line_y + r->dy;
  5016. x += r->gap;
  5017. if (l->draw && vis) {
  5018. if (r->form) {
  5019. unsigned int node = r->form - 1;
  5020. struct form_state *fs = form_get(node, 1);
  5021. int hh = r->ih ? r->ih : 20;
  5022. int focused = form_focus == node;
  5023. int disabled = r->form_disabled;
  5024. unsigned short bg = l->ui->theme.panel_alt;
  5025. unsigned short fg = disabled ? 0x8410 : r->color;
  5026. struct ngui_rect box = {x, ry, w, hh};
  5027. if (r->form_kind == FORM_CHECKBOX ||
  5028. r->form_kind == FORM_RADIO) {
  5029. ngui_fill_rect(l->ui, box, bg);
  5030. ngui_frame(l->ui, box,
  5031. focused ? l->ui->theme.accent :
  5032. l->ui->theme.border);
  5033. if (fs && fs->checked) {
  5034. struct ngui_rect dot = {
  5035. x + 4, ry + 4,
  5036. w > 8 ? w - 8 : 1,
  5037. hh > 8 ? hh - 8 : 1
  5038. };
  5039. if (r->form_kind == FORM_RADIO)
  5040. ngui_fill_round_rect(
  5041. l->ui, dot, 4,
  5042. 4, 4, 4,
  5043. l->ui->theme.accent);
  5044. else
  5045. ngui_fill_rect(l->ui,
  5046. dot,
  5047. l->ui->theme.accent);
  5048. }
  5049. } else {
  5050. int editable =
  5051. r->form_kind == FORM_TEXT ||
  5052. r->form_kind == FORM_PASSWORD ||
  5053. r->form_kind == FORM_TEXTAREA;
  5054. int scroll = 0;
  5055. /* Editable fields draw the live value
  5056. * (r->lit is a short copy). */
  5057. static char shown[FORM_VALUE_MAX + 1];
  5058. const char *txt = r->lit;
  5059. unsigned int tl = s_len(r->lit);
  5060. if (editable && fs && fs->len) {
  5061. unsigned int k;
  5062. if (r->form_kind == FORM_PASSWORD) {
  5063. for (k = 0; k < fs->len; k++)
  5064. shown[k] = '*';
  5065. shown[k] = '\0';
  5066. txt = shown;
  5067. } else {
  5068. txt = fs->value;
  5069. }
  5070. tl = fs->len;
  5071. }
  5072. /* The box is drawn in theme colours, so
  5073. * the text is too: the page's CSS colour
  5074. * (dark on a light page) would vanish on
  5075. * the dark field. */
  5076. if (!disabled)
  5077. fg = editable && fs && !fs->len ?
  5078. l->ui->theme.text_dim :
  5079. l->ui->theme.text;
  5080. ngui_fill_rect(l->ui, box, bg);
  5081. ngui_frame(l->ui, box,
  5082. focused ? l->ui->theme.accent :
  5083. l->ui->theme.border);
  5084. /* A value wider than the field shows its
  5085. * tail (where typing happens). */
  5086. if (editable && fs && fs->len && w > 12) {
  5087. int tw = (int)run_text_width(l->ui,
  5088. r, txt, tl);
  5089. if (tw > w - 12)
  5090. scroll = tw - (w - 12);
  5091. }
  5092. ngui_push_clip(l->ui, (struct ngui_rect){
  5093. x + 1, ry + 1,
  5094. w > 2 ? w - 2 : 1,
  5095. hh > 2 ? hh - 2 : 1 });
  5096. ngui_text_px_face(l->ui, run_face(r),
  5097. x + 6 - scroll,
  5098. ry + (hh - r->font_px) / 2 - 1,
  5099. txt, tl, fg, r->font_px,
  5100. r->bold, r->italic, r->mono);
  5101. if (focused && fs && editable) {
  5102. int cw = 0;
  5103. if (fs->len && fs->caret)
  5104. cw = (int)run_text_width(
  5105. l->ui, r, txt,
  5106. fs->caret < fs->len ?
  5107. fs->caret : fs->len);
  5108. ngui_fill_rect(l->ui,
  5109. (struct ngui_rect){
  5110. x + 6 + cw - scroll,
  5111. ry + 4, 1,
  5112. hh > 8 ? hh - 8 : 1
  5113. },
  5114. l->ui->theme.accent);
  5115. }
  5116. ngui_pop_clip(l->ui);
  5117. if (r->form_kind == FORM_SELECT) {
  5118. ngui_text_px(l->ui, x + w - 12,
  5119. ry + 2, "v", 1, fg,
  5120. r->font_px, 0, 0, 0);
  5121. }
  5122. }
  5123. } else if (r->img == RUN_SVG) {
  5124. struct br_style sst;
  5125. style_for_node(r->off, &sst);
  5126. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  5127. r->ih);
  5128. } else if (r->img == -2) {
  5129. int hh = r->ih ? r->ih : 20;
  5130. ngui_fill_rect(l->ui,
  5131. (struct ngui_rect){x, ry, w, hh},
  5132. l->ui->theme.panel_alt);
  5133. ngui_frame(l->ui,
  5134. (struct ngui_rect){x, ry, w, hh},
  5135. l->ui->theme.border);
  5136. ngui_text_px_face(l->ui, run_face(r),
  5137. x + 6, ry + 2, r->lit,
  5138. s_len(r->lit), r->color,
  5139. r->font_px, r->bold, r->italic,
  5140. r->mono);
  5141. } else if (r->img >= 0) {
  5142. struct br_image *bi = &images[r->img];
  5143. if (bi->state == 1 && r->transform_scale) {
  5144. draw_image_transformed(l->ui, &bi->img,
  5145. x, ry, r->iw, r->ih,
  5146. r->scale_x, r->scale_y,
  5147. r->rotate_x100, r->origin_x,
  5148. r->origin_y, r->origin_x_kind,
  5149. r->origin_y_kind);
  5150. } else if (bi->state == 1) {
  5151. struct img_blit b;
  5152. b.dst = l->ui->px;
  5153. b.dst_w = l->ui->w;
  5154. b.dst_h = l->ui->h;
  5155. b.clip_x = page_rect.x;
  5156. b.clip_y = page_rect.y;
  5157. b.clip_w = page_rect.w - 12;
  5158. b.clip_h = page_rect.h;
  5159. b.x = x;
  5160. b.y = ry;
  5161. b.scale = ((unsigned int)r->iw << 16) /
  5162. bi->img.w;
  5163. b.bg = ui.theme.bg;
  5164. b.bg2 = ui.theme.bg;
  5165. b.flags = IMG_BLIT_OVER_DST;
  5166. img_draw(&bi->img, &b);
  5167. }
  5168. } else {
  5169. const char *s = r->has_lit ? r->lit :
  5170. doc.text + r->off;
  5171. unsigned int n = r->has_lit ? s_len(r->lit) :
  5172. r->len;
  5173. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5174. s, n, r->color, r->font_px,
  5175. r->bold, r->italic, r->mono);
  5176. if (r->underline)
  5177. ngui_fill_rect(l->ui,
  5178. (struct ngui_rect){x,
  5179. ry + run_ascent(l->ui, r) + 2,
  5180. w, 1}, r->color);
  5181. if (r->strike)
  5182. ngui_fill_rect(l->ui,
  5183. (struct ngui_rect){x,
  5184. ry + run_ascent(l->ui, r) -
  5185. (r->font_px > 3 ?
  5186. r->font_px / 3 : 1),
  5187. w, 1}, r->color);
  5188. if (r->overline)
  5189. ngui_fill_rect(l->ui,
  5190. (struct ngui_rect){x, ry,
  5191. w, 1}, r->color);
  5192. }
  5193. if (r->form || r->href) {
  5194. if (nhits < HIT_MAX) {
  5195. struct hit *h = &hits[nhits];
  5196. unsigned int target = r->form ?
  5197. r->form - 1 : r->href;
  5198. int hh = (r->form || r->img >= 0 ||
  5199. r->img == RUN_SVG) ?
  5200. r->ih :
  5201. run_line_height(l->ui, r);
  5202. int merge = nhits > 0 &&
  5203. hits[nhits - 1].node == target &&
  5204. hits[nhits - 1].y == ry &&
  5205. hits[nhits - 1].h == hh &&
  5206. x <= hits[nhits - 1].x +
  5207. hits[nhits - 1].w + 2;
  5208. if (merge) {
  5209. struct hit *p = &hits[nhits - 1];
  5210. int end = x + w;
  5211. if (end > p->x + p->w)
  5212. p->w = end - p->x;
  5213. } else {
  5214. h->x = x;
  5215. h->y = ry;
  5216. h->w = w;
  5217. h->h = hh;
  5218. h->node = (unsigned short)target;
  5219. nhits++;
  5220. }
  5221. }
  5222. }
  5223. }
  5224. x += w;
  5225. }
  5226. l->y += l->line_h + 2;
  5227. if (l->float_active && l->y >= l->float_bottom)
  5228. l->float_active = 0;
  5229. l->nruns = 0;
  5230. l->line_x = l->left;
  5231. l->run_x = l->left;
  5232. l->line_left = l->left;
  5233. l->line_right = l->right;
  5234. l->line_h = 0;
  5235. l->space_pending = 0;
  5236. }
  5237. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5238. const struct br_style *st, unsigned short href,
  5239. const char *lit)
  5240. {
  5241. unsigned int n = lit ? s_len(lit) : len;
  5242. const char *tp = lit ? lit : doc.text + off;
  5243. int w = (int)face_text_width(l->ui, st, tp, n);
  5244. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5245. flush_line(l);
  5246. if (l->nruns == 0) {
  5247. l->line_y = l->y;
  5248. l->line_h = 0;
  5249. start_line(l, st);
  5250. }
  5251. {
  5252. struct lay_run *r = &l->runs[l->nruns++];
  5253. int gap = l->line_x - l->run_x;
  5254. if (gap < 0)
  5255. gap = 0;
  5256. r->gap = (unsigned short)gap;
  5257. r->off = off;
  5258. r->len = len;
  5259. r->color = st->color;
  5260. r->href = href;
  5261. r->dy = 0;
  5262. r->has_lit = 0;
  5263. r->form = 0;
  5264. r->form_kind = 0;
  5265. r->form_disabled = 0;
  5266. r->lit[0] = '\0';
  5267. if (lit && lit[0]) {
  5268. unsigned int i;
  5269. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5270. r->lit[i] = lit[i];
  5271. r->lit[i] = '\0';
  5272. r->has_lit = 1;
  5273. }
  5274. r->img = -1;
  5275. r->iw = r->ih = 0;
  5276. r->font_px = st->font_px;
  5277. r->bold = st->bold;
  5278. r->italic = st->italic;
  5279. r->mono = st->mono;
  5280. r->font_face = st->font_face;
  5281. /* A control with its own background is a button, not body copy;
  5282. * an inherited link underline would strike through the fill. */
  5283. r->underline = st->underline && !st->has_bg;
  5284. r->strike = st->strike && !st->has_bg;
  5285. r->overline = st->overline && !st->has_bg;
  5286. r->w = (unsigned short)w;
  5287. if (r->has_lit)
  5288. r->w = (unsigned short)run_text_width(
  5289. l->ui, r, r->lit, s_len(r->lit));
  5290. w = r->w;
  5291. }
  5292. l->line_x += w;
  5293. l->run_x = l->line_x;
  5294. {
  5295. int lh = face_line_height(l->ui, st);
  5296. if (st->line_h_px)
  5297. lh = st->line_h_px;
  5298. else if (st->line_h_pct)
  5299. lh = st->font_px * st->line_h_pct / 100;
  5300. if (lh < face_line_height(l->ui, st))
  5301. lh = face_line_height(l->ui, st);
  5302. if (l->line_h < lh)
  5303. l->line_h = lh;
  5304. }
  5305. }
  5306. static void add_image_run(struct lay *l, unsigned int node,
  5307. const struct br_style *st, unsigned short href)
  5308. {
  5309. struct br_image *bi = 0;
  5310. int idx = doc.nodes[node].img_index;
  5311. int dw, dh, maxw;
  5312. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  5313. bi = &images[idx];
  5314. if (l->nruns == 0)
  5315. start_line(l, st);
  5316. if (l->space_pending &&
  5317. (l->nruns > 0 || l->line_x > l->line_left)) {
  5318. int sp = (int)face_text_width(l->ui, st, " ", 1);
  5319. if (l->line_x + sp <= l->line_right)
  5320. l->line_x += sp;
  5321. }
  5322. l->space_pending = 0;
  5323. if (!bi) {
  5324. const char *alt = br_alt(&doc, node);
  5325. struct br_style gs = *st;
  5326. char tmp[96];
  5327. unsigned int n = 0;
  5328. int w;
  5329. gs.color = BR_GRAY;
  5330. gs.underline = 0;
  5331. s_append(tmp, &n, "[", sizeof(tmp));
  5332. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  5333. s_append(tmp, &n, "]", sizeof(tmp));
  5334. w = (int)face_text_width(l->ui, &gs, tmp, n);
  5335. if (l->line_x + w > l->line_right &&
  5336. (l->nruns > 0 || l->line_x > l->line_left))
  5337. flush_line(l);
  5338. add_run(l, 0, 0, &gs, href, tmp);
  5339. if (!l->draw) {
  5340. int t = l->line_y < 0 ? 0 : l->line_y;
  5341. int hh = face_line_height(l->ui, &gs);
  5342. if (t > 65535)
  5343. t = 65535;
  5344. if (hh > 65535)
  5345. hh = 65535;
  5346. img_top[node] = (unsigned short)t;
  5347. img_h[node] = (unsigned short)hh;
  5348. }
  5349. return;
  5350. }
  5351. maxw = l->line_right - l->line_left;
  5352. if (maxw < 8)
  5353. maxw = 8;
  5354. {
  5355. int iw = bi->native_w, ih = bi->native_h;
  5356. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  5357. if (iw <= 0 || ih <= 0) {
  5358. iw = (int)bi->img.w;
  5359. ih = (int)bi->img.h;
  5360. }
  5361. dw = iw;
  5362. dh = ih;
  5363. if (doc.nodes[node].width_attr) {
  5364. int want = doc.nodes[node].width_attr;
  5365. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  5366. have_w = 1;
  5367. }
  5368. if (doc.nodes[node].height_attr) {
  5369. int want = doc.nodes[node].height_attr;
  5370. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  5371. have_h = 1;
  5372. }
  5373. if (have_w && !have_h)
  5374. dh = ih ? ih * dw / iw : 0;
  5375. if (have_h && !have_w)
  5376. dw = iw ? iw * dh / ih : 0;
  5377. if (st->width_kind) {
  5378. css_w = 1;
  5379. if (st->width_kind == 3)
  5380. dw = maxw * st->width_calc_pct / 100 +
  5381. st->width_calc_px;
  5382. else
  5383. dw = st->width_kind == 2 ?
  5384. maxw * (int)st->width / 100 :
  5385. (int)st->width;
  5386. }
  5387. if (st->height_kind) {
  5388. css_h = 1;
  5389. if (st->height_kind == 3)
  5390. dh = maxw * st->height_calc_pct / 100 +
  5391. st->height_calc_px;
  5392. else
  5393. dh = st->height_kind == 2 ?
  5394. maxw * (int)st->height / 100 :
  5395. (int)st->height;
  5396. }
  5397. if (css_w && !css_h)
  5398. dh = ih ? ih * dw / iw : 0;
  5399. if (css_h && !css_w)
  5400. dw = iw ? iw * dh / ih : 0;
  5401. if (st->max_width_kind) {
  5402. int mw = st->max_width_kind == 3 ?
  5403. maxw * st->max_width_calc_pct / 100 +
  5404. st->max_width_calc_px :
  5405. st->max_width_kind == 2 ?
  5406. maxw * (int)st->max_width / 100 :
  5407. (int)st->max_width;
  5408. if (mw > 0 && dw > mw) {
  5409. dh = iw ? ih * mw / iw : 0;
  5410. dw = mw;
  5411. }
  5412. }
  5413. }
  5414. if (dw < 8)
  5415. dw = 8;
  5416. if (dh < 8)
  5417. dh = 8;
  5418. if (dw > maxw) {
  5419. dh = dw ? dh * maxw / dw : dh;
  5420. dw = maxw;
  5421. }
  5422. if (!l->draw) {
  5423. int t = l->line_y < 0 ? 0 : l->line_y;
  5424. if (t > 65535)
  5425. t = 65535;
  5426. if (dh > 65535)
  5427. dh = 65535;
  5428. img_top[node] = (unsigned short)t;
  5429. img_h[node] = (unsigned short)dh;
  5430. }
  5431. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  5432. l->line_x > l->line_left))
  5433. flush_line(l);
  5434. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5435. flush_line(l);
  5436. if (l->nruns == 0) {
  5437. l->line_y = l->y;
  5438. l->line_h = 0;
  5439. start_line(l, st);
  5440. }
  5441. {
  5442. struct lay_run *r = &l->runs[l->nruns++];
  5443. int gap = l->line_x - l->run_x;
  5444. if (gap < 0)
  5445. gap = 0;
  5446. r->gap = (unsigned short)gap;
  5447. r->off = 0;
  5448. r->len = 0;
  5449. r->color = 0;
  5450. r->href = href;
  5451. r->form = 0;
  5452. r->form_kind = 0;
  5453. r->form_disabled = 0;
  5454. /* Inline replaced elements honour their vertical margins; this
  5455. * is how Bootstrap's negative logo margins centre the wordmark. */
  5456. {
  5457. int idy = mp_px(st, 0, l->right - l->left);
  5458. if (idy < -2048)
  5459. idy = -2048;
  5460. if (idy > 2048)
  5461. idy = 2048;
  5462. r->dy = (signed short)idy;
  5463. }
  5464. r->has_lit = 0;
  5465. r->lit[0] = '\0';
  5466. r->img = (short)idx;
  5467. r->iw = (unsigned short)dw;
  5468. r->ih = (unsigned short)dh;
  5469. r->w = (unsigned short)dw;
  5470. r->font_px = st->font_px;
  5471. r->bold = st->bold;
  5472. r->italic = st->italic;
  5473. r->mono = st->mono;
  5474. r->font_face = st->font_face;
  5475. r->transform_scale = st->transform_scale;
  5476. r->scale_x = st->scale_x;
  5477. r->scale_y = st->scale_y;
  5478. r->rotate_x100 = st->rotate_x100;
  5479. r->origin_x = st->origin_x;
  5480. r->origin_y = st->origin_y;
  5481. r->origin_x_kind = st->origin_x_kind;
  5482. r->origin_y_kind = st->origin_y_kind;
  5483. r->underline = 0;
  5484. }
  5485. if (node < BR_MAX_NODES) {
  5486. layout_boxes[node].x = l->line_x;
  5487. layout_boxes[node].y = l->line_y +
  5488. mp_px(st, 0, l->right - l->left);
  5489. layout_boxes[node].w = dw;
  5490. layout_boxes[node].h = dh;
  5491. layout_boxes[node].valid = 1;
  5492. }
  5493. l->line_x += dw;
  5494. l->run_x = l->line_x;
  5495. if (l->line_h < dh)
  5496. l->line_h = dh;
  5497. }
  5498. /* An inline (or inline-block) <svg> is a replaced element in the text
  5499. * line, like an <img>: comment bubbles and arrows sit next to their label
  5500. * instead of starting a block of their own. */
  5501. static void add_svg_run(struct lay *l, unsigned int node,
  5502. const struct br_style *st, unsigned short href)
  5503. {
  5504. struct lay_run *r;
  5505. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  5506. if (lw < 8)
  5507. lw = 8;
  5508. cw = st->width_kind ? style_width_px(st, lw) : lw;
  5509. if (cw < 1)
  5510. cw = 1;
  5511. svg_size(node, st, cw, &dw, &dh);
  5512. if (dw > lw)
  5513. dw = lw;
  5514. ml = mp_px(st, 3, lw);
  5515. mr = mp_px(st, 1, lw);
  5516. if (ml < 0)
  5517. ml = 0;
  5518. if (mr < 0)
  5519. mr = 0;
  5520. if (l->line_x + ml + dw > l->line_right &&
  5521. (l->nruns > 0 || l->line_x > l->line_left))
  5522. flush_line(l);
  5523. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5524. flush_line(l);
  5525. if (l->nruns == 0) {
  5526. l->line_y = l->y;
  5527. l->line_h = 0;
  5528. start_line(l, st);
  5529. }
  5530. l->line_x += ml;
  5531. r = &l->runs[l->nruns++];
  5532. memset(r, 0, sizeof(*r));
  5533. r->gap = (unsigned short)(l->line_x > l->run_x ?
  5534. l->line_x - l->run_x : 0);
  5535. r->off = node;
  5536. r->color = st->color;
  5537. r->href = href;
  5538. r->img = RUN_SVG;
  5539. r->iw = (unsigned short)dw;
  5540. r->ih = (unsigned short)dh;
  5541. r->w = (unsigned short)dw;
  5542. r->font_px = st->font_px;
  5543. if (node < BR_MAX_NODES) {
  5544. layout_boxes[node].x = l->line_x;
  5545. layout_boxes[node].y = l->line_y;
  5546. layout_boxes[node].w = dw;
  5547. layout_boxes[node].h = dh;
  5548. layout_boxes[node].valid = 1;
  5549. }
  5550. l->line_x += dw + mr;
  5551. l->run_x = l->line_x;
  5552. if (l->line_h < dh)
  5553. l->line_h = dh;
  5554. }
  5555. static int text_width(struct lay *l, const char *s, unsigned int n,
  5556. const struct br_style *st)
  5557. {
  5558. return (int)face_text_width(l->ui, st, s, n);
  5559. }
  5560. /* Longest prefix that fits in maxw, at least one byte. */
  5561. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  5562. const struct br_style *st, int maxw)
  5563. {
  5564. unsigned int take = 0;
  5565. while (take < n) {
  5566. if (text_width(l, s, take + 1, st) > maxw)
  5567. break;
  5568. take++;
  5569. }
  5570. return take ? take : 1;
  5571. }
  5572. static void emit_word(struct lay *l, const char *s, unsigned int start,
  5573. unsigned int n, unsigned int base,
  5574. const struct br_style *st, unsigned short href)
  5575. {
  5576. int avail;
  5577. int w = text_width(l, s + start, n, st);
  5578. unsigned int off = start;
  5579. if (l->nruns == 0)
  5580. start_line(l, st);
  5581. avail = l->line_right - l->line_left;
  5582. if (st->nowrap) {
  5583. if (n)
  5584. add_run(l, base + start,
  5585. (unsigned short)n, st, href, 0);
  5586. return;
  5587. }
  5588. /* A padded/bordered one-word button can be a few pixels wider than
  5589. * the content box; keep it on one line instead of splitting it. */
  5590. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  5591. add_run(l, base + start,
  5592. (unsigned short)n, st, href, 0);
  5593. return;
  5594. }
  5595. if (l->line_x + w > l->line_right &&
  5596. (l->nruns > 0 || l->line_x > l->line_left)) {
  5597. flush_line(l);
  5598. start_line(l, st);
  5599. avail = l->line_right - l->line_left;
  5600. }
  5601. if (w <= avail) {
  5602. if (n)
  5603. add_run(l, base + start,
  5604. (unsigned short)n, st, href, 0);
  5605. return;
  5606. }
  5607. while (n > 0) {
  5608. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  5609. add_run(l, base + off,
  5610. (unsigned short)take, st, href, 0);
  5611. off += take;
  5612. n -= take;
  5613. if (n) {
  5614. flush_line(l);
  5615. start_line(l, st);
  5616. avail = l->line_right - l->line_left;
  5617. }
  5618. }
  5619. }
  5620. static void emit_text(struct lay *l, const char *s, unsigned int len,
  5621. const struct br_style *st, unsigned short href, int pre)
  5622. {
  5623. unsigned int i = 0;
  5624. unsigned int base;
  5625. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  5626. if (!s || !len)
  5627. return;
  5628. if (space_w <= 0)
  5629. space_w = 8;
  5630. if (l->nruns == 0)
  5631. start_line(l, st);
  5632. base = (unsigned int)(s - doc.text);
  5633. if (st->uppercase) {
  5634. char *p = (char *)s;
  5635. unsigned int j;
  5636. for (j = 0; j < len; j++)
  5637. if (p[j] >= 'a' && p[j] <= 'z')
  5638. p[j] = (char)(p[j] - 'a' + 'A');
  5639. }
  5640. if (pre) {
  5641. while (i < len) {
  5642. unsigned int start;
  5643. if (s[i] == '\n') {
  5644. flush_line(l);
  5645. start_line(l, st);
  5646. i++;
  5647. continue;
  5648. }
  5649. if (s[i] == ' ') {
  5650. if (l->line_x + space_w > l->line_right &&
  5651. (l->nruns > 0 || l->line_x > l->line_left)) {
  5652. flush_line(l);
  5653. start_line(l, st);
  5654. } else {
  5655. l->line_x += space_w;
  5656. }
  5657. i++;
  5658. continue;
  5659. }
  5660. start = i;
  5661. while (i < len && s[i] != ' ' && s[i] != '\n')
  5662. i++;
  5663. emit_word(l, s, start, i - start, base, st, href);
  5664. }
  5665. return;
  5666. }
  5667. while (i < len) {
  5668. unsigned int start, n;
  5669. if (s[i] == ' ') {
  5670. l->space_pending = 1;
  5671. i++;
  5672. continue;
  5673. }
  5674. start = i;
  5675. while (i < len && s[i] != ' ')
  5676. i++;
  5677. n = i - start;
  5678. if (l->space_pending &&
  5679. (l->nruns > 0 || l->line_x > l->line_left)) {
  5680. if (st->nowrap ||
  5681. l->line_x + space_w <= l->line_right)
  5682. l->line_x += space_w;
  5683. }
  5684. l->space_pending = 0;
  5685. emit_word(l, s, start, n, base, st, href);
  5686. }
  5687. }
  5688. static int list_index(unsigned int parent, unsigned int node)
  5689. {
  5690. unsigned int n = 0, i;
  5691. for (i = doc.nodes[parent].first; i && i != node;
  5692. i = doc.nodes[i].next)
  5693. if (doc.nodes[i].tag == BR_TAG_LI)
  5694. n++;
  5695. return (int)n + 1;
  5696. }
  5697. static void list_roman(char *m, unsigned int *n, int v, int upper,
  5698. unsigned int cap)
  5699. {
  5700. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  5701. 50, 40, 10, 9, 5, 4, 1 };
  5702. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  5703. "l", "xl", "x", "ix", "v", "iv", "i" };
  5704. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  5705. "L", "XL", "X", "IX", "V", "IV", "I" };
  5706. unsigned int i;
  5707. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  5708. while (v >= val[i] && *n + 1 < cap) {
  5709. const char *s = upper ? up[i] : lo[i];
  5710. while (*s && *n + 1 < cap)
  5711. m[(*n)++] = *s++;
  5712. v -= val[i];
  5713. }
  5714. }
  5715. }
  5716. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  5717. {
  5718. unsigned int n = 0;
  5719. if (style == BR_LIST_DISC) {
  5720. m[n++] = '-';
  5721. } else if (style == BR_LIST_CIRCLE) {
  5722. m[n++] = 'o';
  5723. } else if (style == BR_LIST_SQUARE) {
  5724. m[n++] = '+';
  5725. } else if (style == BR_LIST_LOWER_ALPHA ||
  5726. style == BR_LIST_UPPER_ALPHA) {
  5727. if (idx >= 1 && idx <= 26)
  5728. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  5729. 'A' : 'a') + idx - 1);
  5730. else
  5731. m[n++] = '?';
  5732. m[n++] = '.';
  5733. } else if (style == BR_LIST_LOWER_ROMAN ||
  5734. style == BR_LIST_UPPER_ROMAN) {
  5735. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  5736. if (n + 1 < cap)
  5737. m[n++] = '.';
  5738. } else {
  5739. s_append_dec(m, &n, (unsigned int)idx, cap);
  5740. if (n + 1 < cap)
  5741. m[n++] = '.';
  5742. }
  5743. m[n] = '\0';
  5744. }
  5745. /* Set by the layout when the control is stretched to its line: a flex item
  5746. * (its box width was assigned by the flex row) or a child of a flex column,
  5747. * whose default align-items: stretch makes inputs full width. */
  5748. static int form_fill_line;
  5749. static void add_form_run(struct lay *l, unsigned int node,
  5750. const struct br_style *st, unsigned short href)
  5751. {
  5752. struct form_state *fs = form_get(node, 1);
  5753. char shown[FORM_VALUE_MAX + 1];
  5754. char opt[64];
  5755. const char *text = "";
  5756. struct lay_run *r;
  5757. int kind = form_kind_of(node);
  5758. int disabled = form_disabled(node);
  5759. int tw, w = 120, h = 20, i;
  5760. if (!fs)
  5761. return;
  5762. if (l->nruns == 0)
  5763. start_line(l, st);
  5764. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  5765. text = "";
  5766. w = 16;
  5767. h = 16;
  5768. } else if (kind == FORM_SELECT) {
  5769. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  5770. s_copy(opt, "Select", sizeof(opt));
  5771. text = opt;
  5772. w = 120;
  5773. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  5774. kind == FORM_RESET) {
  5775. if (fs->len)
  5776. text = fs->value;
  5777. else
  5778. text = kind == FORM_SUBMIT ? "Submit" :
  5779. kind == FORM_RESET ? "Reset" : "Button";
  5780. } else if (kind == FORM_PASSWORD) {
  5781. for (i = 0; i < fs->len; i++)
  5782. shown[i] = '*';
  5783. shown[fs->len] = '\0';
  5784. text = fs->len ? shown : br_placeholder(&doc, node);
  5785. } else {
  5786. if (fs->len)
  5787. text = fs->value;
  5788. else
  5789. text = br_placeholder(&doc, node);
  5790. if (kind == FORM_TEXTAREA) {
  5791. w = 180;
  5792. h = 40;
  5793. }
  5794. }
  5795. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  5796. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  5797. w = tw + 18;
  5798. if (w < 64)
  5799. w = 64;
  5800. h = 22;
  5801. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  5802. int line_w = l->line_right - l->line_left;
  5803. if (st->width_kind == 1)
  5804. w = st->width;
  5805. else if (st->width_kind == 2)
  5806. w = css_size(st->width_kind, st->width, line_w);
  5807. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  5808. w = line_w - (l->line_x - l->line_left);
  5809. else
  5810. w = 120;
  5811. /* Taller fields for large text (min-height/padding on login
  5812. * pages): keep the box around the glyphs. */
  5813. if (st->font_px + 8 > h)
  5814. h = st->font_px + 8;
  5815. } else if (kind == FORM_SELECT) {
  5816. w = st->width_kind == 1 ? st->width : 120;
  5817. }
  5818. if (w > l->line_right - l->line_left)
  5819. w = l->line_right - l->line_left;
  5820. if (w < 8)
  5821. w = 8;
  5822. if (l->line_x + w > l->line_right &&
  5823. (l->nruns > 0 || l->line_x > l->line_left))
  5824. flush_line(l);
  5825. if (l->nruns >= 96)
  5826. return;
  5827. if (l->nruns == 0) {
  5828. l->line_y = l->y;
  5829. l->line_h = 0;
  5830. start_line(l, st);
  5831. }
  5832. r = &l->runs[l->nruns++];
  5833. r->gap = (unsigned short)(l->line_x - l->run_x);
  5834. r->off = r->len = 0;
  5835. r->color = st->color;
  5836. r->href = href;
  5837. r->dy = 0;
  5838. r->has_lit = 1;
  5839. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5840. r->lit[i] = text[i];
  5841. r->lit[i] = '\0';
  5842. r->img = -2;
  5843. r->iw = (unsigned short)w;
  5844. r->ih = (unsigned short)h;
  5845. r->w = (unsigned short)w;
  5846. r->font_px = st->font_px;
  5847. r->bold = st->bold;
  5848. r->italic = st->italic;
  5849. r->mono = st->mono;
  5850. r->font_face = st->font_face;
  5851. r->underline = 0;
  5852. r->form = node + 1;
  5853. r->form_kind = (unsigned char)kind;
  5854. r->form_disabled = (unsigned char)disabled;
  5855. if (node < BR_MAX_NODES) {
  5856. layout_boxes[node].x = l->line_x;
  5857. layout_boxes[node].y = l->line_y;
  5858. layout_boxes[node].w = w;
  5859. layout_boxes[node].h = h;
  5860. layout_boxes[node].valid = 1;
  5861. }
  5862. l->line_x += w;
  5863. l->run_x = l->line_x;
  5864. if (l->line_h < h)
  5865. l->line_h = h;
  5866. }
  5867. /* A poster wrapper is absolutely positioned over the media slot; the
  5868. * measured height of its picture is normally added back to the flow. When a
  5869. * loading-skeleton sibling already reserves that slot, adding both doubles
  5870. * the media height and pushes the article text a full screen down. */
  5871. static int has_skeleton_sibling(unsigned int node)
  5872. {
  5873. unsigned int p = doc.nodes[node].parent, c;
  5874. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5875. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5876. continue;
  5877. if (doc.nodes[c].class_off &&
  5878. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5879. "skeleton"))
  5880. return 1;
  5881. }
  5882. return 0;
  5883. }
  5884. static void layout_children(struct lay *l, unsigned int parent,
  5885. const struct br_style *pst, int depth,
  5886. unsigned short link);
  5887. static void layout_flex_children(struct lay *l, unsigned int parent,
  5888. const struct br_style *pst, int depth,
  5889. unsigned short link);
  5890. static void layout_grid_children(struct lay *l, unsigned int parent,
  5891. const struct br_style *pst, int depth,
  5892. unsigned short link);
  5893. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5894. const struct br_style *pst, int depth,
  5895. unsigned short link);
  5896. static int flex_item_width(struct lay *l, unsigned int n,
  5897. const struct br_style *cs, int avail);
  5898. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5899. const struct br_style *pst, int depth,
  5900. unsigned short link);
  5901. static void layout_table_row(struct lay *l, unsigned int row,
  5902. const struct br_style *pst, int depth,
  5903. unsigned short link);
  5904. static int table_has_rowspan(unsigned int table);
  5905. static void layout_table(struct lay *l, unsigned int table,
  5906. const struct br_style *st, int depth,
  5907. unsigned short link);
  5908. /* A flex container whose items are only inline spans is usually just a
  5909. * heading/icon pair. Our flex row positions such items without emitting
  5910. * their inline text in some deep page contexts; normal inline flow renders
  5911. * the same content correctly. */
  5912. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5913. {
  5914. unsigned int c;
  5915. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5916. struct br_node *nd = &doc.nodes[c];
  5917. struct br_style cs;
  5918. if (nd->type == BR_NODE_TEXT)
  5919. continue;
  5920. br_style_for(&doc, c, pst, &cs);
  5921. if (cs.display == BR_DISPLAY_NONE)
  5922. continue;
  5923. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5924. cs.width_kind || cs.has_bg ||
  5925. cs.border_w[0] || cs.border_w[1] ||
  5926. cs.border_w[2] || cs.border_w[3] ||
  5927. nd->tag == BR_TAG_IMG)
  5928. return 1;
  5929. }
  5930. return 0;
  5931. }
  5932. static int css_radius(const struct br_style *st, int corner,
  5933. int w, int h)
  5934. {
  5935. int r = st->radius[corner];
  5936. if (r <= 0)
  5937. return 0;
  5938. if (r > w / 2)
  5939. r = w / 2;
  5940. if (r > h / 2)
  5941. r = h / 2;
  5942. return r;
  5943. }
  5944. /* ---- inline SVG ----
  5945. *
  5946. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5947. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5948. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5949. * opacity and solid paint; a gradient paints the average of its stops) and
  5950. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5951. #define SVG_CACHE_MAX 48
  5952. #define SVG_CACHE_PIXELS (640 * 1024)
  5953. #define SVG_MAX_POINTS 24576
  5954. struct svg_cache_ent {
  5955. unsigned int node;
  5956. int w, h;
  5957. unsigned short *px;
  5958. unsigned char *a;
  5959. unsigned int stamp;
  5960. };
  5961. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5962. static unsigned int svg_cache_pixels, svg_cache_clock;
  5963. static struct svgr svg_geom;
  5964. static void *svg_geom_buf;
  5965. /* Current viewport in user units: percentage lengths resolve against it
  5966. * (the viewBox size, not the device pixels). */
  5967. static double svg_vp_w = 300, svg_vp_h = 150;
  5968. /* The layers live in the page heap: forget them before heap_reset(). */
  5969. static void svg_cache_clear(void)
  5970. {
  5971. memset(svg_cache, 0, sizeof(svg_cache));
  5972. svg_cache_pixels = 0;
  5973. svg_geom_buf = 0;
  5974. }
  5975. static int svg_name_is(const char *a, const char *b)
  5976. {
  5977. while (*a && *b) {
  5978. char x = *a, y = *b;
  5979. if (x >= 'A' && x <= 'Z')
  5980. x = (char)(x - 'A' + 'a');
  5981. if (x != y)
  5982. return 0;
  5983. a++;
  5984. b++;
  5985. }
  5986. return *a == *b;
  5987. }
  5988. static const char *svg_elem_name(unsigned int node)
  5989. {
  5990. const struct br_node *nd = &doc.nodes[node];
  5991. if (nd->name_off)
  5992. return doc.attrs + nd->name_off;
  5993. return br_tag_name(nd->tag);
  5994. }
  5995. /* A numeric attribute; a percentage resolves against `base`. */
  5996. static double svg_attr_num(unsigned int node, const char *name, double def,
  5997. double base)
  5998. {
  5999. const char *v = br_find_attr(&doc, node, name);
  6000. const char *p = v;
  6001. int ok = 0;
  6002. double x;
  6003. if (!v)
  6004. return def;
  6005. x = svgr_num(&p, &ok);
  6006. if (!ok)
  6007. return def;
  6008. if (*p == '%')
  6009. x = x * base / 100.0;
  6010. return x;
  6011. }
  6012. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  6013. static int svg_viewbox4(unsigned int node, double vb[4])
  6014. {
  6015. const char *v = br_find_attr(&doc, node, "viewbox");
  6016. const char *p = v;
  6017. int i, ok = 1;
  6018. if (!v)
  6019. return 0;
  6020. for (i = 0; i < 4 && ok; i++)
  6021. vb[i] = svgr_num(&p, &ok);
  6022. return ok && vb[2] > 0 && vb[3] > 0;
  6023. }
  6024. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  6025. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  6026. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  6027. double w, double h, double m[6])
  6028. {
  6029. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  6030. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  6031. int ax = 1, ay = 1;
  6032. if (par && contains_ci(par, "none")) {
  6033. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  6034. m[4] = -vb[0] * sx;
  6035. m[5] = -vb[1] * sy;
  6036. return;
  6037. }
  6038. if (par) {
  6039. if (contains_ci(par, "xmin"))
  6040. ax = 0;
  6041. else if (contains_ci(par, "xmax"))
  6042. ax = 2;
  6043. if (contains_ci(par, "ymin"))
  6044. ay = 0;
  6045. else if (contains_ci(par, "ymax"))
  6046. ay = 2;
  6047. }
  6048. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  6049. (sx < sy ? sx : sy);
  6050. tx = (w - vb[2] * s) * ax / 2.0;
  6051. ty = (h - vb[3] * s) * ay / 2.0;
  6052. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  6053. m[4] = tx - vb[0] * s;
  6054. m[5] = ty - vb[1] * s;
  6055. }
  6056. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  6057. * the paint attribute, then average the gradient's stops. */
  6058. static int svg_url_paint(unsigned int node, const char *attr,
  6059. unsigned short *color, unsigned int *alpha)
  6060. {
  6061. const char *v = 0, *h;
  6062. char id[64];
  6063. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  6064. for (k = 0; node && k < 32 && !v; k++) {
  6065. v = br_find_attr(&doc, node, attr);
  6066. if (!v) {
  6067. const char *style = br_find_attr(&doc, node, "style");
  6068. if (style && contains_ci(style, "url(#"))
  6069. v = strstr(style, "url(#");
  6070. }
  6071. if (v && !contains_ci(v, "url("))
  6072. v = 0;
  6073. node = doc.nodes[node].parent;
  6074. }
  6075. if (!v || !(h = strstr(v, "#")))
  6076. return 0;
  6077. h++;
  6078. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  6079. id[n++] = *h++;
  6080. id[n] = '\0';
  6081. g = br_find_id(&doc, id);
  6082. /* Follow href chains (a gradient that only references another one's
  6083. * stops), at most a few hops. */
  6084. for (k = 0; g && k < 4; k++) {
  6085. unsigned int gi = g - 1;
  6086. const char *ref;
  6087. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  6088. const char *nm, *sc, *so;
  6089. unsigned short col = 0;
  6090. double op = 1;
  6091. if (doc.nodes[c].type != BR_NODE_ELEM)
  6092. continue;
  6093. nm = svg_elem_name(c);
  6094. if (!svg_name_is(nm, "stop"))
  6095. continue;
  6096. sc = br_find_attr(&doc, c, "stop-color");
  6097. so = br_find_attr(&doc, c, "stop-opacity");
  6098. {
  6099. const char *st = br_find_attr(&doc, c, "style");
  6100. const char *q;
  6101. if (st && (q = strstr(st, "stop-color:")) != 0)
  6102. sc = q + 11;
  6103. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  6104. so = q + 13;
  6105. }
  6106. if (sc) {
  6107. unsigned int L = 0;
  6108. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  6109. L++;
  6110. if (!br_parse_color(sc, L, &col))
  6111. col = 0;
  6112. }
  6113. if (so) {
  6114. const char *p = so;
  6115. int ok = 0;
  6116. double x = svgr_num(&p, &ok);
  6117. if (ok)
  6118. op = x < 0 ? 0 : x > 1 ? 1 : x;
  6119. }
  6120. sr += (col >> 11) & 31;
  6121. sg += (col >> 5) & 63;
  6122. sb += col & 31;
  6123. sa += (unsigned int)(op * 255);
  6124. cnt++;
  6125. }
  6126. if (cnt)
  6127. break;
  6128. ref = br_find_attr(&doc, gi, "href");
  6129. if (!ref)
  6130. ref = br_find_attr(&doc, gi, "xlink:href");
  6131. if (!ref || ref[0] != '#')
  6132. break;
  6133. g = br_find_id(&doc, ref + 1);
  6134. }
  6135. if (!cnt)
  6136. return 0;
  6137. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  6138. (sb / cnt));
  6139. *alpha = sa / cnt;
  6140. return 1;
  6141. }
  6142. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  6143. unsigned short *color, unsigned int *alpha)
  6144. {
  6145. int mode = fill ? st->fill_mode : st->stroke_mode;
  6146. const char *op = br_find_attr(&doc, node,
  6147. fill ? "fill-opacity" : "stroke-opacity");
  6148. *alpha = 255;
  6149. switch (mode) {
  6150. case BR_PAINT_UNSET:
  6151. if (!fill)
  6152. return 0;
  6153. *color = 0;
  6154. break;
  6155. case BR_PAINT_COLOR:
  6156. *color = fill ? st->fill : st->stroke;
  6157. break;
  6158. case BR_PAINT_CURRENT:
  6159. *color = st->color;
  6160. break;
  6161. case BR_PAINT_URL:
  6162. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  6163. alpha))
  6164. return 0;
  6165. break;
  6166. default:
  6167. return 0;
  6168. }
  6169. if (op) {
  6170. const char *p = op;
  6171. int ok = 0;
  6172. double x = svgr_num(&p, &ok);
  6173. if (ok)
  6174. *alpha = (unsigned int)(*alpha *
  6175. (x < 0 ? 0 : x > 1 ? 1 : x));
  6176. }
  6177. return *alpha > 0;
  6178. }
  6179. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6180. const double m[6], const struct br_style *pst,
  6181. unsigned int alpha, int depth);
  6182. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  6183. const double m[6], const struct br_style *st,
  6184. unsigned int alpha, int depth)
  6185. {
  6186. unsigned int c;
  6187. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  6188. if (doc.nodes[c].type == BR_NODE_ELEM)
  6189. svg_draw_node(L, c, m, st, alpha, depth + 1);
  6190. }
  6191. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6192. const double pm[6], const struct br_style *pst,
  6193. unsigned int alpha, int depth)
  6194. {
  6195. struct br_style st;
  6196. const char *nm = svg_elem_name(node);
  6197. const char *tf;
  6198. double m[6];
  6199. unsigned short color;
  6200. unsigned int pa;
  6201. int shape = 0, fillable = 1;
  6202. if (depth > 24 || !nm)
  6203. return;
  6204. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  6205. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  6206. svg_name_is(nm, "lineargradient") ||
  6207. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  6208. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  6209. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  6210. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  6211. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  6212. svg_name_is(nm, "foreignobject"))
  6213. return;
  6214. br_style_for(&doc, node, pst, &st);
  6215. if (st.display == BR_DISPLAY_NONE)
  6216. return;
  6217. memcpy(m, pm, sizeof(m));
  6218. tf = br_find_attr(&doc, node, "transform");
  6219. if (tf)
  6220. svgr_transform(m, tf);
  6221. {
  6222. const char *op = br_find_attr(&doc, node, "opacity");
  6223. if (op) {
  6224. const char *p = op;
  6225. int ok = 0;
  6226. double x = svgr_num(&p, &ok);
  6227. if (ok)
  6228. alpha = (unsigned int)(alpha *
  6229. (x < 0 ? 0 :
  6230. x > 1 ? 1 : x));
  6231. }
  6232. }
  6233. if (!alpha)
  6234. return;
  6235. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  6236. svg_name_is(nm, "switch")) {
  6237. svg_draw_children(L, node, m, &st, alpha, depth);
  6238. return;
  6239. }
  6240. if (svg_name_is(nm, "svg")) {
  6241. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  6242. y = svg_attr_num(node, "y", 0, 0);
  6243. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6244. t[4] = x;
  6245. t[5] = y;
  6246. svgr_mat_mul(m, m, t);
  6247. double ow = svg_vp_w, oh = svg_vp_h;
  6248. if (svg_viewbox4(node, vb)) {
  6249. double w = svg_attr_num(node, "width", vb[2], ow);
  6250. double h = svg_attr_num(node, "height", vb[3], oh);
  6251. double vm[6];
  6252. svg_viewport_matrix(node, vb, w, h, vm);
  6253. svgr_mat_mul(m, m, vm);
  6254. svg_vp_w = vb[2];
  6255. svg_vp_h = vb[3];
  6256. }
  6257. svg_draw_children(L, node, m, &st, alpha, depth);
  6258. svg_vp_w = ow;
  6259. svg_vp_h = oh;
  6260. return;
  6261. }
  6262. if (svg_name_is(nm, "use")) {
  6263. const char *ref = br_find_attr(&doc, node, "href");
  6264. unsigned int tgt;
  6265. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6266. if (!ref)
  6267. ref = br_find_attr(&doc, node, "xlink:href");
  6268. if (!ref || ref[0] != '#')
  6269. return;
  6270. tgt = br_find_id(&doc, ref + 1);
  6271. if (!tgt || tgt - 1 == node)
  6272. return;
  6273. tgt--;
  6274. t[4] = svg_attr_num(node, "x", 0, 0);
  6275. t[5] = svg_attr_num(node, "y", 0, 0);
  6276. svgr_mat_mul(m, m, t);
  6277. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  6278. double vb[4];
  6279. double ow = svg_vp_w, oh = svg_vp_h;
  6280. if (svg_viewbox4(tgt, vb)) {
  6281. double w = svg_attr_num(node, "width", vb[2],
  6282. ow);
  6283. double h = svg_attr_num(node, "height", vb[3],
  6284. oh);
  6285. double vm[6];
  6286. svg_viewport_matrix(tgt, vb, w, h, vm);
  6287. svgr_mat_mul(m, m, vm);
  6288. svg_vp_w = vb[2];
  6289. svg_vp_h = vb[3];
  6290. }
  6291. svg_draw_children(L, tgt, m, &st, alpha, depth);
  6292. svg_vp_w = ow;
  6293. svg_vp_h = oh;
  6294. } else {
  6295. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  6296. }
  6297. return;
  6298. }
  6299. svgr_reset(&svg_geom, m);
  6300. if (svg_name_is(nm, "path")) {
  6301. const char *d = br_find_attr(&doc, node, "d");
  6302. if (d) {
  6303. svgr_path(&svg_geom, d);
  6304. shape = 1;
  6305. }
  6306. } else if (svg_name_is(nm, "rect")) {
  6307. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  6308. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  6309. double rx = svg_attr_num(node, "rx", -1, w);
  6310. double ry = svg_attr_num(node, "ry", -1, h);
  6311. if (rx < 0)
  6312. rx = ry < 0 ? 0 : ry;
  6313. if (ry < 0)
  6314. ry = rx;
  6315. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  6316. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  6317. shape = 1;
  6318. } else if (svg_name_is(nm, "circle")) {
  6319. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  6320. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6321. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  6322. shape = 1;
  6323. } else if (svg_name_is(nm, "ellipse")) {
  6324. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  6325. svg_attr_num(node, "cy", 0, svg_vp_h),
  6326. svg_attr_num(node, "rx", 0, svg_vp_w),
  6327. svg_attr_num(node, "ry", 0, svg_vp_h));
  6328. shape = 1;
  6329. } else if (svg_name_is(nm, "line")) {
  6330. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  6331. svg_attr_num(node, "y1", 0, svg_vp_h));
  6332. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  6333. svg_attr_num(node, "y2", 0, svg_vp_h));
  6334. shape = 1;
  6335. fillable = 0;
  6336. } else if (svg_name_is(nm, "polyline") ||
  6337. svg_name_is(nm, "polygon")) {
  6338. const char *pts = br_find_attr(&doc, node, "points");
  6339. if (pts) {
  6340. svgr_points(&svg_geom, pts,
  6341. svg_name_is(nm, "polygon"));
  6342. shape = 1;
  6343. }
  6344. }
  6345. if (!shape)
  6346. return;
  6347. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  6348. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  6349. st.fill_evenodd);
  6350. if (svg_paint(node, &st, 0, &color, &pa)) {
  6351. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  6352. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6353. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  6354. }
  6355. }
  6356. /* <text> elements: drawn straight onto the page every frame (the glyph
  6357. * renderer targets the ngui canvas, not a layer). x/y map through the
  6358. * accumulated transform; the font size scales with it. */
  6359. static void svg_draw_text(struct ngui *ui, unsigned int node,
  6360. const double pm[6], const struct br_style *pst,
  6361. int ox, int oy, int depth)
  6362. {
  6363. unsigned int c;
  6364. if (depth > 24)
  6365. return;
  6366. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6367. struct br_style st;
  6368. const char *nm, *tf;
  6369. double m[6];
  6370. if (doc.nodes[c].type != BR_NODE_ELEM)
  6371. continue;
  6372. nm = svg_elem_name(c);
  6373. if (!nm || svg_name_is(nm, "defs") ||
  6374. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  6375. svg_name_is(nm, "clippath"))
  6376. continue;
  6377. br_style_for(&doc, c, pst, &st);
  6378. if (st.display == BR_DISPLAY_NONE)
  6379. continue;
  6380. memcpy(m, pm, sizeof(m));
  6381. tf = br_find_attr(&doc, c, "transform");
  6382. if (tf)
  6383. svgr_transform(m, tf);
  6384. if (svg_name_is(nm, "text")) {
  6385. unsigned int t = doc.nodes[c].first;
  6386. const char *s;
  6387. unsigned int n, tw;
  6388. double x = svg_attr_num(c, "x", 0, 0),
  6389. y = svg_attr_num(c, "y", 0, 0);
  6390. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  6391. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  6392. int tx, ty, anchor;
  6393. unsigned short col;
  6394. unsigned int pa;
  6395. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  6396. continue;
  6397. if (px < 6)
  6398. px = 6;
  6399. if (px > 72)
  6400. px = 72;
  6401. if (!svg_paint(c, &st, 1, &col, &pa))
  6402. continue;
  6403. s = doc.text + doc.nodes[t].text_off;
  6404. n = doc.nodes[t].text_len;
  6405. st.font_px = (unsigned char)px;
  6406. tw = face_text_width(ui, &st, s, n);
  6407. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  6408. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  6409. ngui_text_ascent_face(ui, style_face(&st), px,
  6410. st.mono);
  6411. anchor = st.align;
  6412. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  6413. anchor = BR_ALIGN_CENTER;
  6414. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  6415. anchor = BR_ALIGN_RIGHT;
  6416. if (anchor == BR_ALIGN_CENTER)
  6417. tx -= (int)tw / 2;
  6418. else if (anchor == BR_ALIGN_RIGHT)
  6419. tx -= (int)tw;
  6420. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  6421. col, px, st.bold, st.italic,
  6422. st.mono);
  6423. } else {
  6424. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  6425. }
  6426. }
  6427. }
  6428. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  6429. {
  6430. double vb[4];
  6431. if (svg_viewbox4(node, vb)) {
  6432. svg_viewport_matrix(node, vb, w, h, m);
  6433. } else {
  6434. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  6435. }
  6436. }
  6437. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  6438. const struct br_style *st)
  6439. {
  6440. struct svg_cache_ent *e = 0;
  6441. struct svgr_layer L;
  6442. double m[6];
  6443. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  6444. svg_cache_clock++;
  6445. for (i = 0; i < SVG_CACHE_MAX; i++)
  6446. if (svg_cache[i].px && svg_cache[i].node == node &&
  6447. svg_cache[i].w == w && svg_cache[i].h == h) {
  6448. svg_cache[i].stamp = svg_cache_clock;
  6449. return &svg_cache[i];
  6450. }
  6451. if (need > SVG_CACHE_PIXELS)
  6452. return 0;
  6453. /* Evict least recently used layers until this one fits. */
  6454. for (;;) {
  6455. struct svg_cache_ent *lru = 0, *free_slot = 0;
  6456. for (i = 0; i < SVG_CACHE_MAX; i++) {
  6457. if (!svg_cache[i].px) {
  6458. if (!free_slot)
  6459. free_slot = &svg_cache[i];
  6460. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  6461. lru = &svg_cache[i];
  6462. }
  6463. }
  6464. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  6465. e = free_slot;
  6466. break;
  6467. }
  6468. if (!lru)
  6469. return 0;
  6470. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  6471. free(lru->px);
  6472. free(lru->a);
  6473. memset(lru, 0, sizeof(*lru));
  6474. }
  6475. if (!svg_geom_buf) {
  6476. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6477. if (!svg_geom_buf)
  6478. return 0;
  6479. }
  6480. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6481. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6482. e->a = (unsigned char *)calloc(need, 1);
  6483. if (!e->px || !e->a) {
  6484. free(e->px);
  6485. free(e->a);
  6486. memset(e, 0, sizeof(*e));
  6487. return 0;
  6488. }
  6489. e->node = node;
  6490. e->w = w;
  6491. e->h = h;
  6492. e->stamp = svg_cache_clock;
  6493. svg_cache_pixels += need;
  6494. L.px = e->px;
  6495. L.a = e->a;
  6496. L.w = w;
  6497. L.h = h;
  6498. svg_root_matrix(node, w, h, m);
  6499. {
  6500. double vb[4];
  6501. if (svg_viewbox4(node, vb)) {
  6502. svg_vp_w = vb[2];
  6503. svg_vp_h = vb[3];
  6504. } else {
  6505. svg_vp_w = w;
  6506. svg_vp_h = h;
  6507. }
  6508. }
  6509. svg_draw_children(&L, node, m, st, 255, 0);
  6510. return e;
  6511. }
  6512. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  6513. *
  6514. * The markup is parsed into a detached subtree of the page document and
  6515. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  6516. * bitmap, which then behaves like any decoded image. currentColor is
  6517. * black (an image has no inherited text colour); <text> is not drawn. */
  6518. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  6519. {
  6520. unsigned int i = 0;
  6521. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  6522. i = 3;
  6523. while (i < len) {
  6524. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  6525. d[i] == '\r' || d[i] == '\n'))
  6526. i++;
  6527. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  6528. return 1;
  6529. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  6530. i += 4;
  6531. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  6532. i++;
  6533. i += 3;
  6534. continue;
  6535. }
  6536. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  6537. while (i < len && d[i] != '>')
  6538. i++;
  6539. i++;
  6540. continue;
  6541. }
  6542. return 0;
  6543. }
  6544. return 0;
  6545. }
  6546. static int svg_len_attr(unsigned int node, const char *name)
  6547. {
  6548. const char *v = br_find_attr(&doc, node, name);
  6549. int n = 0, any = 0;
  6550. if (!v)
  6551. return 0;
  6552. while (*v == ' ')
  6553. v++;
  6554. while (*v >= '0' && *v <= '9') {
  6555. n = n * 10 + (*v++ - '0');
  6556. any = 1;
  6557. }
  6558. if (*v == '.')
  6559. while (*++v >= '0' && *v <= '9')
  6560. ;
  6561. if (!any || *v == '%')
  6562. return 0;
  6563. return n;
  6564. }
  6565. static int svg_decode_image(const unsigned char *data, unsigned int len,
  6566. struct br_image *bi, int box_w, int box_h)
  6567. {
  6568. unsigned int holder, svg = 0, c, need, i;
  6569. struct br_style base = base_style(), st;
  6570. struct svgr_layer L;
  6571. double vb[4], m[6];
  6572. int w, h, have_vb, nat_w, nat_h;
  6573. holder = br_create_element(&doc, "div", 3);
  6574. if (!holder) {
  6575. s_copy(bi->err, "page is full", sizeof(bi->err));
  6576. return -1;
  6577. }
  6578. holder--;
  6579. br_set_inner_html(&doc, holder, (const char *)data, len);
  6580. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  6581. if (doc.nodes[c].type == BR_NODE_ELEM &&
  6582. doc.nodes[c].tag == BR_TAG_SVG) {
  6583. svg = c;
  6584. break;
  6585. }
  6586. if (!svg) {
  6587. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  6588. return -1;
  6589. }
  6590. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  6591. w = svg_len_attr(svg, "width");
  6592. h = svg_len_attr(svg, "height");
  6593. if (box_w > 0 && box_h > 0) {
  6594. w = box_w;
  6595. h = box_h;
  6596. } else if (!w && !h) {
  6597. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  6598. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  6599. } else if (!w) {
  6600. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  6601. } else if (!h) {
  6602. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  6603. }
  6604. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  6605. * so CSS scaling stays crisp. */
  6606. nat_w = w;
  6607. nat_h = h;
  6608. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  6609. w *= 2;
  6610. h *= 2;
  6611. }
  6612. if (w > BR_IMG_LAYOUT_W) {
  6613. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  6614. w = BR_IMG_LAYOUT_W;
  6615. }
  6616. if (h > 2048)
  6617. h = 2048;
  6618. if (w < 1)
  6619. w = 1;
  6620. if (h < 1)
  6621. h = 1;
  6622. need = (unsigned int)w * (unsigned int)h;
  6623. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  6624. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  6625. return -1;
  6626. }
  6627. if (!svg_geom_buf) {
  6628. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6629. if (!svg_geom_buf) {
  6630. s_copy(bi->err, "out of memory", sizeof(bi->err));
  6631. return -1;
  6632. }
  6633. }
  6634. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6635. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6636. L.a = (unsigned char *)calloc(need, 1);
  6637. if (!L.px || !L.a) {
  6638. free(L.px);
  6639. free(L.a);
  6640. s_copy(bi->err, "out of memory", sizeof(bi->err));
  6641. return -1;
  6642. }
  6643. for (i = 0; i < need; i++)
  6644. L.px[i] = 0xFFFF;
  6645. L.w = w;
  6646. L.h = h;
  6647. base.color = 0x0000;
  6648. br_style_for(&doc, svg, &base, &st);
  6649. svg_root_matrix(svg, w, h, m);
  6650. svg_vp_w = have_vb ? vb[2] : w;
  6651. svg_vp_h = have_vb ? vb[3] : h;
  6652. svg_draw_children(&L, svg, m, &st, 255, 0);
  6653. bi->native_w = nat_w;
  6654. bi->native_h = nat_h;
  6655. bi->img.format = 0;
  6656. bi->img.w = (unsigned int)w;
  6657. bi->img.h = (unsigned int)h;
  6658. bi->img.px = L.px;
  6659. bi->img.alpha = L.a;
  6660. bi->img.flags = 0;
  6661. bi->state = 1;
  6662. image_pixels += need;
  6663. return 0;
  6664. }
  6665. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  6666. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6667. int *out_w, int *out_h)
  6668. {
  6669. double vb[4];
  6670. int has_vb = svg_viewbox4(node, vb);
  6671. double aw = svg_attr_num(node, "width", -1, cw);
  6672. double ah = svg_attr_num(node, "height", -1, 0);
  6673. int w, h;
  6674. if (st->width_kind)
  6675. w = cw;
  6676. else if (aw > 0)
  6677. w = (int)(aw + 0.5);
  6678. else if (st->height_kind == 1 && has_vb)
  6679. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  6680. else if (ah > 0 && has_vb)
  6681. w = (int)(ah * vb[2] / vb[3] + 0.5);
  6682. else if (has_vb)
  6683. w = cw;
  6684. else
  6685. w = 300;
  6686. if (st->max_width_kind == 1 && w > st->max_width)
  6687. w = st->max_width;
  6688. if (w > cw && cw > 0 && !(aw > 0))
  6689. w = cw;
  6690. if (w < 1)
  6691. w = 1;
  6692. if (w > 2000)
  6693. w = 2000;
  6694. if (st->height_kind == 1)
  6695. h = st->height;
  6696. else if (ah > 0)
  6697. h = (int)(ah + 0.5);
  6698. else if (has_vb)
  6699. h = (int)(w * vb[3] / vb[2] + 0.5);
  6700. else
  6701. h = 150;
  6702. if (h < 1)
  6703. h = 1;
  6704. if (h > 1400)
  6705. h = 1400;
  6706. *out_w = w;
  6707. *out_h = h;
  6708. }
  6709. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6710. const struct br_style *st, int x, int y, int w, int h)
  6711. {
  6712. struct svg_cache_ent *e;
  6713. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  6714. int cx0, cy0, cx1, cy1, px, py;
  6715. double m[6];
  6716. if (ui->nclip > 0)
  6717. clip = ui->clip[ui->nclip - 1];
  6718. cx0 = r.x > clip.x ? r.x : clip.x;
  6719. cy0 = r.y > clip.y ? r.y : clip.y;
  6720. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  6721. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  6722. if (cx0 >= cx1 || cy0 >= cy1)
  6723. return;
  6724. e = svg_layer(node, w, h, st);
  6725. if (e) {
  6726. for (py = cy0; py < cy1; py++) {
  6727. unsigned int srow = (unsigned int)(py - y) *
  6728. (unsigned int)w;
  6729. unsigned short *dst = ui->px + py * ui->w;
  6730. for (px = cx0; px < cx1; px++) {
  6731. unsigned int si = srow + (unsigned int)(px - x);
  6732. unsigned int a = e->a[si];
  6733. if (!a)
  6734. continue;
  6735. dst[px] = a >= 255 ? e->px[si] :
  6736. blend_rgb565(dst[px], e->px[si], a);
  6737. }
  6738. }
  6739. }
  6740. svg_root_matrix(node, w, h, m);
  6741. ngui_push_clip(ui, r);
  6742. svg_draw_text(ui, node, m, st, x, y, 0);
  6743. ngui_pop_clip(ui);
  6744. }
  6745. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  6746. * keep using add_image_run(); this covers the CSS `position:absolute;
  6747. * width:100%` poster pattern used by news sites. */
  6748. static void image_block_size(unsigned int node, const struct br_style *st,
  6749. int cbw, int *out_w, int *out_h)
  6750. {
  6751. struct br_node *nd = &doc.nodes[node];
  6752. int idx = nd->img_index;
  6753. int iw = 0, ih = 0, w, h, aw, ah;
  6754. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6755. iw = (int)images[idx].img.w;
  6756. ih = (int)images[idx].img.h;
  6757. if (iw <= 0 || ih <= 0) {
  6758. iw = (int)images[idx].native_w;
  6759. ih = (int)images[idx].native_h;
  6760. }
  6761. }
  6762. if (st->width_kind)
  6763. w = style_width_px(st, cbw);
  6764. else if (nd->width_attr)
  6765. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  6766. (int)nd->width_attr;
  6767. else if (nd->height_attr && !nd->height_pct && iw && ih)
  6768. w = iw * (int)nd->height_attr / ih;
  6769. else if (iw)
  6770. w = iw;
  6771. else
  6772. w = 64;
  6773. /* max-width/min-width against the containing block: Tailwind's
  6774. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  6775. * 300x300 thumbnail to its 75 px avatar box. */
  6776. if (st->max_width_kind) {
  6777. int mw = st->max_width_kind == 3 ?
  6778. cbw * st->max_width_calc_pct / 100 +
  6779. st->max_width_calc_px :
  6780. st->max_width_kind == 2 ?
  6781. cbw * (int)st->max_width / 100 : (int)st->max_width;
  6782. if (mw > 0 && w > mw)
  6783. w = mw;
  6784. }
  6785. if (st->min_width_kind) {
  6786. int mn = st->min_width_kind == 3 ?
  6787. cbw * st->min_width_calc_pct / 100 +
  6788. st->min_width_calc_px :
  6789. st->min_width_kind == 2 ?
  6790. cbw * (int)st->min_width / 100 : (int)st->min_width;
  6791. if (mn > w)
  6792. w = mn;
  6793. }
  6794. if (w < 8)
  6795. w = 8;
  6796. if (cbw > 0 && w > cbw)
  6797. w = cbw;
  6798. /* Without a CSS height the attributes (or the bitmap) only give the
  6799. * aspect ratio: a width clamped by max-width scales the height too,
  6800. * instead of letterboxing the image into its attribute height. */
  6801. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  6802. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  6803. if (st->height_kind)
  6804. h = style_height_px(st, cbw);
  6805. else if (aw > 0 && ah > 0)
  6806. h = w * ah / aw;
  6807. else if (nd->height_attr)
  6808. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  6809. (int)nd->height_attr;
  6810. else
  6811. h = 64;
  6812. if (h < 8)
  6813. h = 8;
  6814. *out_w = w;
  6815. *out_h = h;
  6816. }
  6817. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  6818. int dw, int dh)
  6819. {
  6820. int idx = doc.nodes[node].img_index;
  6821. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6822. struct img_blit b;
  6823. b.dst = l->ui->px;
  6824. b.dst_w = l->ui->w;
  6825. b.dst_h = l->ui->h;
  6826. b.clip_x = page_rect.x;
  6827. b.clip_y = page_rect.y;
  6828. b.clip_w = page_rect.w - 12;
  6829. b.clip_h = page_rect.h;
  6830. b.x = x;
  6831. b.y = y;
  6832. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  6833. b.bg = ui.theme.bg;
  6834. b.bg2 = ui.theme.bg;
  6835. b.flags = IMG_BLIT_OVER_DST;
  6836. img_draw(&images[idx].img, &b);
  6837. } else if (l->draw) {
  6838. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  6839. 0xD69A);
  6840. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  6841. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  6842. }
  6843. }
  6844. static void layout_block(struct lay *l, unsigned int node,
  6845. const struct br_style *st, int depth,
  6846. unsigned short link)
  6847. {
  6848. int old_left = l->left, old_right = l->right, old_align = l->align;
  6849. int parent_cb_h = l->cb_h;
  6850. int saved_parent_top = l->parent_top;
  6851. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  6852. int saved_cb_top = l->cb_top;
  6853. int top, l0, r0;
  6854. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  6855. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  6856. int deco_w, deco_h, content_w, content_h, box_h;
  6857. int img_dh = 0;
  6858. int definite_w = 0;
  6859. int normal_top = 0;
  6860. int rel_dx = 0, rel_dy = 0;
  6861. int clip_pushed = 0;
  6862. struct ngui_rect clip_rect;
  6863. /* A DOM level costs about two depth units (layout_block ->
  6864. * layout_children), so 48 covers a ~24-level page. Real news pages
  6865. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  6866. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  6867. return;
  6868. flow_y = l->y;
  6869. flow_left = l->left;
  6870. flow_right = l->right;
  6871. positioned = st->pos == 1 || st->pos == 2;
  6872. relative = st->pos == 3;
  6873. sticky = st->pos == 4;
  6874. shifted = relative || sticky || st->transform_set;
  6875. if (positioned) {
  6876. int def_w = st->width_kind == 1 ? st->width : -1;
  6877. if (st->pos == 2) {
  6878. int avail_w = page_rect.w - 12;
  6879. if (st->right_set && def_w >= 0)
  6880. l->left = page_rect.x + avail_w - st->right -
  6881. def_w;
  6882. else
  6883. l->left = page_rect.x +
  6884. (st->left_set ? st->left : 0);
  6885. l->right = def_w >= 0 ? l->left + def_w :
  6886. page_rect.x + avail_w;
  6887. if (st->bottom_set && st->height_kind)
  6888. l->y = page_rect.y + page_rect.h -
  6889. st->bottom -
  6890. style_height_px(st, page_rect.w);
  6891. else
  6892. l->y = page_rect.y +
  6893. (st->top_set ? st->top : 0);
  6894. } else {
  6895. int left = flow_left + (st->left_set ? st->left : 0);
  6896. unsigned int parent = doc.nodes[node].parent;
  6897. if (st->right_set && def_w >= 0)
  6898. left = flow_right - st->right - def_w;
  6899. l->left = left;
  6900. l->right = def_w >= 0 ? left + def_w :
  6901. flow_right +
  6902. (st->left_set ? st->left : 0);
  6903. l->y = flow_y + (st->top_set ? st->top : 0);
  6904. if (st->bottom_set && st->height_kind &&
  6905. parent < BR_MAX_NODES && block_h[parent] > 0)
  6906. l->y = flow_y + block_h[parent] - st->bottom -
  6907. style_height_px(st, old_right - old_left);
  6908. }
  6909. old_left = l->left;
  6910. old_right = l->right;
  6911. } else if (relative) {
  6912. rel_dx = st->left_set ? st->left :
  6913. (st->right_set ? -st->right : 0);
  6914. rel_dy = st->top_set ? st->top :
  6915. (st->bottom_set ? -st->bottom : 0);
  6916. }
  6917. if (st->transform_set) {
  6918. rel_dx += st->tx;
  6919. rel_dy += st->ty;
  6920. }
  6921. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  6922. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  6923. doc.nodes[node].tag == BR_TAG_SELECT ||
  6924. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  6925. !button_has_elements(node)) {
  6926. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  6927. s_eq(br_type(&doc, node), "hidden"))
  6928. return;
  6929. /* Reached as a block-level box (a flex item): the control
  6930. * fills the box the caller assigned, and its line is flushed
  6931. * here; flex layout resets the run list for the next item, so
  6932. * a queued run would never be drawn. */
  6933. form_fill_line = 1;
  6934. add_form_run(l, node, st, link);
  6935. form_fill_line = 0;
  6936. flush_line(l);
  6937. return;
  6938. }
  6939. flush_line(l);
  6940. cbw = old_right - old_left;
  6941. if (cbw < 8)
  6942. cbw = 8;
  6943. l->y += mp_px(st, 0, cbw);
  6944. top = l->y;
  6945. ml = mp_px(st, 3, cbw);
  6946. mr = mp_px(st, 1, cbw);
  6947. bl = st->border_w[3];
  6948. br = st->border_w[1];
  6949. pl = mp_px(st, 7, cbw);
  6950. pr = mp_px(st, 5, cbw);
  6951. bt = st->border_w[0];
  6952. bb = st->border_w[2];
  6953. pt = mp_px(st, 4, cbw);
  6954. pb = mp_px(st, 6, cbw);
  6955. deco_w = bl + br + pl + pr;
  6956. deco_h = bt + bb + pt + pb;
  6957. if (st->width_kind) {
  6958. int w;
  6959. if (st->width_kind == 3)
  6960. w = cbw * st->width_calc_pct / 100 +
  6961. st->width_calc_px;
  6962. else
  6963. w = css_size(st->width_kind, st->width, cbw);
  6964. if (w < 0)
  6965. w = 0;
  6966. content_w = st->box_sizing ? w - deco_w : w;
  6967. definite_w = 1;
  6968. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  6969. doc.nodes[node].tag == BR_TAG_TD ||
  6970. doc.nodes[node].tag == BR_TAG_TH) &&
  6971. doc.nodes[node].width_attr) {
  6972. /* Legacy table/cell width attributes: percentages resolve
  6973. * against the containing block, bare numbers are pixels. */
  6974. int w = doc.nodes[node].width_pct ?
  6975. cbw * doc.nodes[node].width_attr / 100 :
  6976. doc.nodes[node].width_attr;
  6977. if (w < 0)
  6978. w = 0;
  6979. content_w = st->box_sizing ? w - deco_w : w;
  6980. definite_w = 1;
  6981. } else {
  6982. content_w = cbw - ml - mr - deco_w;
  6983. }
  6984. if (content_w < 0)
  6985. content_w = 0;
  6986. if (st->max_width_kind) {
  6987. int mw = st->max_width_kind == 3 ?
  6988. cbw * st->max_width_calc_pct / 100 +
  6989. st->max_width_calc_px :
  6990. css_size(st->max_width_kind, st->max_width, cbw);
  6991. int max_box = st->box_sizing ? mw : mw + deco_w;
  6992. if (content_w + deco_w > max_box)
  6993. content_w = max_box - deco_w;
  6994. }
  6995. if (st->min_width_kind) {
  6996. int mw = st->min_width_kind == 3 ?
  6997. cbw * st->min_width_calc_pct / 100 +
  6998. st->min_width_calc_px :
  6999. css_size(st->min_width_kind, st->min_width, cbw);
  7000. int min_box = st->box_sizing ? mw : mw + deco_w;
  7001. if (content_w + deco_w < min_box) {
  7002. content_w = min_box - deco_w;
  7003. definite_w = 1;
  7004. }
  7005. }
  7006. if (content_w < 8)
  7007. content_w = 8;
  7008. if (definite_w) {
  7009. int free_w = cbw - ml - mr - deco_w - content_w;
  7010. if (free_w < 0)
  7011. free_w = 0;
  7012. if (st->ml_auto && st->mr_auto) {
  7013. ml = free_w / 2;
  7014. mr = free_w - ml;
  7015. } else if (st->ml_auto) {
  7016. ml = free_w;
  7017. } else if (st->mr_auto) {
  7018. mr = free_w;
  7019. }
  7020. }
  7021. if (doc.nodes[node].tag == BR_TAG_IMG) {
  7022. int iw, ih;
  7023. image_block_size(node, st, cbw, &iw, &ih);
  7024. content_w = iw;
  7025. img_dh = ih;
  7026. }
  7027. l0 = old_left + ml;
  7028. r0 = l0 + deco_w + content_w;
  7029. if (r0 < l0 + 8)
  7030. r0 = l0 + 8;
  7031. normal_top = top;
  7032. if (sticky) {
  7033. if (st->top_set) {
  7034. int stick = page_rect.y + 4 + st->top;
  7035. if (normal_top < stick)
  7036. rel_dy += stick - normal_top;
  7037. } else if (st->bottom_set && block_h[node]) {
  7038. int stick = page_rect.y + page_rect.h - st->bottom -
  7039. block_h[node];
  7040. if (normal_top > stick)
  7041. rel_dy += stick - normal_top;
  7042. }
  7043. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  7044. block_h[doc.nodes[node].parent]) {
  7045. unsigned int p = doc.nodes[node].parent;
  7046. int ptop = l->parent_top;
  7047. int pbottom = ptop + block_h[p];
  7048. int eh = block_h[node];
  7049. int moved_top = normal_top + rel_dy;
  7050. int moved_bottom = moved_top + eh;
  7051. if (moved_bottom > pbottom)
  7052. rel_dy -= moved_bottom - pbottom;
  7053. moved_top = normal_top + rel_dy;
  7054. if (moved_top < ptop)
  7055. rel_dy += ptop - moved_top;
  7056. }
  7057. }
  7058. if (shifted && l->draw) {
  7059. top += rel_dy;
  7060. l0 += rel_dx;
  7061. r0 += rel_dx;
  7062. }
  7063. l->parent_top = top;
  7064. if (st->pos != 0) {
  7065. /* Positioned boxes establish the containing block for their
  7066. * absolutely positioned descendants. */
  7067. l->cb_left = l0;
  7068. l->cb_right = r0;
  7069. l->cb_top = top;
  7070. }
  7071. if (l->draw && block_h[node] &&
  7072. top < page_rect.y + page_rect.h &&
  7073. top + block_h[node] > page_rect.y) {
  7074. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  7075. int rtl = css_radius(st, 0, box.w, box.h);
  7076. int rtr = css_radius(st, 1, box.w, box.h);
  7077. int rbr = css_radius(st, 2, box.w, box.h);
  7078. int rbl = css_radius(st, 3, box.w, box.h);
  7079. if (st->transform_scale) {
  7080. if (st->has_bg)
  7081. fill_transformed_rect(l->ui, box, st->bg, st);
  7082. } else if (rtl || rtr || rbr || rbl) {
  7083. if (st->has_bg) {
  7084. int bw = st->border_w[0];
  7085. if (bw > 0 && !st->border_t[0] &&
  7086. st->border_c[0] != st->bg &&
  7087. box.w > bw * 2 && box.h > bw * 2) {
  7088. struct ngui_rect inner = {
  7089. box.x + bw, box.y + bw,
  7090. box.w - bw * 2, box.h - bw * 2
  7091. };
  7092. int itl = rtl > bw ? rtl - bw : 0;
  7093. int itr = rtr > bw ? rtr - bw : 0;
  7094. int ibr = rbr > bw ? rbr - bw : 0;
  7095. int ibl = rbl > bw ? rbl - bw : 0;
  7096. ngui_fill_round_rect(l->ui, box, rtl,
  7097. rtr, rbr, rbl,
  7098. st->border_c[0]);
  7099. ngui_fill_round_rect(l->ui, inner,
  7100. itl, itr, ibr,
  7101. ibl, st->bg);
  7102. } else {
  7103. ngui_fill_round_rect(l->ui, box, rtl,
  7104. rtr, rbr, rbl,
  7105. st->bg);
  7106. }
  7107. } else if (st->border_w[0] && !st->border_t[0]) {
  7108. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  7109. rbl, st->border_w[0],
  7110. st->border_c[0]);
  7111. }
  7112. /* Rounded boxes paint their background image too
  7113. * (app icons are rounded squares), kept inside the
  7114. * corner arcs. */
  7115. if (st->bg_image)
  7116. draw_bg_image_round(l, box, node, st, rtl, rtr,
  7117. rbr, rbl);
  7118. } else {
  7119. if (st->has_bg)
  7120. ngui_fill_rect(l->ui, box, st->bg);
  7121. if (st->bg_image)
  7122. draw_bg_image(l, box, node, st);
  7123. if (st->border_w[0] || st->border_w[1] ||
  7124. st->border_w[2] || st->border_w[3])
  7125. draw_border_box(l->ui, box, st);
  7126. }
  7127. }
  7128. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  7129. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  7130. content_w, img_dh);
  7131. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  7132. l->ui && l->ui->nclip < 4) {
  7133. clip_rect.x = l0 + bl;
  7134. clip_rect.y = top + bt;
  7135. clip_rect.w = (r0 - l0) - bl - br;
  7136. clip_rect.h = (int)block_h[node] - bt - bb;
  7137. if (clip_rect.w > 0 && clip_rect.h > 0) {
  7138. ngui_push_clip(l->ui, clip_rect);
  7139. clip_pushed = 1;
  7140. }
  7141. }
  7142. l->left = l0 + bl + pl;
  7143. l->right = l->left + content_w;
  7144. if (l->right < l->left + 8)
  7145. l->right = l->left + 8;
  7146. l->align = st->align;
  7147. l->line_left = l->left;
  7148. l->line_right = l->right;
  7149. l->y = top + bt + pt;
  7150. if (doc.nodes[node].tag == BR_TAG_HR) {
  7151. if (l->draw)
  7152. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  7153. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  7154. l->y += 8;
  7155. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  7156. int vw = l->right - l->left;
  7157. int vh;
  7158. if (doc.nodes[node].width_pct)
  7159. vw = vw * doc.nodes[node].width_attr / 100;
  7160. else if (doc.nodes[node].width_attr)
  7161. vw = doc.nodes[node].width_attr;
  7162. if (vw > l->right - l->left)
  7163. vw = l->right - l->left;
  7164. if (vw < 8)
  7165. vw = 8;
  7166. vh = vw * 9 / 16;
  7167. if (vh > 240)
  7168. vh = 240;
  7169. if (vh < 80)
  7170. vh = 80;
  7171. if (l->draw) {
  7172. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  7173. vw, vh}, 0xD69A);
  7174. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  7175. vw, vh}, 0x8410);
  7176. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  7177. 0x4208);
  7178. }
  7179. l->y += vh + 4;
  7180. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  7181. int dw, dh, cw = l->right - l->left;
  7182. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  7183. if (l->draw && l->y < page_rect.y + page_rect.h &&
  7184. l->y + dh > page_rect.y)
  7185. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  7186. l->y += dh;
  7187. } else {
  7188. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  7189. !st->no_bullet) {
  7190. char *m = li_marker[node];
  7191. if (!m[0]) {
  7192. unsigned int parent = doc.nodes[node].parent;
  7193. int style = st->list_style;
  7194. int idx = parent ? list_index(parent, node) : 1;
  7195. if (style == BR_LIST_AUTO)
  7196. style = (parent &&
  7197. doc.nodes[parent].tag ==
  7198. BR_TAG_OL) ?
  7199. BR_LIST_DECIMAL : BR_LIST_DISC;
  7200. list_marker_text(m, sizeof(li_marker[node]),
  7201. style, idx);
  7202. }
  7203. if (l->draw && m[0]) {
  7204. int mw = (int)ngui_text_width_ui(l->ui, m);
  7205. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  7206. st->color);
  7207. }
  7208. }
  7209. /* This box's definite content height, for its children's
  7210. * percentage heights. */
  7211. if (doc.nodes[node].tag == BR_TAG_HTML ||
  7212. doc.nodes[node].tag == BR_TAG_BODY)
  7213. l->cb_h = layout_view_h;
  7214. else if (st->height_kind == 1)
  7215. l->cb_h = (int)st->height -
  7216. (st->box_sizing ? deco_h : 0);
  7217. else if (st->height_kind == 2 && parent_cb_h > 0)
  7218. l->cb_h = parent_cb_h * (int)st->height / 100 -
  7219. (st->box_sizing ? deco_h : 0);
  7220. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  7221. l->cb_h = content_w * (int)st->aspect_h /
  7222. (int)st->aspect_w;
  7223. else
  7224. l->cb_h = 0;
  7225. if (l->cb_h < 0)
  7226. l->cb_h = 0;
  7227. if (doc.nodes[node].tag == BR_TAG_TR)
  7228. layout_table_row(l, node, st, depth + 1, link);
  7229. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  7230. table_has_rowspan(node))
  7231. layout_table(l, node, st, depth + 1, link);
  7232. else if (st->grid_auto)
  7233. layout_grid_auto(l, node, st, depth + 1, link);
  7234. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  7235. st->grid_gap > 0)
  7236. layout_grid_children(l, node, st, depth + 1, link);
  7237. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  7238. flex_wants_row(node, st))
  7239. layout_flex_children(l, node, st, depth + 1, link);
  7240. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  7241. st->align_items == 1) {
  7242. /* align-items: center in a column: the items' lines
  7243. * (an app card's icon and label) are centred; a child
  7244. * with its own text-align keeps it. */
  7245. struct br_style cst = *st;
  7246. cst.align = BR_ALIGN_CENTER;
  7247. l->align = BR_ALIGN_CENTER;
  7248. layout_children(l, node, &cst, depth + 1, link);
  7249. } else
  7250. layout_children(l, node, st, depth + 1, link);
  7251. l->cb_h = parent_cb_h;
  7252. }
  7253. flush_line(l);
  7254. if (clip_pushed)
  7255. ngui_pop_clip(l->ui);
  7256. if (l->float_active) {
  7257. if (l->y < l->float_bottom)
  7258. l->y = l->float_bottom;
  7259. l->float_active = 0;
  7260. }
  7261. if (doc.nodes[node].tag == BR_TAG_IMG) {
  7262. content_h = img_dh;
  7263. } else if (st->height_kind == 2 &&
  7264. doc.nodes[node].tag != BR_TAG_HTML &&
  7265. doc.nodes[node].tag != BR_TAG_BODY) {
  7266. /* A percentage of the containing block's definite height, or
  7267. * auto when it has none (it used to resolve against the
  7268. * width). The result is a minimum: without scrollable inner
  7269. * boxes, an app shell's height:100%; overflow:hidden column
  7270. * would otherwise clip everything past the first screen. */
  7271. int auto_h = l->y - (top + bt + pt);
  7272. content_h = parent_cb_h > 0 ?
  7273. parent_cb_h * (int)st->height / 100 -
  7274. (st->box_sizing ? deco_h : 0) : 0;
  7275. if (content_h < auto_h)
  7276. content_h = auto_h;
  7277. } else if (st->height_kind &&
  7278. !((doc.nodes[node].tag == BR_TAG_HTML ||
  7279. doc.nodes[node].tag == BR_TAG_BODY) &&
  7280. st->height_kind == 2)) {
  7281. content_h = style_height_px(st, cbw);
  7282. if (st->box_sizing)
  7283. content_h -= deco_h;
  7284. } else {
  7285. /* Percentage heights on html/body resolve against the
  7286. * viewport, but their content still defines the document
  7287. * scroll height. Treating them as auto avoids collapsing
  7288. * the measured page to the containing block width. */
  7289. content_h = l->y - (top + bt + pt);
  7290. /* aspect-ratio: the preferred height of an auto-height box
  7291. * (Tailwind aspect-video image frames); content can still
  7292. * make it taller, as with min-height: auto. */
  7293. if (st->aspect_w && st->aspect_h && content_w > 0) {
  7294. int ah = content_w * (int)st->aspect_h /
  7295. (int)st->aspect_w;
  7296. if (content_h < ah)
  7297. content_h = ah;
  7298. }
  7299. }
  7300. if (content_h < 0)
  7301. content_h = 0;
  7302. if (st->max_height_kind) {
  7303. int mh = st->max_height_kind == 3 ?
  7304. cbw * st->max_height_calc_pct / 100 +
  7305. st->max_height_calc_px :
  7306. css_size(st->max_height_kind, st->max_height, cbw);
  7307. int max_box = st->box_sizing ? mh : mh + deco_h;
  7308. if (content_h + deco_h > max_box)
  7309. content_h = max_box - deco_h;
  7310. }
  7311. if (st->min_height_kind &&
  7312. !((doc.nodes[node].tag == BR_TAG_HTML ||
  7313. doc.nodes[node].tag == BR_TAG_BODY) &&
  7314. st->min_height_kind == 2)) {
  7315. int mh = st->min_height_kind == 3 ?
  7316. cbw * st->min_height_calc_pct / 100 +
  7317. st->min_height_calc_px :
  7318. css_size(st->min_height_kind, st->min_height, cbw);
  7319. int min_box = st->box_sizing ? mh : mh + deco_h;
  7320. if (content_h + deco_h < min_box)
  7321. content_h = min_box - deco_h;
  7322. }
  7323. if (content_h < 0)
  7324. content_h = 0;
  7325. box_h = deco_h + content_h;
  7326. if (box_h < 0)
  7327. box_h = 0;
  7328. l->y = (shifted ? normal_top : top) + box_h;
  7329. if (node < BR_MAX_NODES) {
  7330. layout_boxes[node].x = l0;
  7331. layout_boxes[node].y = top;
  7332. layout_boxes[node].w = r0 - l0;
  7333. layout_boxes[node].h = box_h;
  7334. layout_boxes[node].valid = r0 > l0;
  7335. }
  7336. l->left = old_left;
  7337. l->right = old_right;
  7338. l->align = old_align;
  7339. l->y += mp_px(st, 2, cbw);
  7340. if (!l->draw) {
  7341. if (box_h > 65535)
  7342. box_h = 65535;
  7343. block_h[node] = (unsigned short)box_h;
  7344. block_top[node] = (unsigned short)(top < 0 ? 0 :
  7345. top > 65535 ? 65535 : top);
  7346. }
  7347. if (positioned) {
  7348. l->y = flow_y;
  7349. l->left = flow_left;
  7350. l->right = flow_right;
  7351. }
  7352. l->parent_top = saved_parent_top;
  7353. l->cb_left = saved_cb_left;
  7354. l->cb_right = saved_cb_right;
  7355. l->cb_top = saved_cb_top;
  7356. }
  7357. static int text_node_blank(const struct br_node *nd)
  7358. {
  7359. const char *t = doc.text + nd->text_off;
  7360. unsigned int i;
  7361. for (i = 0; i < nd->text_len; i++)
  7362. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  7363. t[i] != '\r')
  7364. return 0;
  7365. return 1;
  7366. }
  7367. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  7368. * text/image widths in the subtree, plus padding and margins. This keeps
  7369. * Bootstrap's floated nav items on one line instead of giving each the whole
  7370. * row. */
  7371. static int text_space(char c)
  7372. {
  7373. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  7374. }
  7375. static int intrinsic_width(struct ngui *ui, unsigned int node,
  7376. const struct br_style *pst, int depth, int base)
  7377. {
  7378. unsigned int c;
  7379. int line_w = 0, max_w = 0;
  7380. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  7381. if (depth > 32)
  7382. return 0;
  7383. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7384. struct br_node *nd = &doc.nodes[c];
  7385. struct br_style cs;
  7386. if (nd->type == BR_NODE_TEXT) {
  7387. const char *t = doc.text + nd->text_off;
  7388. unsigned int tn = nd->text_len;
  7389. if (doc.nodes[node].tag == BR_TAG_PRE) {
  7390. line_w += (int)face_text_width(ui, pst, t, tn);
  7391. } else {
  7392. unsigned int ti = 0;
  7393. int first = 1;
  7394. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  7395. int sp = (int)face_text_width(ui, pst, " ", 1);
  7396. while (ti < tn) {
  7397. unsigned int ts;
  7398. while (ti < tn && text_space(t[ti]))
  7399. ti++;
  7400. ts = ti;
  7401. while (ti < tn && !text_space(t[ti]))
  7402. ti++;
  7403. if (ti == ts)
  7404. break;
  7405. if (!first || lead)
  7406. line_w += sp;
  7407. lead = 0;
  7408. line_w += (int)face_text_width(ui, pst,
  7409. t + ts, ti - ts);
  7410. first = 0;
  7411. }
  7412. }
  7413. continue;
  7414. }
  7415. br_style_for(&doc, c, pst, &cs);
  7416. if (cs.display == BR_DISPLAY_NONE)
  7417. continue;
  7418. if (nd->tag == BR_TAG_BR) {
  7419. if (line_w > max_w)
  7420. max_w = line_w;
  7421. line_w = 0;
  7422. continue;
  7423. }
  7424. if (nd->tag == BR_TAG_IMG) {
  7425. /* Measure the image as layout will draw it: a CSS or
  7426. * attribute height keeps the intrinsic aspect ratio, and
  7427. * a CSS width overrides the native pixel width. Bootstrap
  7428. * sizes the Cloudron logo with height:40px only. */
  7429. int idx = nd->img_index;
  7430. int iw = 0, ih = 0;
  7431. if (idx >= 0 && idx < image_count &&
  7432. images[idx].state == 1) {
  7433. iw = (int)images[idx].native_w;
  7434. ih = (int)images[idx].native_h;
  7435. if (iw <= 0 || ih <= 0) {
  7436. iw = (int)images[idx].img.w;
  7437. ih = (int)images[idx].img.h;
  7438. }
  7439. }
  7440. if (cs.width_kind) {
  7441. int ww = style_width_px(&cs, base);
  7442. line_w += ww > 0 ? ww : 64;
  7443. } else if (nd->width_attr) {
  7444. line_w += nd->width_attr;
  7445. } else if (nd->height_attr && iw && ih) {
  7446. line_w += iw * (int)nd->height_attr / ih;
  7447. } else if (cs.height_kind && iw && ih) {
  7448. int hh = style_height_px(&cs, base);
  7449. line_w += hh > 0 ? iw * hh / ih : iw;
  7450. } else if (iw) {
  7451. line_w += iw;
  7452. } else {
  7453. line_w += 64;
  7454. }
  7455. continue;
  7456. }
  7457. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  7458. nd->tag == BR_TAG_TEXTAREA) &&
  7459. !s_eq(br_type(&doc, c), "hidden")) {
  7460. /* Form controls are replaced: CSS width applies even
  7461. * when they are inline (add_form_run's sizes). */
  7462. int fw = cs.width_kind ? style_width_px(&cs, base) :
  7463. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  7464. if (s_eq(br_type(&doc, c), "checkbox") ||
  7465. s_eq(br_type(&doc, c), "radio"))
  7466. fw = 16;
  7467. line_w += (fw > 0 ? fw : 120) +
  7468. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  7469. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  7470. continue;
  7471. }
  7472. if (nd->tag == BR_TAG_SVG) {
  7473. /* A replaced element: its own size, like add_svg_run()
  7474. * (its path children have no width). */
  7475. int sw, sh, sb = cs.width_kind ?
  7476. style_width_px(&cs, base) : base;
  7477. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  7478. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  7479. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  7480. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7481. line_w += sw;
  7482. } else {
  7483. if (line_w > max_w)
  7484. max_w = line_w;
  7485. line_w = 0;
  7486. if (sw > max_w)
  7487. max_w = sw;
  7488. }
  7489. continue;
  7490. }
  7491. {
  7492. int cw = mp_px(&cs, 7, base) +
  7493. mp_px(&cs, 5, base) +
  7494. mp_px(&cs, 3, base) +
  7495. mp_px(&cs, 1, base) +
  7496. cs.border_w[1] + cs.border_w[3];
  7497. /* width/height do not apply to non-replaced inline
  7498. * boxes. The tagesschau home label is an inline span
  7499. * with width:1px for the mobile icon-only header; using
  7500. * that width made the whole subnav collapse to a
  7501. * one-character column. */
  7502. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  7503. cw += cs.width_kind == 1 ? cs.width :
  7504. style_width_px(&cs, base);
  7505. else
  7506. cw += intrinsic_width(ui, c, &cs, depth + 1,
  7507. base);
  7508. if (flex_row || cs.float_left ||
  7509. cs.display == BR_DISPLAY_INLINE ||
  7510. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  7511. line_w += cw;
  7512. } else {
  7513. if (line_w > max_w)
  7514. max_w = line_w;
  7515. line_w = 0;
  7516. if (cw > max_w)
  7517. max_w = cw;
  7518. }
  7519. }
  7520. if (line_w > 4096 || max_w > 4096)
  7521. break;
  7522. }
  7523. return line_w > max_w ? line_w : max_w;
  7524. }
  7525. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  7526. * the main user: .row > .col-md-* with float:left and a percentage width.
  7527. * Each column is laid out with its own left/right edge and the row advances
  7528. * to the tallest column. Returns the first child not consumed. */
  7529. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  7530. const struct br_style *pst, int depth,
  7531. unsigned short link)
  7532. {
  7533. unsigned int n = first;
  7534. int row_left = l->left, row_right = l->right;
  7535. int row_top, row_bottom, xl, xr, any = 0;
  7536. int fl_left = row_left, fl_right = row_right, fl_bottom;
  7537. flush_line(l);
  7538. row_top = l->y;
  7539. row_bottom = l->y;
  7540. fl_bottom = row_top;
  7541. xl = row_left;
  7542. xr = row_right;
  7543. while (n) {
  7544. struct br_node *nd = &doc.nodes[n];
  7545. struct br_style cs;
  7546. unsigned short lk = link;
  7547. int colw, right;
  7548. if (nd->type == BR_NODE_TEXT) {
  7549. if (text_node_blank(nd)) {
  7550. n = nd->next;
  7551. continue;
  7552. }
  7553. break;
  7554. }
  7555. br_style_for(&doc, n, pst, &cs);
  7556. if (cs.display == BR_DISPLAY_NONE) {
  7557. n = nd->next;
  7558. continue;
  7559. }
  7560. /* A float blockifies its box: Bootstrap floats inline
  7561. * anchors too (the navbar brand and its text links), and
  7562. * their padding must be honoured. */
  7563. if (!cs.float_left)
  7564. break;
  7565. if (nd->tag == BR_TAG_A && nd->href_off)
  7566. lk = (unsigned short)n;
  7567. right = cs.float_left == 2;
  7568. if (cs.width_kind == 2 || cs.width_kind == 3) {
  7569. colw = style_width_px(&cs, row_right - row_left);
  7570. } else if (cs.width_kind == 1) {
  7571. colw = (int)cs.width;
  7572. } else {
  7573. int base = row_right - row_left;
  7574. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  7575. mp_px(&cs, 7, base) +
  7576. mp_px(&cs, 5, base) +
  7577. mp_px(&cs, 3, base) +
  7578. mp_px(&cs, 1, base);
  7579. if (colw < 8)
  7580. colw = 8;
  7581. }
  7582. if (colw < 8)
  7583. colw = 8;
  7584. if (colw > row_right - row_left)
  7585. colw = row_right - row_left;
  7586. /* The float column width is already resolved. */
  7587. cs.width_kind = 0;
  7588. cs.max_width_kind = 0;
  7589. if (right) {
  7590. if (any && xr - colw < xl) {
  7591. row_top = row_bottom;
  7592. row_bottom = row_top;
  7593. xl = row_left;
  7594. xr = row_right;
  7595. }
  7596. if (xr - colw < xl)
  7597. colw = xr - xl;
  7598. if (colw < 8)
  7599. colw = 8;
  7600. l->left = xr - colw;
  7601. if (l->left < row_left)
  7602. l->left = row_left;
  7603. l->right = xr;
  7604. xr = l->left;
  7605. if (xr < fl_right)
  7606. fl_right = xr;
  7607. } else {
  7608. if (any && xl + colw > xr) {
  7609. row_top = row_bottom;
  7610. row_bottom = row_top;
  7611. xl = row_left;
  7612. xr = row_right;
  7613. }
  7614. l->left = xl;
  7615. l->right = xl + colw;
  7616. xl += colw;
  7617. if (xl > fl_left)
  7618. fl_left = xl;
  7619. }
  7620. if (l->right < l->left + 8)
  7621. l->right = l->left + 8;
  7622. l->y = row_top;
  7623. l->line_x = l->left;
  7624. l->run_x = l->left;
  7625. l->line_y = l->y;
  7626. l->line_h = 0;
  7627. l->nruns = 0;
  7628. l->space_pending = 0;
  7629. l->align = cs.align;
  7630. layout_block(l, n, &cs, depth + 1, lk);
  7631. if (l->y > row_bottom)
  7632. row_bottom = l->y;
  7633. if (l->y > fl_bottom)
  7634. fl_bottom = l->y;
  7635. any = 1;
  7636. n = nd->next;
  7637. }
  7638. l->left = row_left;
  7639. l->right = row_right;
  7640. if (n && any) {
  7641. struct br_node *nd = &doc.nodes[n];
  7642. int inline_next = 0;
  7643. if (nd->type == BR_NODE_TEXT) {
  7644. inline_next = 1;
  7645. } else if (nd->type == BR_NODE_ELEM) {
  7646. struct br_style cs;
  7647. br_style_for(&doc, n, pst, &cs);
  7648. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  7649. cs.display != BR_DISPLAY_NONE &&
  7650. !br_tag_is_block(nd->tag);
  7651. }
  7652. if (inline_next) {
  7653. if (l->float_active) {
  7654. if (l->float_left > fl_left)
  7655. fl_left = l->float_left;
  7656. if (l->float_right < fl_right)
  7657. fl_right = l->float_right;
  7658. if (l->float_bottom > fl_bottom)
  7659. fl_bottom = l->float_bottom;
  7660. }
  7661. l->float_active = 1;
  7662. l->float_left = fl_left;
  7663. l->float_right = fl_right;
  7664. l->float_bottom = fl_bottom;
  7665. l->y = row_top;
  7666. } else {
  7667. l->float_active = 0;
  7668. l->y = row_bottom;
  7669. }
  7670. } else {
  7671. l->float_active = 0;
  7672. l->y = row_bottom;
  7673. }
  7674. l->line_x = l->left;
  7675. l->run_x = l->left;
  7676. l->line_left = l->left;
  7677. l->line_right = l->right;
  7678. l->line_y = l->y;
  7679. l->line_h = 0;
  7680. l->nruns = 0;
  7681. l->space_pending = 0;
  7682. return n;
  7683. }
  7684. static int flex_item_width(struct lay *l, unsigned int n,
  7685. const struct br_style *cs, int avail)
  7686. {
  7687. struct br_node *nd = &doc.nodes[n];
  7688. (void)l;
  7689. int w;
  7690. if (cs->width_kind == 2 || cs->width_kind == 3)
  7691. w = style_width_px(cs, avail);
  7692. else if (cs->width_kind == 1)
  7693. w = (int)cs->width;
  7694. else if (nd->tag == BR_TAG_IMG) {
  7695. int idx = nd->img_index;
  7696. if (idx >= 0 && idx < image_count &&
  7697. images[idx].state == 1)
  7698. w = (int)images[idx].img.w;
  7699. else if (nd->width_attr)
  7700. w = (int)nd->width_attr;
  7701. else
  7702. w = 64;
  7703. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  7704. nd->tag == BR_TAG_TEXTAREA) {
  7705. /* A control has no content to measure: its default size
  7706. * (a search field in a filter bar). */
  7707. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  7708. } else {
  7709. w = intrinsic_width(l->ui, n, cs, 0, avail);
  7710. }
  7711. /* Explicit widths are content-box sizes; the flex item's outer width
  7712. * must include padding, borders and margins. */
  7713. w += mp_px(cs, 7, avail);
  7714. w += mp_px(cs, 5, avail);
  7715. w += mp_px(cs, 3, avail);
  7716. w += mp_px(cs, 1, avail);
  7717. w += cs->border_w[1] + cs->border_w[3];
  7718. if (w < 24)
  7719. w = 24;
  7720. if (w > avail)
  7721. w = avail;
  7722. return w;
  7723. }
  7724. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  7725. int depth);
  7726. /* An inline child of a text-only inline-block: the same test minus the
  7727. * display check (an inline <span> may have padding/background in CSS, but
  7728. * the inline path paints those for spans anyway). */
  7729. static int inline_block_flows_inline(unsigned int node,
  7730. const struct br_style *cs, int depth)
  7731. {
  7732. unsigned int c;
  7733. if (depth > 3 || cs->pos)
  7734. return 0;
  7735. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7736. const struct br_node *nd = &doc.nodes[c];
  7737. struct br_style ch;
  7738. if (nd->type != BR_NODE_ELEM)
  7739. continue;
  7740. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  7741. br_tag_is_block(nd->tag))
  7742. return 0;
  7743. br_style_for(&doc, c, cs, &ch);
  7744. if (ch.display == BR_DISPLAY_NONE)
  7745. continue;
  7746. if (ch.display != BR_DISPLAY_INLINE ||
  7747. !inline_block_flows_inline(c, &ch, depth + 1))
  7748. return 0;
  7749. }
  7750. return 1;
  7751. }
  7752. /* An inline-block that is only text in a line (a <time> in a byline, a
  7753. * label) with no box of its own -- no size, background, border or padding
  7754. * -- lays out exactly like an inline element, so it stays in the text line
  7755. * instead of ending it. Boxes with any of those keep the row path. */
  7756. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  7757. int depth)
  7758. {
  7759. unsigned int c;
  7760. int i;
  7761. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  7762. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  7763. cs->pos || depth > 3)
  7764. return 0;
  7765. for (i = 0; i < 4; i++)
  7766. if (cs->border_w[i])
  7767. return 0;
  7768. for (i = 4; i < 8; i++)
  7769. if (mp_px(cs, i, 0) > 0)
  7770. return 0;
  7771. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7772. const struct br_node *nd = &doc.nodes[c];
  7773. struct br_style ch;
  7774. if (nd->type != BR_NODE_ELEM)
  7775. continue;
  7776. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  7777. br_tag_is_block(nd->tag))
  7778. return 0;
  7779. br_style_for(&doc, c, cs, &ch);
  7780. if (ch.display == BR_DISPLAY_NONE)
  7781. continue;
  7782. if (ch.display != BR_DISPLAY_INLINE ||
  7783. !inline_block_flows_inline(c, &ch, depth + 1))
  7784. return 0;
  7785. }
  7786. return 1;
  7787. }
  7788. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  7789. * on one line, not one full-width block each. Place intrinsic widths from
  7790. * left to right and wrap when the row is full. */
  7791. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7792. const struct br_style *pst, int depth,
  7793. unsigned short link)
  7794. {
  7795. unsigned int n = first;
  7796. int row_left = l->left, row_right = l->right;
  7797. int avail = row_right - row_left;
  7798. int x = row_left, y = l->y, row_h = 0, any = 0;
  7799. /* Each box sets l->align from its own style; the text after the row
  7800. * must keep the container's (a centred .fa-fw icon centred the menu
  7801. * label that followed it). */
  7802. unsigned char row_align = l->align;
  7803. flush_line(l);
  7804. y = l->y;
  7805. while (n) {
  7806. struct br_node *nd = &doc.nodes[n];
  7807. struct br_style cs;
  7808. unsigned short lk = link;
  7809. int colw, h;
  7810. if (nd->type == BR_NODE_TEXT) {
  7811. if (!text_node_blank(nd))
  7812. break;
  7813. if (any)
  7814. x += 4;
  7815. n = nd->next;
  7816. continue;
  7817. }
  7818. br_style_for(&doc, n, pst, &cs);
  7819. if (cs.display == BR_DISPLAY_NONE) {
  7820. n = nd->next;
  7821. continue;
  7822. }
  7823. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  7824. break;
  7825. if (nd->tag == BR_TAG_A && nd->href_off)
  7826. lk = (unsigned short)n;
  7827. colw = flex_item_width(l, n, &cs, avail);
  7828. /* A few pixels of slack keep a single long token (boot.S)
  7829. * from wrapping at the exact content width. */
  7830. colw += 8;
  7831. if (colw > avail)
  7832. colw = avail;
  7833. cs.width_kind = 0;
  7834. cs.max_width_kind = 0;
  7835. if (any && x + colw > row_right) {
  7836. y += row_h + 2;
  7837. x = row_left;
  7838. row_h = 0;
  7839. any = 0;
  7840. }
  7841. if (any && x > row_left)
  7842. x += 4;
  7843. l->left = x;
  7844. l->right = x + colw;
  7845. if (l->right < l->left + 8)
  7846. l->right = l->left + 8;
  7847. l->y = y;
  7848. l->line_x = l->left;
  7849. l->run_x = l->left;
  7850. l->line_y = l->y;
  7851. l->line_h = 0;
  7852. l->nruns = 0;
  7853. l->space_pending = 0;
  7854. l->align = cs.align;
  7855. layout_block(l, n, &cs, depth + 1, lk);
  7856. h = l->y - y;
  7857. if (h > row_h)
  7858. row_h = h;
  7859. x += colw;
  7860. any = 1;
  7861. n = nd->next;
  7862. }
  7863. if (any)
  7864. y += row_h;
  7865. l->left = row_left;
  7866. l->right = row_right;
  7867. l->align = row_align;
  7868. l->y = y;
  7869. l->line_x = l->left;
  7870. l->run_x = l->left;
  7871. l->line_y = l->y;
  7872. l->line_h = 0;
  7873. l->nruns = 0;
  7874. l->space_pending = 0;
  7875. return n;
  7876. }
  7877. struct flex_item {
  7878. unsigned int node;
  7879. unsigned short link;
  7880. int w;
  7881. };
  7882. static void layout_flex_children(struct lay *l, unsigned int parent,
  7883. const struct br_style *pst, int depth,
  7884. unsigned short link)
  7885. {
  7886. struct flex_item it[32];
  7887. unsigned int c;
  7888. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  7889. int row_left = l->left, row_right = l->right;
  7890. int avail = row_right - row_left;
  7891. int idx, row_top;
  7892. unsigned char row_align = l->align;
  7893. if (avail < 160 || depth > 48) {
  7894. layout_children(l, parent, pst, depth, link);
  7895. return;
  7896. }
  7897. /* If direct text is not just whitespace, normal block flow handles it
  7898. * better than pretending it is a flex item. */
  7899. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7900. struct br_node *nd = &doc.nodes[c];
  7901. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7902. layout_children(l, parent, pst, depth, link);
  7903. return;
  7904. }
  7905. }
  7906. for (c = doc.nodes[parent].first;
  7907. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  7908. c = doc.nodes[c].next) {
  7909. struct br_node *nd = &doc.nodes[c];
  7910. struct br_style cs;
  7911. if (nd->type == BR_NODE_TEXT)
  7912. continue;
  7913. br_style_for(&doc, c, pst, &cs);
  7914. if (cs.display == BR_DISPLAY_NONE)
  7915. continue;
  7916. it[nitem].node = c;
  7917. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  7918. (unsigned short)c : link;
  7919. it[nitem].w = 0;
  7920. if (cs.flex_grow && !cs.width_kind)
  7921. grow_count++;
  7922. else
  7923. fixed += flex_item_width(l, c, &cs, avail);
  7924. nitem++;
  7925. }
  7926. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  7927. if (grow_w < 96)
  7928. grow_w = 96;
  7929. for (idx = 0; idx < nitem; idx++) {
  7930. struct br_style cs;
  7931. br_style_for(&doc, it[idx].node, pst, &cs);
  7932. if (cs.flex_grow && !cs.width_kind)
  7933. it[idx].w = grow_w;
  7934. else
  7935. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  7936. if (it[idx].w > avail)
  7937. it[idx].w = avail;
  7938. if (it[idx].w < 8)
  7939. it[idx].w = 8;
  7940. }
  7941. row_top = l->y;
  7942. idx = 0;
  7943. while (idx < nitem) {
  7944. int start = idx, count = 0, row_w = 0;
  7945. int free_w, x, extra = 0, row_h = 0, k;
  7946. while (idx < nitem) {
  7947. int add = it[idx].w + (count ? gap : 0);
  7948. /* CSS default is nowrap; only flex-wrap: wrap (1)
  7949. * starts a new row. */
  7950. if (count && pst->flex_wrap == 1 &&
  7951. row_w + add > avail)
  7952. break;
  7953. row_w += add;
  7954. count++;
  7955. idx++;
  7956. }
  7957. if (!count) {
  7958. count = 1;
  7959. row_w = it[start].w;
  7960. idx = start + 1;
  7961. }
  7962. free_w = avail - row_w;
  7963. if (free_w < 0)
  7964. free_w = 0;
  7965. x = row_left;
  7966. if (pst->justify == 1) {
  7967. x += free_w / 2;
  7968. } else if (pst->justify == 2) {
  7969. x += free_w;
  7970. } else if (pst->justify == 3) {
  7971. extra = count > 1 ? free_w / (count - 1) : 0;
  7972. } else if (pst->justify == 4) {
  7973. extra = count ? free_w / count : 0;
  7974. x += extra / 2;
  7975. } else if (pst->justify == 5) {
  7976. extra = count ? free_w / (count + 1) : 0;
  7977. x += extra;
  7978. }
  7979. for (k = 0; k < count; k++) {
  7980. int node = (int)it[start + k].node;
  7981. int h = block_h[node];
  7982. if (h > row_h)
  7983. row_h = h;
  7984. }
  7985. if (pst->height_kind) {
  7986. int hh = style_height_px(pst, avail);
  7987. if (hh > row_h)
  7988. row_h = hh;
  7989. }
  7990. for (k = 0; k < count; k++) {
  7991. struct br_style cs;
  7992. int node = (int)it[start + k].node;
  7993. int yoff = 0;
  7994. br_style_for(&doc, node, pst, &cs);
  7995. cs.width_kind = 0;
  7996. cs.max_width_kind = 0;
  7997. if (l->draw && pst->align_items &&
  7998. row_h > block_h[node]) {
  7999. if (pst->align_items == 1)
  8000. yoff = (row_h - block_h[node]) / 2;
  8001. else if (pst->align_items == 2)
  8002. yoff = row_h - block_h[node];
  8003. }
  8004. l->left = x;
  8005. l->right = x + it[start + k].w;
  8006. if (l->right < l->left + 8)
  8007. l->right = l->left + 8;
  8008. l->y = row_top + yoff;
  8009. l->line_x = l->left;
  8010. l->run_x = l->left;
  8011. l->line_y = l->y;
  8012. l->line_h = 0;
  8013. l->nruns = 0;
  8014. l->space_pending = 0;
  8015. l->align = cs.align;
  8016. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  8017. if (!l->draw) {
  8018. int h = l->y - row_top;
  8019. if (h > row_h)
  8020. row_h = h;
  8021. }
  8022. x += it[start + k].w;
  8023. if (k + 1 < count)
  8024. x += gap + extra;
  8025. }
  8026. row_top += row_h;
  8027. }
  8028. l->left = row_left;
  8029. l->right = row_right;
  8030. l->align = row_align;
  8031. l->y = row_top;
  8032. l->line_x = l->left;
  8033. l->run_x = l->left;
  8034. l->line_y = l->y;
  8035. l->line_h = 0;
  8036. l->nruns = 0;
  8037. l->space_pending = 0;
  8038. }
  8039. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  8040. * plus the grid-area hints used by site shells (site notice/footer full
  8041. * width, column-start left, page-content right). Anything more elaborate
  8042. * falls back to normal block flow. */
  8043. static int grid_track_width(unsigned char kind, unsigned short val,
  8044. int avail, int other)
  8045. {
  8046. if (kind == 2)
  8047. return avail * (int)val / 100;
  8048. if (kind == 1)
  8049. return val;
  8050. return other;
  8051. }
  8052. static void layout_grid_children(struct lay *l, unsigned int parent,
  8053. const struct br_style *pst, int depth,
  8054. unsigned short link)
  8055. {
  8056. unsigned int n;
  8057. int row_left = l->left, row_right = l->right;
  8058. int avail = row_right - row_left;
  8059. int gap = pst->grid_gap;
  8060. int track_total = avail - gap;
  8061. int col0, col1, x0, x1;
  8062. int row_y, row_bottom, have_left = 0, have_right = 0;
  8063. unsigned int c;
  8064. if (avail < 32 || depth > 48)
  8065. return;
  8066. if (track_total < 16)
  8067. track_total = 16;
  8068. col0 = grid_track_width((unsigned char)(pst->width_kind),
  8069. pst->width, track_total, 0);
  8070. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  8071. pst->max_width, track_total, 0);
  8072. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  8073. int w0 = pst->width ? pst->width : 1;
  8074. int w1 = pst->max_width ? pst->max_width : 1;
  8075. col0 = track_total * w0 / (w0 + w1);
  8076. col1 = track_total - col0;
  8077. } else if (pst->width_kind == 3) {
  8078. col0 = track_total - col1;
  8079. if (col0 < 24)
  8080. col0 = 24;
  8081. } else if (pst->max_width_kind == 3) {
  8082. col1 = track_total - col0;
  8083. if (col1 < 24)
  8084. col1 = 24;
  8085. }
  8086. if (col0 < 24)
  8087. col0 = 24;
  8088. if (col1 < 24)
  8089. col1 = 24;
  8090. if (col0 + col1 > track_total) {
  8091. col1 = track_total - col0;
  8092. if (col1 < 24)
  8093. col1 = 24;
  8094. }
  8095. x0 = row_left;
  8096. x1 = row_left + col0 + gap;
  8097. /* Direct text makes a grid ambiguous; use block flow instead. */
  8098. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8099. struct br_node *nd = &doc.nodes[c];
  8100. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8101. layout_children(l, parent, pst, depth, link);
  8102. return;
  8103. }
  8104. }
  8105. row_y = row_bottom = l->y;
  8106. n = doc.nodes[parent].first;
  8107. while (n) {
  8108. struct br_node *nd = &doc.nodes[n];
  8109. struct br_style cs;
  8110. unsigned short lk = link;
  8111. int slot, x, w;
  8112. if (nd->type == BR_NODE_TEXT) {
  8113. n = nd->next;
  8114. continue;
  8115. }
  8116. br_style_for(&doc, n, pst, &cs);
  8117. if (cs.display == BR_DISPLAY_NONE) {
  8118. n = nd->next;
  8119. continue;
  8120. }
  8121. if (nd->tag == BR_TAG_A && nd->href_off)
  8122. lk = (unsigned short)n;
  8123. slot = cs.grid_slot;
  8124. if (!slot) {
  8125. if (!have_left)
  8126. slot = 2;
  8127. else if (!have_right)
  8128. slot = 3;
  8129. else
  8130. slot = 2;
  8131. }
  8132. if (slot == 1) {
  8133. if (have_left || have_right) {
  8134. row_y = row_bottom;
  8135. have_left = have_right = 0;
  8136. }
  8137. x = row_left;
  8138. w = avail;
  8139. } else if (slot == 2) {
  8140. if (have_left) {
  8141. row_y = row_bottom;
  8142. have_left = have_right = 0;
  8143. }
  8144. x = x0;
  8145. w = col0;
  8146. have_left = 1;
  8147. } else {
  8148. if (have_right) {
  8149. row_y = row_bottom;
  8150. have_left = have_right = 0;
  8151. }
  8152. x = x1;
  8153. w = col1;
  8154. have_right = 1;
  8155. }
  8156. cs.width_kind = 0;
  8157. cs.max_width_kind = 0;
  8158. l->left = x;
  8159. l->right = x + w;
  8160. if (l->right < l->left + 8)
  8161. l->right = l->left + 8;
  8162. l->y = row_y;
  8163. l->line_x = l->left;
  8164. l->run_x = l->left;
  8165. l->line_y = l->y;
  8166. l->line_h = 0;
  8167. l->nruns = 0;
  8168. l->space_pending = 0;
  8169. l->align = cs.align;
  8170. layout_block(l, n, &cs, depth + 1, lk);
  8171. if (l->y > row_bottom)
  8172. row_bottom = l->y;
  8173. n = nd->next;
  8174. }
  8175. l->left = row_left;
  8176. l->right = row_right;
  8177. l->y = row_bottom;
  8178. l->line_x = l->left;
  8179. l->run_x = l->left;
  8180. l->line_y = l->y;
  8181. l->line_h = 0;
  8182. l->nruns = 0;
  8183. l->space_pending = 0;
  8184. }
  8185. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  8186. * capped at four. Used by the project docs' card grids. A fixed
  8187. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  8188. static void layout_grid_auto(struct lay *l, unsigned int parent,
  8189. const struct br_style *pst, int depth,
  8190. unsigned short link)
  8191. {
  8192. unsigned int n, c;
  8193. int row_left = l->left, row_right = l->right;
  8194. int avail = row_right - row_left;
  8195. int gap = pst->grid_gap;
  8196. int minw = pst->width_kind == 1 ? pst->width : 200;
  8197. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  8198. if (avail < 32 || depth > 48) {
  8199. layout_children(l, parent, pst, depth, link);
  8200. return;
  8201. }
  8202. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8203. struct br_node *nd = &doc.nodes[c];
  8204. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8205. layout_children(l, parent, pst, depth, link);
  8206. return;
  8207. }
  8208. }
  8209. if (minw < 80)
  8210. minw = 80;
  8211. ncols = (avail + gap) / (minw + gap);
  8212. if (ncols < 1)
  8213. ncols = 1;
  8214. if (ncols > 4)
  8215. ncols = 4;
  8216. if (pst->grid_auto > BR_GRID_FIXED) {
  8217. /* grid-template-columns: repeat(N, 1fr) */
  8218. ncols = pst->grid_auto - BR_GRID_FIXED;
  8219. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  8220. ncols--;
  8221. }
  8222. colw = (avail - gap * (ncols - 1)) / ncols;
  8223. if (colw < 24)
  8224. colw = 24;
  8225. x = row_left;
  8226. n = doc.nodes[parent].first;
  8227. while (n) {
  8228. struct br_node *nd = &doc.nodes[n];
  8229. struct br_style cs;
  8230. unsigned short lk = link;
  8231. int h;
  8232. if (nd->type == BR_NODE_TEXT) {
  8233. n = nd->next;
  8234. continue;
  8235. }
  8236. br_style_for(&doc, n, pst, &cs);
  8237. if (cs.display == BR_DISPLAY_NONE) {
  8238. n = nd->next;
  8239. continue;
  8240. }
  8241. if (nd->tag == BR_TAG_A && nd->href_off)
  8242. lk = (unsigned short)n;
  8243. cs.width_kind = 0;
  8244. cs.max_width_kind = 0;
  8245. l->left = x;
  8246. l->right = x + colw;
  8247. if (l->right < l->left + 8)
  8248. l->right = l->left + 8;
  8249. l->y = y;
  8250. l->line_x = l->left;
  8251. l->run_x = l->left;
  8252. l->line_y = l->y;
  8253. l->line_h = 0;
  8254. l->nruns = 0;
  8255. l->space_pending = 0;
  8256. l->align = cs.align;
  8257. layout_block(l, n, &cs, depth + 1, lk);
  8258. h = l->y - y;
  8259. if (h > row_h)
  8260. row_h = h;
  8261. col++;
  8262. n = nd->next;
  8263. if (col == ncols) {
  8264. y += row_h + gap;
  8265. x = row_left;
  8266. row_h = 0;
  8267. col = 0;
  8268. } else {
  8269. x += colw + gap;
  8270. }
  8271. }
  8272. if (col)
  8273. y += row_h;
  8274. else if (y > start_y)
  8275. y -= gap;
  8276. l->left = row_left;
  8277. l->right = row_right;
  8278. l->y = y;
  8279. l->line_x = l->left;
  8280. l->run_x = l->left;
  8281. l->line_y = l->y;
  8282. l->line_h = 0;
  8283. l->nruns = 0;
  8284. l->space_pending = 0;
  8285. }
  8286. /* Column widths are the widest cell in each column across every row, so all
  8287. * rows line up. The table model is still deliberately basic: no colspan,
  8288. * border-collapse or percentage columns. */
  8289. static void table_columns(struct lay *l, unsigned int table,
  8290. const struct br_style *pst, int avail,
  8291. int *raw, int maxcols, int *out_cols,
  8292. int *out_total)
  8293. {
  8294. unsigned int r, c;
  8295. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  8296. int fixed[12];
  8297. for (c = 0; c < (unsigned int)maxcols; c++) {
  8298. raw[c] = 0;
  8299. fixed[c] = 0;
  8300. }
  8301. /* Intrinsic widths of single-column cells. */
  8302. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8303. struct br_node *rn = &doc.nodes[r];
  8304. int col = 0;
  8305. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8306. continue;
  8307. for (c = rn->first; c; c = doc.nodes[c].next) {
  8308. struct br_node *cn = &doc.nodes[c];
  8309. struct br_style cs;
  8310. int w, span;
  8311. if (cn->type != BR_NODE_ELEM ||
  8312. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  8313. continue;
  8314. span = cn->colspan ? cn->colspan : 1;
  8315. br_style_for(&doc, c, pst, &cs);
  8316. if (cs.display == BR_DISPLAY_NONE)
  8317. continue;
  8318. if (col + span > maxcols)
  8319. span = maxcols - col;
  8320. if (span < 1)
  8321. break;
  8322. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  8323. mp_px(&cs, 7, avail) +
  8324. mp_px(&cs, 5, avail) +
  8325. mp_px(&cs, 3, avail) +
  8326. mp_px(&cs, 1, avail) +
  8327. cs.border_w[0] + cs.border_w[1] +
  8328. cs.border_w[2] + cs.border_w[3];
  8329. if (w < 24)
  8330. w = 24;
  8331. if (span == 1) {
  8332. if (w > raw[col])
  8333. raw[col] = w;
  8334. }
  8335. if (col + span > cols)
  8336. cols = col + span;
  8337. col += span;
  8338. }
  8339. }
  8340. /* A colspan cell only has to be as wide as the sum of its columns. */
  8341. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8342. struct br_node *rn = &doc.nodes[r];
  8343. int col = 0;
  8344. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8345. continue;
  8346. for (c = rn->first; c; c = doc.nodes[c].next) {
  8347. struct br_node *cn = &doc.nodes[c];
  8348. struct br_style cs;
  8349. int span, w, sum, i;
  8350. if (cn->type != BR_NODE_ELEM ||
  8351. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  8352. continue;
  8353. span = cn->colspan ? cn->colspan : 1;
  8354. if (col + span > maxcols)
  8355. span = maxcols - col;
  8356. if (span < 1)
  8357. break;
  8358. if (span > 1) {
  8359. br_style_for(&doc, c, pst, &cs);
  8360. if (cs.display != BR_DISPLAY_NONE) {
  8361. w = intrinsic_width(l->ui, c, &cs,
  8362. 0, avail) +
  8363. mp_px(&cs, 7, avail) +
  8364. mp_px(&cs, 5, avail) +
  8365. mp_px(&cs, 3, avail) +
  8366. mp_px(&cs, 1, avail) +
  8367. cs.border_w[0] + cs.border_w[1] +
  8368. cs.border_w[2] + cs.border_w[3];
  8369. sum = 0;
  8370. for (i = 0; i < span; i++)
  8371. sum += raw[col + i];
  8372. if (w > sum)
  8373. raw[col + span - 1] += w - sum;
  8374. }
  8375. }
  8376. col += span;
  8377. }
  8378. }
  8379. /* Explicit and percentage widths override intrinsic widths. */
  8380. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8381. struct br_node *rn = &doc.nodes[r];
  8382. int col = 0;
  8383. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8384. continue;
  8385. for (c = rn->first; c; c = doc.nodes[c].next) {
  8386. struct br_node *cn = &doc.nodes[c];
  8387. struct br_style cs;
  8388. int span;
  8389. if (cn->type != BR_NODE_ELEM ||
  8390. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  8391. continue;
  8392. span = cn->colspan ? cn->colspan : 1;
  8393. if (col + span > maxcols)
  8394. span = maxcols - col;
  8395. if (span < 1)
  8396. break;
  8397. if (span == 1) {
  8398. br_style_for(&doc, c, pst, &cs);
  8399. if (cs.display != BR_DISPLAY_NONE) {
  8400. if (cs.width_kind == 1) {
  8401. raw[col] = cs.width;
  8402. fixed[col] = 1;
  8403. } else if (cs.width_kind == 2 ||
  8404. cs.width_kind == 3) {
  8405. raw[col] = style_width_px(&cs,
  8406. avail);
  8407. fixed[col] = 1;
  8408. }
  8409. }
  8410. }
  8411. col += span;
  8412. }
  8413. }
  8414. for (c = 0; c < (unsigned int)cols; c++) {
  8415. if (raw[c] < 8)
  8416. raw[c] = 8;
  8417. total += raw[c];
  8418. if (fixed[c])
  8419. fixed_sum += raw[c];
  8420. else {
  8421. free_raw += raw[c];
  8422. free_cols++;
  8423. }
  8424. }
  8425. if (fixed_sum > 0 && fixed_sum < avail) {
  8426. int free_avail = avail - fixed_sum;
  8427. int i;
  8428. if (free_raw > 0) {
  8429. for (i = 0; i < cols; i++)
  8430. if (!fixed[i])
  8431. raw[i] = free_avail * raw[i] /
  8432. free_raw;
  8433. } else if (free_cols > 0) {
  8434. for (i = 0; i < cols; i++)
  8435. if (!fixed[i])
  8436. raw[i] = free_avail / free_cols;
  8437. }
  8438. total = 0;
  8439. for (i = 0; i < cols; i++)
  8440. total += raw[i];
  8441. } else if (total < avail && total > 0) {
  8442. int i;
  8443. for (i = 0; i < cols; i++)
  8444. raw[i] = raw[i] * avail / total;
  8445. total = 0;
  8446. for (i = 0; i < cols; i++)
  8447. total += raw[i];
  8448. }
  8449. *out_cols = cols;
  8450. *out_total = total;
  8451. }
  8452. static void layout_table_row(struct lay *l, unsigned int row,
  8453. const struct br_style *pst, int depth,
  8454. unsigned short link)
  8455. {
  8456. unsigned int n, cell[12];
  8457. int raw[12], colstart[12], colspan[12];
  8458. int prefix[13];
  8459. int ncell = 0, total = 0, cols = 0, col = 0;
  8460. int row_left = l->left, row_right = l->right;
  8461. int avail = row_right - row_left;
  8462. int y = l->y, bottom = l->y;
  8463. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  8464. struct br_node *nd = &doc.nodes[n];
  8465. struct br_style cs;
  8466. int span;
  8467. if (nd->type == BR_NODE_TEXT) {
  8468. if (text_node_blank(nd))
  8469. continue;
  8470. layout_children(l, row, pst, depth, link);
  8471. return;
  8472. }
  8473. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  8474. layout_children(l, row, pst, depth, link);
  8475. return;
  8476. }
  8477. br_style_for(&doc, n, pst, &cs);
  8478. if (cs.display == BR_DISPLAY_NONE)
  8479. continue;
  8480. if (ncell >= 12) {
  8481. layout_children(l, row, pst, depth, link);
  8482. return;
  8483. }
  8484. span = nd->colspan ? nd->colspan : 1;
  8485. if (span > 12 - col)
  8486. span = 12 - col;
  8487. if (span < 1)
  8488. continue;
  8489. cell[ncell] = n;
  8490. colstart[ncell] = col;
  8491. colspan[ncell] = span;
  8492. col += span;
  8493. ncell++;
  8494. }
  8495. if (ncell < 1 || avail < 32) {
  8496. layout_children(l, row, pst, depth, link);
  8497. return;
  8498. }
  8499. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  8500. &total);
  8501. if (cols < 2 || total <= 0) {
  8502. int c;
  8503. total = 0;
  8504. for (c = 0; c < ncell; c++) {
  8505. struct br_style cs;
  8506. br_style_for(&doc, cell[c], pst, &cs);
  8507. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  8508. avail) +
  8509. mp_px(&cs, 7, avail) +
  8510. mp_px(&cs, 5, avail) +
  8511. mp_px(&cs, 3, avail) +
  8512. mp_px(&cs, 1, avail);
  8513. if (raw[c] < 24)
  8514. raw[c] = 24;
  8515. total += raw[c];
  8516. }
  8517. /* A one-column table still has to fill its own width; the
  8518. * intrinsic fallback above otherwise leaves the cell at its
  8519. * text width (HN's outer table and nested story table). */
  8520. if (total > 0 && total < avail) {
  8521. int c;
  8522. for (c = 0; c < ncell; c++)
  8523. raw[c] = raw[c] * avail / total;
  8524. total = avail;
  8525. }
  8526. }
  8527. prefix[0] = row_left;
  8528. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  8529. prefix[n + 1] = prefix[n] + raw[n];
  8530. for (n = 0; n < (unsigned int)ncell; n++) {
  8531. struct br_style cs;
  8532. int start = colstart[n];
  8533. int end = start + colspan[n];
  8534. int w;
  8535. if (end > cols)
  8536. end = cols;
  8537. if (start >= cols)
  8538. continue;
  8539. w = prefix[end] - prefix[start];
  8540. br_style_for(&doc, cell[n], pst, &cs);
  8541. /* The column width already reflects the cell's width property. */
  8542. cs.width_kind = 0;
  8543. cs.max_width_kind = 0;
  8544. if (w < 24)
  8545. w = 24;
  8546. if (w < 8)
  8547. w = 8;
  8548. l->left = prefix[start];
  8549. l->right = l->left + w;
  8550. l->y = y;
  8551. l->line_x = l->left;
  8552. l->run_x = l->left;
  8553. l->line_y = l->y;
  8554. l->line_h = 0;
  8555. l->nruns = 0;
  8556. l->space_pending = 0;
  8557. l->align = cs.align;
  8558. layout_block(l, cell[n], &cs, depth + 1, link);
  8559. if (l->y > bottom)
  8560. bottom = l->y;
  8561. }
  8562. l->left = row_left;
  8563. l->right = row_right;
  8564. l->y = bottom;
  8565. l->line_x = l->left;
  8566. l->run_x = l->left;
  8567. l->line_y = l->y;
  8568. l->line_h = 0;
  8569. l->nruns = 0;
  8570. l->space_pending = 0;
  8571. }
  8572. #define TBL_MAX_ROWS 32
  8573. #define TBL_MAX_COLS 12
  8574. #define TBL_MAX_CELLS 128
  8575. struct tbl_cell {
  8576. unsigned int node;
  8577. unsigned char row, col, rowspan, colspan;
  8578. int height;
  8579. };
  8580. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  8581. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  8582. static int table_active;
  8583. static int table_has_rowspan(unsigned int table)
  8584. {
  8585. unsigned int r, c;
  8586. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8587. struct br_node *rn = &doc.nodes[r];
  8588. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8589. continue;
  8590. for (c = rn->first; c; c = doc.nodes[c].next) {
  8591. struct br_node *cn = &doc.nodes[c];
  8592. if (cn->type == BR_NODE_ELEM &&
  8593. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  8594. cn->rowspan > 1)
  8595. return 1;
  8596. }
  8597. }
  8598. return 0;
  8599. }
  8600. static void table_cell_style(unsigned int row, unsigned int cell,
  8601. const struct br_style *st, struct br_style *out)
  8602. {
  8603. struct br_style trs;
  8604. br_style_for(&doc, row, st, &trs);
  8605. br_style_for(&doc, cell, &trs, out);
  8606. }
  8607. /* Tables that use rowspan need row heights before anything is painted. This
  8608. * path builds a small occupancy grid, measures the natural cell heights, then
  8609. * lays every cell out at its row/column position. Tables without rowspan
  8610. * keep the lighter per-row path in layout_table_row(). */
  8611. static void layout_table(struct lay *l, unsigned int table,
  8612. const struct br_style *st, int depth,
  8613. unsigned short link)
  8614. {
  8615. unsigned int rows[TBL_MAX_ROWS];
  8616. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  8617. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  8618. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  8619. int free_raw = 0, free_cols = 0;
  8620. int table_left = l->left, table_right = l->right;
  8621. int top = l->y, avail = table_right - table_left;
  8622. unsigned int r, c;
  8623. int i, rr, cc;
  8624. if (depth > 48 || table_active) {
  8625. layout_children(l, table, st, depth, link);
  8626. return;
  8627. }
  8628. table_active = 1;
  8629. for (r = doc.nodes[table].first;
  8630. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  8631. struct br_node *rn = &doc.nodes[r];
  8632. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  8633. rows[nrows++] = r;
  8634. }
  8635. if (!nrows) {
  8636. table_active = 0;
  8637. layout_children(l, table, st, depth, link);
  8638. return;
  8639. }
  8640. for (rr = 0; rr < nrows; rr++)
  8641. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  8642. tbl_at[rr][cc] = 0;
  8643. for (rr = 0; rr < nrows; rr++) {
  8644. int col = 0;
  8645. for (c = doc.nodes[rows[rr]].first; c;
  8646. c = doc.nodes[c].next) {
  8647. struct br_node *cn = &doc.nodes[c];
  8648. struct br_style cs;
  8649. int rs, csn;
  8650. if (cn->type != BR_NODE_ELEM ||
  8651. (cn->tag != BR_TAG_TD &&
  8652. cn->tag != BR_TAG_TH))
  8653. continue;
  8654. table_cell_style(rows[rr], c, st, &cs);
  8655. if (cs.display == BR_DISPLAY_NONE)
  8656. continue;
  8657. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  8658. col++;
  8659. if (col >= TBL_MAX_COLS)
  8660. break;
  8661. rs = cn->rowspan ? cn->rowspan : 1;
  8662. csn = cn->colspan ? cn->colspan : 1;
  8663. if (rr + rs > nrows)
  8664. rs = nrows - rr;
  8665. if (col + csn > TBL_MAX_COLS)
  8666. csn = TBL_MAX_COLS - col;
  8667. if (rs < 1 || csn < 1)
  8668. continue;
  8669. if (ncells >= TBL_MAX_CELLS)
  8670. break;
  8671. tbl_cells[ncells].node = c;
  8672. tbl_cells[ncells].row = (unsigned char)rr;
  8673. tbl_cells[ncells].col = (unsigned char)col;
  8674. tbl_cells[ncells].rowspan = (unsigned char)rs;
  8675. tbl_cells[ncells].colspan = (unsigned char)csn;
  8676. tbl_cells[ncells].height = 0;
  8677. for (i = rr; i < rr + rs; i++)
  8678. for (int j = col; j < col + csn; j++)
  8679. tbl_at[i][j] =
  8680. (unsigned short)(ncells + 1);
  8681. ncells++;
  8682. col += csn;
  8683. if (col > cols)
  8684. cols = col;
  8685. }
  8686. }
  8687. if (!ncells || cols < 1) {
  8688. table_active = 0;
  8689. layout_children(l, table, st, depth, link);
  8690. return;
  8691. }
  8692. for (i = 0; i < cols; i++) {
  8693. raw[i] = 0;
  8694. fixed[i] = 0;
  8695. }
  8696. /* Intrinsic widths of single-column cells. */
  8697. for (i = 0; i < ncells; i++) {
  8698. struct br_style cs;
  8699. int w;
  8700. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8701. st, &cs);
  8702. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8703. mp_px(&cs, 7, avail) +
  8704. mp_px(&cs, 5, avail) +
  8705. mp_px(&cs, 3, avail) +
  8706. mp_px(&cs, 1, avail) +
  8707. cs.border_w[0] + cs.border_w[1] +
  8708. cs.border_w[2] + cs.border_w[3];
  8709. if (w < 24)
  8710. w = 24;
  8711. if (tbl_cells[i].colspan == 1) {
  8712. int col = tbl_cells[i].col;
  8713. if (w > raw[col])
  8714. raw[col] = w;
  8715. }
  8716. }
  8717. /* A spanning cell only needs the sum of its columns to be large
  8718. * enough; put the deficit in the last column. */
  8719. for (i = 0; i < ncells; i++) {
  8720. struct br_style cs;
  8721. int w, sum, col, span;
  8722. if (tbl_cells[i].colspan < 2)
  8723. continue;
  8724. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8725. st, &cs);
  8726. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  8727. mp_px(&cs, 7, avail) +
  8728. mp_px(&cs, 5, avail) +
  8729. mp_px(&cs, 3, avail) +
  8730. mp_px(&cs, 1, avail) +
  8731. cs.border_w[0] + cs.border_w[1] +
  8732. cs.border_w[2] + cs.border_w[3];
  8733. col = tbl_cells[i].col;
  8734. span = tbl_cells[i].colspan;
  8735. sum = 0;
  8736. for (int j = 0; j < span; j++)
  8737. sum += raw[col + j];
  8738. if (w > sum)
  8739. raw[col + span - 1] += w - sum;
  8740. }
  8741. /* Explicit/percentage widths, as in table_columns(). */
  8742. for (i = 0; i < ncells; i++) {
  8743. struct br_style cs;
  8744. int col;
  8745. if (tbl_cells[i].colspan != 1)
  8746. continue;
  8747. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8748. st, &cs);
  8749. col = tbl_cells[i].col;
  8750. if (cs.width_kind == 1) {
  8751. raw[col] = cs.width;
  8752. fixed[col] = 1;
  8753. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  8754. raw[col] = style_width_px(&cs, avail);
  8755. fixed[col] = 1;
  8756. }
  8757. }
  8758. for (i = 0; i < cols; i++) {
  8759. if (raw[i] < 8)
  8760. raw[i] = 8;
  8761. total += raw[i];
  8762. if (fixed[i])
  8763. fixed_sum += raw[i];
  8764. else {
  8765. free_raw += raw[i];
  8766. free_cols++;
  8767. }
  8768. }
  8769. if (fixed_sum > 0 && fixed_sum < avail) {
  8770. int free_avail = avail - fixed_sum;
  8771. if (free_raw > 0) {
  8772. for (i = 0; i < cols; i++)
  8773. if (!fixed[i])
  8774. raw[i] = free_avail * raw[i] /
  8775. free_raw;
  8776. } else if (free_cols > 0) {
  8777. for (i = 0; i < cols; i++)
  8778. if (!fixed[i])
  8779. raw[i] = free_avail / free_cols;
  8780. }
  8781. } else if (total < avail && total > 0) {
  8782. for (i = 0; i < cols; i++)
  8783. raw[i] = raw[i] * avail / total;
  8784. }
  8785. prefix[0] = table_left;
  8786. for (i = 0; i < cols; i++)
  8787. prefix[i + 1] = prefix[i] + raw[i];
  8788. /* Measure natural cell heights with the column widths. */
  8789. for (i = 0; i < ncells; i++) {
  8790. struct br_style cs;
  8791. int col = tbl_cells[i].col;
  8792. int span = tbl_cells[i].colspan;
  8793. int w = prefix[col + span] - prefix[col];
  8794. int sl = l->left, sr = l->right, sy = l->y;
  8795. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8796. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8797. int sal = l->align, sdraw = l->draw;
  8798. struct ngui *sui = l->ui;
  8799. if (w < 8)
  8800. w = 8;
  8801. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8802. st, &cs);
  8803. cs.width_kind = 0;
  8804. cs.max_width_kind = 0;
  8805. l->draw = 0;
  8806. l->ui = 0;
  8807. l->left = prefix[col];
  8808. l->right = l->left + w;
  8809. l->y = 0;
  8810. l->line_x = l->left;
  8811. l->run_x = l->left;
  8812. l->line_y = 0;
  8813. l->line_h = 0;
  8814. l->nruns = 0;
  8815. l->space_pending = 0;
  8816. l->align = cs.align;
  8817. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8818. tbl_cells[i].height = block_h[tbl_cells[i].node];
  8819. l->left = sl;
  8820. l->right = sr;
  8821. l->y = sy;
  8822. l->line_x = slx;
  8823. l->run_x = srx;
  8824. l->line_y = sly;
  8825. l->line_h = slh;
  8826. l->nruns = snr;
  8827. l->space_pending = ssp;
  8828. l->align = sal;
  8829. l->draw = sdraw;
  8830. l->ui = sui;
  8831. }
  8832. for (i = 0; i < nrows; i++)
  8833. rowh[i] = 0;
  8834. for (i = 0; i < ncells; i++) {
  8835. int row = tbl_cells[i].row;
  8836. if (tbl_cells[i].rowspan == 1) {
  8837. if (tbl_cells[i].height > rowh[row])
  8838. rowh[row] = tbl_cells[i].height;
  8839. }
  8840. }
  8841. for (i = 0; i < ncells; i++) {
  8842. int row = tbl_cells[i].row;
  8843. int span = tbl_cells[i].rowspan;
  8844. int sum = 0;
  8845. if (span < 2)
  8846. continue;
  8847. for (int j = 0; j < span; j++)
  8848. sum += rowh[row + j];
  8849. if (sum < tbl_cells[i].height)
  8850. rowh[row + span - 1] +=
  8851. tbl_cells[i].height - sum;
  8852. }
  8853. for (i = 0; i < nrows; i++)
  8854. if (rowh[i] < 8)
  8855. rowh[i] = 8;
  8856. rowy[0] = top;
  8857. for (i = 1; i < nrows; i++)
  8858. rowy[i] = rowy[i - 1] + rowh[i - 1];
  8859. if (!l->draw) {
  8860. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8861. table_active = 0;
  8862. return;
  8863. }
  8864. for (i = 0; i < ncells; i++) {
  8865. struct br_style cs;
  8866. int col = tbl_cells[i].col;
  8867. int span = tbl_cells[i].colspan;
  8868. int row = tbl_cells[i].row;
  8869. int rspan = tbl_cells[i].rowspan;
  8870. int w = prefix[col + span] - prefix[col];
  8871. int h = 0;
  8872. int sl = l->left, sr = l->right, sy = l->y;
  8873. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8874. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8875. int sal = l->align;
  8876. int deco;
  8877. for (int j = 0; j < rspan; j++)
  8878. h += rowh[row + j];
  8879. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  8880. cs.width_kind = 0;
  8881. cs.max_width_kind = 0;
  8882. cs.box_sizing = 0;
  8883. deco = mp_px(&cs, 4, avail) +
  8884. mp_px(&cs, 6, avail) +
  8885. cs.border_w[0] + cs.border_w[2];
  8886. cs.height_kind = 1;
  8887. cs.height = h > deco ? h - deco : 0;
  8888. /* The block painter reads block_h[] from the measure pass; make
  8889. * the table cell fill its row/rowspan, not just its content. */
  8890. if (h > 0 && h < 65536)
  8891. block_h[tbl_cells[i].node] = (unsigned short)h;
  8892. l->left = prefix[col];
  8893. l->right = l->left + w;
  8894. l->y = rowy[row];
  8895. l->line_x = l->left;
  8896. l->run_x = l->left;
  8897. l->line_y = l->y;
  8898. l->line_h = 0;
  8899. l->nruns = 0;
  8900. l->space_pending = 0;
  8901. l->align = cs.align;
  8902. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8903. l->left = sl;
  8904. l->right = sr;
  8905. l->y = sy;
  8906. l->line_x = slx;
  8907. l->run_x = srx;
  8908. l->line_y = sly;
  8909. l->line_h = slh;
  8910. l->nruns = snr;
  8911. l->space_pending = ssp;
  8912. l->align = sal;
  8913. }
  8914. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8915. table_active = 0;
  8916. }
  8917. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  8918. * flow so they sit above it, like CSS painting order. Their flow origin is
  8919. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  8920. struct br_deferred {
  8921. unsigned int node;
  8922. int flow_y, flow_left, flow_right;
  8923. int parent_top; /* the parent box top, for sticky clamping */
  8924. unsigned short link;
  8925. signed short z_index;
  8926. unsigned char z_set;
  8927. unsigned int order;
  8928. };
  8929. /* Positioned boxes painted after the flow. News front pages have one or two
  8930. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  8931. * old 16 entries the rest fell back into the flow, so a hero image landed
  8932. * below its padding-top aspect box instead of on top of it. */
  8933. #define BR_MAX_DEFERRED 256
  8934. static struct br_deferred deferred[BR_MAX_DEFERRED];
  8935. static int ndeferred;
  8936. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  8937. * element's line. A block-level pseudo-element gets its own line; its box
  8938. * (margins, padding, background) is not drawn. */
  8939. static void emit_pseudo(struct lay *l, unsigned int node,
  8940. const struct br_style *st, int pe, unsigned short link)
  8941. {
  8942. char buf[160];
  8943. struct br_style ps;
  8944. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  8945. unsigned int i = 0;
  8946. int block, space_w;
  8947. if (!n)
  8948. return;
  8949. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  8950. if (block)
  8951. flush_line(l);
  8952. if (ps.uppercase)
  8953. for (i = 0; i < n; i++)
  8954. if (buf[i] >= 'a' && buf[i] <= 'z')
  8955. buf[i] = (char)(buf[i] - 'a' + 'A');
  8956. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  8957. if (space_w <= 0)
  8958. space_w = 8;
  8959. i = 0;
  8960. while (i < n) {
  8961. char word[28];
  8962. unsigned int k = 0;
  8963. int w;
  8964. if (buf[i] == ' ') {
  8965. l->space_pending = 1;
  8966. i++;
  8967. continue;
  8968. }
  8969. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  8970. word[k++] = buf[i++];
  8971. word[k] = '\0';
  8972. if (l->space_pending &&
  8973. (l->nruns > 0 || l->line_x > l->line_left) &&
  8974. l->line_x + space_w <= l->line_right)
  8975. l->line_x += space_w;
  8976. l->space_pending = 0;
  8977. w = (int)face_text_width(l->ui, &ps, word, k);
  8978. if (l->line_x + w > l->line_right &&
  8979. (l->nruns > 0 || l->line_x > l->line_left))
  8980. flush_line(l);
  8981. add_run(l, 0, 0, &ps, link, word);
  8982. }
  8983. if (block)
  8984. flush_line(l);
  8985. }
  8986. static void layout_children(struct lay *l, unsigned int parent,
  8987. const struct br_style *pst, int depth,
  8988. unsigned short link)
  8989. {
  8990. unsigned int n;
  8991. if (depth > 48)
  8992. return;
  8993. emit_pseudo(l, parent, pst, 1, link);
  8994. n = doc.nodes[parent].first;
  8995. while (n) {
  8996. struct br_node *nd = &doc.nodes[n];
  8997. struct br_style cs;
  8998. unsigned short lk = link;
  8999. if (nd->type == BR_NODE_TEXT) {
  9000. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  9001. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  9002. n = nd->next;
  9003. continue;
  9004. }
  9005. br_style_for(&doc, n, pst, &cs);
  9006. if (cs.display == BR_DISPLAY_NONE) {
  9007. n = nd->next;
  9008. continue;
  9009. }
  9010. if (cs.clear && l->float_active) {
  9011. flush_line(l);
  9012. if (l->y < l->float_bottom)
  9013. l->y = l->float_bottom;
  9014. l->float_active = 0;
  9015. l->line_x = l->left;
  9016. l->run_x = l->left;
  9017. l->line_left = l->left;
  9018. l->line_right = l->right;
  9019. l->line_y = l->y;
  9020. l->line_h = 0;
  9021. l->nruns = 0;
  9022. l->space_pending = 0;
  9023. }
  9024. if (nd->tag == BR_TAG_A && nd->href_off)
  9025. lk = (unsigned short)n;
  9026. if (cs.pos == 1 || cs.pos == 2 ||
  9027. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  9028. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  9029. ndeferred < BR_MAX_DEFERRED) {
  9030. /* Relative or sticky z-index (a sticky site
  9031. * header): measure and advance the flow without
  9032. * painting, then paint it in the deferred
  9033. * (stacked) pass, above the content after it. */
  9034. int fy = l->y, fl = l->left, fr = l->right;
  9035. int save_draw = l->draw;
  9036. l->draw = 0;
  9037. layout_block(l, n, &cs, depth + 1, lk);
  9038. l->draw = save_draw;
  9039. deferred[ndeferred].node = n;
  9040. deferred[ndeferred].parent_top = l->parent_top;
  9041. deferred[ndeferred].flow_y = fy;
  9042. deferred[ndeferred].flow_left = fl;
  9043. deferred[ndeferred].flow_right = fr;
  9044. deferred[ndeferred].link = lk;
  9045. deferred[ndeferred].z_index = cs.z_index;
  9046. deferred[ndeferred].z_set = cs.z_set;
  9047. deferred[ndeferred].order = (unsigned int)ndeferred;
  9048. ndeferred++;
  9049. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  9050. deferred[ndeferred].node = n;
  9051. deferred[ndeferred].parent_top = l->parent_top;
  9052. deferred[ndeferred].flow_y =
  9053. cs.pos == 1 ? l->cb_top : l->y;
  9054. deferred[ndeferred].flow_left =
  9055. cs.pos == 1 ? l->cb_left : l->left;
  9056. deferred[ndeferred].flow_right =
  9057. cs.pos == 1 ? l->cb_right : l->right;
  9058. deferred[ndeferred].link = lk;
  9059. deferred[ndeferred].z_index = cs.z_index;
  9060. deferred[ndeferred].z_set = cs.z_set;
  9061. deferred[ndeferred].order = (unsigned int)ndeferred;
  9062. ndeferred++;
  9063. } else if (l->draw && cs.pos == 1) {
  9064. /* Deferred list full: paint in place, but still
  9065. * against the containing block, not the flow. */
  9066. int fy = l->y, fl = l->left, fr = l->right;
  9067. l->y = l->cb_top;
  9068. l->left = l->cb_left;
  9069. l->right = l->cb_right;
  9070. layout_block(l, n, &cs, depth + 1, lk);
  9071. l->y = fy;
  9072. l->left = fl;
  9073. l->right = fr;
  9074. } else {
  9075. layout_block(l, n, &cs, depth + 1, lk);
  9076. }
  9077. if (cs.pos == 1 && block_h[n] &&
  9078. doc.nodes[n].class_off) {
  9079. const char *cl = doc.attrs +
  9080. doc.nodes[n].class_off;
  9081. if ((contains_ci(cl, "poster-wrapper") ||
  9082. contains_ci(cl, "ts-picture")) &&
  9083. !has_skeleton_sibling(n))
  9084. l->y += block_h[n];
  9085. }
  9086. n = nd->next;
  9087. continue;
  9088. }
  9089. if (nd->tag == BR_TAG_BR) {
  9090. flush_line(l);
  9091. n = nd->next;
  9092. continue;
  9093. }
  9094. if (nd->tag == BR_TAG_HR) {
  9095. flush_line(l);
  9096. if (l->draw)
  9097. ngui_fill_rect(l->ui,
  9098. (struct ngui_rect){l->left, l->y + 2,
  9099. l->right - l->left, 1}, BR_GRAY);
  9100. l->y += 8;
  9101. n = nd->next;
  9102. continue;
  9103. }
  9104. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  9105. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  9106. !button_has_elements(n)) {
  9107. if (!(nd->tag == BR_TAG_INPUT &&
  9108. s_eq(br_type(&doc, n), "hidden"))) {
  9109. form_fill_line = pst->display ==
  9110. BR_DISPLAY_FLEX &&
  9111. pst->flex_col;
  9112. add_form_run(l, n, &cs, lk);
  9113. form_fill_line = 0;
  9114. }
  9115. n = nd->next;
  9116. continue;
  9117. }
  9118. if (nd->tag == BR_TAG_IMG) {
  9119. add_image_run(l, n, &cs, lk);
  9120. n = nd->next;
  9121. continue;
  9122. }
  9123. if (nd->tag == BR_TAG_SVG &&
  9124. (cs.display == BR_DISPLAY_INLINE ||
  9125. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  9126. !cs.float_left) {
  9127. add_svg_run(l, n, &cs, lk);
  9128. n = nd->next;
  9129. continue;
  9130. }
  9131. if (nd->tag == BR_TAG_VIDEO) {
  9132. layout_block(l, n, &cs, depth + 1, lk);
  9133. n = nd->next;
  9134. continue;
  9135. }
  9136. if (cs.float_left) {
  9137. n = layout_float_group(l, n, pst, depth, lk);
  9138. continue;
  9139. }
  9140. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  9141. inline_block_flows(n, &cs, 0)) {
  9142. layout_children(l, n, &cs, depth + 1, lk);
  9143. n = nd->next;
  9144. continue;
  9145. }
  9146. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9147. n = layout_inline_blocks(l, n, pst, depth, link);
  9148. continue;
  9149. }
  9150. /* A flex container is block-level like any block box even when
  9151. * the element is an inline tag such as <a> (a link card with
  9152. * display:flex is common on news sites). Without the block box
  9153. * its children were laid out in the parent flow with a 0x0 box
  9154. * of their own. */
  9155. /* inline-flex around inline content only ("| mehr" link
  9156. * tails, icon+label pills) stays in the text line. */
  9157. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  9158. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  9159. !flex_wants_row(n, &cs)) {
  9160. layout_children(l, n, &cs, depth + 1, lk);
  9161. } else if (cs.display == BR_DISPLAY_BLOCK ||
  9162. cs.display == BR_DISPLAY_FLEX ||
  9163. br_tag_is_block(nd->tag))
  9164. layout_block(l, n, &cs, depth + 1, lk);
  9165. else {
  9166. layout_children(l, n, &cs, depth + 1, lk);
  9167. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  9168. l->space_pending = 1;
  9169. }
  9170. n = nd->next;
  9171. }
  9172. emit_pseudo(l, parent, pst, 2, link);
  9173. }
  9174. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  9175. * runs and a recursive page can otherwise overflow the stack. */
  9176. static struct lay layout_state;
  9177. static int measure_page(int left, int right)
  9178. {
  9179. struct lay *l = &layout_state;
  9180. struct br_style base = base_style();
  9181. unsigned int i;
  9182. for (i = 0; i < BR_MAX_NODES; i++) {
  9183. block_h[i] = 0;
  9184. img_top[i] = 0;
  9185. block_top[i] = 0;
  9186. img_h[i] = 0;
  9187. layout_boxes[i].valid = 0;
  9188. }
  9189. memset(li_marker, 0, sizeof(li_marker));
  9190. l->draw = 0;
  9191. l->ui = &ui;
  9192. l->left = left;
  9193. l->right = right;
  9194. l->y = 0;
  9195. l->line_x = left;
  9196. l->run_x = left;
  9197. l->line_left = left;
  9198. l->line_right = right;
  9199. l->line_y = 0;
  9200. l->line_h = 0;
  9201. l->align = BR_ALIGN_LEFT;
  9202. l->cb_h = layout_view_h;
  9203. l->float_active = 0;
  9204. l->parent_top = 0;
  9205. l->cb_left = left;
  9206. l->cb_right = right;
  9207. l->cb_top = 0;
  9208. l->depth = 0;
  9209. l->nruns = 0;
  9210. l->space_pending = 0;
  9211. layout_children(l, doc.root, &base, 0, 0);
  9212. return l->y + 8;
  9213. }
  9214. static int deferred_cmp(const struct br_deferred *a,
  9215. const struct br_deferred *b)
  9216. {
  9217. int az = a->z_set ? a->z_index : 0;
  9218. int bz = b->z_set ? b->z_index : 0;
  9219. if (az != bz)
  9220. return az < bz ? -1 : 1;
  9221. if (a->order != b->order)
  9222. return a->order < b->order ? -1 : 1;
  9223. return 0;
  9224. }
  9225. static void sort_deferred(void)
  9226. {
  9227. int i;
  9228. for (i = 1; i < ndeferred; i++) {
  9229. struct br_deferred key = deferred[i];
  9230. int j = i;
  9231. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  9232. deferred[j] = deferred[j - 1];
  9233. j--;
  9234. }
  9235. deferred[j] = key;
  9236. }
  9237. }
  9238. static void render_page(int left, int right, int y0)
  9239. {
  9240. struct lay *l = &layout_state;
  9241. struct br_style base = base_style();
  9242. l->draw = 1;
  9243. l->ui = &ui;
  9244. l->left = left;
  9245. l->right = right;
  9246. l->y = y0;
  9247. l->line_x = left;
  9248. l->run_x = left;
  9249. l->line_left = left;
  9250. l->line_right = right;
  9251. l->line_y = y0;
  9252. l->line_h = 0;
  9253. l->align = BR_ALIGN_LEFT;
  9254. l->cb_h = layout_view_h;
  9255. l->float_active = 0;
  9256. l->parent_top = 0;
  9257. l->cb_left = left;
  9258. l->cb_right = right;
  9259. l->cb_top = y0;
  9260. l->depth = 0;
  9261. l->nruns = 0;
  9262. l->space_pending = 0;
  9263. nhits = 0;
  9264. ndeferred = 0;
  9265. layout_children(l, doc.root, &base, 0, 0);
  9266. sort_deferred();
  9267. {
  9268. int i;
  9269. for (i = 0; i < ndeferred; i++) {
  9270. struct br_style st;
  9271. br_style_for(&doc, deferred[i].node, &base, &st);
  9272. if (st.display == BR_DISPLAY_NONE)
  9273. continue;
  9274. l->draw = 1;
  9275. l->left = deferred[i].flow_left;
  9276. l->right = deferred[i].flow_right;
  9277. l->y = deferred[i].flow_y;
  9278. l->parent_top = deferred[i].parent_top;
  9279. l->line_x = l->left;
  9280. l->run_x = l->left;
  9281. l->line_y = l->y;
  9282. l->line_h = 0;
  9283. l->nruns = 0;
  9284. l->space_pending = 0;
  9285. l->align = st.align;
  9286. if (st.pos == 2 && block_h[deferred[i].node]) {
  9287. struct ngui_rect clip;
  9288. int ch = block_h[deferred[i].node] + 24;
  9289. clip.x = page_rect.x;
  9290. clip.y = page_rect.y;
  9291. clip.w = page_rect.w - 12;
  9292. if (ch > page_rect.h)
  9293. ch = page_rect.h;
  9294. clip.h = ch;
  9295. ngui_push_clip(&ui, clip);
  9296. if (st.has_bg)
  9297. ngui_fill_rect(&ui, clip, st.bg);
  9298. layout_block(l, deferred[i].node, &st, 0,
  9299. deferred[i].link);
  9300. ngui_pop_clip(&ui);
  9301. } else {
  9302. layout_block(l, deferred[i].node, &st, 0,
  9303. deferred[i].link);
  9304. }
  9305. }
  9306. }
  9307. }
  9308. /* ---- UI ---- */
  9309. static int find_hit(int x, int y)
  9310. {
  9311. int i;
  9312. for (i = nhits - 1; i >= 0; i--) {
  9313. struct hit *h = &hits[i];
  9314. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  9315. y < h->y + h->h)
  9316. return (int)h->node;
  9317. }
  9318. return 0;
  9319. }
  9320. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  9321. {
  9322. int x = r.x + 4, y = r.y + 4, h = 22;
  9323. int compact = r.w < 560;
  9324. int go_w = r.w < 420 ? 32 : 42;
  9325. int in_x, in_w, res;
  9326. ngui_fill_rect(&ui, r, ui.theme.panel);
  9327. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  9328. ui.theme.border);
  9329. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  9330. NGUI_ICON_CHEVRON_LEFT))
  9331. *action |= ACT_BACK;
  9332. x += 32;
  9333. if (!compact) {
  9334. if (ngui_icon_button(&ui, ID_FORWARD,
  9335. (struct ngui_rect){x, y, 28, h},
  9336. NGUI_ICON_CHEVRON_RIGHT))
  9337. *action |= ACT_FORWARD;
  9338. x += 32;
  9339. }
  9340. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  9341. NGUI_ICON_REFRESH))
  9342. *action |= ACT_RELOAD;
  9343. x += 32;
  9344. if (!compact) {
  9345. if (ngui_icon_button(&ui, ID_HOME,
  9346. (struct ngui_rect){x, y, 28, h},
  9347. NGUI_ICON_HOME))
  9348. *action |= ACT_HOME;
  9349. x += 32;
  9350. }
  9351. in_x = x + 2;
  9352. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  9353. if (in_w < 60)
  9354. in_w = 60;
  9355. res = ngui_text_input(&ui, ID_URL,
  9356. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  9357. if (res & NGUI_INPUT_SUBMIT)
  9358. *action |= ACT_NAV;
  9359. if (res & NGUI_INPUT_CANCEL)
  9360. ngui_set_focus(&ui, 0);
  9361. if (ngui_button(&ui, ID_GO,
  9362. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  9363. "Go"))
  9364. *action |= ACT_NAV;
  9365. }
  9366. static int page_hover_node(void)
  9367. {
  9368. if (!ui.inside)
  9369. return 0;
  9370. if (ui.mouse_x < page_rect.x ||
  9371. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  9372. ui.mouse_y < page_rect.y ||
  9373. ui.mouse_y >= page_rect.y + page_rect.h)
  9374. return 0;
  9375. return find_hit(ui.mouse_x, ui.mouse_y);
  9376. }
  9377. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  9378. {
  9379. int x, y, w = page.w, h = page.h;
  9380. if (!src || w <= 0 || h <= 0)
  9381. return;
  9382. for (y = 0; y < h; y++) {
  9383. unsigned short *s = src + (page.y + y) * sw + page.x;
  9384. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  9385. for (x = 0; x + 1 < w; x += 2) {
  9386. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  9387. }
  9388. if (x < w)
  9389. d[x] = s[x];
  9390. }
  9391. }
  9392. static void draw_page(struct ngui_rect page)
  9393. {
  9394. int left, right, ch;
  9395. int old_panel, old_dim;
  9396. unsigned short *saved_px;
  9397. unsigned short page_bg = ui.theme.bg;
  9398. int saved_w, saved_h, use_buf;
  9399. page_rect = page;
  9400. {
  9401. unsigned int root = doc.nnode > 1 ?
  9402. br_find_tag(&doc, BR_TAG_HTML) : 0;
  9403. unsigned int body = doc.nnode > 1 ?
  9404. br_find_tag(&doc, BR_TAG_BODY) : 0;
  9405. struct br_style bs;
  9406. if (root) {
  9407. style_for_node(root - 1, &bs);
  9408. if (bs.has_bg)
  9409. page_bg = bs.bg;
  9410. }
  9411. if (body) {
  9412. style_for_node(body - 1, &bs);
  9413. if (bs.has_bg)
  9414. page_bg = bs.bg;
  9415. }
  9416. }
  9417. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  9418. page_cache_valid && layout_valid &&
  9419. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  9420. !(ui.scroll_y &&
  9421. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  9422. page_scroll.offset == page_cache_scroll &&
  9423. page_cache_nnode == doc.nnode &&
  9424. page_cache_x == page.x && page_cache_y == page.y &&
  9425. page_cache_w == page.w && page_cache_h == page.h) {
  9426. blit_page(page, page_backbuf, pagebuf_w);
  9427. return;
  9428. }
  9429. ngui_fill_rect(&ui, page, page_bg);
  9430. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  9431. const char *s = page_loading ? "Loading..." : "No page";
  9432. int w = (int)ngui_text_width_ui(&ui, s);
  9433. ngui_text(&ui, page.x + (page.w - w) / 2,
  9434. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  9435. page_scroll.content_h = 0;
  9436. page_scroll.view_h = page.h;
  9437. page_cache_valid = 0;
  9438. return;
  9439. }
  9440. if (page.w < 40 || page.h < 40) {
  9441. page_cache_valid = 0;
  9442. return;
  9443. }
  9444. saved_px = ui.px;
  9445. saved_w = ui.w;
  9446. saved_h = ui.h;
  9447. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  9448. if (use_buf) {
  9449. ui.px = page_backbuf;
  9450. ui.w = pagebuf_w;
  9451. ui.h = pagebuf_h;
  9452. ngui_fill_rect(&ui, page, page_bg);
  9453. }
  9454. left = page.x + 8;
  9455. right = page.x + page.w - 16;
  9456. if (!layout_valid || left != layout_left || right != layout_right ||
  9457. layout_nnode != doc.nnode) {
  9458. layout_view_h = page.h - 8;
  9459. layout_content_h = measure_page(left, right);
  9460. layout_valid = 1;
  9461. layout_left = left;
  9462. layout_right = right;
  9463. layout_nnode = doc.nnode;
  9464. /* Scripts that measured before any layout (offsetWidth on
  9465. * mount) get a resize event once real boxes exist, and again
  9466. * whenever the page width changes. */
  9467. if (js_browser_active() && right - left != resize_sent_w)
  9468. resize_pending = 1;
  9469. }
  9470. ch = layout_content_h;
  9471. page_scroll.content_h = ch;
  9472. page_scroll.view_h = page.h;
  9473. ngui_scroll_begin(&ui, page, &page_scroll);
  9474. ngui_scroll_wheel(&ui, page, &page_scroll);
  9475. render_page(left, right, page.y + 4 - page_scroll.offset);
  9476. old_panel = ui.theme.panel_alt;
  9477. old_dim = ui.theme.text_dim;
  9478. ui.theme.panel_alt = 0xC618;
  9479. ui.theme.text_dim = 0x8410;
  9480. ngui_scroll_end(&ui, page, &page_scroll);
  9481. ui.theme.panel_alt = old_panel;
  9482. ui.theme.text_dim = old_dim;
  9483. if (use_buf) {
  9484. ui.px = saved_px;
  9485. ui.w = saved_w;
  9486. ui.h = saved_h;
  9487. blit_page(page, page_backbuf, pagebuf_w);
  9488. page_cache_valid = 1;
  9489. page_cache_scroll = page_scroll.offset;
  9490. page_cache_nnode = doc.nnode;
  9491. page_cache_x = page.x;
  9492. page_cache_y = page.y;
  9493. page_cache_w = page.w;
  9494. page_cache_h = page.h;
  9495. } else {
  9496. page_cache_valid = 0;
  9497. }
  9498. }
  9499. static void draw_status(struct ngui_rect r)
  9500. {
  9501. char msg[BR_URL_MAX + 32];
  9502. unsigned int n = 0;
  9503. int hover = page_hover_node();
  9504. unsigned short color;
  9505. const char *kind;
  9506. ngui_fill_rect(&ui, r, ui.theme.panel);
  9507. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  9508. ui.theme.border);
  9509. if (hover) {
  9510. const char *href = br_href(&doc, (unsigned int)hover);
  9511. char url[BR_URL_MAX];
  9512. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  9513. s_append(msg, &n, "Link: ", sizeof(msg));
  9514. s_append(msg, &n, url, sizeof(msg));
  9515. } else {
  9516. s_copy(msg, "Link", sizeof(msg));
  9517. }
  9518. color = ui.theme.accent;
  9519. } else if (status_text[0]) {
  9520. s_copy(msg, status_text, sizeof(msg));
  9521. color = status_error ? ui.theme.error : ui.theme.text;
  9522. } else if (page_title[0]) {
  9523. s_copy(msg, page_title, sizeof(msg));
  9524. color = ui.theme.text;
  9525. } else {
  9526. s_copy(msg, "Ready", sizeof(msg));
  9527. color = ui.theme.text_dim;
  9528. }
  9529. kind = s_eq(page_url, "about:home") ? "HOME" :
  9530. page_is_local ? "FILE" :
  9531. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  9532. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  9533. {
  9534. int kw = (int)ngui_text_width_ui(&ui, kind);
  9535. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  9536. ui.theme.text_dim);
  9537. }
  9538. }
  9539. static void draw(unsigned int *action)
  9540. {
  9541. struct ngui_rect r = {0, 0, ui.w, ui.h};
  9542. struct ngui_rect toolbar, status, page;
  9543. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  9544. status = ngui_cut_bottom(&r, BR_STATUS_H);
  9545. page = r;
  9546. draw_toolbar(toolbar, action);
  9547. draw_page(page);
  9548. draw_status(status);
  9549. }
  9550. static void redraw_now(void)
  9551. {
  9552. unsigned int action = 0;
  9553. ngui_begin(&ui);
  9554. draw(&action);
  9555. ngui_end(&ui);
  9556. }
  9557. static void handle_keys(unsigned int *action)
  9558. {
  9559. int k, scrolled = 0;
  9560. if (form_focus >= doc.nnode)
  9561. form_focus = 0;
  9562. if (form_focus && !ngui_focus(&ui)) {
  9563. while ((k = ngui_key(&ui)) != 0)
  9564. form_key(k);
  9565. return;
  9566. }
  9567. /* Batch queued page keys: a slow full-page render must not make a
  9568. * held Page Down advance only once every few frames. */
  9569. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  9570. scrolled++;
  9571. if (scrolled)
  9572. ngui_invalidate(&ui);
  9573. if (ngui_focus(&ui))
  9574. return;
  9575. while ((k = ngui_key(&ui)) != 0) {
  9576. switch (k) {
  9577. case NGUI_KEY_ESC:
  9578. *action |= ACT_CLOSE;
  9579. break;
  9580. case NGUI_KEY_TAB:
  9581. case 0x0C: /* Ctrl+L */
  9582. ngui_set_focus(&ui, ID_URL);
  9583. break;
  9584. case 0x12: /* Ctrl+R */
  9585. *action |= ACT_RELOAD;
  9586. break;
  9587. case NGUI_KEY_BACKSPACE:
  9588. *action |= ACT_BACK;
  9589. break;
  9590. case NGUI_KEY_UP:
  9591. ngui_scroll_to(&page_scroll,
  9592. page_scroll.offset - 24);
  9593. ngui_invalidate(&ui);
  9594. break;
  9595. case NGUI_KEY_DOWN:
  9596. ngui_scroll_to(&page_scroll,
  9597. page_scroll.offset + 24);
  9598. ngui_invalidate(&ui);
  9599. break;
  9600. case NGUI_KEY_HOME:
  9601. ngui_scroll_to(&page_scroll, 0);
  9602. ngui_invalidate(&ui);
  9603. break;
  9604. case NGUI_KEY_END:
  9605. ngui_scroll_to(&page_scroll,
  9606. page_scroll.content_h -
  9607. page_scroll.view_h);
  9608. ngui_invalidate(&ui);
  9609. break;
  9610. default:
  9611. break;
  9612. }
  9613. }
  9614. }
  9615. static unsigned int form_ancestor(unsigned int node)
  9616. {
  9617. unsigned int p = node;
  9618. while (p && p < doc.nnode) {
  9619. if (doc.nodes[p].tag == BR_TAG_FORM &&
  9620. doc.nodes[p].type == BR_NODE_ELEM)
  9621. return p;
  9622. p = doc.nodes[p].parent;
  9623. }
  9624. return 0;
  9625. }
  9626. static int form_descendant(unsigned int node, unsigned int form)
  9627. {
  9628. unsigned int p = node;
  9629. while (p && p < doc.nnode) {
  9630. if (p == form)
  9631. return 1;
  9632. p = doc.nodes[p].parent;
  9633. }
  9634. return 0;
  9635. }
  9636. static void form_reset_form(unsigned int form)
  9637. {
  9638. unsigned int i;
  9639. for (i = 0; i < FORM_MAX; i++)
  9640. if (form_states[i].used &&
  9641. form_descendant(form_states[i].node, form))
  9642. form_states[i].used = 0;
  9643. form_focus = 0;
  9644. }
  9645. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  9646. const char *s)
  9647. {
  9648. static const char hex[] = "0123456789ABCDEF";
  9649. while (s && *s && *n + 1 < cap) {
  9650. unsigned char c = (unsigned char)*s++;
  9651. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  9652. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  9653. c == '.' || c == '~') {
  9654. dst[(*n)++] = (char)c;
  9655. } else if (c == ' ') {
  9656. dst[(*n)++] = '+';
  9657. } else if (*n + 3 < cap) {
  9658. dst[(*n)++] = '%';
  9659. dst[(*n)++] = hex[c >> 4];
  9660. dst[(*n)++] = hex[c & 15];
  9661. }
  9662. }
  9663. dst[*n] = '\0';
  9664. }
  9665. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  9666. const char *name, const char *value, int *first)
  9667. {
  9668. if (!name || !name[0])
  9669. return;
  9670. if (!*first && *n + 1 < cap)
  9671. dst[(*n)++] = '&';
  9672. *first = 0;
  9673. form_url_append(dst, n, cap, name);
  9674. if (*n + 1 < cap)
  9675. dst[(*n)++] = '=';
  9676. form_url_append(dst, n, cap, value ? value : "");
  9677. dst[*n] = '\0';
  9678. }
  9679. static int form_submit_form(unsigned int node, int fire_event)
  9680. {
  9681. unsigned int form = form_ancestor(node);
  9682. char action[BR_URL_MAX], query[2048];
  9683. unsigned int qn = 0, i;
  9684. int first = 1, is_post = 0;
  9685. const char *a, *method;
  9686. if (!form)
  9687. return 0;
  9688. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  9689. return 0;
  9690. method = br_find_attr(&doc, form, "method");
  9691. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  9692. is_post = 1;
  9693. a = br_find_attr(&doc, form, "action");
  9694. if (a && a[0]) {
  9695. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  9696. return 0;
  9697. } else {
  9698. s_copy(action, page_url, sizeof(action));
  9699. }
  9700. query[0] = '\0';
  9701. for (i = 0; i < doc.nnode; i++) {
  9702. struct br_node *nd = &doc.nodes[i];
  9703. struct form_state *fs;
  9704. const char *name;
  9705. const char *value = "";
  9706. if (nd->type != BR_NODE_ELEM || i == form ||
  9707. !form_descendant(i, form))
  9708. continue;
  9709. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  9710. nd->tag != BR_TAG_SELECT)
  9711. continue;
  9712. if (form_disabled(i))
  9713. continue;
  9714. name = br_find_attr(&doc, i, "name");
  9715. if (!name || !name[0])
  9716. continue;
  9717. fs = form_get(i, 1);
  9718. if (!fs)
  9719. continue;
  9720. if (nd->tag == BR_TAG_SELECT) {
  9721. char opt[64];
  9722. if (!form_option_text(i, fs->selected, opt,
  9723. sizeof(opt)))
  9724. s_copy(opt, "", sizeof(opt));
  9725. value = opt;
  9726. {
  9727. unsigned int c, oi = 0;
  9728. for (c = nd->first; c;
  9729. c = doc.nodes[c].next) {
  9730. if (doc.nodes[c].type != BR_NODE_ELEM ||
  9731. doc.nodes[c].tag != BR_TAG_OPTION)
  9732. continue;
  9733. if (oi == fs->selected) {
  9734. const char *v =
  9735. br_value(&doc, c);
  9736. if (v && v[0])
  9737. value = v;
  9738. break;
  9739. }
  9740. oi++;
  9741. }
  9742. }
  9743. } else if (nd->tag == BR_TAG_INPUT) {
  9744. int kind = form_kind_of(i);
  9745. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9746. if (!fs->checked)
  9747. continue;
  9748. value = br_value(&doc, i);
  9749. if (!value || !value[0])
  9750. value = "on";
  9751. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  9752. kind == FORM_BUTTON) {
  9753. if (i != node)
  9754. continue;
  9755. value = fs->value;
  9756. } else {
  9757. value = fs->value;
  9758. }
  9759. } else {
  9760. value = fs->value;
  9761. }
  9762. form_add_param(query, &qn, sizeof(query), name, value, &first);
  9763. }
  9764. if (is_post) {
  9765. if (action[0] == '/') {
  9766. set_status("POST forms need an HTTP action URL", 1, 4000);
  9767. ngui_invalidate(&ui);
  9768. return 0;
  9769. }
  9770. if (qn >= sizeof(pending_post))
  9771. qn = sizeof(pending_post) - 1;
  9772. if (qn)
  9773. memcpy(pending_post, query, qn);
  9774. pending_post[qn] = '\0';
  9775. pending_post_len = qn;
  9776. pending_post_is = 1;
  9777. } else {
  9778. pending_post_len = 0;
  9779. pending_post_is = 0;
  9780. if (qn) {
  9781. unsigned int an = s_len(action);
  9782. if (an + qn + 2 < sizeof(action)) {
  9783. action[an++] = strchr(action, '?') ? '&' : '?';
  9784. action[an] = '\0';
  9785. s_copy(action + an, query,
  9786. sizeof(action) - an);
  9787. }
  9788. }
  9789. }
  9790. s_copy(pending_url, action, sizeof(pending_url));
  9791. pending_action |= ACT_NAV;
  9792. cancel_fetch = 1;
  9793. ngui_invalidate(&ui);
  9794. return 1;
  9795. }
  9796. static void form_reset_event(unsigned int form)
  9797. {
  9798. if (form && !js_browser_event(form, "reset", 1, 1))
  9799. return;
  9800. if (form)
  9801. form_reset_form(form);
  9802. else
  9803. form_reset_state();
  9804. form_dirty = 0;
  9805. layout_valid = 0;
  9806. ngui_invalidate(&ui);
  9807. }
  9808. static void form_blur(void)
  9809. {
  9810. unsigned int node = form_focus;
  9811. form_focus = 0;
  9812. if (node && form_dirty) {
  9813. form_dirty = 0;
  9814. js_browser_event(node, "change", 1, 0);
  9815. }
  9816. }
  9817. static void form_click(unsigned int node)
  9818. {
  9819. struct form_state *fs;
  9820. int kind, changed = 0;
  9821. if (!form_is_control(node) || form_disabled(node))
  9822. return;
  9823. if (form_focus != node)
  9824. form_blur();
  9825. if (!js_browser_event(node, "click", 1, 1))
  9826. return;
  9827. fs = form_get(node, 1);
  9828. if (!fs)
  9829. return;
  9830. kind = form_kind_of(node);
  9831. form_focus = node;
  9832. form_dirty = 0;
  9833. if (kind == FORM_CHECKBOX) {
  9834. fs->checked = !fs->checked;
  9835. changed = 1;
  9836. } else if (kind == FORM_RADIO) {
  9837. const char *name = br_find_attr(&doc, node, "name");
  9838. unsigned int i;
  9839. fs->checked = 1;
  9840. changed = 1;
  9841. if (name) {
  9842. for (i = 0; i < FORM_MAX; i++) {
  9843. struct form_state *o = &form_states[i];
  9844. if (!o->used || o->node == node)
  9845. continue;
  9846. if (form_kind_of(o->node) == FORM_RADIO) {
  9847. const char *on = br_find_attr(&doc,
  9848. o->node,
  9849. "name");
  9850. if (on && s_eq(on, name))
  9851. o->checked = 0;
  9852. }
  9853. }
  9854. }
  9855. } else if (kind == FORM_SELECT) {
  9856. unsigned int n = form_option_count(node);
  9857. if (n) {
  9858. fs->selected = (unsigned char)
  9859. ((fs->selected + 1) % n);
  9860. changed = 1;
  9861. }
  9862. } else if (kind == FORM_SUBMIT) {
  9863. form_submit_form(node, 1);
  9864. return;
  9865. } else if (kind == FORM_RESET) {
  9866. form_reset_event(form_ancestor(node));
  9867. return;
  9868. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  9869. kind == FORM_TEXTAREA) {
  9870. fs->caret = fs->len;
  9871. }
  9872. if (changed) {
  9873. js_browser_event(node, "input", 1, 0);
  9874. js_browser_event(node, "change", 1, 0);
  9875. }
  9876. layout_valid = 0;
  9877. ngui_invalidate(&ui);
  9878. }
  9879. static void form_focus_next(void)
  9880. {
  9881. unsigned int start = form_focus ? form_focus + 1 : 0;
  9882. unsigned int i;
  9883. form_blur();
  9884. for (i = start; i < doc.nnode; i++) {
  9885. if (form_is_control(i) && !form_disabled(i) &&
  9886. !s_eq(br_type(&doc, i), "hidden")) {
  9887. form_focus = i;
  9888. layout_valid = 0;
  9889. ngui_invalidate(&ui);
  9890. return;
  9891. }
  9892. }
  9893. form_focus = 0;
  9894. layout_valid = 0;
  9895. ngui_invalidate(&ui);
  9896. }
  9897. static void form_key(int k)
  9898. {
  9899. struct form_state *fs;
  9900. int kind;
  9901. if (!form_focus || form_focus >= doc.nnode) {
  9902. form_focus = 0;
  9903. return;
  9904. }
  9905. fs = form_get(form_focus, 1);
  9906. if (!fs || form_disabled(form_focus))
  9907. return;
  9908. kind = form_kind_of(form_focus);
  9909. if (kind == FORM_SELECT) {
  9910. unsigned int n = form_option_count(form_focus);
  9911. int changed = 0;
  9912. if (k == NGUI_KEY_UP && n) {
  9913. fs->selected = (unsigned char)
  9914. ((fs->selected + n - 1) % n);
  9915. changed = 1;
  9916. } else if (k == NGUI_KEY_DOWN && n) {
  9917. fs->selected = (unsigned char)
  9918. ((fs->selected + 1) % n);
  9919. changed = 1;
  9920. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9921. form_blur();
  9922. layout_valid = 0;
  9923. ngui_invalidate(&ui);
  9924. return;
  9925. } else {
  9926. return;
  9927. }
  9928. if (changed) {
  9929. js_browser_event(form_focus, "input", 1, 0);
  9930. js_browser_event(form_focus, "change", 1, 0);
  9931. }
  9932. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9933. if (k == ' ') {
  9934. form_click(form_focus);
  9935. return;
  9936. }
  9937. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9938. form_blur();
  9939. layout_valid = 0;
  9940. ngui_invalidate(&ui);
  9941. }
  9942. return;
  9943. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  9944. kind == FORM_RESET) {
  9945. if (k == NGUI_KEY_ESC) {
  9946. form_blur();
  9947. layout_valid = 0;
  9948. ngui_invalidate(&ui);
  9949. } else if (k == '\r' || k == '\n' || k == ' ') {
  9950. form_click(form_focus);
  9951. }
  9952. return;
  9953. } else if (k == NGUI_KEY_TAB) {
  9954. form_focus_next();
  9955. return;
  9956. } else if (k == NGUI_KEY_ESC) {
  9957. form_blur();
  9958. layout_valid = 0;
  9959. ngui_invalidate(&ui);
  9960. return;
  9961. } else if (k == '\r' || k == '\n') {
  9962. unsigned int node = form_focus;
  9963. form_blur();
  9964. if (form_ancestor(node))
  9965. form_submit_form(node, 1);
  9966. layout_valid = 0;
  9967. ngui_invalidate(&ui);
  9968. return;
  9969. } else if (k == NGUI_KEY_BACKSPACE) {
  9970. if (fs->caret) {
  9971. unsigned int i = --fs->caret;
  9972. for (; i < fs->len; i++)
  9973. fs->value[i] = fs->value[i + 1];
  9974. if (fs->len)
  9975. fs->len--;
  9976. form_dirty = 1;
  9977. js_browser_event(form_focus, "input", 1, 0);
  9978. }
  9979. } else if (k == NGUI_KEY_DELETE) {
  9980. if (fs->caret < fs->len) {
  9981. unsigned int i;
  9982. for (i = fs->caret; i < fs->len; i++)
  9983. fs->value[i] = fs->value[i + 1];
  9984. fs->len--;
  9985. form_dirty = 1;
  9986. js_browser_event(form_focus, "input", 1, 0);
  9987. }
  9988. } else if (k == NGUI_KEY_LEFT) {
  9989. if (fs->caret)
  9990. fs->caret--;
  9991. } else if (k == NGUI_KEY_RIGHT) {
  9992. if (fs->caret < fs->len)
  9993. fs->caret++;
  9994. } else if (k == NGUI_KEY_HOME) {
  9995. fs->caret = 0;
  9996. } else if (k == NGUI_KEY_END) {
  9997. fs->caret = fs->len;
  9998. } else if (k >= 32 && k < 127) {
  9999. if (fs->len < FORM_VALUE_MAX) {
  10000. unsigned int i;
  10001. for (i = fs->len; i > fs->caret; i--)
  10002. fs->value[i] = fs->value[i - 1];
  10003. fs->value[fs->caret++] = (char)k;
  10004. fs->len++;
  10005. form_dirty = 1;
  10006. js_browser_event(form_focus, "input", 1, 0);
  10007. }
  10008. } else {
  10009. return;
  10010. }
  10011. fs->value[fs->len] = '\0';
  10012. layout_valid = 0;
  10013. ngui_invalidate(&ui);
  10014. }
  10015. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  10016. * a same-document navigation: update the URL and fire hashchange. Returns
  10017. * 1 when handled. */
  10018. static int link_fragment_nav(unsigned int node)
  10019. {
  10020. const char *href = br_href(&doc, node);
  10021. char url[BR_URL_MAX];
  10022. unsigned int n = 0;
  10023. if (!href || !href[0] || !js_browser_active())
  10024. return 0;
  10025. if (href[0] == '#') {
  10026. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  10027. url[n] = page_url[n];
  10028. n++;
  10029. }
  10030. url[n] = '\0';
  10031. s_append(url, &n, href, sizeof(url));
  10032. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  10033. return 0;
  10034. }
  10035. if (!same_doc_fragment(url))
  10036. return href[0] == '#';
  10037. page_set_fragment(url, 1);
  10038. js_browser_hashchange();
  10039. return 1;
  10040. }
  10041. /* The innermost laid-out box under a screen point: the smallest valid box
  10042. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  10043. * Used to deliver clicks to elements that are neither links nor controls
  10044. * (a Vue <div role="button">, a card with a click listener). */
  10045. static unsigned int find_box_hit(int x, int y)
  10046. {
  10047. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  10048. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  10049. const struct br_layout_box *b = &layout_boxes[i];
  10050. unsigned int area;
  10051. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  10052. x < b->x || y < b->y || x >= b->x + b->w ||
  10053. y >= b->y + b->h)
  10054. continue;
  10055. area = (unsigned int)b->w * (unsigned int)b->h;
  10056. if (area <= best_area) {
  10057. best = i;
  10058. best_area = area;
  10059. }
  10060. }
  10061. return best;
  10062. }
  10063. static void handle_page_click(unsigned int *action)
  10064. {
  10065. int node;
  10066. char url[BR_URL_MAX];
  10067. if (!ui.pressed)
  10068. return;
  10069. if (ui.press_x < page_rect.x ||
  10070. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  10071. ui.press_y < page_rect.y ||
  10072. ui.press_y >= page_rect.y + page_rect.h)
  10073. return;
  10074. node = find_hit(ui.press_x, ui.press_y);
  10075. if (!node) {
  10076. unsigned int box;
  10077. if (!js_browser_active())
  10078. return;
  10079. box = find_box_hit(ui.press_x, ui.press_y);
  10080. if (box) {
  10081. form_blur();
  10082. js_browser_event(box, "click", 1, 1);
  10083. }
  10084. return;
  10085. }
  10086. if (form_is_control((unsigned int)node)) {
  10087. form_click((unsigned int)node);
  10088. return;
  10089. }
  10090. form_blur();
  10091. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  10092. return;
  10093. if (link_fragment_nav((unsigned int)node))
  10094. return;
  10095. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  10096. sizeof(url)) != 0)
  10097. return;
  10098. s_copy(click_url, url, sizeof(click_url));
  10099. *action |= ACT_NAV;
  10100. }
  10101. void _start(const char *arg)
  10102. {
  10103. struct win_info wi;
  10104. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  10105. u_win_create(960, 640, "Browser", &wi) != 0 &&
  10106. u_win_create(780, 540, "Browser", &wi) != 0) {
  10107. u_puts("browser: no graphics window\n");
  10108. u_exit(1);
  10109. }
  10110. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  10111. url_in.placeholder = "http://...";
  10112. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  10113. ui.theme.accent);
  10114. br_set_viewport(wi.width);
  10115. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  10116. s_copy(cwd, "/", sizeof(cwd));
  10117. heap_clear();
  10118. origin_cache_load();
  10119. css_cache_init();
  10120. script_cache_init();
  10121. persist_restore();
  10122. page_scroll.offset = 0;
  10123. page_scroll.content_h = 0;
  10124. if (arg && arg[0]) {
  10125. navigate(arg, 1);
  10126. } else {
  10127. load_home(1);
  10128. /* Start ready to type: keep the home page, but leave the address
  10129. * bar empty instead of showing "about:home". */
  10130. ngui_input_set(&url_in, "");
  10131. ngui_set_focus(&ui, ID_URL);
  10132. }
  10133. for (;;) {
  10134. unsigned int action = 0;
  10135. unsigned int now;
  10136. click_url[0] = '\0';
  10137. if (pending_action) {
  10138. action |= pending_action & ACT_WAIT_NAV;
  10139. if (pending_url[0])
  10140. s_copy(click_url, pending_url, sizeof(click_url));
  10141. pending_action = 0;
  10142. pending_url[0] = '\0';
  10143. cancel_fetch = 0;
  10144. } else if (preload_active) {
  10145. if (preload_wait)
  10146. preload_wait = 0;
  10147. else
  10148. preload_step();
  10149. } else if ((preload_pending &&
  10150. page_scroll.offset != preload_scroll) ||
  10151. (preload_rescan && layout_valid)) {
  10152. preload_scroll = page_scroll.offset;
  10153. preload_rescan = 0;
  10154. preload_pending = 0;
  10155. preload_node = 0;
  10156. preload_active = 1;
  10157. }
  10158. js_browser_tick();
  10159. if (resize_pending && !pending_action) {
  10160. resize_pending = 0;
  10161. resize_sent_w = layout_right - layout_left;
  10162. js_browser_window_event("resize");
  10163. }
  10164. persist_tick();
  10165. if (pending_action)
  10166. continue;
  10167. now = u_ticks_ms();
  10168. if (status_until && (int)(now - status_until) >= 0) {
  10169. status_text[0] = '\0';
  10170. status_until = 0;
  10171. status_error = 0;
  10172. ngui_invalidate(&ui);
  10173. }
  10174. if (!ngui_begin(&ui)) {
  10175. /* A queued navigation (e.g. Enter in the URL bar during
  10176. * a slow fetch) must be handled even when this frame
  10177. * needs no redraw. */
  10178. if (!action) {
  10179. fetch_workers_stop_if_unfocused();
  10180. u_sleep_ms(10);
  10181. continue;
  10182. }
  10183. } else {
  10184. draw(&action);
  10185. handle_keys(&action);
  10186. handle_page_click(&action);
  10187. ngui_end(&ui);
  10188. }
  10189. if (action & ACT_NAV) {
  10190. if (click_url[0]) {
  10191. navigate(click_url, 1);
  10192. click_url[0] = '\0';
  10193. } else {
  10194. navigate(url_in.text, 1);
  10195. }
  10196. }
  10197. if (action & ACT_BACK) {
  10198. if (hist_pos > 0) {
  10199. hist_pos--;
  10200. if (same_doc_fragment(history[hist_pos])) {
  10201. page_set_fragment(history[hist_pos], 0);
  10202. js_browser_hashchange();
  10203. } else {
  10204. navigate(history[hist_pos], 0);
  10205. }
  10206. }
  10207. }
  10208. if (action & ACT_FORWARD) {
  10209. if (hist_pos + 1 < hist_len) {
  10210. hist_pos++;
  10211. if (same_doc_fragment(history[hist_pos])) {
  10212. page_set_fragment(history[hist_pos], 0);
  10213. js_browser_hashchange();
  10214. } else {
  10215. navigate(history[hist_pos], 0);
  10216. }
  10217. }
  10218. }
  10219. if (action & ACT_RELOAD) {
  10220. if (s_eq(page_url, "about:home"))
  10221. load_home(0);
  10222. else
  10223. navigate(page_url, 0);
  10224. }
  10225. if (action & ACT_HOME)
  10226. load_home(1);
  10227. if (action & ACT_CLOSE)
  10228. quit = 1;
  10229. if (quit)
  10230. break;
  10231. if (pending_action)
  10232. continue;
  10233. fetch_workers_stop_if_unfocused();
  10234. u_sleep_ms(10);
  10235. }
  10236. fetch_workers_stop_all();
  10237. u_win_close();
  10238. u_exit(0);
  10239. }