browser.c 259 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160
  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 "img.h"
  22. #include "inflate.h"
  23. #include "ufont.h"
  24. #include "svg_raster.h"
  25. static void svg_cache_clear(void);
  26. static unsigned char *decode_arena; /* see decode_arena_get() */
  27. static unsigned int decode_arena_size;
  28. /* Start wide enough for the desktop nav; smaller screens fall back to
  29. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  30. #define BR_W 1100
  31. #define BR_H 700
  32. #define BR_TOOLBAR_H 30
  33. #define BR_STATUS_H 18
  34. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  35. #define BR_IMG_FILE_MAX (512u * 1024u)
  36. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  37. #define BR_MAX_IMAGES 256
  38. /* Decoded display bitmaps share the page heap: cap their total pixels
  39. * (RGB565 plus an optional alpha plane) instead of their count. */
  40. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  41. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  42. #define BR_IMG_LAYOUT_W 1000
  43. /* An image job may hold a fetch helper this long. The page/script
  44. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  45. * must not starve the other images of all four helpers that long. */
  46. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  47. #define BR_CSS_MAX (832u * 1024u)
  48. #define BR_CSS_COMP_MAX (192u * 1024u)
  49. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  50. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  51. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  52. #define FETCH_ABORT (-2)
  53. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  54. #define CSS_CACHE_MAX 16
  55. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  56. #define CSS_CACHE_PREFIX "bcss-"
  57. #define SCRIPT_CACHE_MAX 24
  58. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  59. #define SCRIPT_CACHE_PREFIX "bjs-"
  60. #define BR_MAX_SHEETS 6
  61. #define BR_HISTORY 16
  62. #define BR_URL_MAX 512
  63. #define BR_STATUS_MAX 200
  64. #define BR_IMG_RGB565(r, g, b) \
  65. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  66. #define BR_GRAY 0x8410
  67. enum {
  68. ID_URL = 1,
  69. ID_GO,
  70. ID_BACK,
  71. ID_FORWARD,
  72. ID_RELOAD,
  73. ID_HOME
  74. };
  75. #define ACT_NAV (1u << 0)
  76. #define ACT_BACK (1u << 1)
  77. #define ACT_FORWARD (1u << 2)
  78. #define ACT_RELOAD (1u << 3)
  79. #define ACT_HOME (1u << 4)
  80. #define ACT_CLOSE (1u << 5)
  81. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  82. ACT_HOME | ACT_CLOSE)
  83. struct br_image {
  84. int state; /* 0 empty, 1 ready */
  85. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  86. int native_w, native_h;
  87. char err[32];
  88. };
  89. static struct ngui ui;
  90. static struct ngui_input url_in;
  91. static struct ngui_scroll page_scroll;
  92. static struct br_doc doc;
  93. static struct br_image images[BR_MAX_IMAGES];
  94. static int image_count;
  95. static unsigned int image_pixels;
  96. /* Painted border boxes, in page/screen coordinates (layout starts at
  97. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  98. struct br_layout_box {
  99. int x, y;
  100. int w, h;
  101. unsigned char valid;
  102. };
  103. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  104. /* Images are loaded one per main-loop iteration so the parsed page stays
  105. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  106. static int preload_active;
  107. static int preload_max_jobs;
  108. static int preload_pending;
  109. static int preload_wait;
  110. static unsigned int preload_node;
  111. static int preload_loaded;
  112. static int preload_scroll;
  113. static int preload_rescan;
  114. static char post_status_text[BR_STATUS_MAX];
  115. static int post_status_error;
  116. static unsigned int post_status_ttl;
  117. /* Content-relative position/height of each <img>, recorded by the measure
  118. * pass so image loading can be deferred until it is near the viewport. */
  119. static unsigned short img_top[BR_MAX_NODES];
  120. static unsigned short img_h[BR_MAX_NODES];
  121. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  122. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  123. * body. Decode arenas are allocated per image instead of living here. */
  124. static unsigned char *image_io_buf;
  125. static struct ufont_face *font_faces[BR_MAX_FACES];
  126. #define image_file_buf (image_io_buf)
  127. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  128. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  129. static struct inflate image_inflate_ws;
  130. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  131. #error "CSS scratch must fit in image_io_buf"
  132. #endif
  133. static char page_url[BR_URL_MAX];
  134. static char page_title[BR_TITLE_MAX];
  135. static char cwd[64];
  136. static int page_is_local;
  137. static int page_loading;
  138. static char status_text[BR_STATUS_MAX];
  139. static unsigned int status_until;
  140. static int status_error;
  141. static char history[BR_HISTORY][BR_URL_MAX];
  142. static int hist_len, hist_pos;
  143. static char click_url[BR_URL_MAX];
  144. static char pending_url[BR_URL_MAX];
  145. #define BR_POST_MAX 4096
  146. static char pending_post[BR_POST_MAX];
  147. static unsigned int pending_post_len;
  148. /* The pending navigation is a POST even when its body is empty (a form
  149. * without fields, e.g. the OIDC consent auto-submit). */
  150. static int pending_post_is;
  151. static unsigned int pending_action;
  152. static int cancel_fetch;
  153. static int quit;
  154. static struct ngui_rect page_rect;
  155. static unsigned short *page_backbuf;
  156. static int pagebuf_w, pagebuf_h;
  157. static int page_cache_valid;
  158. static int page_cache_scroll;
  159. static unsigned int page_cache_nnode;
  160. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  161. static int layout_valid, layout_left, layout_right;
  162. static unsigned int layout_nnode;
  163. static int layout_content_h;
  164. /* layout output */
  165. struct lay_run {
  166. unsigned int off;
  167. unsigned short len;
  168. unsigned short gap;
  169. unsigned short color;
  170. unsigned short href;
  171. char lit[28];
  172. short img;
  173. signed short dy; /* inline image vertical offset */
  174. unsigned short iw, ih;
  175. unsigned short w;
  176. unsigned char font_px, bold, italic, mono, underline, strike;
  177. unsigned char overline, font_face;
  178. unsigned char transform_scale;
  179. unsigned char origin_x_kind, origin_y_kind;
  180. signed short scale_x, scale_y, rotate_x100;
  181. signed short origin_x, origin_y;
  182. unsigned char has_lit;
  183. unsigned int form; /* node + 1, 0 = not a control */
  184. unsigned char form_kind;
  185. unsigned char form_disabled;
  186. };
  187. struct lay {
  188. int draw;
  189. struct ngui *ui;
  190. int left, right;
  191. int y;
  192. int line_x, line_y, line_h;
  193. int line_left, line_right;
  194. int parent_top;
  195. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  196. int run_x;
  197. int align;
  198. int depth;
  199. int space_pending;
  200. unsigned char float_active;
  201. int float_left, float_right, float_bottom;
  202. struct lay_run runs[96];
  203. int nruns;
  204. };
  205. struct hit {
  206. int x, y, w, h;
  207. unsigned short node;
  208. };
  209. /* Live form state; the DOM attributes stay the initial/default value. */
  210. #define FORM_MAX 64
  211. #define FORM_VALUE_MAX 63
  212. enum {
  213. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  214. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  215. };
  216. struct form_state {
  217. unsigned int node;
  218. char value[FORM_VALUE_MAX + 1];
  219. unsigned char len, caret, checked, selected, used;
  220. };
  221. static struct form_state form_states[FORM_MAX];
  222. static unsigned int form_focus;
  223. static unsigned int form_dirty;
  224. static int form_descendant(unsigned int node, unsigned int form);
  225. static int form_submit_form(unsigned int node, int fire_event);
  226. static void form_reset_event(unsigned int form);
  227. static unsigned int s_len(const char *s);
  228. static int s_eq(const char *a, const char *b);
  229. static void form_key(int k);
  230. static void form_click(unsigned int node);
  231. static void style_for_node(unsigned int node, struct br_style *out);
  232. static int form_disabled(unsigned int node)
  233. {
  234. struct br_node *n = &doc.nodes[node];
  235. if (n->attr_flags & BR_ATTR_DISABLED)
  236. return 1;
  237. return br_find_attr(&doc, node, "disabled") != 0;
  238. }
  239. static int form_kind_of(unsigned int node)
  240. {
  241. const char *type = br_type(&doc, node);
  242. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  243. return FORM_TEXTAREA;
  244. if (doc.nodes[node].tag == BR_TAG_SELECT)
  245. return FORM_SELECT;
  246. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  247. if (s_eq(type, "reset"))
  248. return FORM_RESET;
  249. if (s_eq(type, "button"))
  250. return FORM_BUTTON;
  251. return FORM_SUBMIT;
  252. }
  253. if (s_eq(type, "password"))
  254. return FORM_PASSWORD;
  255. if (s_eq(type, "checkbox"))
  256. return FORM_CHECKBOX;
  257. if (s_eq(type, "radio"))
  258. return FORM_RADIO;
  259. if (s_eq(type, "submit"))
  260. return FORM_SUBMIT;
  261. if (s_eq(type, "reset"))
  262. return FORM_RESET;
  263. if (s_eq(type, "button"))
  264. return FORM_BUTTON;
  265. return FORM_TEXT;
  266. }
  267. static unsigned int form_option_count(unsigned int node)
  268. {
  269. unsigned int c, n = 0;
  270. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  271. if (doc.nodes[c].type == BR_NODE_ELEM &&
  272. doc.nodes[c].tag == BR_TAG_OPTION)
  273. n++;
  274. return n;
  275. }
  276. static unsigned int form_option_selected(unsigned int node)
  277. {
  278. unsigned int c, i = 0;
  279. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  280. if (doc.nodes[c].type != BR_NODE_ELEM ||
  281. doc.nodes[c].tag != BR_TAG_OPTION)
  282. continue;
  283. if (br_find_attr(&doc, c, "selected"))
  284. return i;
  285. i++;
  286. }
  287. return 0;
  288. }
  289. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  290. char *out, unsigned int cap)
  291. {
  292. unsigned int c, i = 0;
  293. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  294. if (doc.nodes[c].type != BR_NODE_ELEM ||
  295. doc.nodes[c].tag != BR_TAG_OPTION)
  296. continue;
  297. if (i == idx)
  298. return br_text_content(&doc, c, out, cap);
  299. i++;
  300. }
  301. return 0;
  302. }
  303. static struct form_state *form_get(unsigned int node, int create)
  304. {
  305. struct form_state *slot = 0;
  306. unsigned int i;
  307. for (i = 0; i < FORM_MAX; i++) {
  308. if (form_states[i].used) {
  309. if (form_states[i].node == node)
  310. return &form_states[i];
  311. } else if (!slot) {
  312. slot = &form_states[i];
  313. }
  314. }
  315. if (!create || !slot)
  316. return 0;
  317. slot->node = node;
  318. slot->len = 0;
  319. slot->caret = 0;
  320. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  321. slot->selected = form_option_selected(node);
  322. slot->used = 1;
  323. {
  324. unsigned int n = 0;
  325. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  326. n = br_text_content(&doc, node, slot->value,
  327. FORM_VALUE_MAX + 1);
  328. } else {
  329. const char *v = br_value(&doc, node);
  330. if (v) {
  331. n = s_len(v);
  332. if (n > FORM_VALUE_MAX)
  333. n = FORM_VALUE_MAX;
  334. for (unsigned int j = 0; j < n; j++)
  335. slot->value[j] = v[j];
  336. }
  337. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  338. n = br_text_content(&doc, node, slot->value,
  339. FORM_VALUE_MAX + 1);
  340. }
  341. if (n > FORM_VALUE_MAX)
  342. n = FORM_VALUE_MAX;
  343. slot->value[n] = '\0';
  344. slot->len = (unsigned char)n;
  345. slot->caret = (unsigned char)n;
  346. }
  347. return slot;
  348. }
  349. static void form_reset_state(void)
  350. {
  351. unsigned int i;
  352. for (i = 0; i < FORM_MAX; i++)
  353. form_states[i].used = 0;
  354. form_focus = 0;
  355. }
  356. static int form_is_control(unsigned int node)
  357. {
  358. unsigned int tag;
  359. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  360. return 0;
  361. tag = doc.nodes[node].tag;
  362. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  363. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  364. }
  365. #define HIT_MAX 96
  366. static struct hit hits[HIT_MAX];
  367. static int nhits;
  368. static unsigned short block_h[BR_MAX_NODES];
  369. /* Measure-pass top of each block, in the same document coordinates as
  370. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  371. * paint, so it cannot drive the lazy background loader). */
  372. static unsigned short block_top[BR_MAX_NODES];
  373. static char li_marker[BR_MAX_NODES][12];
  374. /* one connection object; the browser fetches one resource at a time */
  375. /* ---- tiny strings ---- */
  376. static unsigned int s_len(const char *s)
  377. {
  378. unsigned int n = 0;
  379. while (s && s[n])
  380. n++;
  381. return n;
  382. }
  383. static void s_copy(char *d, const char *s, unsigned int cap)
  384. {
  385. unsigned int i = 0;
  386. if (!cap)
  387. return;
  388. while (s && s[i] && i + 1 < cap) {
  389. d[i] = s[i];
  390. i++;
  391. }
  392. d[i] = '\0';
  393. }
  394. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  395. {
  396. while (s && *s && *n + 1 < cap)
  397. d[(*n)++] = *s++;
  398. d[*n] = '\0';
  399. }
  400. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  401. unsigned int cap)
  402. {
  403. char tmp[12];
  404. unsigned int i = 0, j;
  405. do {
  406. tmp[i++] = (char)('0' + v % 10);
  407. v /= 10;
  408. } while (v && i < sizeof(tmp));
  409. for (j = 0; j < i && *n + 1 < cap; j++)
  410. d[(*n)++] = tmp[i - 1 - j];
  411. d[*n] = '\0';
  412. }
  413. static int s_eq(const char *a, const char *b)
  414. {
  415. while (*a && *b) {
  416. if (*a != *b)
  417. return 0;
  418. a++;
  419. b++;
  420. }
  421. return *a == *b;
  422. }
  423. static int starts_with(const char *s, const char *p)
  424. {
  425. unsigned int i = 0;
  426. while (p[i]) {
  427. if (s[i] != p[i])
  428. return 0;
  429. i++;
  430. }
  431. return 1;
  432. }
  433. static int contains_ci(const char *s, const char *p)
  434. {
  435. unsigned int i, j;
  436. for (i = 0; s[i]; i++) {
  437. for (j = 0; p[j]; j++) {
  438. char a = s[i + j];
  439. if (a >= 'A' && a <= 'Z')
  440. a = (char)(a - 'A' + 'a');
  441. if (a != p[j])
  442. break;
  443. }
  444. if (!p[j])
  445. return 1;
  446. }
  447. return 0;
  448. }
  449. static char *trim(char *s)
  450. {
  451. unsigned int n;
  452. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  453. s++;
  454. n = s_len(s);
  455. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  456. s[n - 1] == '\r' || s[n - 1] == '\n'))
  457. s[--n] = '\0';
  458. return s;
  459. }
  460. /* ---- per-process heap ---- */
  461. static int heap_start(void)
  462. {
  463. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  464. if (!image_io_buf)
  465. return -1;
  466. page_backbuf = (unsigned short *)malloc(
  467. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  468. pagebuf_w = page_backbuf ? ui.w : 0;
  469. pagebuf_h = page_backbuf ? ui.h : 0;
  470. page_cache_valid = 0;
  471. return 0;
  472. }
  473. static void heap_clear(void)
  474. {
  475. memset(font_faces, 0, sizeof(font_faces));
  476. ngui_font_detach(&ui);
  477. svg_cache_clear();
  478. decode_arena = 0; /* lives in the page heap too */
  479. decode_arena_size = 0;
  480. heap_reset();
  481. /* The document arenas live in that heap; drop the stale pointers so
  482. * the next br_parse_plain() allocates fresh ones. */
  483. doc.nodes = 0;
  484. doc.text = 0;
  485. doc.attrs = 0;
  486. image_io_buf = 0;
  487. page_backbuf = 0;
  488. pagebuf_w = pagebuf_h = 0;
  489. page_cache_valid = 0;
  490. }
  491. static void browser_rules_alloc(void)
  492. {
  493. struct br_rule *rules;
  494. rules = (struct br_rule *)malloc(
  495. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  496. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  497. }
  498. /* ---- status ---- */
  499. static void set_status(const char *s, int err, unsigned int ttl_ms)
  500. {
  501. s_copy(status_text, s, sizeof(status_text));
  502. status_error = err;
  503. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  504. ngui_invalidate(&ui);
  505. }
  506. /* ---- JavaScript ---- */
  507. static int resolve_link(const char *base, const char *href, char *out,
  508. unsigned int cap);
  509. static char js_last_status[BR_STATUS_MAX];
  510. static int js_last_error;
  511. static void js_host_status(const char *msg, int error)
  512. {
  513. s_copy(js_last_status, msg, sizeof(js_last_status));
  514. js_last_error = error;
  515. set_status(msg, error, 6000);
  516. }
  517. static void js_host_report(const char *msg)
  518. {
  519. u_puts("[js] ");
  520. u_puts(msg);
  521. u_putc('\n');
  522. s_copy(js_last_status, msg, sizeof(js_last_status));
  523. js_last_error = 1;
  524. set_status(msg, 1, 8000);
  525. }
  526. static void js_host_navigate(const char *url)
  527. {
  528. char resolved[BR_URL_MAX];
  529. if (!url || !url[0])
  530. return;
  531. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  532. return;
  533. s_copy(pending_url, resolved, sizeof(pending_url));
  534. pending_action |= ACT_NAV;
  535. cancel_fetch = 1;
  536. }
  537. static void js_host_changed(void)
  538. {
  539. /* Class/style/attribute mutations change computed styles, not just the
  540. * text: drop the per-node style cache before the next layout. */
  541. br_reset_styles(&doc);
  542. layout_valid = 0;
  543. /* Script-built content (Angular's ng-repeat cards) brings new images
  544. * and inline background styles: rescan once the main loop is idle. */
  545. preload_rescan = 1;
  546. ngui_invalidate(&ui);
  547. }
  548. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  549. {
  550. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  551. return 0;
  552. *x = layout_boxes[node].x - page_rect.x;
  553. *y = layout_boxes[node].y - page_rect.y;
  554. *w = layout_boxes[node].w;
  555. *h = layout_boxes[node].h;
  556. return 1;
  557. }
  558. static void form_copy_out(const char *s, char *buf, int cap)
  559. {
  560. int i = 0;
  561. if (!buf || cap <= 0)
  562. return;
  563. while (s && s[i] && i + 1 < cap) {
  564. buf[i] = s[i];
  565. i++;
  566. }
  567. buf[i] = '\0';
  568. }
  569. static int js_host_form_value(unsigned int node, char *buf, int cap)
  570. {
  571. struct form_state *fs;
  572. int kind;
  573. if (!form_is_control(node))
  574. return 0;
  575. kind = form_kind_of(node);
  576. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  577. return 0;
  578. if (kind == FORM_SELECT) {
  579. char opt[64] = "";
  580. unsigned int c, i = 0;
  581. fs = form_get(node, 1);
  582. if (!fs)
  583. return 0;
  584. form_option_text(node, fs->selected, opt, sizeof(opt));
  585. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  586. if (doc.nodes[c].type != BR_NODE_ELEM ||
  587. doc.nodes[c].tag != BR_TAG_OPTION)
  588. continue;
  589. if (i == fs->selected) {
  590. const char *v = br_value(&doc, c);
  591. if (v && v[0])
  592. form_copy_out(v, buf, cap);
  593. else
  594. form_copy_out(opt, buf, cap);
  595. return 1;
  596. }
  597. i++;
  598. }
  599. form_copy_out(opt, buf, cap);
  600. return 1;
  601. }
  602. fs = form_get(node, 1);
  603. if (!fs)
  604. return 0;
  605. form_copy_out(fs->value, buf, cap);
  606. return 1;
  607. }
  608. static int js_host_form_checked(unsigned int node)
  609. {
  610. struct form_state *fs;
  611. int kind;
  612. if (!form_is_control(node))
  613. return -1;
  614. kind = form_kind_of(node);
  615. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  616. return -1;
  617. fs = form_get(node, 1);
  618. return fs ? fs->checked : 0;
  619. }
  620. static int js_host_form_selected(unsigned int node)
  621. {
  622. struct form_state *fs;
  623. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  624. return -1;
  625. fs = form_get(node, 1);
  626. return fs ? fs->selected : 0;
  627. }
  628. static int js_host_form_set_value(unsigned int node, const char *value)
  629. {
  630. struct form_state *fs;
  631. unsigned int n;
  632. if (!form_is_control(node))
  633. return 0;
  634. fs = form_get(node, 1);
  635. if (!fs)
  636. return 0;
  637. n = s_len(value ? value : "");
  638. if (n > FORM_VALUE_MAX)
  639. n = FORM_VALUE_MAX;
  640. for (unsigned int i = 0; i < n; i++)
  641. fs->value[i] = value[i];
  642. fs->value[n] = '\0';
  643. fs->len = (unsigned char)n;
  644. fs->caret = (unsigned char)n;
  645. layout_valid = 0;
  646. ngui_invalidate(&ui);
  647. return 1;
  648. }
  649. static int js_host_form_set_checked(unsigned int node, int checked)
  650. {
  651. struct form_state *fs;
  652. int kind;
  653. if (!form_is_control(node))
  654. return 0;
  655. kind = form_kind_of(node);
  656. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  657. return 0;
  658. fs = form_get(node, 1);
  659. if (!fs)
  660. return 0;
  661. fs->checked = (unsigned char)(checked != 0);
  662. layout_valid = 0;
  663. ngui_invalidate(&ui);
  664. return 1;
  665. }
  666. static int js_host_form_set_selected(unsigned int node, int index)
  667. {
  668. struct form_state *fs;
  669. unsigned int n;
  670. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  671. return 0;
  672. fs = form_get(node, 1);
  673. if (!fs)
  674. return 0;
  675. n = form_option_count(node);
  676. if (index < 0)
  677. index = 0;
  678. if (n && (unsigned int)index >= n)
  679. index = (int)n - 1;
  680. fs->selected = (unsigned char)index;
  681. layout_valid = 0;
  682. ngui_invalidate(&ui);
  683. return 1;
  684. }
  685. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  686. {
  687. unsigned int i;
  688. int n = 0;
  689. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  690. doc.nodes[form].tag != BR_TAG_FORM)
  691. return 0;
  692. for (i = 0; i < doc.nnode && n < cap; i++) {
  693. struct br_node *nd = &doc.nodes[i];
  694. if (i == form || nd->type != BR_NODE_ELEM)
  695. continue;
  696. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  697. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  698. continue;
  699. if (!form_descendant(i, form))
  700. continue;
  701. out[n++] = i;
  702. }
  703. return n;
  704. }
  705. static int js_host_form_submit(unsigned int form)
  706. {
  707. form_submit_form(form, 0);
  708. return 1;
  709. }
  710. static int js_host_form_reset(unsigned int form)
  711. {
  712. form_reset_event(form);
  713. return 1;
  714. }
  715. static void css_computed_name(const char *p, char *out, int cap)
  716. {
  717. int n = 0;
  718. for (; p && *p && n + 2 < cap; p++) {
  719. char c = *p;
  720. if (c >= 'A' && c <= 'Z') {
  721. out[n++] = '-';
  722. c = (char)(c - 'A' + 'a');
  723. } else if (c == '_') {
  724. c = '-';
  725. } else if (c >= 'a' && c <= 'z') {
  726. /* keep */
  727. }
  728. out[n++] = c;
  729. }
  730. out[n] = '\0';
  731. if (!strcmp(out, "css-float"))
  732. strcpy(out, "float");
  733. }
  734. static void css_rgb(unsigned short c, char *buf, int cap)
  735. {
  736. int r = ((c >> 11) & 31) * 255 / 31;
  737. int g = ((c >> 5) & 63) * 255 / 63;
  738. int b = (c & 31) * 255 / 31;
  739. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  740. }
  741. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  742. int font_px)
  743. {
  744. if (unit == 4) {
  745. snprintf(buf, cap, "auto");
  746. } else if (unit == 0) {
  747. snprintf(buf, cap, "%dpx", raw);
  748. } else if (unit == 1) {
  749. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  750. } else if (unit == 2) {
  751. /* Chrome's getComputedStyle() reports used pixel values. */
  752. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  753. } else if (unit == 3) {
  754. snprintf(buf, cap, "%dpx",
  755. (int)br_root_font_px() * raw / 100);
  756. } else {
  757. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  758. raw / 100, raw % 100, px);
  759. }
  760. }
  761. static int js_host_computed(unsigned int node, const char *property,
  762. char *buf, int cap)
  763. {
  764. struct br_style st;
  765. char name[40];
  766. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  767. return 0;
  768. buf[0] = '\0';
  769. css_computed_name(property, name, sizeof(name));
  770. style_for_node(node, &st);
  771. if (!strcmp(name, "display")) {
  772. const char *v = "inline";
  773. if (st.display == BR_DISPLAY_BLOCK)
  774. v = "block";
  775. else if (st.display == BR_DISPLAY_NONE)
  776. v = "none";
  777. else if (st.display == BR_DISPLAY_FLEX)
  778. v = "flex";
  779. else if (st.display == BR_DISPLAY_GRID)
  780. v = "grid";
  781. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  782. v = "inline-block";
  783. snprintf(buf, cap, "%s", v);
  784. } else if (!strcmp(name, "position")) {
  785. static const char *pos[] = {
  786. "static", "absolute", "fixed", "relative", "sticky"
  787. };
  788. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  789. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  790. int is_w = name[0] == 'w';
  791. int kind = is_w ? st.width_kind : st.height_kind;
  792. int val = is_w ? st.width : st.height;
  793. if (kind == 3) {
  794. if (is_w)
  795. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  796. st.width_calc_pct / 100,
  797. st.width_calc_pct % 100,
  798. st.width_calc_px);
  799. else
  800. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  801. st.height_calc_pct / 100,
  802. st.height_calc_pct % 100,
  803. st.height_calc_px);
  804. } else if (kind == 1) {
  805. snprintf(buf, cap, "%dpx", val);
  806. } else if (kind == 2) {
  807. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  808. } else {
  809. snprintf(buf, cap, "auto");
  810. }
  811. } else if (!strcmp(name, "color") ||
  812. !strcmp(name, "background-color")) {
  813. if (!strcmp(name, "background-color") && !st.has_bg)
  814. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  815. else
  816. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  817. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  818. int is_fill = name[0] == 'f';
  819. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  820. if (mode == BR_PAINT_COLOR)
  821. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  822. else if (mode == BR_PAINT_CURRENT)
  823. css_rgb(st.color, buf, cap);
  824. else if (mode == BR_PAINT_UNSET && is_fill)
  825. snprintf(buf, cap, "rgb(0, 0, 0)");
  826. else if (mode == BR_PAINT_URL)
  827. snprintf(buf, cap, "url()");
  828. else
  829. snprintf(buf, cap, "none");
  830. } else if (!strcmp(name, "font-size")) {
  831. snprintf(buf, cap, "%dpx", st.font_px);
  832. } else if (!strcmp(name, "font-weight")) {
  833. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  834. } else if (!strcmp(name, "font-style")) {
  835. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  836. } else if (!strcmp(name, "font-family")) {
  837. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  838. br_font_face_family(st.font_face)[0])
  839. snprintf(buf, cap, "%s",
  840. br_font_face_family(st.font_face));
  841. else
  842. snprintf(buf, cap, "%s",
  843. st.mono ? "monospace" : "sans-serif");
  844. } else if (!strcmp(name, "text-align")) {
  845. static const char *al[] = { "left", "center", "right", "justify" };
  846. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  847. } else if (!strcmp(name, "float")) {
  848. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  849. st.float_left == 2 ? "right" : "none");
  850. } else if (!strcmp(name, "clear")) {
  851. static const char *cl[] = { "none", "left", "right", "both" };
  852. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  853. } else if (!strcmp(name, "opacity")) {
  854. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  855. } else if (!strcmp(name, "visibility")) {
  856. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  857. } else if (!strcmp(name, "overflow")) {
  858. snprintf(buf, cap, "%s",
  859. st.overflow_hidden ? "hidden" : "visible");
  860. } else if (!strcmp(name, "white-space")) {
  861. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  862. } else if (!strcmp(name, "text-transform")) {
  863. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  864. } else if (!strcmp(name, "box-sizing")) {
  865. snprintf(buf, cap, "%s",
  866. st.box_sizing ? "border-box" : "content-box");
  867. } else if (!strcmp(name, "line-height")) {
  868. if (st.line_h_px)
  869. snprintf(buf, cap, "%dpx", st.line_h_px);
  870. else if (st.line_h_pct)
  871. snprintf(buf, cap, "%d%%", st.line_h_pct);
  872. else
  873. snprintf(buf, cap, "normal");
  874. } else if (!strcmp(name, "z-index")) {
  875. if (st.z_set)
  876. snprintf(buf, cap, "%d", st.z_index);
  877. else
  878. snprintf(buf, cap, "auto");
  879. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  880. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  881. int set = name[0] == 't' ? st.top_set :
  882. name[0] == 'l' ? st.left_set :
  883. name[0] == 'r' ? st.right_set : st.bottom_set;
  884. int v = name[0] == 't' ? st.top :
  885. name[0] == 'l' ? st.left :
  886. name[0] == 'r' ? st.right : st.bottom;
  887. if (set)
  888. snprintf(buf, cap, "%dpx", v);
  889. else
  890. snprintf(buf, cap, "auto");
  891. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  892. !strcmp(name, "margin-bottom") ||
  893. !strcmp(name, "margin-left") ||
  894. !strcmp(name, "padding-top") ||
  895. !strcmp(name, "padding-right") ||
  896. !strcmp(name, "padding-bottom") ||
  897. !strcmp(name, "padding-left")) {
  898. int is_pad = name[0] == 'p';
  899. int side = name[strlen(name) - 1] == 'p' ? 0 :
  900. name[strlen(name) - 1] == 't' ? 1 :
  901. name[strlen(name) - 1] == 'm' ? 2 : 3;
  902. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  903. if (!strcmp(name, "margin-right") ||
  904. !strcmp(name, "padding-right"))
  905. side = 1;
  906. else if (!strcmp(name, "margin-bottom") ||
  907. !strcmp(name, "padding-bottom"))
  908. side = 2;
  909. else if (!strcmp(name, "margin-left") ||
  910. !strcmp(name, "padding-left"))
  911. side = 3;
  912. else
  913. side = 0;
  914. side += is_pad ? 4 : 0;
  915. css_mp_value(buf, cap,
  916. side == 0 ? st.mt : side == 1 ? st.mr :
  917. side == 2 ? st.mb : side == 3 ? st.ml :
  918. side == 4 ? st.pt : side == 5 ? st.pr :
  919. side == 6 ? st.pb : st.pl,
  920. st.mp_unit[side], st.mp_calc_px[side],
  921. st.font_px);
  922. } else if (!strcmp(name, "border-top-width") ||
  923. !strcmp(name, "border-right-width") ||
  924. !strcmp(name, "border-bottom-width") ||
  925. !strcmp(name, "border-left-width")) {
  926. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  927. name[7] == 'b' ? 2 : 3;
  928. snprintf(buf, cap, "%dpx", st.border_w[side]);
  929. } else if (!strcmp(name, "border-top-color") ||
  930. !strcmp(name, "border-right-color") ||
  931. !strcmp(name, "border-bottom-color") ||
  932. !strcmp(name, "border-left-color")) {
  933. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  934. name[7] == 'b' ? 2 : 3;
  935. if (st.border_w[side] && !st.border_t[side])
  936. css_rgb(st.border_c[side], buf, cap);
  937. else
  938. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  939. } else if (!strcmp(name, "background-image")) {
  940. if (st.bg_image)
  941. snprintf(buf, cap, "url(\"%s\")",
  942. br_bg_image_url(st.bg_image - 1));
  943. else
  944. snprintf(buf, cap, "none");
  945. } else if (!strcmp(name, "background-repeat")) {
  946. static const char *rp[] = {
  947. "repeat", "no-repeat", "repeat-x", "repeat-y"
  948. };
  949. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  950. st.bg_repeat : 0]);
  951. } else if (!strcmp(name, "background-position")) {
  952. if (st.bg_pos_x_kind == 1)
  953. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  954. st.bg_pos_y);
  955. else
  956. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  957. st.bg_pos_y);
  958. } else if (!strcmp(name, "background-size")) {
  959. if (st.bg_size_kind == 3)
  960. snprintf(buf, cap, "cover");
  961. else if (st.bg_size_kind == 4)
  962. snprintf(buf, cap, "contain");
  963. else if (st.bg_size_kind == 1)
  964. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  965. st.bg_size_h);
  966. else if (st.bg_size_kind == 2)
  967. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  968. st.bg_size_h);
  969. else
  970. snprintf(buf, cap, "auto");
  971. } else if (!strcmp(name, "transform")) {
  972. char tmp[128];
  973. unsigned int n = 0;
  974. if (!st.transform_set) {
  975. snprintf(buf, cap, "none");
  976. } else {
  977. tmp[0] = '\0';
  978. if (st.tx || st.ty) {
  979. snprintf(tmp + n, sizeof(tmp) - n,
  980. "translate(%dpx, %dpx)", st.tx, st.ty);
  981. n = (unsigned int)strlen(tmp);
  982. }
  983. if (st.transform_scale) {
  984. snprintf(tmp + n, sizeof(tmp) - n,
  985. "%sscale(%d.%02d, %d.%02d)",
  986. n ? " " : "", st.scale_x / 100,
  987. st.scale_x % 100, st.scale_y / 100,
  988. st.scale_y % 100);
  989. n = (unsigned int)strlen(tmp);
  990. if (st.rotate_x100) {
  991. snprintf(tmp + n, sizeof(tmp) - n,
  992. " rotate(%d.%02ddeg)",
  993. st.rotate_x100 / 100,
  994. st.rotate_x100 % 100);
  995. }
  996. } else if (st.rotate_x100) {
  997. snprintf(tmp + n, sizeof(tmp) - n,
  998. "%srotate(%d.%02ddeg)",
  999. n ? " " : "", st.rotate_x100 / 100,
  1000. st.rotate_x100 % 100);
  1001. }
  1002. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1003. }
  1004. } else {
  1005. return 0;
  1006. }
  1007. return buf[0] != '\0';
  1008. }
  1009. static int js_host_click(unsigned int node)
  1010. {
  1011. char url[BR_URL_MAX];
  1012. const char *href;
  1013. if (node >= doc.nnode)
  1014. return 0;
  1015. if (form_is_control(node)) {
  1016. form_click(node); /* dispatches its own click event */
  1017. return 1;
  1018. }
  1019. /* element.click() fires a bubbling, cancelable click before the
  1020. * default action, like a real click (delegated list handlers). */
  1021. if (!js_browser_event(node, "click", 1, 1))
  1022. return 1;
  1023. href = br_href(&doc, node);
  1024. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1025. return 0;
  1026. s_copy(pending_url, url, sizeof(pending_url));
  1027. pending_action |= ACT_NAV;
  1028. cancel_fetch = 1;
  1029. ngui_invalidate(&ui);
  1030. return 1;
  1031. }
  1032. static int fetch_script_text(const char *url, unsigned char **out,
  1033. unsigned int *outlen, char *err,
  1034. unsigned int errcap);
  1035. struct fetch_worker;
  1036. static struct fetch_worker *fetch_worker_alloc(void);
  1037. static void fetch_worker_release(struct fetch_worker *w);
  1038. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1039. unsigned int cap, const char *post,
  1040. unsigned int post_len, unsigned int node,
  1041. int bg, char *err, unsigned int errcap);
  1042. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1043. unsigned int errcap);
  1044. static int fetch_worker_read_body(struct fetch_worker *w,
  1045. unsigned char *plain,
  1046. unsigned int plaincap,
  1047. unsigned char *comp,
  1048. unsigned int compcap,
  1049. int *truncated, char *err,
  1050. unsigned int errcap);
  1051. static void fetch_workers_stop_all(void);
  1052. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1053. unsigned int cap, const char *method,
  1054. const char *ctype, const char *post,
  1055. unsigned int post_len, unsigned int node,
  1056. int bg, char *err, unsigned int errcap);
  1057. static int script_cache_has(const char *url);
  1058. static void script_cache_put(const char *url, const unsigned char *data,
  1059. unsigned int len);
  1060. static unsigned int script_cache_hash(const char *s);
  1061. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1062. unsigned int errcap);
  1063. static void fetch_workers_cancel_busy(void);
  1064. static void worker_wait_ui(void);
  1065. static int fetch_worker_status(const struct fetch_worker *w);
  1066. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1067. * module load: the wait must not pump input, or a click would dispatch DOM
  1068. * events into the middle of the running script. */
  1069. static int fetch_wait_passive;
  1070. static void script_error(const char *what, const char *url, const char *why)
  1071. {
  1072. char msg[192];
  1073. unsigned int n = 0;
  1074. s_append(msg, &n, what, sizeof(msg));
  1075. if (url && url[0]) {
  1076. s_append(msg, &n, " ", sizeof(msg));
  1077. s_append(msg, &n, url, sizeof(msg));
  1078. }
  1079. if (why && why[0]) {
  1080. s_append(msg, &n, ": ", sizeof(msg));
  1081. s_append(msg, &n, why, sizeof(msg));
  1082. }
  1083. js_host_report(msg);
  1084. }
  1085. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1086. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1087. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1088. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1089. #define JS_HTTP_POST_MAX (16u * 1024u)
  1090. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1091. static int js_worker_http(const char *method, const char *url,
  1092. const char *ctype, const char *body,
  1093. unsigned int body_len, struct js_http_resp *r,
  1094. char *err, int errcap);
  1095. static int js_host_http(const char *method, const char *url,
  1096. const char *ctype, const char *body,
  1097. unsigned int body_len, struct js_http_resp *r,
  1098. char *err, int errcap)
  1099. {
  1100. if (pending_action) {
  1101. s_copy(err, "page is navigating", (unsigned int)errcap);
  1102. return -1;
  1103. }
  1104. if (url[0] == '/') {
  1105. /* Local file: GET only. */
  1106. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1107. int rv;
  1108. if (!buf) {
  1109. s_copy(err, "out of memory", (unsigned int)errcap);
  1110. return -1;
  1111. }
  1112. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1113. (int)JS_HTTP_MAX);
  1114. r->status = rv < 0 ? 404 : 200;
  1115. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1116. buf[r->len] = '\0';
  1117. r->body = (char *)buf;
  1118. s_copy(r->url, url, sizeof(r->url));
  1119. if (contains_ci(url, ".json"))
  1120. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1121. return 0;
  1122. }
  1123. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1124. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1125. return -1;
  1126. }
  1127. if (body_len > JS_HTTP_POST_MAX) {
  1128. s_copy(err, "request body too large", (unsigned int)errcap);
  1129. return -1;
  1130. }
  1131. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1132. errcap);
  1133. }
  1134. /* Module source for the engine's loader: the boot script cache first, then
  1135. * one blocking fetch with input pumping disabled (the loader runs inside
  1136. * JavaScript). */
  1137. static char *js_host_load_script(const char *url, unsigned int *len)
  1138. {
  1139. unsigned char *data = 0;
  1140. char err[64];
  1141. int rv;
  1142. fetch_wait_passive++;
  1143. set_status("Loading module...", 0, 0);
  1144. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1145. fetch_wait_passive--;
  1146. if (rv != 0) {
  1147. script_error("Cannot load module", url,
  1148. rv == FETCH_ABORT ? "navigation" : err);
  1149. return 0;
  1150. }
  1151. return (char *)data;
  1152. }
  1153. /* Web Storage lives in /share, outside the page heap that every navigation
  1154. * resets: localStorage per origin for the boot, sessionStorage per origin
  1155. * and browser window. */
  1156. static void js_storage_path(int kind, char *out, unsigned int cap)
  1157. {
  1158. char origin[160];
  1159. unsigned int n = 0, i = 0, slashes = 0;
  1160. while (page_url[i] && i + 1 < sizeof(origin)) {
  1161. if (page_url[i] == '/' && ++slashes == 3)
  1162. break;
  1163. origin[i] = page_url[i];
  1164. i++;
  1165. }
  1166. origin[i] = '\0';
  1167. s_append(out, &n, kind ? "/share/bss" : "/share/bls", cap);
  1168. if (kind) {
  1169. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1170. s_append(out, &n, "-", cap);
  1171. }
  1172. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1173. }
  1174. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1175. {
  1176. char path[48];
  1177. int rv;
  1178. js_storage_path(kind, path, sizeof(path));
  1179. if (set) {
  1180. if (!set[0] || !strcmp(set, "{}")) {
  1181. u_syscall1(SYS_UNLINK, (int)path);
  1182. return 0;
  1183. }
  1184. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1185. (int)strlen(set)) < 0 ? -1 : 0;
  1186. }
  1187. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1188. if (rv < 0)
  1189. return -1;
  1190. out[rv] = '\0';
  1191. return rv;
  1192. }
  1193. /* <link rel="modulepreload">: download the page's module graph on all
  1194. * helpers at once into the boot script cache, before any script runs. The
  1195. * engine's module loader is sequential (one blocking fetch per import), so
  1196. * without this a Vite app with a dozen chunks pays every round trip in a
  1197. * row. Failures are ignored; the loader fetches what is missing. */
  1198. #define MODULE_PRELOAD_MAX 24
  1199. static void prefetch_module_preloads(void)
  1200. {
  1201. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1202. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1203. unsigned int count = 0, next = 0, done = 0, i;
  1204. char err[64];
  1205. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1206. struct br_node *nd = &doc.nodes[i];
  1207. const char *rel, *href;
  1208. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1209. continue;
  1210. rel = br_rel(&doc, i);
  1211. href = br_href(&doc, i);
  1212. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1213. continue;
  1214. if (resolve_link(page_url, href, urls[count],
  1215. sizeof(urls[count])) != 0 ||
  1216. urls[count][0] == '/' || script_cache_has(urls[count]))
  1217. continue;
  1218. slot[count++] = 0;
  1219. }
  1220. if (!count)
  1221. return;
  1222. set_status("Loading modules...", 0, 0);
  1223. while (done < count) {
  1224. struct fetch_worker *w;
  1225. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1226. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1227. 0, 0, 0, err,
  1228. sizeof(err)) != 0) {
  1229. fetch_worker_release(w);
  1230. done++;
  1231. } else {
  1232. slot[next] = w;
  1233. }
  1234. next++;
  1235. }
  1236. worker_wait_ui();
  1237. if (cancel_fetch || pending_action) {
  1238. fetch_workers_cancel_busy();
  1239. return;
  1240. }
  1241. for (i = 0; i < next; i++) {
  1242. unsigned char *body;
  1243. int rv, tr = 0;
  1244. if (!slot[i])
  1245. continue;
  1246. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1247. if (rv == 0)
  1248. continue;
  1249. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1250. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1251. if (body) {
  1252. rv = fetch_worker_read_body(slot[i], body,
  1253. BR_SCRIPT_MAX, image_io_buf,
  1254. BR_PAGE_COMP_MAX, &tr, err,
  1255. sizeof(err));
  1256. if (rv > 0 && !tr)
  1257. script_cache_put(urls[i], body,
  1258. (unsigned int)rv);
  1259. free(body);
  1260. }
  1261. fetch_worker_release(slot[i]);
  1262. slot[i] = 0;
  1263. done++;
  1264. }
  1265. u_sleep_ms(10);
  1266. }
  1267. }
  1268. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1269. * submitted to helper workers ahead of time, but scripts still execute in
  1270. * document order. */
  1271. #define SCRIPT_INLINE 0
  1272. #define SCRIPT_LOCAL 1
  1273. #define SCRIPT_REMOTE 2
  1274. #define SCRIPT_ERROR 3
  1275. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1276. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1277. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1278. static void script_submit_window(unsigned int *next, char *err,
  1279. unsigned int errcap)
  1280. {
  1281. while (*next < doc.nscripts) {
  1282. struct fetch_worker *w;
  1283. if (script_kind[*next] != SCRIPT_REMOTE) {
  1284. (*next)++;
  1285. continue;
  1286. }
  1287. w = fetch_worker_alloc();
  1288. if (!w)
  1289. return;
  1290. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1291. 0, 0, 0, 0, err, errcap) != 0) {
  1292. fetch_worker_release(w);
  1293. script_kind[*next] = SCRIPT_ERROR;
  1294. (*next)++;
  1295. continue;
  1296. }
  1297. script_slot[*next] = w;
  1298. (*next)++;
  1299. }
  1300. }
  1301. /* Run the page's scripts in document order. External bodies are prefetched
  1302. * in parallel so downloading script N+1 overlaps executing script N; inline
  1303. * bodies are copied because the engine needs NUL-terminated text. */
  1304. static void run_page_scripts(void)
  1305. {
  1306. struct js_browser_host host;
  1307. unsigned int i, next = 0;
  1308. char err[64], ferr[64];
  1309. if (!doc.nscripts)
  1310. return;
  1311. host.status = js_host_status;
  1312. host.report = js_host_report;
  1313. host.navigate = js_host_navigate;
  1314. host.changed = js_host_changed;
  1315. host.rect = js_host_rect;
  1316. host.form_value = js_host_form_value;
  1317. host.form_checked = js_host_form_checked;
  1318. host.form_selected = js_host_form_selected;
  1319. host.form_set_value = js_host_form_set_value;
  1320. host.form_set_checked = js_host_form_set_checked;
  1321. host.form_set_selected = js_host_form_set_selected;
  1322. host.form_elements = js_host_form_elements;
  1323. host.form_submit = js_host_form_submit;
  1324. host.form_reset = js_host_form_reset;
  1325. host.click = js_host_click;
  1326. host.computed = js_host_computed;
  1327. host.http = js_host_http;
  1328. host.load_script = js_host_load_script;
  1329. host.storage = js_host_storage;
  1330. host.page_url = page_url;
  1331. host.width = ui.w;
  1332. host.height = ui.h;
  1333. if (js_browser_start(&doc, &host) != 0) {
  1334. js_host_status("JavaScript: out of memory", 1);
  1335. return;
  1336. }
  1337. prefetch_module_preloads();
  1338. for (i = 0; i < doc.nscripts; i++) {
  1339. struct br_script *script = &doc.scripts[i];
  1340. const char *src_attr = script->src_off ?
  1341. doc.attrs + script->src_off : "";
  1342. script_slot[i] = 0;
  1343. if (!script->src_off) {
  1344. script_kind[i] = SCRIPT_INLINE;
  1345. continue;
  1346. }
  1347. if (!src_attr[0] ||
  1348. resolve_link(page_url, src_attr, script_urls[i],
  1349. sizeof(script_urls[i])) != 0) {
  1350. script_urls[i][0] = '\0';
  1351. script_kind[i] = SCRIPT_ERROR;
  1352. continue;
  1353. }
  1354. if (script_urls[i][0] == '/' ||
  1355. script_cache_has(script_urls[i]))
  1356. script_kind[i] = SCRIPT_LOCAL;
  1357. else
  1358. script_kind[i] = SCRIPT_REMOTE;
  1359. }
  1360. script_submit_window(&next, ferr, sizeof(ferr));
  1361. for (i = 0; i < doc.nscripts; i++) {
  1362. struct br_script *script = &doc.scripts[i];
  1363. if (script_kind[i] == SCRIPT_INLINE) {
  1364. unsigned int off = script->off;
  1365. unsigned int len = script->len;
  1366. unsigned int k;
  1367. char *src = (char *)malloc(len + 1);
  1368. if (!src) {
  1369. js_host_status("JavaScript: out of memory", 1);
  1370. break;
  1371. }
  1372. for (k = 0; k < len; k++)
  1373. src[k] = doc.script_src[off + k];
  1374. src[len] = '\0';
  1375. if (script->module) {
  1376. /* A distinct module name per inline module
  1377. * (QuickJS registers modules by name); the
  1378. * fragment keeps relative imports resolving
  1379. * against the page. */
  1380. char mname[BR_URL_MAX + 16];
  1381. unsigned int mn = 0;
  1382. s_append(mname, &mn, page_url, sizeof(mname));
  1383. s_append(mname, &mn, "#module", sizeof(mname));
  1384. s_append_dec(mname, &mn, i, sizeof(mname));
  1385. js_browser_run_module(src, mname);
  1386. } else {
  1387. js_browser_run(src, page_url);
  1388. }
  1389. free(src);
  1390. } else if (script->src_off) {
  1391. const char *src_attr = doc.attrs + script->src_off;
  1392. if (script_kind[i] == SCRIPT_ERROR) {
  1393. script_error("Cannot load script", src_attr,
  1394. script_urls[i][0] ?
  1395. "network busy" :
  1396. "unsupported URL");
  1397. continue;
  1398. }
  1399. if (script_kind[i] == SCRIPT_LOCAL) {
  1400. unsigned char *data = 0;
  1401. unsigned int len = 0;
  1402. int rv;
  1403. set_status("Loading script...", 0, 0);
  1404. rv = fetch_script_text(script_urls[i], &data,
  1405. &len, err, sizeof(err));
  1406. if (rv == FETCH_ABORT)
  1407. break;
  1408. if (rv != 0) {
  1409. script_error("Cannot load script",
  1410. script_urls[i], err);
  1411. continue;
  1412. }
  1413. if (script->module)
  1414. js_browser_run_module(
  1415. (const char *)data,
  1416. script_urls[i]);
  1417. else
  1418. js_browser_run((const char *)data,
  1419. script_urls[i]);
  1420. free(data);
  1421. } else {
  1422. struct fetch_worker *w = script_slot[i];
  1423. unsigned char *body = 0;
  1424. int tr = 0, rv;
  1425. if (!w) {
  1426. w = fetch_worker_alloc();
  1427. if (!w)
  1428. continue;
  1429. if (fetch_worker_submit(w,
  1430. script_urls[i],
  1431. BR_SCRIPT_MAX,
  1432. 0, 0, 0, 0, err,
  1433. sizeof(err)) != 0) {
  1434. fetch_worker_release(w);
  1435. script_kind[i] = SCRIPT_ERROR;
  1436. if (i == next)
  1437. next++;
  1438. continue;
  1439. }
  1440. script_slot[i] = w;
  1441. if (i == next)
  1442. next++;
  1443. }
  1444. set_status("Loading script...", 0, 0);
  1445. rv = fetch_worker_wait(w, err, sizeof(err));
  1446. if (rv == FETCH_ABORT) {
  1447. fetch_workers_stop_all();
  1448. break;
  1449. }
  1450. /* The body gets its own buffer (scripts are up
  1451. * to 2 MB); image_io_buf takes the gzip
  1452. * stream. */
  1453. body = rv == 0 ? (unsigned char *)malloc(
  1454. BR_SCRIPT_MAX + 1) : 0;
  1455. if (body)
  1456. rv = fetch_worker_read_body(w, body,
  1457. BR_SCRIPT_MAX, image_io_buf,
  1458. BR_PAGE_COMP_MAX, &tr, err,
  1459. sizeof(err));
  1460. else {
  1461. if (rv == 0)
  1462. s_copy(err, "out of memory",
  1463. sizeof(err));
  1464. rv = -1;
  1465. }
  1466. fetch_worker_release(w);
  1467. script_slot[i] = 0;
  1468. script_submit_window(&next, ferr, sizeof(ferr));
  1469. if (rv <= 0)
  1470. script_error("Cannot load script",
  1471. script_urls[i], err);
  1472. else if (tr || (unsigned int)rv >=
  1473. BR_SCRIPT_MAX)
  1474. script_error("Cannot load script",
  1475. script_urls[i],
  1476. "script is too large");
  1477. else {
  1478. body[rv] = '\0';
  1479. script_cache_put(script_urls[i], body,
  1480. (unsigned int)rv);
  1481. if (script->module)
  1482. js_browser_run_module(
  1483. (const char *)body,
  1484. script_urls[i]);
  1485. else
  1486. js_browser_run(
  1487. (const char *)body,
  1488. script_urls[i]);
  1489. }
  1490. free(body);
  1491. }
  1492. }
  1493. if (pending_action)
  1494. break;
  1495. }
  1496. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1497. * load_home() stop it before the next navigation. */
  1498. if (doc.scripts_truncated && !js_last_error)
  1499. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1500. 1);
  1501. }
  1502. /* ---- images ---- */
  1503. static void image_reset(void)
  1504. {
  1505. int i;
  1506. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1507. images[i].state = 0;
  1508. images[i].native_w = images[i].native_h = 0;
  1509. images[i].err[0] = '\0';
  1510. }
  1511. image_count = 0;
  1512. image_pixels = 0;
  1513. preload_active = 0;
  1514. preload_pending = 0;
  1515. preload_wait = 0;
  1516. preload_node = 0;
  1517. preload_loaded = 0;
  1518. }
  1519. /* Decode into the shared arena, then copy/scale the result into a display
  1520. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1521. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1522. * pixels. Transparent edges are composited over white. */
  1523. /* One decode scratch arena per page, reused across images. Allocating and
  1524. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  1525. * each small display bitmap landed in the hole the previous arena left, so
  1526. * the next arena no longer fit and the heap ratcheted up until an app
  1527. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  1528. * still released right after their one image. */
  1529. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  1530. static unsigned char *decode_arena_get(unsigned int bytes)
  1531. {
  1532. if (decode_arena && decode_arena_size >= bytes)
  1533. return decode_arena;
  1534. free(decode_arena);
  1535. decode_arena = (unsigned char *)malloc(bytes);
  1536. decode_arena_size = decode_arena ? bytes : 0;
  1537. return decode_arena;
  1538. }
  1539. static void decode_arena_put(void)
  1540. {
  1541. if (decode_arena_size > DECODE_ARENA_KEEP) {
  1542. free(decode_arena);
  1543. decode_arena = 0;
  1544. decode_arena_size = 0;
  1545. }
  1546. }
  1547. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  1548. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  1549. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  1550. static int decode_image_data(const unsigned char *data, unsigned int len,
  1551. struct br_image *bi, int box_w, int box_h)
  1552. {
  1553. struct img_info info;
  1554. struct img_options opt;
  1555. struct img_mem mem;
  1556. struct img_image decoded;
  1557. unsigned char *arena;
  1558. unsigned int est, bytes, i;
  1559. unsigned short *px;
  1560. unsigned char *alpha = 0;
  1561. int dw, dh, r;
  1562. if (img_sniff(data, len, &info) != 0) {
  1563. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1564. return -1;
  1565. }
  1566. est = img_estimate(&info);
  1567. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1568. s_copy(bi->err, "image too large", sizeof(bi->err));
  1569. return -1;
  1570. }
  1571. arena = decode_arena_get(est);
  1572. if (!arena) {
  1573. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1574. return -1;
  1575. }
  1576. img_mem_init(&mem, arena, est);
  1577. opt.max_pixels = BR_IMG_PIX_MAX;
  1578. r = img_decode(data, len, &opt, &mem, &decoded);
  1579. if (r != 0) {
  1580. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1581. goto fail;
  1582. }
  1583. if (decoded.w == 0 || decoded.h == 0) {
  1584. s_copy(bi->err, "empty image", sizeof(bi->err));
  1585. goto fail;
  1586. }
  1587. bi->native_w = (int)decoded.w;
  1588. bi->native_h = (int)decoded.h;
  1589. dw = (int)decoded.w;
  1590. dh = (int)decoded.h;
  1591. if (box_w > 0 && box_h > 0) {
  1592. /* cover: scale so both box sides are filled, never up */
  1593. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  1594. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  1595. unsigned int sc = sw > sh ? sw : sh;
  1596. if (sc < 0x10000u) {
  1597. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  1598. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  1599. }
  1600. }
  1601. if (dw > BR_IMG_LAYOUT_W) {
  1602. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  1603. dw = BR_IMG_LAYOUT_W;
  1604. }
  1605. if (dh < 1)
  1606. dh = 1;
  1607. if (dw < 1)
  1608. dw = 1;
  1609. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  1610. BR_IMG_PIXEL_BUDGET) {
  1611. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  1612. goto fail;
  1613. }
  1614. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1615. px = (unsigned short *)malloc(bytes);
  1616. if (!px) {
  1617. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1618. goto fail;
  1619. }
  1620. /* Keep the alpha plane for the scaled image so transparent logos and
  1621. * icons composite over the page instead of the browser's dark theme
  1622. * background. Very large alpha images stay flattened to bound the
  1623. * heap use. */
  1624. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1625. alpha = (unsigned char *)malloc((unsigned int)dw *
  1626. (unsigned int)dh);
  1627. if (alpha) {
  1628. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1629. alpha[i] = 255;
  1630. }
  1631. }
  1632. /* With an alpha plane the colour under transparent pixels only shows
  1633. * through partially covered edge pixels of the downscale: use white,
  1634. * as documented above, not the dark browser theme (which left a dark
  1635. * fringe around scaled app icons). */
  1636. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1637. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  1638. {
  1639. struct img_blit b;
  1640. b.dst = px;
  1641. b.dst_w = dw;
  1642. b.dst_h = dh;
  1643. b.clip_x = 0;
  1644. b.clip_y = 0;
  1645. b.clip_w = dw;
  1646. b.clip_h = dh;
  1647. b.x = 0;
  1648. b.y = 0;
  1649. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1650. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  1651. b.bg2 = b.bg;
  1652. b.dst_a = alpha;
  1653. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1654. img_draw(&decoded, &b);
  1655. }
  1656. bi->img.format = decoded.format;
  1657. bi->img.w = (unsigned int)dw;
  1658. bi->img.h = (unsigned int)dh;
  1659. bi->img.px = px;
  1660. bi->img.alpha = alpha;
  1661. bi->img.flags = 0;
  1662. bi->state = 1;
  1663. image_pixels += (unsigned int)dw * (unsigned int)dh;
  1664. decode_arena_put();
  1665. return 0;
  1666. fail:
  1667. decode_arena_put();
  1668. return -1;
  1669. }
  1670. /* ---- URL / local path handling ---- */
  1671. static int is_http(const char *s)
  1672. {
  1673. return starts_with(s, "http://") || starts_with(s, "https://");
  1674. }
  1675. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1676. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1677. {
  1678. char seg[64];
  1679. unsigned int i = 0, o = 1;
  1680. int depth = 0;
  1681. int trailing;
  1682. if (!in || in[0] != '/' || cap < 2)
  1683. return -1;
  1684. trailing = 0;
  1685. {
  1686. unsigned int n = s_len(in);
  1687. if (n > 1 && in[n - 1] == '/')
  1688. trailing = 1;
  1689. }
  1690. out[0] = '/';
  1691. while (in[i]) {
  1692. unsigned int n = 0;
  1693. while (in[i] == '/')
  1694. i++;
  1695. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1696. if (n + 1 < sizeof(seg))
  1697. seg[n++] = in[i];
  1698. i++;
  1699. }
  1700. seg[n] = '\0';
  1701. if (n == 0)
  1702. break;
  1703. if (s_eq(seg, "."))
  1704. continue;
  1705. if (s_eq(seg, "..")) {
  1706. if (depth > 0) {
  1707. while (o > 1 && out[o - 1] != '/')
  1708. o--;
  1709. if (o > 1)
  1710. o--;
  1711. depth--;
  1712. }
  1713. continue;
  1714. }
  1715. if (o > 1) {
  1716. if (o + 1 >= cap)
  1717. return -1;
  1718. out[o++] = '/';
  1719. }
  1720. if (o + n + 1 >= cap)
  1721. return -1;
  1722. {
  1723. unsigned int j;
  1724. for (j = 0; j < n; j++)
  1725. out[o++] = seg[j];
  1726. }
  1727. depth++;
  1728. }
  1729. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  1730. if (o + 1 >= cap)
  1731. return -1;
  1732. out[o++] = '/';
  1733. }
  1734. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  1735. if (in[i] == '?' || in[i] == '#') {
  1736. while (in[i]) {
  1737. if (o + 1 >= cap)
  1738. return -1;
  1739. out[o++] = in[i++];
  1740. }
  1741. }
  1742. out[o] = '\0';
  1743. return 0;
  1744. }
  1745. static void make_abs_local(const char *in, char *out, unsigned int cap)
  1746. {
  1747. char joined[BR_URL_MAX];
  1748. if (!in || !in[0]) {
  1749. s_copy(out, cwd[0] ? cwd : "/", cap);
  1750. return;
  1751. }
  1752. if (in[0] == '/') {
  1753. if (normalize_abs(in, out, cap) != 0)
  1754. s_copy(out, in, cap);
  1755. return;
  1756. }
  1757. {
  1758. unsigned int n = 0;
  1759. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  1760. s_append(joined, &n, "/", sizeof(joined));
  1761. s_append(joined, &n, in, sizeof(joined));
  1762. }
  1763. if (normalize_abs(joined, out, cap) != 0)
  1764. s_copy(out, joined, cap);
  1765. }
  1766. /* ---- canonical origin cache ---- *
  1767. *
  1768. * Sites commonly redirect http://host to https://host and then to
  1769. * https://www.host. Remember the final scheme/host of the last navigation so
  1770. * a bare domain typed again goes straight there instead of paying for two
  1771. * more connections and TLS handshakes. Only default-port requests are
  1772. * rewritten; explicit ports are left alone. */
  1773. #define ORIGIN_CACHE_MAX 8
  1774. #define ORIGIN_FILE "/share/borigins"
  1775. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  1776. UHTTP_HOST_MAX + 2))
  1777. struct origin_cache_entry {
  1778. char host[UHTTP_HOST_MAX];
  1779. char origin[UHTTP_HOST_MAX + 16];
  1780. };
  1781. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  1782. static int origin_count;
  1783. static char origin_buf[ORIGIN_BUF_SIZE];
  1784. static int default_port(const struct uhttp_url *u)
  1785. {
  1786. return u->secure ? u->port == 443 : u->port == 80;
  1787. }
  1788. static void url_origin(const struct uhttp_url *u, char *out,
  1789. unsigned int cap)
  1790. {
  1791. unsigned int n = 0;
  1792. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  1793. s_append(out, &n, u->host, cap);
  1794. if (!default_port(u)) {
  1795. s_append(out, &n, ":", cap);
  1796. s_append_dec(out, &n, u->port, cap);
  1797. }
  1798. }
  1799. static void origin_cache_apply(char *url, unsigned int cap)
  1800. {
  1801. struct uhttp_url u;
  1802. char out[BR_URL_MAX];
  1803. unsigned int n = 0;
  1804. int i;
  1805. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  1806. return;
  1807. for (i = 0; i < origin_count; i++) {
  1808. if (!s_eq(u.host, origins[i].host))
  1809. continue;
  1810. s_append(out, &n, origins[i].origin, sizeof(out));
  1811. s_append(out, &n, u.path, sizeof(out));
  1812. s_copy(url, out, cap);
  1813. return;
  1814. }
  1815. }
  1816. static void origin_cache_save(void)
  1817. {
  1818. unsigned int n = 0;
  1819. int i;
  1820. for (i = 0; i < origin_count; i++) {
  1821. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  1822. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  1823. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  1824. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  1825. }
  1826. if (n)
  1827. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  1828. (int)origin_buf, (int)n);
  1829. }
  1830. static void origin_cache_load(void)
  1831. {
  1832. char *p;
  1833. int rn;
  1834. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  1835. (int)(sizeof(origin_buf) - 1));
  1836. if (rn <= 0)
  1837. return;
  1838. origin_buf[rn] = '\0';
  1839. p = origin_buf;
  1840. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  1841. char *line = p, *origin;
  1842. while (*p && *p != '\n')
  1843. p++;
  1844. if (*p)
  1845. *p++ = '\0';
  1846. if (!line[0])
  1847. continue;
  1848. origin = line;
  1849. while (*origin && *origin != ' ')
  1850. origin++;
  1851. if (!*origin)
  1852. continue;
  1853. *origin++ = '\0';
  1854. if (!line[0] || !is_http(origin))
  1855. continue;
  1856. {
  1857. struct uhttp_url uo;
  1858. if (uhttp_parse_url(origin, &uo) != 0 ||
  1859. !s_eq(uo.path, "/"))
  1860. continue;
  1861. }
  1862. s_copy(origins[origin_count].host, line,
  1863. sizeof(origins[origin_count].host));
  1864. s_copy(origins[origin_count].origin, origin,
  1865. sizeof(origins[origin_count].origin));
  1866. origin_count++;
  1867. }
  1868. }
  1869. static int host_is_www_of(const char *host, const char *base)
  1870. {
  1871. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  1872. host[3] == '.' && s_eq(host + 4, base);
  1873. }
  1874. static void origin_cache_learn(const char *requested, const char *final)
  1875. {
  1876. struct uhttp_url from, to;
  1877. char origin[UHTTP_HOST_MAX + 16];
  1878. int i;
  1879. if (!is_http(requested) || !is_http(final))
  1880. return;
  1881. if (uhttp_parse_url(requested, &from) != 0 ||
  1882. uhttp_parse_url(final, &to) != 0)
  1883. return;
  1884. if (!default_port(&from))
  1885. return;
  1886. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  1887. from.port == to.port)
  1888. return;
  1889. /* Only remember origin-level canonicalisation: the same path, and
  1890. * either the same host or its www./apex sibling. A path- or
  1891. * host-specific redirect (a shortener, a login page) must not poison
  1892. * every request to the typed host. */
  1893. if (!s_eq(from.path, to.path))
  1894. return;
  1895. if (!s_eq(from.host, to.host) &&
  1896. !host_is_www_of(to.host, from.host) &&
  1897. !host_is_www_of(from.host, to.host))
  1898. return;
  1899. url_origin(&to, origin, sizeof(origin));
  1900. for (i = 0; i < origin_count; i++) {
  1901. if (s_eq(origins[i].host, from.host)) {
  1902. if (!s_eq(origins[i].origin, origin)) {
  1903. s_copy(origins[i].origin, origin,
  1904. sizeof(origins[i].origin));
  1905. origin_cache_save();
  1906. }
  1907. return;
  1908. }
  1909. }
  1910. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  1911. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  1912. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  1913. origin_cache_save();
  1914. }
  1915. static int path_dir(const char *path, char *out, unsigned int cap)
  1916. {
  1917. unsigned int i, last = 0;
  1918. for (i = 0; path[i]; i++)
  1919. if (path[i] == '/')
  1920. last = i;
  1921. if (last == 0) {
  1922. if (cap < 2)
  1923. return -1;
  1924. out[0] = '/';
  1925. out[1] = '\0';
  1926. return 0;
  1927. }
  1928. if (last + 1 >= cap)
  1929. return -1;
  1930. {
  1931. unsigned int j;
  1932. for (j = 0; j < last; j++)
  1933. out[j] = path[j];
  1934. out[last] = '\0';
  1935. }
  1936. return 0;
  1937. }
  1938. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  1939. static int resolve_link(const char *base, const char *href, char *out,
  1940. unsigned int cap)
  1941. {
  1942. char joined[BR_URL_MAX];
  1943. if (!href || !href[0] || href[0] == '#')
  1944. return -1;
  1945. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  1946. starts_with(href, "data:") || starts_with(href, "tel:"))
  1947. return -1;
  1948. if (starts_with(href, "about:")) {
  1949. s_copy(out, href, cap);
  1950. return 0;
  1951. }
  1952. if (is_http(href)) {
  1953. s_copy(out, href, cap);
  1954. return 0;
  1955. }
  1956. if (starts_with(href, "//")) {
  1957. if (is_http(base)) {
  1958. unsigned int n = 0;
  1959. s_append(out, &n, starts_with(base, "https:") ?
  1960. "https:" : "http:", cap);
  1961. s_append(out, &n, href, cap);
  1962. return 0;
  1963. }
  1964. return -1;
  1965. }
  1966. if (is_http(base)) {
  1967. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  1968. }
  1969. /* local page */
  1970. if (href[0] == '/') {
  1971. if (normalize_abs(href, out, cap) != 0)
  1972. return -1;
  1973. return 0;
  1974. }
  1975. {
  1976. char dir[BR_URL_MAX];
  1977. unsigned int n = 0;
  1978. if (s_eq(base, "about:home"))
  1979. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  1980. else if (path_dir(base, dir, sizeof(dir)) != 0)
  1981. s_copy(dir, "/", sizeof(dir));
  1982. s_append(joined, &n, dir, sizeof(joined));
  1983. if (n == 0 || joined[n - 1] != '/')
  1984. s_append(joined, &n, "/", sizeof(joined));
  1985. s_append(joined, &n, href, sizeof(joined));
  1986. }
  1987. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  1988. }
  1989. /* Best-effort decompression: keep the first `cap` bytes and discard the
  1990. * rest instead of failing when a page or stylesheet is larger than the
  1991. * buffer. The stream is still walked to the end, so a normal page is
  1992. * verified; a truncated compressed input still returns whatever was decoded
  1993. * so far. */
  1994. struct trunc_buf {
  1995. unsigned char *dst;
  1996. unsigned int cap, pos;
  1997. int full;
  1998. };
  1999. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2000. {
  2001. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2002. if (len > m->cap - m->pos) {
  2003. unsigned int room = m->cap - m->pos;
  2004. if (room) {
  2005. unsigned int i;
  2006. for (i = 0; i < room; i++)
  2007. m->dst[m->pos + i] = data[i];
  2008. m->pos += room;
  2009. }
  2010. m->full = 1;
  2011. return 0;
  2012. }
  2013. {
  2014. unsigned int i;
  2015. for (i = 0; i < len; i++)
  2016. m->dst[m->pos + i] = data[i];
  2017. }
  2018. m->pos += len;
  2019. return 0;
  2020. }
  2021. static void worker_wait_ui(void);
  2022. static void inflate_ui_pump(void *ctx)
  2023. {
  2024. static unsigned int last;
  2025. unsigned int now = u_ticks_ms();
  2026. (void)ctx;
  2027. if ((int)(now - last) >= 50) {
  2028. last = now;
  2029. worker_wait_ui();
  2030. }
  2031. }
  2032. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2033. unsigned char *dst, unsigned int cap,
  2034. unsigned int *outlen, int gzip, int *truncated)
  2035. {
  2036. struct inflate_src in;
  2037. struct inflate_sink sink;
  2038. struct trunc_buf m;
  2039. unsigned int got = 0;
  2040. int r;
  2041. in.p = src;
  2042. in.len = len;
  2043. in.more = 0;
  2044. in.ctx = 0;
  2045. m.dst = dst;
  2046. m.cap = cap;
  2047. m.pos = 0;
  2048. m.full = 0;
  2049. sink.write = trunc_write;
  2050. sink.ctx = &m;
  2051. inflate_init(&image_inflate_ws, &in, &sink);
  2052. image_inflate_ws.progress = inflate_ui_pump;
  2053. image_inflate_ws.progress_ctx = 0;
  2054. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2055. inflate_zlib(&image_inflate_ws, &got);
  2056. *outlen = m.pos;
  2057. *truncated = m.full || r != 0;
  2058. if (r != 0 && m.pos == 0)
  2059. return -1;
  2060. return 0;
  2061. }
  2062. /* ---- headless fetch workers ------------------------------------------ *
  2063. *
  2064. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2065. * writes the raw response, a small metadata file and a done marker under
  2066. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2067. * or a multi-megabyte body never freezes the UI and images download in
  2068. * parallel.
  2069. */
  2070. struct fetch_meta {
  2071. int status;
  2072. int error;
  2073. int trunc;
  2074. unsigned int len;
  2075. unsigned int open_ms;
  2076. unsigned int first_ms;
  2077. unsigned int total_ms;
  2078. char encoding[16];
  2079. char ctype[64];
  2080. char final[BR_URL_MAX];
  2081. };
  2082. static void draw(unsigned int *action);
  2083. static void handle_keys(unsigned int *action);
  2084. static void handle_page_click(unsigned int *action);
  2085. #define FETCH_WORKERS 4
  2086. #define FETCH_PATH_MAX 32
  2087. /* One long-lived curl __serve helper per worker. Each worker has its own
  2088. * request/body/meta/done files under /share so several downloads can be in
  2089. * flight at once; the keep-alive connection stays in the helper process, so
  2090. * tls.c's per-process state remains valid. */
  2091. struct fetch_worker {
  2092. int pid;
  2093. int slot;
  2094. int busy;
  2095. int ready;
  2096. int image_job;
  2097. unsigned int seq;
  2098. unsigned int deadline;
  2099. int retried;
  2100. char req[FETCH_PATH_MAX];
  2101. char body[FETCH_PATH_MAX];
  2102. char meta[FETCH_PATH_MAX];
  2103. char done[FETCH_PATH_MAX];
  2104. char post[FETCH_PATH_MAX];
  2105. /* Optional preload job attached to this worker. */
  2106. unsigned int node;
  2107. int bg;
  2108. char url[BR_URL_MAX];
  2109. struct fetch_meta m;
  2110. };
  2111. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2112. static int fetch_tty = -2;
  2113. static void fetch_tty_drain(void);
  2114. static unsigned int fetch_session;
  2115. static unsigned int fetch_seq;
  2116. static struct fetch_meta fetch_meta;
  2117. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2118. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2119. static int fetch_last_error;
  2120. static unsigned int meta_uint(char **pp)
  2121. {
  2122. char *p = *pp;
  2123. unsigned int v = 0;
  2124. while (*p >= '0' && *p <= '9') {
  2125. v = v * 10 + (unsigned int)(*p - '0');
  2126. p++;
  2127. }
  2128. while (*p && *p != '\n')
  2129. p++;
  2130. if (*p == '\n')
  2131. p++;
  2132. *pp = p;
  2133. return v;
  2134. }
  2135. static void meta_str(char **pp, char *out, unsigned int cap)
  2136. {
  2137. char *p = *pp;
  2138. unsigned int n = 0;
  2139. while (*p && *p != '\n' && n + 1 < cap)
  2140. out[n++] = *p++;
  2141. out[n] = '\0';
  2142. while (*p && *p != '\n')
  2143. p++;
  2144. if (*p == '\n')
  2145. p++;
  2146. *pp = p;
  2147. }
  2148. static void worker_wait_ui(void)
  2149. {
  2150. unsigned int action = 0;
  2151. if (!ngui_begin(&ui))
  2152. return;
  2153. draw(&action);
  2154. handle_keys(&action);
  2155. handle_page_click(&action);
  2156. if (action & ACT_WAIT_NAV) {
  2157. pending_action |= action & ACT_WAIT_NAV;
  2158. if ((action & ACT_NAV) && click_url[0])
  2159. s_copy(pending_url, click_url, sizeof(pending_url));
  2160. click_url[0] = '\0';
  2161. cancel_fetch = 1;
  2162. }
  2163. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2164. ngui_invalidate(&ui);
  2165. ngui_end(&ui);
  2166. }
  2167. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2168. unsigned int session, int slot)
  2169. {
  2170. unsigned int n = 0;
  2171. s_append(out, &n, "/share/bf", cap);
  2172. s_append_dec(out, &n, session, cap);
  2173. s_append(out, &n, "_", cap);
  2174. s_append_dec(out, &n, (unsigned int)slot, cap);
  2175. s_append(out, &n, kind, cap);
  2176. }
  2177. static void fetch_pool_init(void)
  2178. {
  2179. static int ready;
  2180. int i;
  2181. if (ready)
  2182. return;
  2183. ready = 1;
  2184. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2185. (u_ticks_ms() & 0xFFFFu);
  2186. if (!fetch_session)
  2187. fetch_session = 1;
  2188. for (i = 0; i < FETCH_WORKERS; i++) {
  2189. struct fetch_worker *w = &fetch_workers[i];
  2190. w->pid = -1;
  2191. w->slot = i;
  2192. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2193. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2194. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2195. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2196. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2197. }
  2198. }
  2199. static void fetch_worker_stop(struct fetch_worker *w)
  2200. {
  2201. int i;
  2202. /* An abandoned image job leaves its node loadable again. */
  2203. if (w->busy && w->image_job && w->node < doc.nnode) {
  2204. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2205. doc.nodes[w->node].bg_img_index = -1;
  2206. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2207. doc.nodes[w->node].img_index = -1;
  2208. }
  2209. if (w->pid > 0) {
  2210. u_kill((unsigned int)w->pid);
  2211. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2212. u_sleep_ms(5);
  2213. /* Let the reaper close the socket before we reuse the slot. */
  2214. u_sleep_ms(10);
  2215. }
  2216. w->pid = -1;
  2217. w->busy = 0;
  2218. w->ready = 0;
  2219. w->image_job = 0;
  2220. if (w->req[0]) {
  2221. u_syscall1(SYS_UNLINK, (int)w->done);
  2222. u_syscall1(SYS_UNLINK, (int)w->meta);
  2223. u_syscall1(SYS_UNLINK, (int)w->body);
  2224. u_syscall1(SYS_UNLINK, (int)w->post);
  2225. u_syscall1(SYS_UNLINK, (int)w->req);
  2226. }
  2227. }
  2228. static void fetch_workers_stop_all(void)
  2229. {
  2230. int i;
  2231. for (i = 0; i < FETCH_WORKERS; i++)
  2232. fetch_worker_stop(&fetch_workers[i]);
  2233. }
  2234. /* Abandon the transfers of the current page but keep idle helpers and their
  2235. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2236. * because its response would otherwise land in a reused /share slot. */
  2237. static void fetch_workers_cancel_busy(void)
  2238. {
  2239. int i;
  2240. for (i = 0; i < FETCH_WORKERS; i++)
  2241. if (fetch_workers[i].busy)
  2242. fetch_worker_stop(&fetch_workers[i]);
  2243. }
  2244. static void fetch_workers_prepare_nav(const char *url)
  2245. {
  2246. int i;
  2247. (void)url;
  2248. for (i = 0; i < FETCH_WORKERS; i++) {
  2249. struct fetch_worker *w = &fetch_workers[i];
  2250. if (w->pid <= 0)
  2251. continue;
  2252. /* Only an in-flight transfer must be aborted. Idle helpers
  2253. * stay warm across origins: there are just FETCH_WORKERS of
  2254. * them, and uhttp_open drops the old connection when the
  2255. * next job is for another host. Killing and respawning all
  2256. * four on every navigation churned processes and sockets
  2257. * while images were still loading. */
  2258. if (w->busy)
  2259. fetch_worker_stop(w);
  2260. }
  2261. }
  2262. /* The browser is no longer the active window and no fetch is running: give
  2263. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2264. static void fetch_workers_stop_if_unfocused(void)
  2265. {
  2266. int i;
  2267. fetch_tty_drain();
  2268. if (ui.focused || page_loading || preload_active)
  2269. return;
  2270. for (i = 0; i < FETCH_WORKERS; i++)
  2271. if (fetch_workers[i].pid > 0) {
  2272. fetch_workers_stop_all();
  2273. return;
  2274. }
  2275. }
  2276. /* The helpers (and this process, since u_tty_create() rebinds our own
  2277. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2278. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2279. * a dozen TLS connections every helper hung in its next log line, so the
  2280. * following cross-origin navigation sat at "Loading..." until it timed out.
  2281. * Drain and discard it from every wait/poll loop. */
  2282. static void fetch_tty_drain(void)
  2283. {
  2284. char sink[512];
  2285. int i;
  2286. if (fetch_tty <= 0)
  2287. return;
  2288. for (i = 0; i < 16; i++)
  2289. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2290. break;
  2291. }
  2292. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2293. unsigned int errcap)
  2294. {
  2295. char arg[40];
  2296. unsigned int n = 0;
  2297. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2298. return 0;
  2299. w->pid = -1;
  2300. fetch_pool_init();
  2301. if (fetch_tty == -2) {
  2302. int t = u_tty_create();
  2303. fetch_tty = t > 0 ? t : 0;
  2304. }
  2305. s_append(arg, &n, "__serve ", sizeof(arg));
  2306. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2307. s_append(arg, &n, " ", sizeof(arg));
  2308. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2309. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2310. if (w->pid <= 0) {
  2311. w->pid = -1;
  2312. s_copy(err, "cannot start network helper", errcap);
  2313. return -1;
  2314. }
  2315. return 0;
  2316. }
  2317. static struct fetch_worker *fetch_worker_alloc(void)
  2318. {
  2319. int i;
  2320. fetch_pool_init();
  2321. for (i = 0; i < FETCH_WORKERS; i++)
  2322. if (!fetch_workers[i].busy)
  2323. return &fetch_workers[i];
  2324. return 0;
  2325. }
  2326. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2327. unsigned int cap, const char *method,
  2328. const char *ctype, const char *post,
  2329. unsigned int post_len, unsigned int node,
  2330. int bg, char *err, unsigned int errcap);
  2331. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2332. unsigned int cap, const char *post,
  2333. unsigned int post_len, unsigned int node,
  2334. int bg, char *err, unsigned int errcap)
  2335. {
  2336. /* A body pointer with no bytes is still a POST: the classic request
  2337. * line would turn it into a GET. */
  2338. if (post && !post_len)
  2339. return fetch_worker_submit_req(w, url, cap, "POST",
  2340. "application/x-www-form-urlencoded", post, 0, node,
  2341. bg, err, errcap);
  2342. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2343. node, bg, err, errcap);
  2344. }
  2345. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2346. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2347. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2348. unsigned int cap, const char *method,
  2349. const char *ctype, const char *post,
  2350. unsigned int post_len, unsigned int node,
  2351. int bg, char *err, unsigned int errcap)
  2352. {
  2353. static char req[1024];
  2354. unsigned int n = 0;
  2355. fetch_seq++;
  2356. if (!fetch_seq)
  2357. fetch_seq = 1;
  2358. w->seq = fetch_seq;
  2359. w->ready = 0;
  2360. w->image_job = 0;
  2361. w->retried = 0;
  2362. w->m.error = 0;
  2363. w->node = node;
  2364. w->bg = bg;
  2365. s_copy(w->url, url, sizeof(w->url));
  2366. s_append_dec(req, &n, w->seq, sizeof(req));
  2367. s_append(req, &n, " ", sizeof(req));
  2368. s_append_dec(req, &n, cap, sizeof(req));
  2369. s_append(req, &n, " ", sizeof(req));
  2370. if (method) {
  2371. unsigned int k;
  2372. s_append(req, &n, "X ", sizeof(req));
  2373. s_append(req, &n, method, sizeof(req));
  2374. s_append(req, &n, " ", sizeof(req));
  2375. s_append_dec(req, &n, post_len, sizeof(req));
  2376. s_append(req, &n, " ", sizeof(req));
  2377. if (!ctype || !ctype[0])
  2378. s_append(req, &n, "-", sizeof(req));
  2379. /* One token on the request line: drop the spaces
  2380. * ("application/json; charset=utf-8" stays valid). */
  2381. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2382. if (ctype[k] != ' ')
  2383. req[n++] = ctype[k];
  2384. req[n] = '\0';
  2385. s_append(req, &n, " ", sizeof(req));
  2386. } else if (post_len) {
  2387. s_append(req, &n, "POST ", sizeof(req));
  2388. s_append_dec(req, &n, post_len, sizeof(req));
  2389. s_append(req, &n, " ", sizeof(req));
  2390. }
  2391. s_append(req, &n, url, sizeof(req));
  2392. s_append(req, &n, "\n", sizeof(req));
  2393. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2394. (int)post, (int)post_len) < 0) {
  2395. s_copy(err, "cannot queue form body", errcap);
  2396. return -1;
  2397. }
  2398. u_syscall1(SYS_UNLINK, (int)w->done);
  2399. u_syscall1(SYS_UNLINK, (int)w->meta);
  2400. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2401. s_copy(err, "cannot queue network request", errcap);
  2402. return -1;
  2403. }
  2404. if (fetch_worker_start(w, err, errcap) != 0)
  2405. return -1;
  2406. w->busy = 1;
  2407. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2408. return 0;
  2409. }
  2410. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2411. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2412. unsigned int errcap)
  2413. {
  2414. static char meta[1024];
  2415. char *p;
  2416. int rn, mseq;
  2417. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2418. (int)(sizeof(meta) - 1));
  2419. if (rn <= 0) {
  2420. s_copy(err, "network helper failed", errcap);
  2421. return -1;
  2422. }
  2423. meta[rn] = '\0';
  2424. p = meta;
  2425. mseq = (int)meta_uint(&p);
  2426. if (mseq != (int)w->seq) {
  2427. s_copy(err, "stale network response", errcap);
  2428. return -1;
  2429. }
  2430. w->m.status = (int)meta_uint(&p);
  2431. w->m.error = (int)meta_uint(&p);
  2432. w->m.trunc = (int)meta_uint(&p);
  2433. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2434. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2435. meta_str(&p, w->m.final, sizeof(w->m.final));
  2436. w->m.len = meta_uint(&p);
  2437. w->m.open_ms = 0;
  2438. w->m.first_ms = 0;
  2439. w->m.total_ms = 0;
  2440. if (*p) {
  2441. w->m.open_ms = meta_uint(&p);
  2442. w->m.first_ms = meta_uint(&p);
  2443. w->m.total_ms = meta_uint(&p);
  2444. }
  2445. if (w->m.error) {
  2446. s_copy(err, uhttp_error_string(w->m.error), errcap);
  2447. return -1;
  2448. }
  2449. w->ready = 1;
  2450. return 0;
  2451. }
  2452. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  2453. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  2454. unsigned int errcap)
  2455. {
  2456. static char done[24];
  2457. char *p;
  2458. int rn, mseq;
  2459. fetch_tty_drain();
  2460. if (!w->busy)
  2461. return -1;
  2462. if (w->ready)
  2463. return 1;
  2464. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  2465. (int)(sizeof(done) - 1));
  2466. if (rn > 0) {
  2467. done[rn] = '\0';
  2468. p = done;
  2469. mseq = (int)meta_uint(&p);
  2470. if (mseq == (int)w->seq) {
  2471. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  2472. fetch_worker_stop(w);
  2473. return -1;
  2474. }
  2475. return 1;
  2476. }
  2477. }
  2478. if (!u_alive((unsigned int)w->pid)) {
  2479. w->pid = -1;
  2480. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  2481. w->retried = 1;
  2482. return 0;
  2483. }
  2484. s_copy(err, "network helper stopped", errcap);
  2485. fetch_worker_stop(w);
  2486. return -1;
  2487. }
  2488. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  2489. s_copy(err, "network request timed out", errcap);
  2490. fetch_worker_stop(w);
  2491. return -1;
  2492. }
  2493. return 0;
  2494. }
  2495. /* Copy the completed body, inflating it if the server ignored our identity
  2496. * request. Mirrors the old fetch_remote body path. */
  2497. static int fetch_worker_read_body(struct fetch_worker *w,
  2498. unsigned char *plain,
  2499. unsigned int plaincap,
  2500. unsigned char *comp,
  2501. unsigned int compcap,
  2502. int *truncated, char *err,
  2503. unsigned int errcap)
  2504. {
  2505. int rv, zr, was_trunc;
  2506. if (contains_ci(w->m.encoding, "gzip") ||
  2507. contains_ci(w->m.encoding, "deflate")) {
  2508. unsigned int comp_len = 0, plen = 0;
  2509. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  2510. (int)compcap);
  2511. if (rv < 0) {
  2512. s_copy(err, "empty response", errcap);
  2513. return -1;
  2514. }
  2515. comp_len = (unsigned int)rv;
  2516. if (comp_len < w->m.len) {
  2517. s_copy(err, "compressed response is too large", errcap);
  2518. return -1;
  2519. }
  2520. if (contains_ci(w->m.encoding, "deflate"))
  2521. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2522. &plen, 0, &was_trunc);
  2523. else
  2524. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  2525. &plen, 1, &was_trunc);
  2526. if (zr != 0) {
  2527. s_copy(err, "compressed response is corrupt", errcap);
  2528. return -1;
  2529. }
  2530. *truncated = w->m.trunc || was_trunc;
  2531. return (int)plen;
  2532. }
  2533. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  2534. if (rv < 0) {
  2535. s_copy(err, "empty response", errcap);
  2536. return -1;
  2537. }
  2538. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  2539. return rv;
  2540. }
  2541. static void fetch_worker_release(struct fetch_worker *w)
  2542. {
  2543. u_syscall1(SYS_UNLINK, (int)w->done);
  2544. u_syscall1(SYS_UNLINK, (int)w->meta);
  2545. u_syscall1(SYS_UNLINK, (int)w->body);
  2546. u_syscall1(SYS_UNLINK, (int)w->post);
  2547. u_syscall1(SYS_UNLINK, (int)w->req);
  2548. w->busy = 0;
  2549. w->ready = 0;
  2550. w->image_job = 0;
  2551. }
  2552. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  2553. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  2554. unsigned int errcap)
  2555. {
  2556. for (;;) {
  2557. int rv;
  2558. if (!fetch_wait_passive)
  2559. worker_wait_ui();
  2560. if (cancel_fetch || pending_action) {
  2561. fetch_workers_cancel_busy();
  2562. return FETCH_ABORT;
  2563. }
  2564. rv = fetch_worker_poll(w, err, errcap);
  2565. if (rv != 0)
  2566. return rv == 1 ? 0 : -1;
  2567. u_sleep_ms(10);
  2568. }
  2569. }
  2570. static int fetch_remote(const char *url, unsigned int cap,
  2571. const char *post, unsigned int post_len,
  2572. unsigned char *plain, unsigned int plaincap,
  2573. unsigned char *comp, unsigned int compcap,
  2574. struct fetch_meta *m, int *truncated,
  2575. char *err, unsigned int errcap)
  2576. {
  2577. struct fetch_worker *w = fetch_worker_alloc();
  2578. int rv;
  2579. fetch_last_error = 0;
  2580. if (!w) {
  2581. s_copy(err, "network busy", errcap);
  2582. return -1;
  2583. }
  2584. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  2585. err, errcap) != 0) {
  2586. fetch_worker_release(w);
  2587. return -1;
  2588. }
  2589. rv = fetch_worker_wait(w, err, errcap);
  2590. if (rv == FETCH_ABORT) {
  2591. fetch_worker_release(w);
  2592. return FETCH_ABORT;
  2593. }
  2594. if (rv != 0) {
  2595. fetch_last_error = w->m.error;
  2596. fetch_worker_release(w);
  2597. return -1;
  2598. }
  2599. *m = w->m;
  2600. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  2601. truncated, err, errcap);
  2602. fetch_worker_release(w);
  2603. if (rv >= 0 && (cancel_fetch || pending_action))
  2604. return FETCH_ABORT;
  2605. return rv;
  2606. }
  2607. static int fetch_worker_status(const struct fetch_worker *w)
  2608. {
  2609. return w->m.status;
  2610. }
  2611. /* fetch()/XHR through a helper: one request, the status and body come back
  2612. * whatever the HTTP status (a 401 is an answer, not a network error). */
  2613. static int js_worker_http(const char *method, const char *url,
  2614. const char *ctype, const char *body,
  2615. unsigned int body_len, struct js_http_resp *r,
  2616. char *err, int errcap)
  2617. {
  2618. struct fetch_worker *w = fetch_worker_alloc();
  2619. unsigned char *plain;
  2620. int rv, tr = 0;
  2621. if (!w) {
  2622. s_copy(err, "network busy", (unsigned int)errcap);
  2623. return -1;
  2624. }
  2625. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  2626. body_len, 0, 0, err,
  2627. (unsigned int)errcap) != 0) {
  2628. fetch_worker_release(w);
  2629. return -1;
  2630. }
  2631. fetch_wait_passive++;
  2632. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  2633. fetch_wait_passive--;
  2634. if (rv != 0) {
  2635. if (rv == FETCH_ABORT)
  2636. s_copy(err, "page is navigating", (unsigned int)errcap);
  2637. fetch_worker_release(w);
  2638. return -1;
  2639. }
  2640. r->status = w->m.status;
  2641. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  2642. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  2643. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  2644. if (!plain) {
  2645. fetch_worker_release(w);
  2646. s_copy(err, "out of memory", (unsigned int)errcap);
  2647. return -1;
  2648. }
  2649. if (w->m.len == 0) {
  2650. rv = 0; /* 204, an empty 200: no body file */
  2651. } else {
  2652. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  2653. image_io_buf, BR_PAGE_COMP_MAX,
  2654. &tr, err, (unsigned int)errcap);
  2655. }
  2656. fetch_worker_release(w);
  2657. if (rv < 0) {
  2658. free(plain);
  2659. return -1;
  2660. }
  2661. plain[rv] = '\0';
  2662. r->body = (char *)plain;
  2663. r->len = (unsigned int)rv;
  2664. return 0;
  2665. }
  2666. /* ---- HTTP / file fetch ---- */
  2667. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  2668. unsigned int *outlen, int *is_local, char *ctype,
  2669. unsigned int ctcap, char *final, unsigned int finalcap,
  2670. char *err, unsigned int errcap, int *truncated,
  2671. const char *post, unsigned int post_len)
  2672. {
  2673. unsigned char *buf;
  2674. unsigned int len;
  2675. int tr = 0;
  2676. int rv;
  2677. *out = 0;
  2678. *outlen = 0;
  2679. *truncated = 0;
  2680. if (final && finalcap)
  2681. final[0] = '\0';
  2682. if (ctype && ctcap)
  2683. ctype[0] = '\0';
  2684. if (url[0] == '/') {
  2685. char pathbuf[BR_URL_MAX];
  2686. const char *open_url = url;
  2687. unsigned int i = 0;
  2688. /* A local form GET keeps ?query in the address bar but the
  2689. * file lookup uses the path alone, like a real browser. */
  2690. while (url[i] && url[i] != '?' && url[i] != '#')
  2691. i++;
  2692. if (url[i]) {
  2693. s_copy(pathbuf, url, i + 1);
  2694. open_url = pathbuf;
  2695. }
  2696. buf = (unsigned char *)malloc(cap);
  2697. if (!buf) {
  2698. s_copy(err, "out of memory", errcap);
  2699. return -1;
  2700. }
  2701. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  2702. if (rv < 0) {
  2703. free(buf);
  2704. s_copy(err, "file not found", errcap);
  2705. return -1;
  2706. }
  2707. *out = buf;
  2708. *outlen = (unsigned int)rv;
  2709. *is_local = 1;
  2710. if (ctype)
  2711. s_copy(ctype, "text/html", ctcap);
  2712. if (final)
  2713. s_copy(final, url, finalcap);
  2714. if ((unsigned int)rv == cap)
  2715. *truncated = 1;
  2716. return 0;
  2717. }
  2718. buf = (unsigned char *)malloc(cap);
  2719. if (!buf) {
  2720. s_copy(err, "out of memory", errcap);
  2721. return -1;
  2722. }
  2723. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  2724. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  2725. if (rv == FETCH_ABORT) {
  2726. free(buf);
  2727. return FETCH_ABORT;
  2728. }
  2729. if (rv < 0) {
  2730. free(buf);
  2731. return -1;
  2732. }
  2733. len = (unsigned int)rv;
  2734. if (len == 0) {
  2735. free(buf);
  2736. s_copy(err, "empty response", errcap);
  2737. return -1;
  2738. }
  2739. if (ctype)
  2740. s_copy(ctype, fetch_meta.ctype, ctcap);
  2741. if (final && fetch_meta.final[0])
  2742. s_copy(final, fetch_meta.final, finalcap);
  2743. *is_local = 0;
  2744. *out = buf;
  2745. *outlen = len;
  2746. *truncated = tr;
  2747. return 0;
  2748. }
  2749. /* Load every @font-face the parser registered. Local files go through
  2750. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  2751. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  2752. * to the built-in regular/bold/italic/mono set. */
  2753. static void load_font_faces(void)
  2754. {
  2755. unsigned int i;
  2756. memset(font_faces, 0, sizeof(font_faces));
  2757. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  2758. i <= BR_MAX_FACES; i++) {
  2759. const char *url = br_font_face_url((int)i);
  2760. const char *base = br_font_face_base((int)i);
  2761. char abs[BR_URL_MAX];
  2762. if (!url || !url[0])
  2763. continue;
  2764. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  2765. sizeof(abs)) != 0)
  2766. continue;
  2767. if (abs[0] == '/') {
  2768. font_faces[i - 1] = ufont_face_open_path(abs);
  2769. } else if (is_http(abs)) {
  2770. unsigned char *buf;
  2771. char err[64];
  2772. int rv, tr = 0;
  2773. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  2774. if (!buf)
  2775. continue;
  2776. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  2777. UFONT_MAX_FILE, image_io_buf,
  2778. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  2779. err, sizeof(err));
  2780. if (rv > 0)
  2781. font_faces[i - 1] = ufont_face_open_mem(buf,
  2782. rv);
  2783. free(buf);
  2784. }
  2785. }
  2786. }
  2787. /* Remote scripts are cached under /share for the current boot, like the
  2788. * stylesheet cache, so reloads and later visits skip the network. */
  2789. static int script_cache_count;
  2790. static unsigned int script_cache_hash(const char *s)
  2791. {
  2792. unsigned int h = 2166136261u;
  2793. while (*s) {
  2794. h ^= (unsigned char)*s++;
  2795. h *= 16777619u;
  2796. }
  2797. return h;
  2798. }
  2799. static void script_cache_path(const char *url, char *out, unsigned int cap)
  2800. {
  2801. unsigned int n = 0;
  2802. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  2803. s_append_dec(out, &n, script_cache_hash(url), cap);
  2804. }
  2805. static void script_cache_clear(void)
  2806. {
  2807. struct sys_dirent d;
  2808. char path[96];
  2809. for (;;) {
  2810. int i, found = 0;
  2811. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2812. (int)&d) == 1; i++) {
  2813. unsigned int n = 0;
  2814. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2815. continue;
  2816. s_append(path, &n, "/share/", sizeof(path));
  2817. s_append(path, &n, d.name, sizeof(path));
  2818. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2819. return;
  2820. found = 1;
  2821. break;
  2822. }
  2823. if (!found)
  2824. break;
  2825. }
  2826. script_cache_count = 0;
  2827. }
  2828. static void script_cache_init(void)
  2829. {
  2830. struct sys_dirent d;
  2831. int i, count = 0;
  2832. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2833. (int)&d) == 1; i++)
  2834. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2835. count++;
  2836. if (count >= SCRIPT_CACHE_MAX) {
  2837. script_cache_clear();
  2838. return;
  2839. }
  2840. script_cache_count = count;
  2841. }
  2842. static int script_cache_get(const char *url, unsigned char **out,
  2843. unsigned int *outlen)
  2844. {
  2845. char path[96];
  2846. struct sys_stat st;
  2847. unsigned char *buf;
  2848. int rn;
  2849. script_cache_path(url, path, sizeof(path));
  2850. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  2851. st.size >= SCRIPT_CACHE_FILE_MAX)
  2852. return 0;
  2853. buf = (unsigned char *)malloc(st.size + 1);
  2854. if (!buf)
  2855. return 0;
  2856. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  2857. if (rn != (int)st.size) {
  2858. free(buf);
  2859. return 0;
  2860. }
  2861. buf[st.size] = '\0';
  2862. *out = buf;
  2863. *outlen = st.size;
  2864. return 1;
  2865. }
  2866. static void script_cache_put(const char *url, const unsigned char *data,
  2867. unsigned int len)
  2868. {
  2869. char path[96];
  2870. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  2871. len >= SCRIPT_CACHE_FILE_MAX)
  2872. return;
  2873. script_cache_path(url, path, sizeof(path));
  2874. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2875. (int)len) >= 0)
  2876. script_cache_count++;
  2877. }
  2878. static int script_cache_has(const char *url)
  2879. {
  2880. char path[96];
  2881. struct sys_stat st;
  2882. script_cache_path(url, path, sizeof(path));
  2883. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  2884. st.size < SCRIPT_CACHE_FILE_MAX;
  2885. }
  2886. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  2887. static int fetch_script_text(const char *url, unsigned char **out,
  2888. unsigned int *outlen, char *err,
  2889. unsigned int errcap)
  2890. {
  2891. unsigned char *buf;
  2892. unsigned int len;
  2893. int local, truncated = 0;
  2894. char ctype[64], final[BR_URL_MAX];
  2895. int rv;
  2896. *out = 0;
  2897. *outlen = 0;
  2898. if (url[0] != '/' && script_cache_get(url, out, outlen))
  2899. return 0;
  2900. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  2901. sizeof(ctype), final, sizeof(final), err, errcap,
  2902. &truncated, 0, 0);
  2903. if (rv != 0)
  2904. return rv;
  2905. if (truncated || len >= BR_SCRIPT_MAX) {
  2906. free(buf);
  2907. s_copy(err, "script is too large", errcap);
  2908. return -1;
  2909. }
  2910. buf[len] = '\0';
  2911. if (!local)
  2912. script_cache_put(url, buf, len);
  2913. *out = buf;
  2914. *outlen = len;
  2915. return 0;
  2916. }
  2917. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  2918. * the heap, so images must not allocate their file body from it as well. */
  2919. static int fetch_image(const char *url, unsigned int cap,
  2920. unsigned char **out, unsigned int *outlen,
  2921. char *err, unsigned int errcap)
  2922. {
  2923. unsigned int len;
  2924. int tr = 0;
  2925. int rv;
  2926. *out = 0;
  2927. *outlen = 0;
  2928. if (cap > BR_IMG_FILE_MAX)
  2929. cap = BR_IMG_FILE_MAX;
  2930. if (url[0] == '/') {
  2931. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  2932. (int)cap);
  2933. if (rv < 0) {
  2934. s_copy(err, "file not found", errcap);
  2935. return -1;
  2936. }
  2937. *out = image_file_buf;
  2938. *outlen = (unsigned int)rv;
  2939. return 0;
  2940. }
  2941. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  2942. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  2943. if (rv == FETCH_ABORT)
  2944. return FETCH_ABORT;
  2945. if (rv < 0)
  2946. return -1;
  2947. len = (unsigned int)rv;
  2948. if (len == 0) {
  2949. s_copy(err, "empty image", errcap);
  2950. return -1;
  2951. }
  2952. *out = image_file_buf;
  2953. *outlen = len;
  2954. return 0;
  2955. }
  2956. /* Remote stylesheets are immutable enough for the current boot: keep
  2957. * successful responses under /share so a reload, a second visit or a fresh
  2958. * browser launch does not fetch the same five sheets over the network again.
  2959. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  2960. static int css_cache_count;
  2961. static unsigned int css_cache_hash(const char *s)
  2962. {
  2963. unsigned int h = 2166136261u;
  2964. while (*s) {
  2965. h ^= (unsigned char)*s++;
  2966. h *= 16777619u;
  2967. }
  2968. return h;
  2969. }
  2970. static void css_cache_path(const char *url, char *out, unsigned int cap)
  2971. {
  2972. unsigned int n = 0;
  2973. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  2974. s_append_dec(out, &n, css_cache_hash(url), cap);
  2975. }
  2976. static void css_cache_clear(void)
  2977. {
  2978. struct sys_dirent d;
  2979. char path[96];
  2980. for (;;) {
  2981. int i, found = 0;
  2982. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2983. (int)&d) == 1; i++) {
  2984. unsigned int n = 0;
  2985. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  2986. continue;
  2987. s_append(path, &n, "/share/", sizeof(path));
  2988. s_append(path, &n, d.name, sizeof(path));
  2989. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2990. return;
  2991. found = 1;
  2992. break;
  2993. }
  2994. if (!found)
  2995. break;
  2996. }
  2997. css_cache_count = 0;
  2998. }
  2999. static void css_cache_init(void)
  3000. {
  3001. struct sys_dirent d;
  3002. int i, count = 0;
  3003. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3004. (int)&d) == 1; i++)
  3005. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3006. count++;
  3007. if (count >= CSS_CACHE_MAX) {
  3008. css_cache_clear();
  3009. return;
  3010. }
  3011. css_cache_count = count;
  3012. }
  3013. static int css_cache_get(const char *url, unsigned char **out,
  3014. unsigned int *outlen)
  3015. {
  3016. char path[96];
  3017. int rn;
  3018. css_cache_path(url, path, sizeof(path));
  3019. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3020. (int)CSS_CACHE_FILE_MAX);
  3021. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3022. return 0;
  3023. *out = image_io_buf;
  3024. *outlen = (unsigned int)rn;
  3025. return 1;
  3026. }
  3027. static void css_cache_put(const char *url, const unsigned char *data,
  3028. unsigned int len)
  3029. {
  3030. char path[96];
  3031. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3032. len >= CSS_CACHE_FILE_MAX)
  3033. return;
  3034. css_cache_path(url, path, sizeof(path));
  3035. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3036. (int)len) >= 0)
  3037. css_cache_count++;
  3038. }
  3039. static int css_cache_has(const char *url)
  3040. {
  3041. char path[96];
  3042. struct sys_stat st;
  3043. css_cache_path(url, path, sizeof(path));
  3044. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3045. st.size < CSS_CACHE_FILE_MAX;
  3046. }
  3047. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3048. * immediately, so it does not need the page heap; this leaves the heap for
  3049. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3050. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3051. char *err, unsigned int errcap)
  3052. {
  3053. unsigned int len;
  3054. int tr = 0;
  3055. int rv;
  3056. *out = 0;
  3057. *outlen = 0;
  3058. if (url[0] == '/') {
  3059. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3060. (int)BR_CSS_MAX);
  3061. if (rv < 0) {
  3062. s_copy(err, "stylesheet not found", errcap);
  3063. return -1;
  3064. }
  3065. *out = image_io_buf;
  3066. *outlen = (unsigned int)rv;
  3067. return 0;
  3068. }
  3069. if (css_cache_get(url, out, outlen))
  3070. return 0;
  3071. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3072. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3073. &fetch_meta, &tr, err, errcap);
  3074. if (rv == FETCH_ABORT)
  3075. return FETCH_ABORT;
  3076. if (rv < 0)
  3077. return -1;
  3078. len = (unsigned int)rv;
  3079. if (len == 0) {
  3080. s_copy(err, "empty stylesheet", errcap);
  3081. return -1;
  3082. }
  3083. *out = image_io_buf;
  3084. *outlen = len;
  3085. css_cache_put(url, image_io_buf, len);
  3086. return 0;
  3087. }
  3088. static void redraw_now(void);
  3089. static char error_page[1024];
  3090. static void show_error(const char *title, const char *detail)
  3091. {
  3092. char *page = error_page;
  3093. unsigned int n = 0;
  3094. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3095. s_append(page, &n, title, sizeof(error_page));
  3096. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3097. {
  3098. const char *p = detail;
  3099. while (*p && n + 1 < sizeof(error_page)) {
  3100. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3101. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3102. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3103. else page[n++] = *p;
  3104. p++;
  3105. }
  3106. }
  3107. page[n] = '\0';
  3108. s_append(page, &n, "</p><p>", sizeof(error_page));
  3109. s_append(page, &n, page_url, sizeof(error_page));
  3110. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3111. sizeof(error_page));
  3112. br_parse(&doc, page, n);
  3113. layout_valid = 0;
  3114. preload_active = 0;
  3115. preload_pending = 0;
  3116. preload_wait = 0;
  3117. fetch_workers_cancel_busy();
  3118. s_copy(page_title, title, sizeof(page_title));
  3119. page_loading = 0;
  3120. set_status(title, 1, 0);
  3121. ngui_invalidate(&ui);
  3122. }
  3123. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3124. unsigned int node)
  3125. {
  3126. if (image_count >= BR_MAX_IMAGES)
  3127. return -1;
  3128. if (decode_image_data(data, len, &images[0], 0, 0) != 0)
  3129. return -1;
  3130. doc.nodes[node].img_index = 0;
  3131. image_count = 1;
  3132. return 0;
  3133. }
  3134. static int ancestor_is(unsigned int node, unsigned int tag)
  3135. {
  3136. unsigned int p = doc.nodes[node].parent;
  3137. while (p) {
  3138. if (doc.nodes[p].tag == tag)
  3139. return 1;
  3140. p = doc.nodes[p].parent;
  3141. }
  3142. return 0;
  3143. }
  3144. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3145. * parallel but parsed in document order, so the cascade is unchanged. */
  3146. static int load_stylesheets(void)
  3147. {
  3148. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3149. static unsigned char remote[BR_MAX_SHEETS];
  3150. struct fetch_worker *slot[BR_MAX_SHEETS];
  3151. unsigned int i, n = 0, next = 0, k;
  3152. char err[64];
  3153. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3154. struct br_node *nd = &doc.nodes[i];
  3155. const char *rel, *href;
  3156. char url[BR_URL_MAX];
  3157. int dup = 0;
  3158. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3159. continue;
  3160. rel = br_rel(&doc, i);
  3161. if (!contains_ci(rel, "stylesheet"))
  3162. continue;
  3163. href = br_href(&doc, i);
  3164. if (!href[0])
  3165. continue;
  3166. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3167. continue;
  3168. for (k = 0; k < n; k++)
  3169. if (s_eq(urls[k], url)) {
  3170. dup = 1;
  3171. break;
  3172. }
  3173. if (dup)
  3174. continue;
  3175. s_copy(urls[n], url, BR_URL_MAX);
  3176. remote[n] = url[0] != '/' && !css_cache_has(url);
  3177. n++;
  3178. }
  3179. for (i = 0; i < BR_MAX_SHEETS; i++)
  3180. slot[i] = 0;
  3181. /* Start as many remote sheets as there are free workers. */
  3182. for (; next < n; next++) {
  3183. struct fetch_worker *w;
  3184. if (!remote[next])
  3185. continue;
  3186. w = fetch_worker_alloc();
  3187. if (!w)
  3188. break;
  3189. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3190. err, sizeof(err)) != 0) {
  3191. fetch_worker_release(w);
  3192. remote[next] = 0;
  3193. continue;
  3194. }
  3195. slot[next] = w;
  3196. }
  3197. for (i = 0; i < n; i++) {
  3198. unsigned char *data = 0;
  3199. unsigned int len = 0;
  3200. int rv;
  3201. if (!remote[i]) {
  3202. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3203. if (rv == FETCH_ABORT) {
  3204. fetch_workers_stop_all();
  3205. return FETCH_ABORT;
  3206. }
  3207. if (rv != 0 || !len)
  3208. continue;
  3209. } else {
  3210. struct fetch_worker *w = slot[i];
  3211. int tr = 0;
  3212. if (!w) {
  3213. w = fetch_worker_alloc();
  3214. if (!w)
  3215. continue;
  3216. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3217. 0, 0, 0, 0, err,
  3218. sizeof(err)) != 0) {
  3219. fetch_worker_release(w);
  3220. remote[i] = 0;
  3221. if (i == next)
  3222. next++;
  3223. continue;
  3224. }
  3225. slot[i] = w;
  3226. if (i == next)
  3227. next++;
  3228. }
  3229. rv = fetch_worker_wait(w, err, sizeof(err));
  3230. if (rv == FETCH_ABORT) {
  3231. fetch_workers_stop_all();
  3232. return FETCH_ABORT;
  3233. }
  3234. if (rv == 0)
  3235. rv = fetch_worker_read_body(w, image_io_buf,
  3236. BR_CSS_MAX,
  3237. image_io_buf + BR_CSS_MAX,
  3238. BR_CSS_COMP_MAX, &tr,
  3239. err, sizeof(err));
  3240. else
  3241. rv = -1;
  3242. fetch_worker_release(w);
  3243. slot[i] = 0;
  3244. /* Refill the worker window before parsing this sheet. */
  3245. for (; next < n; next++) {
  3246. struct fetch_worker *nw;
  3247. if (!remote[next])
  3248. continue;
  3249. nw = fetch_worker_alloc();
  3250. if (!nw)
  3251. break;
  3252. if (fetch_worker_submit(nw, urls[next],
  3253. BR_CSS_MAX, 0, 0, 0, 0,
  3254. err, sizeof(err)) != 0) {
  3255. fetch_worker_release(nw);
  3256. remote[next] = 0;
  3257. continue;
  3258. }
  3259. slot[next] = nw;
  3260. }
  3261. if (rv <= 0)
  3262. continue;
  3263. len = (unsigned int)rv;
  3264. data = image_io_buf;
  3265. css_cache_put(urls[i], data, len);
  3266. }
  3267. if (len) {
  3268. br_set_font_base(urls[i]);
  3269. br_parse_css_text(&doc, (const char *)data, len);
  3270. }
  3271. }
  3272. br_set_font_base(page_url);
  3273. br_parse_inline_css(&doc);
  3274. load_font_faces();
  3275. br_reset_styles(&doc);
  3276. layout_valid = 0;
  3277. return 0;
  3278. }
  3279. static void preload_begin(void)
  3280. {
  3281. preload_active = 1;
  3282. preload_pending = 0;
  3283. preload_wait = 1;
  3284. preload_max_jobs = FETCH_WORKERS;
  3285. preload_node = 0;
  3286. preload_loaded = 0;
  3287. preload_scroll = 0;
  3288. }
  3289. /* Styles are computed top-down during layout, but images inside a hidden
  3290. * menu/carousel are never visited and keep img_top == 0. Without this check
  3291. * the preloader walks the DOM in node order and spends the whole image
  3292. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3293. static int node_hidden(unsigned int node)
  3294. {
  3295. unsigned int path[32], n = 0, p = node, i;
  3296. struct br_style st, parent;
  3297. while (p && n < sizeof(path) / sizeof(path[0])) {
  3298. path[n++] = p;
  3299. p = doc.nodes[p].parent;
  3300. }
  3301. parent = (struct br_style){0};
  3302. parent.font_px = 16;
  3303. parent.display = BR_DISPLAY_BLOCK;
  3304. for (i = n; i > 0; i--) {
  3305. br_style_for(&doc, path[i - 1], &parent, &st);
  3306. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3307. st.opacity_hidden)
  3308. return 1;
  3309. parent = st;
  3310. }
  3311. return 0;
  3312. }
  3313. static struct br_style base_style(void);
  3314. static void style_for_node(unsigned int node, struct br_style *out)
  3315. {
  3316. unsigned int p = doc.nodes[node].parent;
  3317. struct br_style parent;
  3318. if (p) {
  3319. style_for_node(p, &parent);
  3320. br_style_for(&doc, node, &parent, out);
  3321. } else {
  3322. parent = base_style();
  3323. br_style_for(&doc, node, &parent, out);
  3324. }
  3325. }
  3326. /* ---- parallel image preloading ---- *
  3327. *
  3328. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3329. * preload_step() only starts jobs and harvests completed ones; the browser
  3330. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3331. */
  3332. static int preload_active_jobs(void)
  3333. {
  3334. int i, n = 0;
  3335. for (i = 0; i < FETCH_WORKERS; i++)
  3336. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3337. n++;
  3338. return n;
  3339. }
  3340. static void preload_job_error(struct fetch_worker *w)
  3341. {
  3342. if (w->node < doc.nnode) {
  3343. if (w->bg)
  3344. doc.nodes[w->node].bg_img_index = -2;
  3345. else
  3346. doc.nodes[w->node].img_index = -2;
  3347. ngui_invalidate(&ui);
  3348. }
  3349. }
  3350. static void preload_decode(unsigned int node, int bg,
  3351. const unsigned char *data, unsigned int len)
  3352. {
  3353. if (image_count >= BR_MAX_IMAGES) {
  3354. if (bg)
  3355. doc.nodes[node].bg_img_index = -2;
  3356. else
  3357. doc.nodes[node].img_index = -2;
  3358. return;
  3359. }
  3360. if (decode_image_data(data, len, &images[image_count],
  3361. bg && node < BR_MAX_NODES &&
  3362. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  3363. bg && node < BR_MAX_NODES &&
  3364. layout_boxes[node].valid ? layout_boxes[node].h : 0) == 0) {
  3365. if (bg)
  3366. doc.nodes[node].bg_img_index = (short)image_count;
  3367. else
  3368. doc.nodes[node].img_index = (short)image_count;
  3369. image_count++;
  3370. preload_loaded++;
  3371. layout_valid = 0;
  3372. } else {
  3373. if (bg)
  3374. doc.nodes[node].bg_img_index = -2;
  3375. else
  3376. doc.nodes[node].img_index = -2;
  3377. }
  3378. ngui_invalidate(&ui);
  3379. }
  3380. /* Harvest one completed worker. Returns 1 when a job was finished. */
  3381. static int preload_finish_worker(struct fetch_worker *w)
  3382. {
  3383. char err[64];
  3384. int rv, tr = 0;
  3385. rv = fetch_worker_poll(w, err, sizeof(err));
  3386. if (rv < 0) {
  3387. preload_job_error(w);
  3388. fetch_worker_release(w);
  3389. return 1;
  3390. }
  3391. if (rv == 0)
  3392. return 0;
  3393. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  3394. image_comp_buf, BR_IMG_FILE_MAX,
  3395. &tr, err, sizeof(err));
  3396. if (rv >= 0)
  3397. preload_decode(w->node, w->bg, image_file_buf,
  3398. (unsigned int)rv);
  3399. else
  3400. preload_job_error(w);
  3401. fetch_worker_release(w);
  3402. return 1;
  3403. }
  3404. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  3405. * the number of jobs started. */
  3406. static int preload_fill_jobs(void)
  3407. {
  3408. int started = 0;
  3409. char err[64];
  3410. while (preload_active && preload_node < doc.nnode) {
  3411. unsigned int i = preload_node;
  3412. struct br_node *nd = &doc.nodes[i];
  3413. const char *src;
  3414. char url[BR_URL_MAX];
  3415. struct fetch_worker *w;
  3416. if (preload_active_jobs() >= preload_max_jobs)
  3417. break;
  3418. if (nd->type != BR_NODE_ELEM) {
  3419. preload_node++;
  3420. continue;
  3421. }
  3422. if (nd->tag != BR_TAG_IMG) {
  3423. if (nd->bg_img_index == -1) {
  3424. struct br_style bs;
  3425. style_for_node(i, &bs);
  3426. if (bs.display != BR_DISPLAY_NONE &&
  3427. !bs.vis_hidden && bs.bg_image) {
  3428. const char *bsrc =
  3429. br_bg_image_url(bs.bg_image - 1);
  3430. /* Lazy like <img>: a background box
  3431. * below the viewport (or not laid
  3432. * out yet) waits for the next scan. */
  3433. if (bsrc[0] &&
  3434. (!layout_boxes[i].valid ||
  3435. block_top[i] >
  3436. (unsigned int)(page_scroll.offset +
  3437. page_rect.h + 160))) {
  3438. preload_pending = 1;
  3439. preload_node++;
  3440. continue;
  3441. }
  3442. if (bsrc[0] &&
  3443. !contains_ci(bsrc, ".svg") &&
  3444. !starts_with(bsrc, "data:") &&
  3445. resolve_link(page_url, bsrc, url,
  3446. sizeof(url)) == 0) {
  3447. if (image_count +
  3448. preload_active_jobs() >=
  3449. BR_MAX_IMAGES) {
  3450. preload_node = doc.nnode;
  3451. break;
  3452. }
  3453. if (url[0] == '/') {
  3454. unsigned char *data = 0;
  3455. unsigned int len = 0;
  3456. preload_node = i + 1;
  3457. if (fetch_image(url,
  3458. BR_IMG_FILE_MAX,
  3459. &data, &len,
  3460. err,
  3461. sizeof(err)) == 0)
  3462. preload_decode(i, 1, data, len);
  3463. else
  3464. nd->bg_img_index = -2;
  3465. continue;
  3466. }
  3467. w = fetch_worker_alloc();
  3468. if (!w)
  3469. return started;
  3470. preload_node = i + 1;
  3471. if (fetch_worker_submit(w, url,
  3472. BR_IMG_FILE_MAX,
  3473. 0, 0, i, 1,
  3474. err,
  3475. sizeof(err)) != 0) {
  3476. nd->bg_img_index = -2;
  3477. fetch_worker_release(w);
  3478. continue;
  3479. }
  3480. w->image_job = 1;
  3481. w->deadline = u_ticks_ms() +
  3482. BR_IMG_JOB_TIMEOUT_MS;
  3483. /* in flight: rescans skip it */
  3484. nd->bg_img_index = -3;
  3485. started++;
  3486. continue;
  3487. }
  3488. }
  3489. nd->bg_img_index = -2;
  3490. }
  3491. preload_node++;
  3492. continue;
  3493. }
  3494. if (nd->img_index != -1) {
  3495. preload_node++;
  3496. continue;
  3497. }
  3498. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  3499. preload_node++;
  3500. continue;
  3501. }
  3502. src = br_src(&doc, i);
  3503. if (!src[0] || contains_ci(src, ".svg") ||
  3504. starts_with(src, "data:")) {
  3505. preload_node++;
  3506. continue;
  3507. }
  3508. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  3509. preload_node++;
  3510. continue;
  3511. }
  3512. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  3513. preload_node = doc.nnode;
  3514. break;
  3515. }
  3516. /* Do not stop at the first below-fold image: DOM order is
  3517. * not visual order, and a footer/ad image early in the DOM
  3518. * used to hide every later article image from the loader. */
  3519. if (img_top[i] >
  3520. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  3521. preload_pending = 1;
  3522. preload_node++;
  3523. continue;
  3524. }
  3525. if (url[0] == '/') {
  3526. unsigned char *data = 0;
  3527. unsigned int len = 0;
  3528. preload_node = i + 1;
  3529. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  3530. err, sizeof(err)) == 0)
  3531. preload_decode(i, 0, data, len);
  3532. else
  3533. nd->img_index = -2;
  3534. continue;
  3535. }
  3536. w = fetch_worker_alloc();
  3537. if (!w)
  3538. return started;
  3539. preload_node = i + 1;
  3540. {
  3541. char msg[64];
  3542. unsigned int n = 0;
  3543. s_append(msg, &n, "Loading images ", sizeof(msg));
  3544. s_append_dec(msg, &n,
  3545. (unsigned int)preload_loaded + 1,
  3546. sizeof(msg));
  3547. s_append(msg, &n, "...", sizeof(msg));
  3548. set_status(msg, 0, 0);
  3549. }
  3550. if (fetch_worker_submit(w, url, BR_IMG_FILE_MAX, 0, 0, i, 0,
  3551. err, sizeof(err)) != 0) {
  3552. nd->img_index = -2;
  3553. fetch_worker_release(w);
  3554. continue;
  3555. }
  3556. w->image_job = 1;
  3557. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  3558. nd->img_index = -3; /* in flight: rescans skip it */
  3559. started++;
  3560. }
  3561. return started;
  3562. }
  3563. static void preload_step(void)
  3564. {
  3565. int i;
  3566. if (!preload_active)
  3567. return;
  3568. if (cancel_fetch || pending_action) {
  3569. preload_active = 0;
  3570. preload_pending = 0;
  3571. fetch_workers_cancel_busy();
  3572. return;
  3573. }
  3574. preload_fill_jobs();
  3575. /* Decode at most one completed image per main-loop pass. A full-size
  3576. * JPEG decode blocks this single-threaded UI for a long time, and
  3577. * harvesting a batch back-to-back starved the TCP pump (and therefore
  3578. * every other image download) on slow CPUs: requests looked stuck
  3579. * while four decodes ran in a row. */
  3580. for (i = 0; i < FETCH_WORKERS; i++) {
  3581. if (!fetch_workers[i].busy)
  3582. continue;
  3583. if (preload_finish_worker(&fetch_workers[i]))
  3584. return;
  3585. }
  3586. if (preload_active && preload_node >= doc.nnode &&
  3587. preload_active_jobs() == 0) {
  3588. preload_active = 0;
  3589. if (preload_pending)
  3590. preload_scroll = page_scroll.offset;
  3591. else
  3592. preload_pending = 0;
  3593. /* Keep the now idle helpers and their connections; a later
  3594. * navigation reuses them. They exit after ten idle seconds,
  3595. * and losing window focus stops them at once. */
  3596. set_status(post_status_text, post_status_error, post_status_ttl);
  3597. ngui_invalidate(&ui);
  3598. }
  3599. }
  3600. /* Set by navigate() when it turned a typed bare host into https://; the next
  3601. * load_page() consumes it and may retry over http. */
  3602. static int nav_https_upgraded;
  3603. /* Errors that mean "https is not served here" rather than "the site is
  3604. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  3605. static int https_fallback_error(int e)
  3606. {
  3607. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  3608. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  3609. e == UHTTP_ERR_RESET;
  3610. }
  3611. static void history_push(const char *url)
  3612. {
  3613. if (!url || !url[0])
  3614. return;
  3615. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  3616. s_eq(history[hist_pos], url))
  3617. return;
  3618. if (hist_len > 0 && hist_pos + 1 < hist_len)
  3619. hist_len = hist_pos + 1;
  3620. if (hist_len < BR_HISTORY) {
  3621. s_copy(history[hist_len], url, BR_URL_MAX);
  3622. hist_pos = hist_len;
  3623. hist_len++;
  3624. } else {
  3625. int i;
  3626. for (i = 1; i < BR_HISTORY; i++)
  3627. s_copy(history[i - 1], history[i], BR_URL_MAX);
  3628. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  3629. hist_pos = BR_HISTORY - 1;
  3630. }
  3631. }
  3632. static void load_page(const char *url, int local, int push)
  3633. {
  3634. unsigned char *body = 0;
  3635. unsigned int len = 0;
  3636. int truncated = 0;
  3637. struct img_info image_info;
  3638. char ctype[64];
  3639. char final[BR_URL_MAX];
  3640. char err[80];
  3641. const char *detail = 0;
  3642. const char *post = pending_post_is ? pending_post : 0;
  3643. unsigned int post_len = pending_post_len;
  3644. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  3645. /* Phase timings for the status line: where a slow load spends it. */
  3646. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  3647. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  3648. int upgraded = nav_https_upgraded;
  3649. int retried = 0;
  3650. int rv;
  3651. nav_https_upgraded = 0;
  3652. final[0] = '\0';
  3653. pending_post_len = 0;
  3654. pending_post_is = 0;
  3655. cancel_fetch = 0;
  3656. preload_active = 0;
  3657. preload_pending = 0;
  3658. fetch_workers_prepare_nav(url);
  3659. js_browser_stop();
  3660. js_last_status[0] = '\0';
  3661. js_last_error = 0;
  3662. heap_clear();
  3663. image_reset();
  3664. form_reset_state();
  3665. layout_valid = 0;
  3666. page_scroll.offset = 0;
  3667. page_scroll.dragging = 0;
  3668. page_title[0] = '\0';
  3669. page_loading = 1;
  3670. page_is_local = local;
  3671. s_copy(page_url, url, sizeof(page_url));
  3672. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3673. url_in.len = s_len(url_in.text);
  3674. url_in.cursor = url_in.len;
  3675. url_in.scroll = 0;
  3676. ngui_set_focus(&ui, 0);
  3677. if (final[0])
  3678. final[0] = '\0';
  3679. if (push)
  3680. history_push(url);
  3681. set_status("Loading...", 0, 0);
  3682. ngui_invalidate(&ui);
  3683. /* heap_clear() detaches the fonts, so attach them again before the
  3684. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  3685. if (heap_start() != 0) {
  3686. show_error("Out of memory", "Cannot allocate the page buffer");
  3687. return;
  3688. }
  3689. br_parse_plain(&doc, "", 0); /* blank while loading */
  3690. ngui_font_attach(&ui);
  3691. redraw_now();
  3692. browser_rules_alloc();
  3693. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3694. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  3695. &truncated, post, post_len);
  3696. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  3697. fetch_last_error == UHTTP_ERR_DNS) {
  3698. /* A busy previous page can leave the receiver ring full just
  3699. * long enough to lose a DNS reply. Tear the old helpers down
  3700. * and try once more before giving up. */
  3701. retried = 1;
  3702. fetch_workers_stop_all();
  3703. u_sleep_ms(500);
  3704. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  3705. sizeof(ctype), final, sizeof(final), err,
  3706. sizeof(err), &truncated, post, post_len);
  3707. }
  3708. if (rv == FETCH_ABORT)
  3709. return;
  3710. t_fetch = u_ticks_ms() - t_start;
  3711. /* Capture the page timing before CSS/script/image fetches overwrite the
  3712. * shared fetch_meta block. */
  3713. if (rv == 0 && !local) {
  3714. page_open_ms = fetch_meta.open_ms;
  3715. page_first_ms = fetch_meta.first_ms;
  3716. page_total_ms = fetch_meta.total_ms;
  3717. }
  3718. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  3719. https_fallback_error(fetch_last_error)) {
  3720. char http_url[BR_URL_MAX];
  3721. unsigned int n = 0;
  3722. s_append(http_url, &n, "http://", sizeof(http_url));
  3723. s_append(http_url, &n, url + 8, sizeof(http_url));
  3724. /* Replace the https entry instead of adding a second one. */
  3725. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  3726. s_eq(history[hist_pos], url))
  3727. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  3728. load_page(http_url, 0, 0);
  3729. return;
  3730. }
  3731. if (rv != 0) {
  3732. detail = err;
  3733. show_error("Cannot load this page", detail);
  3734. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3735. url_in.len = s_len(url_in.text);
  3736. url_in.cursor = url_in.len;
  3737. url_in.scroll = 0;
  3738. return;
  3739. }
  3740. if (!local)
  3741. origin_cache_learn(url, final[0] ? final : url);
  3742. page_is_local = local;
  3743. if (final[0]) {
  3744. s_copy(page_url, final, sizeof(page_url));
  3745. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3746. url_in.len = s_len(url_in.text);
  3747. url_in.cursor = url_in.len;
  3748. url_in.scroll = 0;
  3749. }
  3750. if (contains_ci(ctype, "text/plain")) {
  3751. br_parse_plain(&doc, (const char *)body, len);
  3752. } else if (contains_ci(ctype, "image/") ||
  3753. (!contains_ci(ctype, "text/html") &&
  3754. img_sniff(body, len, &image_info) == 0)) {
  3755. unsigned int node = br_parse_image_doc(&doc, page_url);
  3756. if (node)
  3757. decode_direct_image(body, len, node);
  3758. s_copy(page_title, "Image", sizeof(page_title));
  3759. } else {
  3760. br_set_viewport(ui.w);
  3761. t_mark = u_ticks_ms();
  3762. br_parse(&doc, (const char *)body, len);
  3763. t_parse = u_ticks_ms() - t_mark;
  3764. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  3765. sizeof(page_title));
  3766. t_mark = u_ticks_ms();
  3767. if (load_stylesheets() == FETCH_ABORT)
  3768. return;
  3769. t_css = u_ticks_ms() - t_mark;
  3770. if (pending_action)
  3771. return;
  3772. }
  3773. preload_begin();
  3774. page_loading = 0;
  3775. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3776. url_in.len = s_len(url_in.text);
  3777. url_in.cursor = url_in.len;
  3778. url_in.scroll = 0;
  3779. ngui_set_focus(&ui, 0);
  3780. /* Paint the parsed page before fetching/running scripts. A slow
  3781. * remote <script src> then does not hide the page behind the loading
  3782. * screen; the fetch helper pumps this UI while it waits. */
  3783. set_status("Loading scripts...", 0, 0);
  3784. t_mark = u_ticks_ms();
  3785. redraw_now();
  3786. t_paint = u_ticks_ms() - t_mark;
  3787. /* Start one image download before the scripts. The other workers
  3788. * fetch the external script bodies in parallel, and the remaining
  3789. * images start as soon as the script phase ends. */
  3790. preload_max_jobs = 1;
  3791. preload_fill_jobs();
  3792. preload_wait = 0;
  3793. t_mark = u_ticks_ms();
  3794. run_page_scripts();
  3795. t_js = u_ticks_ms() - t_mark;
  3796. preload_max_jobs = FETCH_WORKERS;
  3797. if (pending_action)
  3798. return;
  3799. post_status_text[0] = '\0';
  3800. post_status_error = 0;
  3801. post_status_ttl = 0;
  3802. if (js_last_status[0]) {
  3803. s_copy(post_status_text, js_last_status,
  3804. sizeof(post_status_text));
  3805. post_status_error = js_last_error;
  3806. post_status_ttl = 8000;
  3807. } else if (truncated) {
  3808. s_copy(post_status_text, "Page truncated at the buffer limit",
  3809. sizeof(post_status_text));
  3810. post_status_ttl = 6000;
  3811. } else if (doc.truncated) {
  3812. s_copy(post_status_text, "Page truncated by the parser",
  3813. sizeof(post_status_text));
  3814. post_status_ttl = 6000;
  3815. } else if (page_total_ms) {
  3816. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  3817. * paint 220, js 1750" -- the phases of this load. */
  3818. unsigned int n = 0;
  3819. static const char *const names[] = {
  3820. ", parse ", ", css ", ", paint ", ", js "
  3821. };
  3822. unsigned int vals[4];
  3823. int k;
  3824. vals[0] = t_parse;
  3825. vals[1] = t_css;
  3826. vals[2] = t_paint;
  3827. vals[3] = t_js;
  3828. (void)page_first_ms;
  3829. if (starts_with(page_url, "https://"))
  3830. s_append(post_status_text, &n,
  3831. "HTTPS (not verified), ",
  3832. sizeof(post_status_text));
  3833. s_append(post_status_text, &n, "Loaded in ",
  3834. sizeof(post_status_text));
  3835. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  3836. sizeof(post_status_text));
  3837. s_append(post_status_text, &n, " ms: page ",
  3838. sizeof(post_status_text));
  3839. s_append_dec(post_status_text, &n, t_fetch,
  3840. sizeof(post_status_text));
  3841. s_append(post_status_text, &n, " (headers ",
  3842. sizeof(post_status_text));
  3843. s_append_dec(post_status_text, &n, page_open_ms,
  3844. sizeof(post_status_text));
  3845. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  3846. for (k = 0; k < 4; k++) {
  3847. s_append(post_status_text, &n, names[k],
  3848. sizeof(post_status_text));
  3849. s_append_dec(post_status_text, &n, vals[k],
  3850. sizeof(post_status_text));
  3851. }
  3852. post_status_ttl = 12000;
  3853. } else if (starts_with(page_url, "https://")) {
  3854. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  3855. sizeof(post_status_text));
  3856. post_status_ttl = 6000;
  3857. }
  3858. set_status(post_status_text, post_status_error, post_status_ttl);
  3859. ngui_invalidate(&ui);
  3860. }
  3861. static void load_home(int push)
  3862. {
  3863. pending_post_len = 0;
  3864. pending_post_is = 0;
  3865. cancel_fetch = 0;
  3866. preload_active = 0;
  3867. preload_pending = 0;
  3868. js_browser_stop();
  3869. js_last_status[0] = '\0';
  3870. js_last_error = 0;
  3871. heap_clear();
  3872. image_reset();
  3873. form_reset_state();
  3874. layout_valid = 0;
  3875. page_scroll.offset = 0;
  3876. page_scroll.dragging = 0;
  3877. page_loading = 1;
  3878. page_is_local = 0;
  3879. s_copy(page_url, "about:home", sizeof(page_url));
  3880. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3881. url_in.len = s_len(url_in.text);
  3882. url_in.cursor = url_in.len;
  3883. url_in.scroll = 0;
  3884. ngui_set_focus(&ui, 0);
  3885. if (push)
  3886. history_push(page_url);
  3887. ngui_invalidate(&ui);
  3888. /* See load_page(): reattach the fonts before the first redraw. */
  3889. if (heap_start() != 0) {
  3890. show_error("Out of memory", "Cannot allocate the browser heap");
  3891. return;
  3892. }
  3893. br_parse_plain(&doc, "", 0);
  3894. ngui_font_attach(&ui);
  3895. redraw_now();
  3896. browser_rules_alloc();
  3897. {
  3898. static const char home[] =
  3899. "<html><head><title>NebOS Browser</title><style>"
  3900. "body { margin: 10px; color: #e4e6f0; }"
  3901. "h1 { color: #7fb0ff; }"
  3902. ".box { background-color: #262b3a; margin: 12px; "
  3903. "padding: 10px; }"
  3904. "a { color: #7fb0ff; }"
  3905. "pre { background-color: #32384a; }"
  3906. "</style></head><body>"
  3907. "<h1>NebOS Browser</h1>"
  3908. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  3909. "shared HTTP client and the image library.</p>"
  3910. "<div class=\"box\"><b>Try:</b>"
  3911. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  3912. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  3913. "<li><a href=\"/floppy1/JS.HTM\">/"
  3914. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  3915. "<li><a href=\"http://10.0.2.2:8000/\">"
  3916. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  3917. "<li><a href=\"https://example.com/\">"
  3918. "https://example.com/</a> (TLS, not verified)</li>"
  3919. "</ul></div>"
  3920. "<p>Type a URL in the bar above. Esc closes the "
  3921. "window, Ctrl+L focuses the address bar.</p>"
  3922. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  3923. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  3924. "</body></html>";
  3925. br_set_viewport(ui.w);
  3926. br_parse(&doc, home, sizeof(home) - 1);
  3927. br_parse_inline_css(&doc);
  3928. br_reset_styles(&doc);
  3929. s_copy(page_title, doc.title, sizeof(page_title));
  3930. }
  3931. post_status_text[0] = '\0';
  3932. post_status_error = 0;
  3933. post_status_ttl = 0;
  3934. page_loading = 0;
  3935. set_status("", 0, 0);
  3936. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  3937. url_in.len = s_len(url_in.text);
  3938. url_in.cursor = url_in.len;
  3939. url_in.scroll = 0;
  3940. ngui_set_focus(&ui, 0);
  3941. ngui_invalidate(&ui);
  3942. }
  3943. /* Extensions the browser opens from the local filesystem. A dotted input
  3944. * with one of these still resolves relative to the cwd. */
  3945. static int local_file_ext(const char *s)
  3946. {
  3947. static const char *const exts[] = {
  3948. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  3949. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  3950. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  3951. "cfg", "conf", 0
  3952. };
  3953. unsigned int i = 0, start = 0, len = 0, e;
  3954. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  3955. s[i] != '#') {
  3956. if (s[i] == '.') {
  3957. start = i + 1;
  3958. len = 0;
  3959. } else if (start) {
  3960. len++;
  3961. }
  3962. i++;
  3963. }
  3964. if (!len)
  3965. return 0;
  3966. for (e = 0; exts[e]; e++) {
  3967. const char *x = exts[e];
  3968. unsigned int xn = s_len(x), k;
  3969. if (xn != len)
  3970. continue;
  3971. for (k = 0; k < len; k++) {
  3972. char a = s[start + k];
  3973. if (a >= 'A' && a <= 'Z')
  3974. a = (char)(a - 'A' + 'a');
  3975. if (a != x[k])
  3976. break;
  3977. }
  3978. if (k == len)
  3979. return 1;
  3980. }
  3981. return 0;
  3982. }
  3983. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  3984. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  3985. * Enter to the first network request. */
  3986. static int looks_like_host(const char *s)
  3987. {
  3988. unsigned int i = 0;
  3989. int dot = 0;
  3990. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  3991. s[i] != ':') {
  3992. char c = s[i];
  3993. if (c == '.') {
  3994. dot = 1;
  3995. } else if (!((c >= 'a' && c <= 'z') ||
  3996. (c >= 'A' && c <= 'Z') ||
  3997. (c >= '0' && c <= '9') ||
  3998. c == '-' || c == '_')) {
  3999. return 0;
  4000. }
  4001. i++;
  4002. }
  4003. return dot && i > 0 && !local_file_ext(s);
  4004. }
  4005. static void load_remote(const char *url, int push)
  4006. {
  4007. char canon[BR_URL_MAX];
  4008. s_copy(canon, url, sizeof(canon));
  4009. origin_cache_apply(canon, sizeof(canon));
  4010. load_page(canon, 0, push);
  4011. }
  4012. static void navigate(const char *input, int push)
  4013. {
  4014. char target[BR_URL_MAX];
  4015. char *t;
  4016. if (!input)
  4017. return;
  4018. s_copy(target, input, sizeof(target));
  4019. t = trim(target);
  4020. if (!t[0])
  4021. return;
  4022. if (s_eq(t, "about:home")) {
  4023. load_home(push);
  4024. return;
  4025. }
  4026. if (starts_with(t, "file://")) {
  4027. make_abs_local(t + 7, target, sizeof(target));
  4028. load_page(target, 1, push);
  4029. return;
  4030. }
  4031. if (is_http(t)) {
  4032. load_remote(t, push);
  4033. return;
  4034. }
  4035. if (t[0] == '/') {
  4036. make_abs_local(t, target, sizeof(target));
  4037. load_page(target, 1, push);
  4038. return;
  4039. }
  4040. if (!looks_like_host(t)) {
  4041. struct sys_stat st;
  4042. if (u_stat(t, &st) == 0 && !st.is_dir) {
  4043. make_abs_local(t, target, sizeof(target));
  4044. load_page(target, 1, push);
  4045. return;
  4046. }
  4047. }
  4048. {
  4049. /* A typed bare host tries https first: nearly every site
  4050. * redirects http -> https anyway, and that hop costs a whole
  4051. * extra connection. load_page() falls back to http when the
  4052. * https connection itself fails. */
  4053. char with_scheme[BR_URL_MAX];
  4054. unsigned int n = 0;
  4055. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  4056. s_append(with_scheme, &n, t, sizeof(with_scheme));
  4057. nav_https_upgraded = 1;
  4058. load_remote(with_scheme, push);
  4059. }
  4060. }
  4061. /* ---- layout ---- */
  4062. static struct ufont_face *style_face(const struct br_style *st)
  4063. {
  4064. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  4065. return font_faces[st->font_face - 1];
  4066. return 0;
  4067. }
  4068. static struct ufont_face *run_face(const struct lay_run *r)
  4069. {
  4070. if (r->font_face && r->font_face <= BR_MAX_FACES)
  4071. return font_faces[r->font_face - 1];
  4072. return 0;
  4073. }
  4074. static unsigned int face_text_width(struct ngui *gui,
  4075. const struct br_style *st,
  4076. const char *s, unsigned int n)
  4077. {
  4078. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  4079. st->bold, st->italic, st->mono);
  4080. }
  4081. static int face_line_height(struct ngui *gui, const struct br_style *st)
  4082. {
  4083. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  4084. st->mono);
  4085. }
  4086. static unsigned int run_text_width(struct ngui *gui,
  4087. const struct lay_run *r,
  4088. const char *s, unsigned int n)
  4089. {
  4090. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  4091. r->bold, r->italic, r->mono);
  4092. }
  4093. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  4094. {
  4095. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  4096. r->mono);
  4097. }
  4098. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  4099. {
  4100. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  4101. }
  4102. static struct br_style base_style(void)
  4103. {
  4104. struct br_style s = { 0 };
  4105. s.color = ui.theme.text;
  4106. s.bg = ui.theme.bg;
  4107. s.has_bg = 0;
  4108. for (int i = 0; i < 4; i++) {
  4109. s.border_c[i] = 0;
  4110. s.border_w[i] = 0;
  4111. s.border_s[i] = BR_BORDER_SOLID;
  4112. }
  4113. s.font_px = 16;
  4114. s.bold = 0;
  4115. s.italic = 0;
  4116. s.mono = 0;
  4117. s.underline = 0;
  4118. s.strike = 0;
  4119. s.overline = 0;
  4120. s.align = BR_ALIGN_LEFT;
  4121. s.display = BR_DISPLAY_BLOCK;
  4122. s.no_bullet = 0;
  4123. s.list_style = BR_LIST_AUTO;
  4124. s.uppercase = 0;
  4125. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  4126. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  4127. s.width = s.max_width = s.min_width = 0;
  4128. s.height = s.min_height = s.max_height = 0;
  4129. s.box_sizing = 0;
  4130. s.ml_auto = s.mr_auto = 0;
  4131. s.line_h_pct = 0;
  4132. s.line_h_px = 0;
  4133. s.mt = s.mb = s.ml = s.mr = 0;
  4134. s.pt = s.pb = s.pl = s.pr = 0;
  4135. return s;
  4136. }
  4137. /* Resolve a margin/padding raw value. Percentages use the containing
  4138. * block width for all four sides, as CSS specifies. */
  4139. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  4140. {
  4141. if (unit == 1)
  4142. return base * v / 10000;
  4143. if (unit == 2)
  4144. return st->font_px * v / 100;
  4145. if (unit == 3)
  4146. return (int)br_root_font_px() * v / 100;
  4147. if (unit == 4)
  4148. return 0;
  4149. return v;
  4150. }
  4151. static int mp_px(const struct br_style *st, int side, int base)
  4152. {
  4153. int raw;
  4154. switch (side) {
  4155. case 0: raw = st->mt; break;
  4156. case 1: raw = st->mr; break;
  4157. case 2: raw = st->mb; break;
  4158. case 3: raw = st->ml; break;
  4159. case 4: raw = st->pt; break;
  4160. case 5: raw = st->pr; break;
  4161. case 6: raw = st->pb; break;
  4162. default: raw = st->pl; break;
  4163. }
  4164. if (st->mp_unit[side] == 5)
  4165. return base * raw / 100 + st->mp_calc_px[side];
  4166. return css_mp_px(st, raw, st->mp_unit[side], base);
  4167. }
  4168. static int style_width_px(const struct br_style *st, int base)
  4169. {
  4170. if (st->width_kind == 1)
  4171. return st->width;
  4172. if (st->width_kind == 2)
  4173. return base * (int)st->width / 100;
  4174. if (st->width_kind == 3)
  4175. return base * st->width_calc_pct / 100 + st->width_calc_px;
  4176. return 0;
  4177. }
  4178. static int style_height_px(const struct br_style *st, int base)
  4179. {
  4180. if (st->height_kind == 1)
  4181. return st->height;
  4182. if (st->height_kind == 2)
  4183. return base * (int)st->height / 100;
  4184. if (st->height_kind == 3)
  4185. return base * st->height_calc_pct / 100 + st->height_calc_px;
  4186. return 0;
  4187. }
  4188. static int css_size(unsigned char kind, int val, int base)
  4189. {
  4190. if (kind == 1)
  4191. return val;
  4192. if (kind == 2)
  4193. return base * val / 100;
  4194. return -1;
  4195. }
  4196. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  4197. int thick, int horizontal, unsigned short color,
  4198. unsigned char style)
  4199. {
  4200. int pos;
  4201. if (len <= 0 || thick <= 0)
  4202. return;
  4203. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  4204. if (horizontal)
  4205. ngui_fill_rect(ui, (struct ngui_rect){
  4206. x, y, len, thick}, color);
  4207. else
  4208. ngui_fill_rect(ui, (struct ngui_rect){
  4209. x, y, thick, len}, color);
  4210. return;
  4211. }
  4212. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  4213. int seg = len - pos;
  4214. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  4215. seg = style == BR_BORDER_DASHED ? 4 : 2;
  4216. if (horizontal)
  4217. ngui_fill_rect(ui, (struct ngui_rect){
  4218. x + pos, y, seg, thick}, color);
  4219. else
  4220. ngui_fill_rect(ui, (struct ngui_rect){
  4221. x, y + pos, thick, seg}, color);
  4222. }
  4223. }
  4224. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  4225. const struct br_style *st)
  4226. {
  4227. int top = st->border_w[0], right = st->border_w[1];
  4228. int bottom = st->border_w[2], left = st->border_w[3];
  4229. if (r.w <= 0 || r.h <= 0)
  4230. return;
  4231. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  4232. int i;
  4233. for (i = 0; i < 4; i++)
  4234. if (st->border_w[i] && !st->border_t[i]) {
  4235. ngui_fill_rect(ui, r, st->border_c[i]);
  4236. break;
  4237. }
  4238. return;
  4239. }
  4240. if (top && !st->border_t[0])
  4241. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  4242. st->border_c[0], st->border_s[0]);
  4243. if (bottom && !st->border_t[2])
  4244. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  4245. st->border_c[2], st->border_s[2]);
  4246. if (left && !st->border_t[3])
  4247. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  4248. left, 0, st->border_c[3], st->border_s[3]);
  4249. if (right && !st->border_t[1])
  4250. draw_border_side(ui, r.x + r.w - right, r.y + top,
  4251. r.h - top - bottom, right, 0,
  4252. st->border_c[1], st->border_s[1]);
  4253. }
  4254. static void transform_origin(const struct br_style *st, int w, int h,
  4255. int *ox, int *oy)
  4256. {
  4257. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  4258. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  4259. }
  4260. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  4261. unsigned int a)
  4262. {
  4263. unsigned int dr, dg, db, sr, sg, sb;
  4264. if (a >= 255)
  4265. return s;
  4266. dr = (d >> 11) & 31;
  4267. dg = (d >> 5) & 63;
  4268. db = d & 31;
  4269. sr = (s >> 11) & 31;
  4270. sg = (s >> 5) & 63;
  4271. sb = s & 31;
  4272. dr = (dr * (255 - a) + sr * a) / 255;
  4273. dg = (dg * (255 - a) + sg * a) / 255;
  4274. db = (db * (255 - a) + sb * a) / 255;
  4275. return (unsigned short)((dr << 11) | (dg << 5) | db);
  4276. }
  4277. /* Paint a solid box through scale()/rotate() around transform-origin. This
  4278. * transforms the element's own background box; text and descendants keep
  4279. * their layout (documented approximation). */
  4280. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  4281. unsigned short color,
  4282. const struct br_style *st)
  4283. {
  4284. double sx = st->scale_x / 100.0;
  4285. double sy = st->scale_y / 100.0;
  4286. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  4287. double c = cos(th), sn = sin(th);
  4288. int ox, oy, minx, miny, maxx, maxy, x, y;
  4289. double ax, ay;
  4290. double px[4], py[4];
  4291. int cx1, cy1, cx2, cy2, i;
  4292. if (sx == 0)
  4293. sx = 0.01;
  4294. if (sy == 0)
  4295. sy = 0.01;
  4296. transform_origin(st, box.w, box.h, &ox, &oy);
  4297. ax = box.x + ox;
  4298. ay = box.y + oy;
  4299. px[0] = -ox; py[0] = -oy;
  4300. px[1] = box.w - ox; py[1] = -oy;
  4301. px[2] = box.w - ox; py[2] = box.h - oy;
  4302. px[3] = -ox; py[3] = box.h - oy;
  4303. minx = miny = 1000000;
  4304. maxx = maxy = -1000000;
  4305. for (i = 0; i < 4; i++) {
  4306. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  4307. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  4308. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4309. if (dx < minx) minx = dx;
  4310. if (dx > maxx) maxx = dx;
  4311. if (dy < miny) miny = dy;
  4312. if (dy > maxy) maxy = dy;
  4313. }
  4314. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4315. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4316. cx2 = page_rect.x + page_rect.w - 12;
  4317. cy2 = page_rect.y + page_rect.h;
  4318. if (cx2 > gui->w) cx2 = gui->w;
  4319. if (cy2 > gui->h) cy2 = gui->h;
  4320. if (minx < cx1) minx = cx1;
  4321. if (miny < cy1) miny = cy1;
  4322. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4323. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4324. for (y = miny; y <= maxy; y++) {
  4325. for (x = minx; x <= maxx; x++) {
  4326. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  4327. double rx = dx * c + dy * sn;
  4328. double ry = -dx * sn + dy * c;
  4329. double bx = rx / sx + ox;
  4330. double by = ry / sy + oy;
  4331. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  4332. gui->px[y * gui->w + x] = color;
  4333. }
  4334. }
  4335. }
  4336. static void draw_image_transformed(struct ngui *gui,
  4337. const struct img_image *im,
  4338. int x, int y, int w, int h,
  4339. int sx100, int sy100, int rot100,
  4340. int origin_x, int origin_y,
  4341. int origin_x_kind, int origin_y_kind)
  4342. {
  4343. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  4344. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  4345. double c = cos(th), sn = sin(th);
  4346. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  4347. double ax, ay;
  4348. double bx[4], by[4];
  4349. int cx1, cy1, cx2, cy2;
  4350. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  4351. return;
  4352. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  4353. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  4354. ax = x + ox;
  4355. ay = y + oy;
  4356. bx[0] = -ox; by[0] = -oy;
  4357. bx[1] = w - ox; by[1] = -oy;
  4358. bx[2] = w - ox; by[2] = h - oy;
  4359. bx[3] = -ox; by[3] = h - oy;
  4360. minx = miny = 1000000;
  4361. maxx = maxy = -1000000;
  4362. for (i = 0; i < 4; i++) {
  4363. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  4364. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  4365. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  4366. if (dx < minx) minx = dx;
  4367. if (dx > maxx) maxx = dx;
  4368. if (dy < miny) miny = dy;
  4369. if (dy > maxy) maxy = dy;
  4370. }
  4371. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  4372. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  4373. cx2 = page_rect.x + page_rect.w - 12;
  4374. cy2 = page_rect.y + page_rect.h;
  4375. if (cx2 > gui->w) cx2 = gui->w;
  4376. if (cy2 > gui->h) cy2 = gui->h;
  4377. if (minx < cx1) minx = cx1;
  4378. if (miny < cy1) miny = cy1;
  4379. if (maxx > cx2 - 1) maxx = cx2 - 1;
  4380. if (maxy > cy2 - 1) maxy = cy2 - 1;
  4381. for (py = miny; py <= maxy; py++) {
  4382. for (px = minx; px <= maxx; px++) {
  4383. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  4384. double rx = dx * c + dy * sn;
  4385. double ry = -dx * sn + dy * c;
  4386. double fx = rx / sx + ox;
  4387. double fy = ry / sy + oy;
  4388. int ix, iy;
  4389. unsigned int si, a;
  4390. unsigned short src;
  4391. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  4392. continue;
  4393. ix = (int)(fx * (double)im->w / w);
  4394. iy = (int)(fy * (double)im->h / h);
  4395. if (ix < 0 || ix >= (int)im->w ||
  4396. iy < 0 || iy >= (int)im->h)
  4397. continue;
  4398. si = (unsigned int)iy * im->w + (unsigned int)ix;
  4399. src = im->px[si];
  4400. a = im->alpha ? im->alpha[si] : 255;
  4401. gui->px[py * gui->w + px] =
  4402. a >= 255 ? src :
  4403. blend_rgb565(gui->px[py * gui->w + px],
  4404. src, a);
  4405. }
  4406. }
  4407. }
  4408. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4409. unsigned int node, const struct br_style *st);
  4410. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  4411. * first and every pixel outside a corner's arc is restored afterwards. */
  4412. #define BG_ROUND_MAX 64
  4413. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  4414. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  4415. unsigned int node, const struct br_style *st,
  4416. int rtl, int rtr, int rbr, int rbl)
  4417. {
  4418. struct ngui *ui = l->ui;
  4419. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  4420. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  4421. if (ui->nclip > 0)
  4422. clip = ui->clip[ui->nclip - 1];
  4423. for (c = 0; c < 4; c++) {
  4424. if (r[c] > BG_ROUND_MAX)
  4425. r[c] = BG_ROUND_MAX;
  4426. if (r[c] > box.w / 2)
  4427. r[c] = box.w / 2;
  4428. if (r[c] > box.h / 2)
  4429. r[c] = box.h / 2;
  4430. }
  4431. for (c = 0; c < 4; c++) {
  4432. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4433. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4434. for (dy = 0; dy < r[c]; dy++)
  4435. for (dx = 0; dx < r[c]; dx++) {
  4436. int px = ox + dx, py = oy + dy;
  4437. if (px >= clip.x && py >= clip.y &&
  4438. px < clip.x + clip.w && py < clip.y + clip.h)
  4439. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  4440. ui->px[py * ui->w + px];
  4441. }
  4442. }
  4443. draw_bg_image(l, box, node, st);
  4444. for (c = 0; c < 4; c++) {
  4445. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  4446. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  4447. /* arc centre, in corner-square coordinates */
  4448. int cx = (c == 1 || c == 2) ? 0 : r[c];
  4449. int cy = (c >= 2) ? 0 : r[c];
  4450. for (dy = 0; dy < r[c]; dy++)
  4451. for (dx = 0; dx < r[c]; dx++) {
  4452. int px = ox + dx, py = oy + dy;
  4453. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  4454. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  4455. continue;
  4456. if (px >= clip.x && py >= clip.y &&
  4457. px < clip.x + clip.w && py < clip.y + clip.h)
  4458. ui->px[py * ui->w + px] =
  4459. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  4460. }
  4461. }
  4462. }
  4463. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  4464. unsigned int node, const struct br_style *st)
  4465. {
  4466. struct br_image *bi;
  4467. struct img_blit b;
  4468. int tw, th, x, y, rep_x, rep_y, posx, posy;
  4469. unsigned int scale = 65536;
  4470. int legacy, tiles = 0, rows = 0;
  4471. int cx1, cy1, cx2, cy2;
  4472. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  4473. return;
  4474. if (doc.nodes[node].bg_img_index < 0 ||
  4475. doc.nodes[node].bg_img_index >= image_count)
  4476. return;
  4477. bi = &images[doc.nodes[node].bg_img_index];
  4478. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  4479. return;
  4480. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  4481. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  4482. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  4483. if (legacy) {
  4484. scale = ((unsigned int)box.w << 16) / bi->img.w;
  4485. tw = box.w;
  4486. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4487. x = box.x;
  4488. y = box.y;
  4489. rep_x = rep_y = 0;
  4490. } else {
  4491. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  4492. unsigned int sx = ((unsigned int)box.w << 16) /
  4493. bi->img.w;
  4494. unsigned int sy = ((unsigned int)box.h << 16) /
  4495. bi->img.h;
  4496. scale = st->bg_size_kind == 3 ?
  4497. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  4498. } else if (st->bg_size_kind == 1 ||
  4499. st->bg_size_kind == 2) {
  4500. int w = st->bg_size_w;
  4501. int h = st->bg_size_h;
  4502. if (st->bg_size_kind == 2) {
  4503. if (w)
  4504. w = box.w * w / 100;
  4505. if (h)
  4506. h = box.h * h / 100;
  4507. }
  4508. if (w)
  4509. scale = ((unsigned int)w << 16) / bi->img.w;
  4510. else if (h)
  4511. scale = ((unsigned int)h << 16) / bi->img.h;
  4512. }
  4513. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  4514. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  4515. if (tw < 1)
  4516. tw = 1;
  4517. if (th < 1)
  4518. th = 1;
  4519. posx = st->bg_pos_x_kind == 1 ?
  4520. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  4521. posy = st->bg_pos_y_kind == 1 ?
  4522. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  4523. x = box.x + posx;
  4524. y = box.y + posy;
  4525. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  4526. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  4527. if (rep_x) {
  4528. int m = (x - box.x) % tw;
  4529. if (m > 0)
  4530. m -= tw;
  4531. x = box.x + m;
  4532. }
  4533. if (rep_y) {
  4534. int m = (y - box.y) % th;
  4535. if (m > 0)
  4536. m -= th;
  4537. y = box.y + m;
  4538. }
  4539. }
  4540. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  4541. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  4542. cx2 = box.x + box.w;
  4543. cy2 = box.y + box.h;
  4544. if (cx2 > page_rect.x + page_rect.w - 12)
  4545. cx2 = page_rect.x + page_rect.w - 12;
  4546. if (cy2 > page_rect.y + page_rect.h)
  4547. cy2 = page_rect.y + page_rect.h;
  4548. if (cx1 >= cx2 || cy1 >= cy2)
  4549. return;
  4550. b.dst = l->ui->px;
  4551. b.dst_w = l->ui->w;
  4552. b.dst_h = l->ui->h;
  4553. b.clip_x = cx1;
  4554. b.clip_y = cy1;
  4555. b.clip_w = cx2 - cx1;
  4556. b.clip_h = cy2 - cy1;
  4557. b.scale = scale;
  4558. b.bg = ui.theme.bg;
  4559. b.bg2 = ui.theme.bg;
  4560. b.flags = IMG_BLIT_OVER_DST;
  4561. {
  4562. int row_x = x;
  4563. for (;;) {
  4564. for (;;) {
  4565. b.x = x;
  4566. b.y = y;
  4567. img_draw(&bi->img, &b);
  4568. if (!rep_x || ++tiles > 512)
  4569. break;
  4570. x += tw;
  4571. if (x >= box.x + box.w)
  4572. break;
  4573. }
  4574. if (!rep_y || ++rows > 64)
  4575. break;
  4576. y += th;
  4577. if (y >= box.y + box.h)
  4578. break;
  4579. x = row_x;
  4580. }
  4581. }
  4582. }
  4583. static int run_width(const struct lay_run *r)
  4584. {
  4585. if (r->img >= 0)
  4586. return r->iw;
  4587. if (r->img == -2)
  4588. return r->iw;
  4589. return (int)r->w;
  4590. }
  4591. static void start_line(struct lay *l, const struct br_style *st)
  4592. {
  4593. (void)st;
  4594. if (l->nruns == 0) {
  4595. l->line_y = l->y;
  4596. l->line_h = 0;
  4597. }
  4598. l->line_left = l->left;
  4599. l->line_right = l->right;
  4600. if (l->float_active && l->line_y < l->float_bottom) {
  4601. if (l->float_left > l->line_left)
  4602. l->line_left = l->float_left;
  4603. if (l->float_right < l->line_right)
  4604. l->line_right = l->float_right;
  4605. }
  4606. if (l->line_right < l->line_left + 8)
  4607. l->line_right = l->line_left + 8;
  4608. l->line_x = l->line_left;
  4609. l->run_x = l->line_left;
  4610. }
  4611. static void flush_line(struct lay *l)
  4612. {
  4613. int total, x, i, vis;
  4614. if (!l->nruns && l->line_x == l->line_left) {
  4615. l->line_h = 0;
  4616. return;
  4617. }
  4618. total = l->line_x - l->line_left;
  4619. x = l->line_left;
  4620. vis = 1;
  4621. if (l->draw) {
  4622. int lh = l->line_h ? l->line_h : 16;
  4623. vis = l->line_y + lh >= page_rect.y &&
  4624. l->line_y <= page_rect.y + page_rect.h;
  4625. }
  4626. if (l->align == BR_ALIGN_CENTER)
  4627. x += (l->line_right - l->line_left - total) / 2;
  4628. else if (l->align == BR_ALIGN_RIGHT)
  4629. x = l->line_right - total;
  4630. if (x < l->line_left)
  4631. x = l->line_left;
  4632. for (i = 0; i < l->nruns; i++) {
  4633. struct lay_run *r = &l->runs[i];
  4634. int w = run_width(r);
  4635. int ry = l->line_y + r->dy;
  4636. x += r->gap;
  4637. if (l->draw && vis) {
  4638. if (r->form) {
  4639. unsigned int node = r->form - 1;
  4640. struct form_state *fs = form_get(node, 1);
  4641. int hh = r->ih ? r->ih : 20;
  4642. int focused = form_focus == node;
  4643. int disabled = r->form_disabled;
  4644. unsigned short bg = l->ui->theme.panel_alt;
  4645. unsigned short fg = disabled ? 0x8410 : r->color;
  4646. struct ngui_rect box = {x, ry, w, hh};
  4647. if (r->form_kind == FORM_CHECKBOX ||
  4648. r->form_kind == FORM_RADIO) {
  4649. ngui_fill_rect(l->ui, box, bg);
  4650. ngui_frame(l->ui, box,
  4651. focused ? l->ui->theme.accent :
  4652. l->ui->theme.border);
  4653. if (fs && fs->checked) {
  4654. struct ngui_rect dot = {
  4655. x + 4, ry + 4,
  4656. w > 8 ? w - 8 : 1,
  4657. hh > 8 ? hh - 8 : 1
  4658. };
  4659. if (r->form_kind == FORM_RADIO)
  4660. ngui_fill_round_rect(
  4661. l->ui, dot, 4,
  4662. 4, 4, 4,
  4663. l->ui->theme.accent);
  4664. else
  4665. ngui_fill_rect(l->ui,
  4666. dot,
  4667. l->ui->theme.accent);
  4668. }
  4669. } else {
  4670. int editable =
  4671. r->form_kind == FORM_TEXT ||
  4672. r->form_kind == FORM_PASSWORD ||
  4673. r->form_kind == FORM_TEXTAREA;
  4674. int scroll = 0;
  4675. /* Editable fields draw the live value
  4676. * (r->lit is a short copy). */
  4677. static char shown[FORM_VALUE_MAX + 1];
  4678. const char *txt = r->lit;
  4679. unsigned int tl = s_len(r->lit);
  4680. if (editable && fs && fs->len) {
  4681. unsigned int k;
  4682. if (r->form_kind == FORM_PASSWORD) {
  4683. for (k = 0; k < fs->len; k++)
  4684. shown[k] = '*';
  4685. shown[k] = '\0';
  4686. txt = shown;
  4687. } else {
  4688. txt = fs->value;
  4689. }
  4690. tl = fs->len;
  4691. }
  4692. /* The box is drawn in theme colours, so
  4693. * the text is too: the page's CSS colour
  4694. * (dark on a light page) would vanish on
  4695. * the dark field. */
  4696. if (!disabled)
  4697. fg = editable && fs && !fs->len ?
  4698. l->ui->theme.text_dim :
  4699. l->ui->theme.text;
  4700. ngui_fill_rect(l->ui, box, bg);
  4701. ngui_frame(l->ui, box,
  4702. focused ? l->ui->theme.accent :
  4703. l->ui->theme.border);
  4704. /* A value wider than the field shows its
  4705. * tail (where typing happens). */
  4706. if (editable && w > 12) {
  4707. int tw = (int)run_text_width(l->ui,
  4708. r, txt, tl);
  4709. if (tw > w - 12)
  4710. scroll = tw - (w - 12);
  4711. }
  4712. ngui_push_clip(l->ui, (struct ngui_rect){
  4713. x + 1, ry + 1,
  4714. w > 2 ? w - 2 : 1,
  4715. hh > 2 ? hh - 2 : 1 });
  4716. ngui_text_px_face(l->ui, run_face(r),
  4717. x + 6 - scroll,
  4718. ry + (hh - r->font_px) / 2 - 1,
  4719. txt, tl, fg, r->font_px,
  4720. r->bold, r->italic, r->mono);
  4721. if (focused && fs && editable) {
  4722. int cw = 0;
  4723. if (fs->len && fs->caret)
  4724. cw = (int)run_text_width(
  4725. l->ui, r, txt,
  4726. fs->caret < fs->len ?
  4727. fs->caret : fs->len);
  4728. ngui_fill_rect(l->ui,
  4729. (struct ngui_rect){
  4730. x + 6 + cw - scroll,
  4731. ry + 4, 1,
  4732. hh > 8 ? hh - 8 : 1
  4733. },
  4734. l->ui->theme.accent);
  4735. }
  4736. ngui_pop_clip(l->ui);
  4737. if (r->form_kind == FORM_SELECT) {
  4738. ngui_text_px(l->ui, x + w - 12,
  4739. ry + 2, "v", 1, fg,
  4740. r->font_px, 0, 0, 0);
  4741. }
  4742. }
  4743. } else if (r->img == -2) {
  4744. int hh = r->ih ? r->ih : 20;
  4745. ngui_fill_rect(l->ui,
  4746. (struct ngui_rect){x, ry, w, hh},
  4747. l->ui->theme.panel_alt);
  4748. ngui_frame(l->ui,
  4749. (struct ngui_rect){x, ry, w, hh},
  4750. l->ui->theme.border);
  4751. ngui_text_px_face(l->ui, run_face(r),
  4752. x + 6, ry + 2, r->lit,
  4753. s_len(r->lit), r->color,
  4754. r->font_px, r->bold, r->italic,
  4755. r->mono);
  4756. } else if (r->img >= 0) {
  4757. struct br_image *bi = &images[r->img];
  4758. if (bi->state == 1 && r->transform_scale) {
  4759. draw_image_transformed(l->ui, &bi->img,
  4760. x, ry, r->iw, r->ih,
  4761. r->scale_x, r->scale_y,
  4762. r->rotate_x100, r->origin_x,
  4763. r->origin_y, r->origin_x_kind,
  4764. r->origin_y_kind);
  4765. } else if (bi->state == 1) {
  4766. struct img_blit b;
  4767. b.dst = l->ui->px;
  4768. b.dst_w = l->ui->w;
  4769. b.dst_h = l->ui->h;
  4770. b.clip_x = page_rect.x;
  4771. b.clip_y = page_rect.y;
  4772. b.clip_w = page_rect.w - 12;
  4773. b.clip_h = page_rect.h;
  4774. b.x = x;
  4775. b.y = ry;
  4776. b.scale = ((unsigned int)r->iw << 16) /
  4777. bi->img.w;
  4778. b.bg = ui.theme.bg;
  4779. b.bg2 = ui.theme.bg;
  4780. b.flags = IMG_BLIT_OVER_DST;
  4781. img_draw(&bi->img, &b);
  4782. }
  4783. } else {
  4784. const char *s = r->has_lit ? r->lit :
  4785. doc.text + r->off;
  4786. unsigned int n = r->has_lit ? s_len(r->lit) :
  4787. r->len;
  4788. ngui_text_px_face(l->ui, run_face(r), x, ry,
  4789. s, n, r->color, r->font_px,
  4790. r->bold, r->italic, r->mono);
  4791. if (r->underline)
  4792. ngui_fill_rect(l->ui,
  4793. (struct ngui_rect){x,
  4794. ry + run_ascent(l->ui, r) + 2,
  4795. w, 1}, r->color);
  4796. if (r->strike)
  4797. ngui_fill_rect(l->ui,
  4798. (struct ngui_rect){x,
  4799. ry + run_ascent(l->ui, r) -
  4800. (r->font_px > 3 ?
  4801. r->font_px / 3 : 1),
  4802. w, 1}, r->color);
  4803. if (r->overline)
  4804. ngui_fill_rect(l->ui,
  4805. (struct ngui_rect){x, ry,
  4806. w, 1}, r->color);
  4807. }
  4808. if (r->form || r->href) {
  4809. if (nhits < HIT_MAX) {
  4810. struct hit *h = &hits[nhits];
  4811. unsigned int target = r->form ?
  4812. r->form - 1 : r->href;
  4813. int hh = (r->form || r->img >= 0) ?
  4814. r->ih :
  4815. run_line_height(l->ui, r);
  4816. int merge = nhits > 0 &&
  4817. hits[nhits - 1].node == target &&
  4818. hits[nhits - 1].y == ry &&
  4819. hits[nhits - 1].h == hh &&
  4820. x <= hits[nhits - 1].x +
  4821. hits[nhits - 1].w + 2;
  4822. if (merge) {
  4823. struct hit *p = &hits[nhits - 1];
  4824. int end = x + w;
  4825. if (end > p->x + p->w)
  4826. p->w = end - p->x;
  4827. } else {
  4828. h->x = x;
  4829. h->y = ry;
  4830. h->w = w;
  4831. h->h = hh;
  4832. h->node = (unsigned short)target;
  4833. nhits++;
  4834. }
  4835. }
  4836. }
  4837. }
  4838. x += w;
  4839. }
  4840. l->y += l->line_h + 2;
  4841. if (l->float_active && l->y >= l->float_bottom)
  4842. l->float_active = 0;
  4843. l->nruns = 0;
  4844. l->line_x = l->left;
  4845. l->run_x = l->left;
  4846. l->line_left = l->left;
  4847. l->line_right = l->right;
  4848. l->line_h = 0;
  4849. l->space_pending = 0;
  4850. }
  4851. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  4852. const struct br_style *st, unsigned short href,
  4853. const char *lit)
  4854. {
  4855. unsigned int n = lit ? s_len(lit) : len;
  4856. const char *tp = lit ? lit : doc.text + off;
  4857. int w = (int)face_text_width(l->ui, st, tp, n);
  4858. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  4859. flush_line(l);
  4860. if (l->nruns == 0) {
  4861. l->line_y = l->y;
  4862. l->line_h = 0;
  4863. start_line(l, st);
  4864. }
  4865. {
  4866. struct lay_run *r = &l->runs[l->nruns++];
  4867. int gap = l->line_x - l->run_x;
  4868. if (gap < 0)
  4869. gap = 0;
  4870. r->gap = (unsigned short)gap;
  4871. r->off = off;
  4872. r->len = len;
  4873. r->color = st->color;
  4874. r->href = href;
  4875. r->dy = 0;
  4876. r->has_lit = 0;
  4877. r->form = 0;
  4878. r->form_kind = 0;
  4879. r->form_disabled = 0;
  4880. r->lit[0] = '\0';
  4881. if (lit && lit[0]) {
  4882. unsigned int i;
  4883. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  4884. r->lit[i] = lit[i];
  4885. r->lit[i] = '\0';
  4886. r->has_lit = 1;
  4887. }
  4888. r->img = -1;
  4889. r->iw = r->ih = 0;
  4890. r->font_px = st->font_px;
  4891. r->bold = st->bold;
  4892. r->italic = st->italic;
  4893. r->mono = st->mono;
  4894. r->font_face = st->font_face;
  4895. /* A control with its own background is a button, not body copy;
  4896. * an inherited link underline would strike through the fill. */
  4897. r->underline = st->underline && !st->has_bg;
  4898. r->strike = st->strike && !st->has_bg;
  4899. r->overline = st->overline && !st->has_bg;
  4900. r->w = (unsigned short)w;
  4901. if (r->has_lit)
  4902. r->w = (unsigned short)run_text_width(
  4903. l->ui, r, r->lit, s_len(r->lit));
  4904. w = r->w;
  4905. }
  4906. l->line_x += w;
  4907. l->run_x = l->line_x;
  4908. {
  4909. int lh = face_line_height(l->ui, st);
  4910. if (st->line_h_px)
  4911. lh = st->line_h_px;
  4912. else if (st->line_h_pct)
  4913. lh = st->font_px * st->line_h_pct / 100;
  4914. if (lh < face_line_height(l->ui, st))
  4915. lh = face_line_height(l->ui, st);
  4916. if (l->line_h < lh)
  4917. l->line_h = lh;
  4918. }
  4919. }
  4920. static void add_image_run(struct lay *l, unsigned int node,
  4921. const struct br_style *st, unsigned short href)
  4922. {
  4923. struct br_image *bi = 0;
  4924. int idx = doc.nodes[node].img_index;
  4925. int dw, dh, maxw;
  4926. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  4927. bi = &images[idx];
  4928. if (l->nruns == 0)
  4929. start_line(l, st);
  4930. if (l->space_pending &&
  4931. (l->nruns > 0 || l->line_x > l->line_left)) {
  4932. int sp = (int)face_text_width(l->ui, st, " ", 1);
  4933. if (l->line_x + sp <= l->line_right)
  4934. l->line_x += sp;
  4935. }
  4936. l->space_pending = 0;
  4937. if (!bi) {
  4938. const char *alt = br_alt(&doc, node);
  4939. struct br_style gs = *st;
  4940. char tmp[96];
  4941. unsigned int n = 0;
  4942. int w;
  4943. gs.color = BR_GRAY;
  4944. gs.underline = 0;
  4945. s_append(tmp, &n, "[", sizeof(tmp));
  4946. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  4947. s_append(tmp, &n, "]", sizeof(tmp));
  4948. w = (int)face_text_width(l->ui, &gs, tmp, n);
  4949. if (l->line_x + w > l->line_right &&
  4950. (l->nruns > 0 || l->line_x > l->line_left))
  4951. flush_line(l);
  4952. add_run(l, 0, 0, &gs, href, tmp);
  4953. if (!l->draw) {
  4954. int t = l->line_y < 0 ? 0 : l->line_y;
  4955. int hh = face_line_height(l->ui, &gs);
  4956. if (t > 65535)
  4957. t = 65535;
  4958. if (hh > 65535)
  4959. hh = 65535;
  4960. img_top[node] = (unsigned short)t;
  4961. img_h[node] = (unsigned short)hh;
  4962. }
  4963. return;
  4964. }
  4965. maxw = l->line_right - l->line_left;
  4966. if (maxw < 8)
  4967. maxw = 8;
  4968. {
  4969. int iw = bi->native_w, ih = bi->native_h;
  4970. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  4971. if (iw <= 0 || ih <= 0) {
  4972. iw = (int)bi->img.w;
  4973. ih = (int)bi->img.h;
  4974. }
  4975. dw = iw;
  4976. dh = ih;
  4977. if (doc.nodes[node].width_attr) {
  4978. int want = doc.nodes[node].width_attr;
  4979. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  4980. have_w = 1;
  4981. }
  4982. if (doc.nodes[node].height_attr) {
  4983. int want = doc.nodes[node].height_attr;
  4984. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  4985. have_h = 1;
  4986. }
  4987. if (have_w && !have_h)
  4988. dh = ih ? ih * dw / iw : 0;
  4989. if (have_h && !have_w)
  4990. dw = iw ? iw * dh / ih : 0;
  4991. if (st->width_kind) {
  4992. css_w = 1;
  4993. if (st->width_kind == 3)
  4994. dw = maxw * st->width_calc_pct / 100 +
  4995. st->width_calc_px;
  4996. else
  4997. dw = st->width_kind == 2 ?
  4998. maxw * (int)st->width / 100 :
  4999. (int)st->width;
  5000. }
  5001. if (st->height_kind) {
  5002. css_h = 1;
  5003. if (st->height_kind == 3)
  5004. dh = maxw * st->height_calc_pct / 100 +
  5005. st->height_calc_px;
  5006. else
  5007. dh = st->height_kind == 2 ?
  5008. maxw * (int)st->height / 100 :
  5009. (int)st->height;
  5010. }
  5011. if (css_w && !css_h)
  5012. dh = ih ? ih * dw / iw : 0;
  5013. if (css_h && !css_w)
  5014. dw = iw ? iw * dh / ih : 0;
  5015. if (st->max_width_kind) {
  5016. int mw = st->max_width_kind == 3 ?
  5017. maxw * st->max_width_calc_pct / 100 +
  5018. st->max_width_calc_px :
  5019. st->max_width_kind == 2 ?
  5020. maxw * (int)st->max_width / 100 :
  5021. (int)st->max_width;
  5022. if (mw > 0 && dw > mw) {
  5023. dh = iw ? ih * mw / iw : 0;
  5024. dw = mw;
  5025. }
  5026. }
  5027. }
  5028. if (dw < 8)
  5029. dw = 8;
  5030. if (dh < 8)
  5031. dh = 8;
  5032. if (dw > maxw) {
  5033. dh = dw ? dh * maxw / dw : dh;
  5034. dw = maxw;
  5035. }
  5036. if (!l->draw) {
  5037. int t = l->line_y < 0 ? 0 : l->line_y;
  5038. if (t > 65535)
  5039. t = 65535;
  5040. if (dh > 65535)
  5041. dh = 65535;
  5042. img_top[node] = (unsigned short)t;
  5043. img_h[node] = (unsigned short)dh;
  5044. }
  5045. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  5046. l->line_x > l->line_left))
  5047. flush_line(l);
  5048. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5049. flush_line(l);
  5050. if (l->nruns == 0) {
  5051. l->line_y = l->y;
  5052. l->line_h = 0;
  5053. start_line(l, st);
  5054. }
  5055. {
  5056. struct lay_run *r = &l->runs[l->nruns++];
  5057. int gap = l->line_x - l->run_x;
  5058. if (gap < 0)
  5059. gap = 0;
  5060. r->gap = (unsigned short)gap;
  5061. r->off = 0;
  5062. r->len = 0;
  5063. r->color = 0;
  5064. r->href = href;
  5065. r->form = 0;
  5066. r->form_kind = 0;
  5067. r->form_disabled = 0;
  5068. /* Inline replaced elements honour their vertical margins; this
  5069. * is how Bootstrap's negative logo margins centre the wordmark. */
  5070. {
  5071. int idy = mp_px(st, 0, l->right - l->left);
  5072. if (idy < -2048)
  5073. idy = -2048;
  5074. if (idy > 2048)
  5075. idy = 2048;
  5076. r->dy = (signed short)idy;
  5077. }
  5078. r->has_lit = 0;
  5079. r->lit[0] = '\0';
  5080. r->img = (short)idx;
  5081. r->iw = (unsigned short)dw;
  5082. r->ih = (unsigned short)dh;
  5083. r->w = (unsigned short)dw;
  5084. r->font_px = st->font_px;
  5085. r->bold = st->bold;
  5086. r->italic = st->italic;
  5087. r->mono = st->mono;
  5088. r->font_face = st->font_face;
  5089. r->transform_scale = st->transform_scale;
  5090. r->scale_x = st->scale_x;
  5091. r->scale_y = st->scale_y;
  5092. r->rotate_x100 = st->rotate_x100;
  5093. r->origin_x = st->origin_x;
  5094. r->origin_y = st->origin_y;
  5095. r->origin_x_kind = st->origin_x_kind;
  5096. r->origin_y_kind = st->origin_y_kind;
  5097. r->underline = 0;
  5098. }
  5099. if (node < BR_MAX_NODES) {
  5100. layout_boxes[node].x = l->line_x;
  5101. layout_boxes[node].y = l->line_y +
  5102. mp_px(st, 0, l->right - l->left);
  5103. layout_boxes[node].w = dw;
  5104. layout_boxes[node].h = dh;
  5105. layout_boxes[node].valid = 1;
  5106. }
  5107. l->line_x += dw;
  5108. l->run_x = l->line_x;
  5109. if (l->line_h < dh)
  5110. l->line_h = dh;
  5111. }
  5112. static int text_width(struct lay *l, const char *s, unsigned int n,
  5113. const struct br_style *st)
  5114. {
  5115. return (int)face_text_width(l->ui, st, s, n);
  5116. }
  5117. /* Longest prefix that fits in maxw, at least one byte. */
  5118. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  5119. const struct br_style *st, int maxw)
  5120. {
  5121. unsigned int take = 0;
  5122. while (take < n) {
  5123. if (text_width(l, s, take + 1, st) > maxw)
  5124. break;
  5125. take++;
  5126. }
  5127. return take ? take : 1;
  5128. }
  5129. static void emit_word(struct lay *l, const char *s, unsigned int start,
  5130. unsigned int n, unsigned int base,
  5131. const struct br_style *st, unsigned short href)
  5132. {
  5133. int avail;
  5134. int w = text_width(l, s + start, n, st);
  5135. unsigned int off = start;
  5136. if (l->nruns == 0)
  5137. start_line(l, st);
  5138. avail = l->line_right - l->line_left;
  5139. if (st->nowrap) {
  5140. if (n)
  5141. add_run(l, base + start,
  5142. (unsigned short)n, st, href, 0);
  5143. return;
  5144. }
  5145. /* A padded/bordered one-word button can be a few pixels wider than
  5146. * the content box; keep it on one line instead of splitting it. */
  5147. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  5148. add_run(l, base + start,
  5149. (unsigned short)n, st, href, 0);
  5150. return;
  5151. }
  5152. if (l->line_x + w > l->line_right &&
  5153. (l->nruns > 0 || l->line_x > l->line_left)) {
  5154. flush_line(l);
  5155. start_line(l, st);
  5156. avail = l->line_right - l->line_left;
  5157. }
  5158. if (w <= avail) {
  5159. if (n)
  5160. add_run(l, base + start,
  5161. (unsigned short)n, st, href, 0);
  5162. return;
  5163. }
  5164. while (n > 0) {
  5165. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  5166. add_run(l, base + off,
  5167. (unsigned short)take, st, href, 0);
  5168. off += take;
  5169. n -= take;
  5170. if (n) {
  5171. flush_line(l);
  5172. start_line(l, st);
  5173. avail = l->line_right - l->line_left;
  5174. }
  5175. }
  5176. }
  5177. static void emit_text(struct lay *l, const char *s, unsigned int len,
  5178. const struct br_style *st, unsigned short href, int pre)
  5179. {
  5180. unsigned int i = 0;
  5181. unsigned int base;
  5182. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  5183. if (!s || !len)
  5184. return;
  5185. if (space_w <= 0)
  5186. space_w = 8;
  5187. if (l->nruns == 0)
  5188. start_line(l, st);
  5189. base = (unsigned int)(s - doc.text);
  5190. if (st->uppercase) {
  5191. char *p = (char *)s;
  5192. unsigned int j;
  5193. for (j = 0; j < len; j++)
  5194. if (p[j] >= 'a' && p[j] <= 'z')
  5195. p[j] = (char)(p[j] - 'a' + 'A');
  5196. }
  5197. if (pre) {
  5198. while (i < len) {
  5199. unsigned int start;
  5200. if (s[i] == '\n') {
  5201. flush_line(l);
  5202. start_line(l, st);
  5203. i++;
  5204. continue;
  5205. }
  5206. if (s[i] == ' ') {
  5207. if (l->line_x + space_w > l->line_right &&
  5208. (l->nruns > 0 || l->line_x > l->line_left)) {
  5209. flush_line(l);
  5210. start_line(l, st);
  5211. } else {
  5212. l->line_x += space_w;
  5213. }
  5214. i++;
  5215. continue;
  5216. }
  5217. start = i;
  5218. while (i < len && s[i] != ' ' && s[i] != '\n')
  5219. i++;
  5220. emit_word(l, s, start, i - start, base, st, href);
  5221. }
  5222. return;
  5223. }
  5224. while (i < len) {
  5225. unsigned int start, n;
  5226. if (s[i] == ' ') {
  5227. l->space_pending = 1;
  5228. i++;
  5229. continue;
  5230. }
  5231. start = i;
  5232. while (i < len && s[i] != ' ')
  5233. i++;
  5234. n = i - start;
  5235. if (l->space_pending &&
  5236. (l->nruns > 0 || l->line_x > l->line_left)) {
  5237. if (st->nowrap ||
  5238. l->line_x + space_w <= l->line_right)
  5239. l->line_x += space_w;
  5240. }
  5241. l->space_pending = 0;
  5242. emit_word(l, s, start, n, base, st, href);
  5243. }
  5244. }
  5245. static int list_index(unsigned int parent, unsigned int node)
  5246. {
  5247. unsigned int n = 0, i;
  5248. for (i = doc.nodes[parent].first; i && i != node;
  5249. i = doc.nodes[i].next)
  5250. if (doc.nodes[i].tag == BR_TAG_LI)
  5251. n++;
  5252. return (int)n + 1;
  5253. }
  5254. static void list_roman(char *m, unsigned int *n, int v, int upper,
  5255. unsigned int cap)
  5256. {
  5257. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  5258. 50, 40, 10, 9, 5, 4, 1 };
  5259. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  5260. "l", "xl", "x", "ix", "v", "iv", "i" };
  5261. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  5262. "L", "XL", "X", "IX", "V", "IV", "I" };
  5263. unsigned int i;
  5264. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  5265. while (v >= val[i] && *n + 1 < cap) {
  5266. const char *s = upper ? up[i] : lo[i];
  5267. while (*s && *n + 1 < cap)
  5268. m[(*n)++] = *s++;
  5269. v -= val[i];
  5270. }
  5271. }
  5272. }
  5273. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  5274. {
  5275. unsigned int n = 0;
  5276. if (style == BR_LIST_DISC) {
  5277. m[n++] = '-';
  5278. } else if (style == BR_LIST_CIRCLE) {
  5279. m[n++] = 'o';
  5280. } else if (style == BR_LIST_SQUARE) {
  5281. m[n++] = '+';
  5282. } else if (style == BR_LIST_LOWER_ALPHA ||
  5283. style == BR_LIST_UPPER_ALPHA) {
  5284. if (idx >= 1 && idx <= 26)
  5285. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  5286. 'A' : 'a') + idx - 1);
  5287. else
  5288. m[n++] = '?';
  5289. m[n++] = '.';
  5290. } else if (style == BR_LIST_LOWER_ROMAN ||
  5291. style == BR_LIST_UPPER_ROMAN) {
  5292. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  5293. if (n + 1 < cap)
  5294. m[n++] = '.';
  5295. } else {
  5296. s_append_dec(m, &n, (unsigned int)idx, cap);
  5297. if (n + 1 < cap)
  5298. m[n++] = '.';
  5299. }
  5300. m[n] = '\0';
  5301. }
  5302. /* Set by the layout when the control is stretched to its line: a flex item
  5303. * (its box width was assigned by the flex row) or a child of a flex column,
  5304. * whose default align-items: stretch makes inputs full width. */
  5305. static int form_fill_line;
  5306. static void add_form_run(struct lay *l, unsigned int node,
  5307. const struct br_style *st, unsigned short href)
  5308. {
  5309. struct form_state *fs = form_get(node, 1);
  5310. char shown[FORM_VALUE_MAX + 1];
  5311. char opt[64];
  5312. const char *text = "";
  5313. struct lay_run *r;
  5314. int kind = form_kind_of(node);
  5315. int disabled = form_disabled(node);
  5316. int tw, w = 120, h = 20, i;
  5317. if (!fs)
  5318. return;
  5319. if (l->nruns == 0)
  5320. start_line(l, st);
  5321. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  5322. text = "";
  5323. w = 16;
  5324. h = 16;
  5325. } else if (kind == FORM_SELECT) {
  5326. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  5327. s_copy(opt, "Select", sizeof(opt));
  5328. text = opt;
  5329. w = 120;
  5330. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  5331. kind == FORM_RESET) {
  5332. if (fs->len)
  5333. text = fs->value;
  5334. else
  5335. text = kind == FORM_SUBMIT ? "Submit" :
  5336. kind == FORM_RESET ? "Reset" : "Button";
  5337. } else if (kind == FORM_PASSWORD) {
  5338. for (i = 0; i < fs->len; i++)
  5339. shown[i] = '*';
  5340. shown[fs->len] = '\0';
  5341. text = fs->len ? shown : br_placeholder(&doc, node);
  5342. } else {
  5343. if (fs->len)
  5344. text = fs->value;
  5345. else
  5346. text = br_placeholder(&doc, node);
  5347. if (kind == FORM_TEXTAREA) {
  5348. w = 180;
  5349. h = 40;
  5350. }
  5351. }
  5352. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  5353. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  5354. w = tw + 18;
  5355. if (w < 64)
  5356. w = 64;
  5357. h = 22;
  5358. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  5359. int line_w = l->line_right - l->line_left;
  5360. if (st->width_kind == 1)
  5361. w = st->width;
  5362. else if (st->width_kind == 2)
  5363. w = css_size(st->width_kind, st->width, line_w);
  5364. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  5365. w = line_w - (l->line_x - l->line_left);
  5366. else
  5367. w = 120;
  5368. /* Taller fields for large text (min-height/padding on login
  5369. * pages): keep the box around the glyphs. */
  5370. if (st->font_px + 8 > h)
  5371. h = st->font_px + 8;
  5372. } else if (kind == FORM_SELECT) {
  5373. w = st->width_kind == 1 ? st->width : 120;
  5374. }
  5375. if (w > l->line_right - l->line_left)
  5376. w = l->line_right - l->line_left;
  5377. if (w < 8)
  5378. w = 8;
  5379. if (l->line_x + w > l->line_right &&
  5380. (l->nruns > 0 || l->line_x > l->line_left))
  5381. flush_line(l);
  5382. if (l->nruns >= 96)
  5383. return;
  5384. if (l->nruns == 0) {
  5385. l->line_y = l->y;
  5386. l->line_h = 0;
  5387. start_line(l, st);
  5388. }
  5389. r = &l->runs[l->nruns++];
  5390. r->gap = (unsigned short)(l->line_x - l->run_x);
  5391. r->off = r->len = 0;
  5392. r->color = st->color;
  5393. r->href = href;
  5394. r->dy = 0;
  5395. r->has_lit = 1;
  5396. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  5397. r->lit[i] = text[i];
  5398. r->lit[i] = '\0';
  5399. r->img = -2;
  5400. r->iw = (unsigned short)w;
  5401. r->ih = (unsigned short)h;
  5402. r->w = (unsigned short)w;
  5403. r->font_px = st->font_px;
  5404. r->bold = st->bold;
  5405. r->italic = st->italic;
  5406. r->mono = st->mono;
  5407. r->font_face = st->font_face;
  5408. r->underline = 0;
  5409. r->form = node + 1;
  5410. r->form_kind = (unsigned char)kind;
  5411. r->form_disabled = (unsigned char)disabled;
  5412. if (node < BR_MAX_NODES) {
  5413. layout_boxes[node].x = l->line_x;
  5414. layout_boxes[node].y = l->line_y;
  5415. layout_boxes[node].w = w;
  5416. layout_boxes[node].h = h;
  5417. layout_boxes[node].valid = 1;
  5418. }
  5419. l->line_x += w;
  5420. l->run_x = l->line_x;
  5421. if (l->line_h < h)
  5422. l->line_h = h;
  5423. }
  5424. /* A poster wrapper is absolutely positioned over the media slot; the
  5425. * measured height of its picture is normally added back to the flow. When a
  5426. * loading-skeleton sibling already reserves that slot, adding both doubles
  5427. * the media height and pushes the article text a full screen down. */
  5428. static int has_skeleton_sibling(unsigned int node)
  5429. {
  5430. unsigned int p = doc.nodes[node].parent, c;
  5431. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  5432. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  5433. continue;
  5434. if (doc.nodes[c].class_off &&
  5435. contains_ci(doc.attrs + doc.nodes[c].class_off,
  5436. "skeleton"))
  5437. return 1;
  5438. }
  5439. return 0;
  5440. }
  5441. static void layout_children(struct lay *l, unsigned int parent,
  5442. const struct br_style *pst, int depth,
  5443. unsigned short link);
  5444. static void layout_flex_children(struct lay *l, unsigned int parent,
  5445. const struct br_style *pst, int depth,
  5446. unsigned short link);
  5447. static void layout_grid_children(struct lay *l, unsigned int parent,
  5448. const struct br_style *pst, int depth,
  5449. unsigned short link);
  5450. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5451. const struct br_style *pst, int depth,
  5452. unsigned short link);
  5453. static int flex_item_width(struct lay *l, unsigned int n,
  5454. const struct br_style *cs, int avail);
  5455. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5456. const struct br_style *pst, int depth,
  5457. unsigned short link);
  5458. static void layout_table_row(struct lay *l, unsigned int row,
  5459. const struct br_style *pst, int depth,
  5460. unsigned short link);
  5461. static int table_has_rowspan(unsigned int table);
  5462. static void layout_table(struct lay *l, unsigned int table,
  5463. const struct br_style *st, int depth,
  5464. unsigned short link);
  5465. /* A flex container whose items are only inline spans is usually just a
  5466. * heading/icon pair. Our flex row positions such items without emitting
  5467. * their inline text in some deep page contexts; normal inline flow renders
  5468. * the same content correctly. */
  5469. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  5470. {
  5471. unsigned int c;
  5472. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5473. struct br_node *nd = &doc.nodes[c];
  5474. struct br_style cs;
  5475. if (nd->type == BR_NODE_TEXT)
  5476. continue;
  5477. br_style_for(&doc, c, pst, &cs);
  5478. if (cs.display == BR_DISPLAY_NONE)
  5479. continue;
  5480. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  5481. cs.width_kind || cs.has_bg ||
  5482. cs.border_w[0] || cs.border_w[1] ||
  5483. cs.border_w[2] || cs.border_w[3] ||
  5484. nd->tag == BR_TAG_IMG)
  5485. return 1;
  5486. }
  5487. return 0;
  5488. }
  5489. static int css_radius(const struct br_style *st, int corner,
  5490. int w, int h)
  5491. {
  5492. int r = st->radius[corner];
  5493. if (r <= 0)
  5494. return 0;
  5495. if (r > w / 2)
  5496. r = w / 2;
  5497. if (r > h / 2)
  5498. r = h / 2;
  5499. return r;
  5500. }
  5501. /* ---- inline SVG ----
  5502. *
  5503. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  5504. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  5505. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  5506. * opacity and solid paint; a gradient paints the average of its stops) and
  5507. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  5508. #define SVG_CACHE_MAX 48
  5509. #define SVG_CACHE_PIXELS (640 * 1024)
  5510. #define SVG_MAX_POINTS 24576
  5511. struct svg_cache_ent {
  5512. unsigned int node;
  5513. int w, h;
  5514. unsigned short *px;
  5515. unsigned char *a;
  5516. unsigned int stamp;
  5517. };
  5518. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  5519. static unsigned int svg_cache_pixels, svg_cache_clock;
  5520. static struct svgr svg_geom;
  5521. static void *svg_geom_buf;
  5522. /* Current viewport in user units: percentage lengths resolve against it
  5523. * (the viewBox size, not the device pixels). */
  5524. static double svg_vp_w = 300, svg_vp_h = 150;
  5525. /* The layers live in the page heap: forget them before heap_reset(). */
  5526. static void svg_cache_clear(void)
  5527. {
  5528. memset(svg_cache, 0, sizeof(svg_cache));
  5529. svg_cache_pixels = 0;
  5530. svg_geom_buf = 0;
  5531. }
  5532. static int svg_name_is(const char *a, const char *b)
  5533. {
  5534. while (*a && *b) {
  5535. char x = *a, y = *b;
  5536. if (x >= 'A' && x <= 'Z')
  5537. x = (char)(x - 'A' + 'a');
  5538. if (x != y)
  5539. return 0;
  5540. a++;
  5541. b++;
  5542. }
  5543. return *a == *b;
  5544. }
  5545. static const char *svg_elem_name(unsigned int node)
  5546. {
  5547. const struct br_node *nd = &doc.nodes[node];
  5548. if (nd->name_off)
  5549. return doc.attrs + nd->name_off;
  5550. return br_tag_name(nd->tag);
  5551. }
  5552. /* A numeric attribute; a percentage resolves against `base`. */
  5553. static double svg_attr_num(unsigned int node, const char *name, double def,
  5554. double base)
  5555. {
  5556. const char *v = br_find_attr(&doc, node, name);
  5557. const char *p = v;
  5558. int ok = 0;
  5559. double x;
  5560. if (!v)
  5561. return def;
  5562. x = svgr_num(&p, &ok);
  5563. if (!ok)
  5564. return def;
  5565. if (*p == '%')
  5566. x = x * base / 100.0;
  5567. return x;
  5568. }
  5569. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  5570. static int svg_viewbox4(unsigned int node, double vb[4])
  5571. {
  5572. const char *v = br_find_attr(&doc, node, "viewbox");
  5573. const char *p = v;
  5574. int i, ok = 1;
  5575. if (!v)
  5576. return 0;
  5577. for (i = 0; i < 4 && ok; i++)
  5578. vb[i] = svgr_num(&p, &ok);
  5579. return ok && vb[2] > 0 && vb[3] > 0;
  5580. }
  5581. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  5582. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  5583. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  5584. double w, double h, double m[6])
  5585. {
  5586. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  5587. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  5588. int ax = 1, ay = 1;
  5589. if (par && contains_ci(par, "none")) {
  5590. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  5591. m[4] = -vb[0] * sx;
  5592. m[5] = -vb[1] * sy;
  5593. return;
  5594. }
  5595. if (par) {
  5596. if (contains_ci(par, "xmin"))
  5597. ax = 0;
  5598. else if (contains_ci(par, "xmax"))
  5599. ax = 2;
  5600. if (contains_ci(par, "ymin"))
  5601. ay = 0;
  5602. else if (contains_ci(par, "ymax"))
  5603. ay = 2;
  5604. }
  5605. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  5606. (sx < sy ? sx : sy);
  5607. tx = (w - vb[2] * s) * ax / 2.0;
  5608. ty = (h - vb[3] * s) * ay / 2.0;
  5609. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  5610. m[4] = tx - vb[0] * s;
  5611. m[5] = ty - vb[1] * s;
  5612. }
  5613. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  5614. * the paint attribute, then average the gradient's stops. */
  5615. static int svg_url_paint(unsigned int node, const char *attr,
  5616. unsigned short *color, unsigned int *alpha)
  5617. {
  5618. const char *v = 0, *h;
  5619. char id[64];
  5620. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  5621. for (k = 0; node && k < 32 && !v; k++) {
  5622. v = br_find_attr(&doc, node, attr);
  5623. if (!v) {
  5624. const char *style = br_find_attr(&doc, node, "style");
  5625. if (style && contains_ci(style, "url(#"))
  5626. v = strstr(style, "url(#");
  5627. }
  5628. if (v && !contains_ci(v, "url("))
  5629. v = 0;
  5630. node = doc.nodes[node].parent;
  5631. }
  5632. if (!v || !(h = strstr(v, "#")))
  5633. return 0;
  5634. h++;
  5635. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  5636. id[n++] = *h++;
  5637. id[n] = '\0';
  5638. g = br_find_id(&doc, id);
  5639. /* Follow href chains (a gradient that only references another one's
  5640. * stops), at most a few hops. */
  5641. for (k = 0; g && k < 4; k++) {
  5642. unsigned int gi = g - 1;
  5643. const char *ref;
  5644. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  5645. const char *nm, *sc, *so;
  5646. unsigned short col = 0;
  5647. double op = 1;
  5648. if (doc.nodes[c].type != BR_NODE_ELEM)
  5649. continue;
  5650. nm = svg_elem_name(c);
  5651. if (!svg_name_is(nm, "stop"))
  5652. continue;
  5653. sc = br_find_attr(&doc, c, "stop-color");
  5654. so = br_find_attr(&doc, c, "stop-opacity");
  5655. {
  5656. const char *st = br_find_attr(&doc, c, "style");
  5657. const char *q;
  5658. if (st && (q = strstr(st, "stop-color:")) != 0)
  5659. sc = q + 11;
  5660. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  5661. so = q + 13;
  5662. }
  5663. if (sc) {
  5664. unsigned int L = 0;
  5665. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  5666. L++;
  5667. if (!br_parse_color(sc, L, &col))
  5668. col = 0;
  5669. }
  5670. if (so) {
  5671. const char *p = so;
  5672. int ok = 0;
  5673. double x = svgr_num(&p, &ok);
  5674. if (ok)
  5675. op = x < 0 ? 0 : x > 1 ? 1 : x;
  5676. }
  5677. sr += (col >> 11) & 31;
  5678. sg += (col >> 5) & 63;
  5679. sb += col & 31;
  5680. sa += (unsigned int)(op * 255);
  5681. cnt++;
  5682. }
  5683. if (cnt)
  5684. break;
  5685. ref = br_find_attr(&doc, gi, "href");
  5686. if (!ref)
  5687. ref = br_find_attr(&doc, gi, "xlink:href");
  5688. if (!ref || ref[0] != '#')
  5689. break;
  5690. g = br_find_id(&doc, ref + 1);
  5691. }
  5692. if (!cnt)
  5693. return 0;
  5694. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  5695. (sb / cnt));
  5696. *alpha = sa / cnt;
  5697. return 1;
  5698. }
  5699. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  5700. unsigned short *color, unsigned int *alpha)
  5701. {
  5702. int mode = fill ? st->fill_mode : st->stroke_mode;
  5703. const char *op = br_find_attr(&doc, node,
  5704. fill ? "fill-opacity" : "stroke-opacity");
  5705. *alpha = 255;
  5706. switch (mode) {
  5707. case BR_PAINT_UNSET:
  5708. if (!fill)
  5709. return 0;
  5710. *color = 0;
  5711. break;
  5712. case BR_PAINT_COLOR:
  5713. *color = fill ? st->fill : st->stroke;
  5714. break;
  5715. case BR_PAINT_CURRENT:
  5716. *color = st->color;
  5717. break;
  5718. case BR_PAINT_URL:
  5719. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  5720. alpha))
  5721. return 0;
  5722. break;
  5723. default:
  5724. return 0;
  5725. }
  5726. if (op) {
  5727. const char *p = op;
  5728. int ok = 0;
  5729. double x = svgr_num(&p, &ok);
  5730. if (ok)
  5731. *alpha = (unsigned int)(*alpha *
  5732. (x < 0 ? 0 : x > 1 ? 1 : x));
  5733. }
  5734. return *alpha > 0;
  5735. }
  5736. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  5737. const double m[6], const struct br_style *pst,
  5738. unsigned int alpha, int depth);
  5739. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  5740. const double m[6], const struct br_style *st,
  5741. unsigned int alpha, int depth)
  5742. {
  5743. unsigned int c;
  5744. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  5745. if (doc.nodes[c].type == BR_NODE_ELEM)
  5746. svg_draw_node(L, c, m, st, alpha, depth + 1);
  5747. }
  5748. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  5749. const double pm[6], const struct br_style *pst,
  5750. unsigned int alpha, int depth)
  5751. {
  5752. struct br_style st;
  5753. const char *nm = svg_elem_name(node);
  5754. const char *tf;
  5755. double m[6];
  5756. unsigned short color;
  5757. unsigned int pa;
  5758. int shape = 0, fillable = 1;
  5759. if (depth > 24 || !nm)
  5760. return;
  5761. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  5762. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  5763. svg_name_is(nm, "lineargradient") ||
  5764. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  5765. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  5766. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  5767. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  5768. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  5769. svg_name_is(nm, "foreignobject"))
  5770. return;
  5771. br_style_for(&doc, node, pst, &st);
  5772. if (st.display == BR_DISPLAY_NONE)
  5773. return;
  5774. memcpy(m, pm, sizeof(m));
  5775. tf = br_find_attr(&doc, node, "transform");
  5776. if (tf)
  5777. svgr_transform(m, tf);
  5778. {
  5779. const char *op = br_find_attr(&doc, node, "opacity");
  5780. if (op) {
  5781. const char *p = op;
  5782. int ok = 0;
  5783. double x = svgr_num(&p, &ok);
  5784. if (ok)
  5785. alpha = (unsigned int)(alpha *
  5786. (x < 0 ? 0 :
  5787. x > 1 ? 1 : x));
  5788. }
  5789. }
  5790. if (!alpha)
  5791. return;
  5792. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  5793. svg_name_is(nm, "switch")) {
  5794. svg_draw_children(L, node, m, &st, alpha, depth);
  5795. return;
  5796. }
  5797. if (svg_name_is(nm, "svg")) {
  5798. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  5799. y = svg_attr_num(node, "y", 0, 0);
  5800. double t[6] = { 1, 0, 0, 1, 0, 0 };
  5801. t[4] = x;
  5802. t[5] = y;
  5803. svgr_mat_mul(m, m, t);
  5804. double ow = svg_vp_w, oh = svg_vp_h;
  5805. if (svg_viewbox4(node, vb)) {
  5806. double w = svg_attr_num(node, "width", vb[2], ow);
  5807. double h = svg_attr_num(node, "height", vb[3], oh);
  5808. double vm[6];
  5809. svg_viewport_matrix(node, vb, w, h, vm);
  5810. svgr_mat_mul(m, m, vm);
  5811. svg_vp_w = vb[2];
  5812. svg_vp_h = vb[3];
  5813. }
  5814. svg_draw_children(L, node, m, &st, alpha, depth);
  5815. svg_vp_w = ow;
  5816. svg_vp_h = oh;
  5817. return;
  5818. }
  5819. if (svg_name_is(nm, "use")) {
  5820. const char *ref = br_find_attr(&doc, node, "href");
  5821. unsigned int tgt;
  5822. double t[6] = { 1, 0, 0, 1, 0, 0 };
  5823. if (!ref)
  5824. ref = br_find_attr(&doc, node, "xlink:href");
  5825. if (!ref || ref[0] != '#')
  5826. return;
  5827. tgt = br_find_id(&doc, ref + 1);
  5828. if (!tgt || tgt - 1 == node)
  5829. return;
  5830. tgt--;
  5831. t[4] = svg_attr_num(node, "x", 0, 0);
  5832. t[5] = svg_attr_num(node, "y", 0, 0);
  5833. svgr_mat_mul(m, m, t);
  5834. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  5835. double vb[4];
  5836. double ow = svg_vp_w, oh = svg_vp_h;
  5837. if (svg_viewbox4(tgt, vb)) {
  5838. double w = svg_attr_num(node, "width", vb[2],
  5839. ow);
  5840. double h = svg_attr_num(node, "height", vb[3],
  5841. oh);
  5842. double vm[6];
  5843. svg_viewport_matrix(tgt, vb, w, h, vm);
  5844. svgr_mat_mul(m, m, vm);
  5845. svg_vp_w = vb[2];
  5846. svg_vp_h = vb[3];
  5847. }
  5848. svg_draw_children(L, tgt, m, &st, alpha, depth);
  5849. svg_vp_w = ow;
  5850. svg_vp_h = oh;
  5851. } else {
  5852. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  5853. }
  5854. return;
  5855. }
  5856. svgr_reset(&svg_geom, m);
  5857. if (svg_name_is(nm, "path")) {
  5858. const char *d = br_find_attr(&doc, node, "d");
  5859. if (d) {
  5860. svgr_path(&svg_geom, d);
  5861. shape = 1;
  5862. }
  5863. } else if (svg_name_is(nm, "rect")) {
  5864. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  5865. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  5866. double rx = svg_attr_num(node, "rx", -1, w);
  5867. double ry = svg_attr_num(node, "ry", -1, h);
  5868. if (rx < 0)
  5869. rx = ry < 0 ? 0 : ry;
  5870. if (ry < 0)
  5871. ry = rx;
  5872. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  5873. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  5874. shape = 1;
  5875. } else if (svg_name_is(nm, "circle")) {
  5876. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  5877. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  5878. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  5879. shape = 1;
  5880. } else if (svg_name_is(nm, "ellipse")) {
  5881. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  5882. svg_attr_num(node, "cy", 0, svg_vp_h),
  5883. svg_attr_num(node, "rx", 0, svg_vp_w),
  5884. svg_attr_num(node, "ry", 0, svg_vp_h));
  5885. shape = 1;
  5886. } else if (svg_name_is(nm, "line")) {
  5887. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  5888. svg_attr_num(node, "y1", 0, svg_vp_h));
  5889. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  5890. svg_attr_num(node, "y2", 0, svg_vp_h));
  5891. shape = 1;
  5892. fillable = 0;
  5893. } else if (svg_name_is(nm, "polyline") ||
  5894. svg_name_is(nm, "polygon")) {
  5895. const char *pts = br_find_attr(&doc, node, "points");
  5896. if (pts) {
  5897. svgr_points(&svg_geom, pts,
  5898. svg_name_is(nm, "polygon"));
  5899. shape = 1;
  5900. }
  5901. }
  5902. if (!shape)
  5903. return;
  5904. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  5905. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  5906. st.fill_evenodd);
  5907. if (svg_paint(node, &st, 0, &color, &pa)) {
  5908. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  5909. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  5910. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  5911. }
  5912. }
  5913. /* <text> elements: drawn straight onto the page every frame (the glyph
  5914. * renderer targets the ngui canvas, not a layer). x/y map through the
  5915. * accumulated transform; the font size scales with it. */
  5916. static void svg_draw_text(struct ngui *ui, unsigned int node,
  5917. const double pm[6], const struct br_style *pst,
  5918. int ox, int oy, int depth)
  5919. {
  5920. unsigned int c;
  5921. if (depth > 24)
  5922. return;
  5923. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  5924. struct br_style st;
  5925. const char *nm, *tf;
  5926. double m[6];
  5927. if (doc.nodes[c].type != BR_NODE_ELEM)
  5928. continue;
  5929. nm = svg_elem_name(c);
  5930. if (!nm || svg_name_is(nm, "defs") ||
  5931. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  5932. svg_name_is(nm, "clippath"))
  5933. continue;
  5934. br_style_for(&doc, c, pst, &st);
  5935. if (st.display == BR_DISPLAY_NONE)
  5936. continue;
  5937. memcpy(m, pm, sizeof(m));
  5938. tf = br_find_attr(&doc, c, "transform");
  5939. if (tf)
  5940. svgr_transform(m, tf);
  5941. if (svg_name_is(nm, "text")) {
  5942. unsigned int t = doc.nodes[c].first;
  5943. const char *s;
  5944. unsigned int n, tw;
  5945. double x = svg_attr_num(c, "x", 0, 0),
  5946. y = svg_attr_num(c, "y", 0, 0);
  5947. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  5948. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  5949. int tx, ty, anchor;
  5950. unsigned short col;
  5951. unsigned int pa;
  5952. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  5953. continue;
  5954. if (px < 6)
  5955. px = 6;
  5956. if (px > 72)
  5957. px = 72;
  5958. if (!svg_paint(c, &st, 1, &col, &pa))
  5959. continue;
  5960. s = doc.text + doc.nodes[t].text_off;
  5961. n = doc.nodes[t].text_len;
  5962. st.font_px = (unsigned char)px;
  5963. tw = face_text_width(ui, &st, s, n);
  5964. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  5965. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  5966. ngui_text_ascent_face(ui, style_face(&st), px,
  5967. st.mono);
  5968. anchor = st.align;
  5969. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  5970. anchor = BR_ALIGN_CENTER;
  5971. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  5972. anchor = BR_ALIGN_RIGHT;
  5973. if (anchor == BR_ALIGN_CENTER)
  5974. tx -= (int)tw / 2;
  5975. else if (anchor == BR_ALIGN_RIGHT)
  5976. tx -= (int)tw;
  5977. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  5978. col, px, st.bold, st.italic,
  5979. st.mono);
  5980. } else {
  5981. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  5982. }
  5983. }
  5984. }
  5985. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  5986. {
  5987. double vb[4];
  5988. if (svg_viewbox4(node, vb)) {
  5989. svg_viewport_matrix(node, vb, w, h, m);
  5990. } else {
  5991. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  5992. }
  5993. }
  5994. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  5995. const struct br_style *st)
  5996. {
  5997. struct svg_cache_ent *e = 0;
  5998. struct svgr_layer L;
  5999. double m[6];
  6000. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  6001. svg_cache_clock++;
  6002. for (i = 0; i < SVG_CACHE_MAX; i++)
  6003. if (svg_cache[i].px && svg_cache[i].node == node &&
  6004. svg_cache[i].w == w && svg_cache[i].h == h) {
  6005. svg_cache[i].stamp = svg_cache_clock;
  6006. return &svg_cache[i];
  6007. }
  6008. if (need > SVG_CACHE_PIXELS)
  6009. return 0;
  6010. /* Evict least recently used layers until this one fits. */
  6011. for (;;) {
  6012. struct svg_cache_ent *lru = 0, *free_slot = 0;
  6013. for (i = 0; i < SVG_CACHE_MAX; i++) {
  6014. if (!svg_cache[i].px) {
  6015. if (!free_slot)
  6016. free_slot = &svg_cache[i];
  6017. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  6018. lru = &svg_cache[i];
  6019. }
  6020. }
  6021. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  6022. e = free_slot;
  6023. break;
  6024. }
  6025. if (!lru)
  6026. return 0;
  6027. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  6028. free(lru->px);
  6029. free(lru->a);
  6030. memset(lru, 0, sizeof(*lru));
  6031. }
  6032. if (!svg_geom_buf) {
  6033. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  6034. if (!svg_geom_buf)
  6035. return 0;
  6036. }
  6037. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  6038. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  6039. e->a = (unsigned char *)calloc(need, 1);
  6040. if (!e->px || !e->a) {
  6041. free(e->px);
  6042. free(e->a);
  6043. memset(e, 0, sizeof(*e));
  6044. return 0;
  6045. }
  6046. e->node = node;
  6047. e->w = w;
  6048. e->h = h;
  6049. e->stamp = svg_cache_clock;
  6050. svg_cache_pixels += need;
  6051. L.px = e->px;
  6052. L.a = e->a;
  6053. L.w = w;
  6054. L.h = h;
  6055. svg_root_matrix(node, w, h, m);
  6056. {
  6057. double vb[4];
  6058. if (svg_viewbox4(node, vb)) {
  6059. svg_vp_w = vb[2];
  6060. svg_vp_h = vb[3];
  6061. } else {
  6062. svg_vp_w = w;
  6063. svg_vp_h = h;
  6064. }
  6065. }
  6066. svg_draw_children(&L, node, m, st, 255, 0);
  6067. return e;
  6068. }
  6069. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  6070. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6071. int *out_w, int *out_h)
  6072. {
  6073. double vb[4];
  6074. int has_vb = svg_viewbox4(node, vb);
  6075. double aw = svg_attr_num(node, "width", -1, cw);
  6076. double ah = svg_attr_num(node, "height", -1, 0);
  6077. int w, h;
  6078. if (st->width_kind)
  6079. w = cw;
  6080. else if (aw > 0)
  6081. w = (int)(aw + 0.5);
  6082. else if (st->height_kind == 1 && has_vb)
  6083. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  6084. else if (ah > 0 && has_vb)
  6085. w = (int)(ah * vb[2] / vb[3] + 0.5);
  6086. else if (has_vb)
  6087. w = cw;
  6088. else
  6089. w = 300;
  6090. if (st->max_width_kind == 1 && w > st->max_width)
  6091. w = st->max_width;
  6092. if (w > cw && cw > 0 && !(aw > 0))
  6093. w = cw;
  6094. if (w < 1)
  6095. w = 1;
  6096. if (w > 2000)
  6097. w = 2000;
  6098. if (st->height_kind == 1)
  6099. h = st->height;
  6100. else if (ah > 0)
  6101. h = (int)(ah + 0.5);
  6102. else if (has_vb)
  6103. h = (int)(w * vb[3] / vb[2] + 0.5);
  6104. else
  6105. h = 150;
  6106. if (h < 1)
  6107. h = 1;
  6108. if (h > 1400)
  6109. h = 1400;
  6110. *out_w = w;
  6111. *out_h = h;
  6112. }
  6113. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6114. const struct br_style *st, int x, int y, int w, int h)
  6115. {
  6116. struct svg_cache_ent *e;
  6117. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  6118. int cx0, cy0, cx1, cy1, px, py;
  6119. double m[6];
  6120. if (ui->nclip > 0)
  6121. clip = ui->clip[ui->nclip - 1];
  6122. cx0 = r.x > clip.x ? r.x : clip.x;
  6123. cy0 = r.y > clip.y ? r.y : clip.y;
  6124. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  6125. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  6126. if (cx0 >= cx1 || cy0 >= cy1)
  6127. return;
  6128. e = svg_layer(node, w, h, st);
  6129. if (e) {
  6130. for (py = cy0; py < cy1; py++) {
  6131. unsigned int srow = (unsigned int)(py - y) *
  6132. (unsigned int)w;
  6133. unsigned short *dst = ui->px + py * ui->w;
  6134. for (px = cx0; px < cx1; px++) {
  6135. unsigned int si = srow + (unsigned int)(px - x);
  6136. unsigned int a = e->a[si];
  6137. if (!a)
  6138. continue;
  6139. dst[px] = a >= 255 ? e->px[si] :
  6140. blend_rgb565(dst[px], e->px[si], a);
  6141. }
  6142. }
  6143. }
  6144. svg_root_matrix(node, w, h, m);
  6145. ngui_push_clip(ui, r);
  6146. svg_draw_text(ui, node, m, st, x, y, 0);
  6147. ngui_pop_clip(ui);
  6148. }
  6149. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  6150. * keep using add_image_run(); this covers the CSS `position:absolute;
  6151. * width:100%` poster pattern used by news sites. */
  6152. static void image_block_size(unsigned int node, const struct br_style *st,
  6153. int cbw, int *out_w, int *out_h)
  6154. {
  6155. struct br_node *nd = &doc.nodes[node];
  6156. int idx = nd->img_index;
  6157. int iw = 0, ih = 0, w, h;
  6158. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6159. iw = (int)images[idx].img.w;
  6160. ih = (int)images[idx].img.h;
  6161. if (iw <= 0 || ih <= 0) {
  6162. iw = (int)images[idx].native_w;
  6163. ih = (int)images[idx].native_h;
  6164. }
  6165. }
  6166. if (st->width_kind)
  6167. w = style_width_px(st, cbw);
  6168. else if (nd->width_attr)
  6169. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  6170. (int)nd->width_attr;
  6171. else if (iw)
  6172. w = iw;
  6173. else
  6174. w = 64;
  6175. if (w < 8)
  6176. w = 8;
  6177. if (cbw > 0 && w > cbw)
  6178. w = cbw;
  6179. if (st->height_kind)
  6180. h = style_height_px(st, cbw);
  6181. else if (nd->height_attr)
  6182. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  6183. (int)nd->height_attr;
  6184. else if (iw && ih)
  6185. h = w * ih / iw;
  6186. else
  6187. h = 64;
  6188. if (h < 8)
  6189. h = 8;
  6190. *out_w = w;
  6191. *out_h = h;
  6192. }
  6193. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  6194. int dw, int dh)
  6195. {
  6196. int idx = doc.nodes[node].img_index;
  6197. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  6198. struct img_blit b;
  6199. b.dst = l->ui->px;
  6200. b.dst_w = l->ui->w;
  6201. b.dst_h = l->ui->h;
  6202. b.clip_x = page_rect.x;
  6203. b.clip_y = page_rect.y;
  6204. b.clip_w = page_rect.w - 12;
  6205. b.clip_h = page_rect.h;
  6206. b.x = x;
  6207. b.y = y;
  6208. b.scale = ((unsigned int)dw << 16) / images[idx].img.w;
  6209. b.bg = ui.theme.bg;
  6210. b.bg2 = ui.theme.bg;
  6211. b.flags = IMG_BLIT_OVER_DST;
  6212. img_draw(&images[idx].img, &b);
  6213. } else if (l->draw) {
  6214. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  6215. 0xD69A);
  6216. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  6217. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  6218. }
  6219. }
  6220. static void layout_block(struct lay *l, unsigned int node,
  6221. const struct br_style *st, int depth,
  6222. unsigned short link)
  6223. {
  6224. int old_left = l->left, old_right = l->right, old_align = l->align;
  6225. int saved_parent_top = l->parent_top;
  6226. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  6227. int saved_cb_top = l->cb_top;
  6228. int top, l0, r0;
  6229. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  6230. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  6231. int deco_w, deco_h, content_w, content_h, box_h;
  6232. int img_dh = 0;
  6233. int definite_w = 0;
  6234. int normal_top = 0;
  6235. int rel_dx = 0, rel_dy = 0;
  6236. int clip_pushed = 0;
  6237. struct ngui_rect clip_rect;
  6238. /* A DOM level costs about two depth units (layout_block ->
  6239. * layout_children), so 48 covers a ~24-level page. Real news pages
  6240. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  6241. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  6242. return;
  6243. flow_y = l->y;
  6244. flow_left = l->left;
  6245. flow_right = l->right;
  6246. positioned = st->pos == 1 || st->pos == 2;
  6247. relative = st->pos == 3;
  6248. sticky = st->pos == 4;
  6249. shifted = relative || sticky || st->transform_set;
  6250. if (positioned) {
  6251. int def_w = st->width_kind == 1 ? st->width : -1;
  6252. if (st->pos == 2) {
  6253. int avail_w = page_rect.w - 12;
  6254. if (st->right_set && def_w >= 0)
  6255. l->left = page_rect.x + avail_w - st->right -
  6256. def_w;
  6257. else
  6258. l->left = page_rect.x +
  6259. (st->left_set ? st->left : 0);
  6260. l->right = def_w >= 0 ? l->left + def_w :
  6261. page_rect.x + avail_w;
  6262. if (st->bottom_set && st->height_kind)
  6263. l->y = page_rect.y + page_rect.h -
  6264. st->bottom -
  6265. style_height_px(st, page_rect.w);
  6266. else
  6267. l->y = page_rect.y +
  6268. (st->top_set ? st->top : 0);
  6269. } else {
  6270. int left = flow_left + (st->left_set ? st->left : 0);
  6271. unsigned int parent = doc.nodes[node].parent;
  6272. if (st->right_set && def_w >= 0)
  6273. left = flow_right - st->right - def_w;
  6274. l->left = left;
  6275. l->right = def_w >= 0 ? left + def_w :
  6276. flow_right +
  6277. (st->left_set ? st->left : 0);
  6278. l->y = flow_y + (st->top_set ? st->top : 0);
  6279. if (st->bottom_set && st->height_kind &&
  6280. parent < BR_MAX_NODES && block_h[parent] > 0)
  6281. l->y = flow_y + block_h[parent] - st->bottom -
  6282. style_height_px(st, old_right - old_left);
  6283. }
  6284. old_left = l->left;
  6285. old_right = l->right;
  6286. } else if (relative) {
  6287. rel_dx = st->left_set ? st->left :
  6288. (st->right_set ? -st->right : 0);
  6289. rel_dy = st->top_set ? st->top :
  6290. (st->bottom_set ? -st->bottom : 0);
  6291. }
  6292. if (st->transform_set) {
  6293. rel_dx += st->tx;
  6294. rel_dy += st->ty;
  6295. }
  6296. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  6297. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  6298. doc.nodes[node].tag == BR_TAG_SELECT ||
  6299. doc.nodes[node].tag == BR_TAG_BUTTON) {
  6300. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  6301. s_eq(br_type(&doc, node), "hidden"))
  6302. return;
  6303. /* Reached as a block-level box (a flex item): the control
  6304. * fills the box the caller assigned, and its line is flushed
  6305. * here; flex layout resets the run list for the next item, so
  6306. * a queued run would never be drawn. */
  6307. form_fill_line = 1;
  6308. add_form_run(l, node, st, link);
  6309. form_fill_line = 0;
  6310. flush_line(l);
  6311. return;
  6312. }
  6313. flush_line(l);
  6314. cbw = old_right - old_left;
  6315. if (cbw < 8)
  6316. cbw = 8;
  6317. l->y += mp_px(st, 0, cbw);
  6318. top = l->y;
  6319. ml = mp_px(st, 3, cbw);
  6320. mr = mp_px(st, 1, cbw);
  6321. bl = st->border_w[3];
  6322. br = st->border_w[1];
  6323. pl = mp_px(st, 7, cbw);
  6324. pr = mp_px(st, 5, cbw);
  6325. bt = st->border_w[0];
  6326. bb = st->border_w[2];
  6327. pt = mp_px(st, 4, cbw);
  6328. pb = mp_px(st, 6, cbw);
  6329. deco_w = bl + br + pl + pr;
  6330. deco_h = bt + bb + pt + pb;
  6331. if (st->width_kind) {
  6332. int w;
  6333. if (st->width_kind == 3)
  6334. w = cbw * st->width_calc_pct / 100 +
  6335. st->width_calc_px;
  6336. else
  6337. w = css_size(st->width_kind, st->width, cbw);
  6338. if (w < 0)
  6339. w = 0;
  6340. content_w = st->box_sizing ? w - deco_w : w;
  6341. definite_w = 1;
  6342. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  6343. doc.nodes[node].tag == BR_TAG_TD ||
  6344. doc.nodes[node].tag == BR_TAG_TH) &&
  6345. doc.nodes[node].width_attr) {
  6346. /* Legacy table/cell width attributes: percentages resolve
  6347. * against the containing block, bare numbers are pixels. */
  6348. int w = doc.nodes[node].width_pct ?
  6349. cbw * doc.nodes[node].width_attr / 100 :
  6350. doc.nodes[node].width_attr;
  6351. if (w < 0)
  6352. w = 0;
  6353. content_w = st->box_sizing ? w - deco_w : w;
  6354. definite_w = 1;
  6355. } else {
  6356. content_w = cbw - ml - mr - deco_w;
  6357. }
  6358. if (content_w < 0)
  6359. content_w = 0;
  6360. if (st->max_width_kind) {
  6361. int mw = st->max_width_kind == 3 ?
  6362. cbw * st->max_width_calc_pct / 100 +
  6363. st->max_width_calc_px :
  6364. css_size(st->max_width_kind, st->max_width, cbw);
  6365. int max_box = st->box_sizing ? mw : mw + deco_w;
  6366. if (content_w + deco_w > max_box)
  6367. content_w = max_box - deco_w;
  6368. }
  6369. if (st->min_width_kind) {
  6370. int mw = st->min_width_kind == 3 ?
  6371. cbw * st->min_width_calc_pct / 100 +
  6372. st->min_width_calc_px :
  6373. css_size(st->min_width_kind, st->min_width, cbw);
  6374. int min_box = st->box_sizing ? mw : mw + deco_w;
  6375. if (content_w + deco_w < min_box) {
  6376. content_w = min_box - deco_w;
  6377. definite_w = 1;
  6378. }
  6379. }
  6380. if (content_w < 8)
  6381. content_w = 8;
  6382. if (definite_w) {
  6383. int free_w = cbw - ml - mr - deco_w - content_w;
  6384. if (free_w < 0)
  6385. free_w = 0;
  6386. if (st->ml_auto && st->mr_auto) {
  6387. ml = free_w / 2;
  6388. mr = free_w - ml;
  6389. } else if (st->ml_auto) {
  6390. ml = free_w;
  6391. } else if (st->mr_auto) {
  6392. mr = free_w;
  6393. }
  6394. }
  6395. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6396. int iw, ih;
  6397. image_block_size(node, st, cbw, &iw, &ih);
  6398. content_w = iw;
  6399. img_dh = ih;
  6400. }
  6401. l0 = old_left + ml;
  6402. r0 = l0 + deco_w + content_w;
  6403. if (r0 < l0 + 8)
  6404. r0 = l0 + 8;
  6405. normal_top = top;
  6406. if (sticky) {
  6407. if (st->top_set) {
  6408. int stick = page_rect.y + 4 + st->top;
  6409. if (normal_top < stick)
  6410. rel_dy += stick - normal_top;
  6411. } else if (st->bottom_set && block_h[node]) {
  6412. int stick = page_rect.y + page_rect.h - st->bottom -
  6413. block_h[node];
  6414. if (normal_top > stick)
  6415. rel_dy += stick - normal_top;
  6416. }
  6417. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  6418. block_h[doc.nodes[node].parent]) {
  6419. unsigned int p = doc.nodes[node].parent;
  6420. int ptop = l->parent_top;
  6421. int pbottom = ptop + block_h[p];
  6422. int eh = block_h[node];
  6423. int moved_top = normal_top + rel_dy;
  6424. int moved_bottom = moved_top + eh;
  6425. if (moved_bottom > pbottom)
  6426. rel_dy -= moved_bottom - pbottom;
  6427. moved_top = normal_top + rel_dy;
  6428. if (moved_top < ptop)
  6429. rel_dy += ptop - moved_top;
  6430. }
  6431. }
  6432. if (shifted && l->draw) {
  6433. top += rel_dy;
  6434. l0 += rel_dx;
  6435. r0 += rel_dx;
  6436. }
  6437. l->parent_top = top;
  6438. if (st->pos != 0) {
  6439. /* Positioned boxes establish the containing block for their
  6440. * absolutely positioned descendants. */
  6441. l->cb_left = l0;
  6442. l->cb_right = r0;
  6443. l->cb_top = top;
  6444. }
  6445. if (l->draw && block_h[node] &&
  6446. top < page_rect.y + page_rect.h &&
  6447. top + block_h[node] > page_rect.y) {
  6448. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  6449. int rtl = css_radius(st, 0, box.w, box.h);
  6450. int rtr = css_radius(st, 1, box.w, box.h);
  6451. int rbr = css_radius(st, 2, box.w, box.h);
  6452. int rbl = css_radius(st, 3, box.w, box.h);
  6453. if (st->transform_scale) {
  6454. if (st->has_bg)
  6455. fill_transformed_rect(l->ui, box, st->bg, st);
  6456. } else if (rtl || rtr || rbr || rbl) {
  6457. if (st->has_bg) {
  6458. int bw = st->border_w[0];
  6459. if (bw > 0 && !st->border_t[0] &&
  6460. st->border_c[0] != st->bg &&
  6461. box.w > bw * 2 && box.h > bw * 2) {
  6462. struct ngui_rect inner = {
  6463. box.x + bw, box.y + bw,
  6464. box.w - bw * 2, box.h - bw * 2
  6465. };
  6466. int itl = rtl > bw ? rtl - bw : 0;
  6467. int itr = rtr > bw ? rtr - bw : 0;
  6468. int ibr = rbr > bw ? rbr - bw : 0;
  6469. int ibl = rbl > bw ? rbl - bw : 0;
  6470. ngui_fill_round_rect(l->ui, box, rtl,
  6471. rtr, rbr, rbl,
  6472. st->border_c[0]);
  6473. ngui_fill_round_rect(l->ui, inner,
  6474. itl, itr, ibr,
  6475. ibl, st->bg);
  6476. } else {
  6477. ngui_fill_round_rect(l->ui, box, rtl,
  6478. rtr, rbr, rbl,
  6479. st->bg);
  6480. }
  6481. } else if (st->border_w[0] && !st->border_t[0]) {
  6482. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  6483. rbl, st->border_w[0],
  6484. st->border_c[0]);
  6485. }
  6486. /* Rounded boxes paint their background image too
  6487. * (app icons are rounded squares), kept inside the
  6488. * corner arcs. */
  6489. if (st->bg_image)
  6490. draw_bg_image_round(l, box, node, st, rtl, rtr,
  6491. rbr, rbl);
  6492. } else {
  6493. if (st->has_bg)
  6494. ngui_fill_rect(l->ui, box, st->bg);
  6495. if (st->bg_image)
  6496. draw_bg_image(l, box, node, st);
  6497. if (st->border_w[0] || st->border_w[1] ||
  6498. st->border_w[2] || st->border_w[3])
  6499. draw_border_box(l->ui, box, st);
  6500. }
  6501. }
  6502. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  6503. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  6504. content_w, img_dh);
  6505. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  6506. l->ui && l->ui->nclip < 4) {
  6507. clip_rect.x = l0 + bl;
  6508. clip_rect.y = top + bt;
  6509. clip_rect.w = (r0 - l0) - bl - br;
  6510. clip_rect.h = (int)block_h[node] - bt - bb;
  6511. if (clip_rect.w > 0 && clip_rect.h > 0) {
  6512. ngui_push_clip(l->ui, clip_rect);
  6513. clip_pushed = 1;
  6514. }
  6515. }
  6516. l->left = l0 + bl + pl;
  6517. l->right = l->left + content_w;
  6518. if (l->right < l->left + 8)
  6519. l->right = l->left + 8;
  6520. l->align = st->align;
  6521. l->line_left = l->left;
  6522. l->line_right = l->right;
  6523. l->y = top + bt + pt;
  6524. if (doc.nodes[node].tag == BR_TAG_HR) {
  6525. if (l->draw)
  6526. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  6527. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  6528. l->y += 8;
  6529. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  6530. int vw = l->right - l->left;
  6531. int vh;
  6532. if (doc.nodes[node].width_pct)
  6533. vw = vw * doc.nodes[node].width_attr / 100;
  6534. else if (doc.nodes[node].width_attr)
  6535. vw = doc.nodes[node].width_attr;
  6536. if (vw > l->right - l->left)
  6537. vw = l->right - l->left;
  6538. if (vw < 8)
  6539. vw = 8;
  6540. vh = vw * 9 / 16;
  6541. if (vh > 240)
  6542. vh = 240;
  6543. if (vh < 80)
  6544. vh = 80;
  6545. if (l->draw) {
  6546. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  6547. vw, vh}, 0xD69A);
  6548. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  6549. vw, vh}, 0x8410);
  6550. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  6551. 0x4208);
  6552. }
  6553. l->y += vh + 4;
  6554. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  6555. int dw, dh, cw = l->right - l->left;
  6556. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  6557. if (l->draw && l->y < page_rect.y + page_rect.h &&
  6558. l->y + dh > page_rect.y)
  6559. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  6560. l->y += dh;
  6561. } else {
  6562. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  6563. !st->no_bullet) {
  6564. char *m = li_marker[node];
  6565. if (!m[0]) {
  6566. unsigned int parent = doc.nodes[node].parent;
  6567. int style = st->list_style;
  6568. int idx = parent ? list_index(parent, node) : 1;
  6569. if (style == BR_LIST_AUTO)
  6570. style = (parent &&
  6571. doc.nodes[parent].tag ==
  6572. BR_TAG_OL) ?
  6573. BR_LIST_DECIMAL : BR_LIST_DISC;
  6574. list_marker_text(m, sizeof(li_marker[node]),
  6575. style, idx);
  6576. }
  6577. if (l->draw && m[0]) {
  6578. int mw = (int)ngui_text_width_ui(l->ui, m);
  6579. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  6580. st->color);
  6581. }
  6582. }
  6583. if (doc.nodes[node].tag == BR_TAG_TR)
  6584. layout_table_row(l, node, st, depth + 1, link);
  6585. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  6586. table_has_rowspan(node))
  6587. layout_table(l, node, st, depth + 1, link);
  6588. else if (st->grid_auto)
  6589. layout_grid_auto(l, node, st, depth + 1, link);
  6590. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  6591. st->grid_gap > 0)
  6592. layout_grid_children(l, node, st, depth + 1, link);
  6593. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  6594. flex_wants_row(node, st))
  6595. layout_flex_children(l, node, st, depth + 1, link);
  6596. else
  6597. layout_children(l, node, st, depth + 1, link);
  6598. }
  6599. flush_line(l);
  6600. if (clip_pushed)
  6601. ngui_pop_clip(l->ui);
  6602. if (l->float_active) {
  6603. if (l->y < l->float_bottom)
  6604. l->y = l->float_bottom;
  6605. l->float_active = 0;
  6606. }
  6607. if (doc.nodes[node].tag == BR_TAG_IMG) {
  6608. content_h = img_dh;
  6609. } else if (st->height_kind &&
  6610. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6611. doc.nodes[node].tag == BR_TAG_BODY) &&
  6612. st->height_kind == 2)) {
  6613. content_h = style_height_px(st, cbw);
  6614. if (st->box_sizing)
  6615. content_h -= deco_h;
  6616. } else {
  6617. /* Percentage heights on html/body resolve against the
  6618. * viewport, but their content still defines the document
  6619. * scroll height. Treating them as auto avoids collapsing
  6620. * the measured page to the containing block width. */
  6621. content_h = l->y - (top + bt + pt);
  6622. }
  6623. if (content_h < 0)
  6624. content_h = 0;
  6625. if (st->max_height_kind) {
  6626. int mh = st->max_height_kind == 3 ?
  6627. cbw * st->max_height_calc_pct / 100 +
  6628. st->max_height_calc_px :
  6629. css_size(st->max_height_kind, st->max_height, cbw);
  6630. int max_box = st->box_sizing ? mh : mh + deco_h;
  6631. if (content_h + deco_h > max_box)
  6632. content_h = max_box - deco_h;
  6633. }
  6634. if (st->min_height_kind &&
  6635. !((doc.nodes[node].tag == BR_TAG_HTML ||
  6636. doc.nodes[node].tag == BR_TAG_BODY) &&
  6637. st->min_height_kind == 2)) {
  6638. int mh = st->min_height_kind == 3 ?
  6639. cbw * st->min_height_calc_pct / 100 +
  6640. st->min_height_calc_px :
  6641. css_size(st->min_height_kind, st->min_height, cbw);
  6642. int min_box = st->box_sizing ? mh : mh + deco_h;
  6643. if (content_h + deco_h < min_box)
  6644. content_h = min_box - deco_h;
  6645. }
  6646. if (content_h < 0)
  6647. content_h = 0;
  6648. box_h = deco_h + content_h;
  6649. if (box_h < 0)
  6650. box_h = 0;
  6651. l->y = (shifted ? normal_top : top) + box_h;
  6652. if (node < BR_MAX_NODES) {
  6653. layout_boxes[node].x = l0;
  6654. layout_boxes[node].y = top;
  6655. layout_boxes[node].w = r0 - l0;
  6656. layout_boxes[node].h = box_h;
  6657. layout_boxes[node].valid = r0 > l0;
  6658. }
  6659. l->left = old_left;
  6660. l->right = old_right;
  6661. l->align = old_align;
  6662. l->y += mp_px(st, 2, cbw);
  6663. if (!l->draw) {
  6664. if (box_h > 65535)
  6665. box_h = 65535;
  6666. block_h[node] = (unsigned short)box_h;
  6667. block_top[node] = (unsigned short)(top < 0 ? 0 :
  6668. top > 65535 ? 65535 : top);
  6669. }
  6670. if (positioned) {
  6671. l->y = flow_y;
  6672. l->left = flow_left;
  6673. l->right = flow_right;
  6674. }
  6675. l->parent_top = saved_parent_top;
  6676. l->cb_left = saved_cb_left;
  6677. l->cb_right = saved_cb_right;
  6678. l->cb_top = saved_cb_top;
  6679. }
  6680. static int text_node_blank(const struct br_node *nd)
  6681. {
  6682. const char *t = doc.text + nd->text_off;
  6683. unsigned int i;
  6684. for (i = 0; i < nd->text_len; i++)
  6685. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  6686. t[i] != '\r')
  6687. return 0;
  6688. return 1;
  6689. }
  6690. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  6691. * text/image widths in the subtree, plus padding and margins. This keeps
  6692. * Bootstrap's floated nav items on one line instead of giving each the whole
  6693. * row. */
  6694. static int text_space(char c)
  6695. {
  6696. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  6697. }
  6698. static int intrinsic_width(struct ngui *ui, unsigned int node,
  6699. const struct br_style *pst, int depth, int base)
  6700. {
  6701. unsigned int c;
  6702. int line_w = 0, max_w = 0;
  6703. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  6704. if (depth > 32)
  6705. return 0;
  6706. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  6707. struct br_node *nd = &doc.nodes[c];
  6708. struct br_style cs;
  6709. if (nd->type == BR_NODE_TEXT) {
  6710. const char *t = doc.text + nd->text_off;
  6711. unsigned int tn = nd->text_len;
  6712. if (doc.nodes[node].tag == BR_TAG_PRE) {
  6713. line_w += (int)face_text_width(ui, pst, t, tn);
  6714. } else {
  6715. unsigned int ti = 0;
  6716. int first = 1;
  6717. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  6718. int sp = (int)face_text_width(ui, pst, " ", 1);
  6719. while (ti < tn) {
  6720. unsigned int ts;
  6721. while (ti < tn && text_space(t[ti]))
  6722. ti++;
  6723. ts = ti;
  6724. while (ti < tn && !text_space(t[ti]))
  6725. ti++;
  6726. if (ti == ts)
  6727. break;
  6728. if (!first || lead)
  6729. line_w += sp;
  6730. lead = 0;
  6731. line_w += (int)face_text_width(ui, pst,
  6732. t + ts, ti - ts);
  6733. first = 0;
  6734. }
  6735. }
  6736. continue;
  6737. }
  6738. br_style_for(&doc, c, pst, &cs);
  6739. if (cs.display == BR_DISPLAY_NONE)
  6740. continue;
  6741. if (nd->tag == BR_TAG_BR) {
  6742. if (line_w > max_w)
  6743. max_w = line_w;
  6744. line_w = 0;
  6745. continue;
  6746. }
  6747. if (nd->tag == BR_TAG_IMG) {
  6748. /* Measure the image as layout will draw it: a CSS or
  6749. * attribute height keeps the intrinsic aspect ratio, and
  6750. * a CSS width overrides the native pixel width. Bootstrap
  6751. * sizes the Cloudron logo with height:40px only. */
  6752. int idx = nd->img_index;
  6753. int iw = 0, ih = 0;
  6754. if (idx >= 0 && idx < image_count &&
  6755. images[idx].state == 1) {
  6756. iw = (int)images[idx].native_w;
  6757. ih = (int)images[idx].native_h;
  6758. if (iw <= 0 || ih <= 0) {
  6759. iw = (int)images[idx].img.w;
  6760. ih = (int)images[idx].img.h;
  6761. }
  6762. }
  6763. if (cs.width_kind) {
  6764. int ww = style_width_px(&cs, base);
  6765. line_w += ww > 0 ? ww : 64;
  6766. } else if (nd->width_attr) {
  6767. line_w += nd->width_attr;
  6768. } else if (nd->height_attr && iw && ih) {
  6769. line_w += iw * (int)nd->height_attr / ih;
  6770. } else if (cs.height_kind && iw && ih) {
  6771. int hh = style_height_px(&cs, base);
  6772. line_w += hh > 0 ? iw * hh / ih : iw;
  6773. } else if (iw) {
  6774. line_w += iw;
  6775. } else {
  6776. line_w += 64;
  6777. }
  6778. continue;
  6779. }
  6780. {
  6781. int cw = mp_px(&cs, 7, base) +
  6782. mp_px(&cs, 5, base) +
  6783. mp_px(&cs, 3, base) +
  6784. mp_px(&cs, 1, base) +
  6785. cs.border_w[1] + cs.border_w[3];
  6786. /* width/height do not apply to non-replaced inline
  6787. * boxes. The tagesschau home label is an inline span
  6788. * with width:1px for the mobile icon-only header; using
  6789. * that width made the whole subnav collapse to a
  6790. * one-character column. */
  6791. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  6792. cw += cs.width_kind == 1 ? cs.width :
  6793. style_width_px(&cs, base);
  6794. else
  6795. cw += intrinsic_width(ui, c, &cs, depth + 1,
  6796. base);
  6797. if (flex_row || cs.float_left ||
  6798. cs.display == BR_DISPLAY_INLINE ||
  6799. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  6800. line_w += cw;
  6801. } else {
  6802. if (line_w > max_w)
  6803. max_w = line_w;
  6804. line_w = 0;
  6805. if (cw > max_w)
  6806. max_w = cw;
  6807. }
  6808. }
  6809. if (line_w > 4096 || max_w > 4096)
  6810. break;
  6811. }
  6812. return line_w > max_w ? line_w : max_w;
  6813. }
  6814. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  6815. * the main user: .row > .col-md-* with float:left and a percentage width.
  6816. * Each column is laid out with its own left/right edge and the row advances
  6817. * to the tallest column. Returns the first child not consumed. */
  6818. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  6819. const struct br_style *pst, int depth,
  6820. unsigned short link)
  6821. {
  6822. unsigned int n = first;
  6823. int row_left = l->left, row_right = l->right;
  6824. int row_top, row_bottom, xl, xr, any = 0;
  6825. int fl_left = row_left, fl_right = row_right, fl_bottom;
  6826. flush_line(l);
  6827. row_top = l->y;
  6828. row_bottom = l->y;
  6829. fl_bottom = row_top;
  6830. xl = row_left;
  6831. xr = row_right;
  6832. while (n) {
  6833. struct br_node *nd = &doc.nodes[n];
  6834. struct br_style cs;
  6835. unsigned short lk = link;
  6836. int colw, right;
  6837. if (nd->type == BR_NODE_TEXT) {
  6838. if (text_node_blank(nd)) {
  6839. n = nd->next;
  6840. continue;
  6841. }
  6842. break;
  6843. }
  6844. br_style_for(&doc, n, pst, &cs);
  6845. if (cs.display == BR_DISPLAY_NONE) {
  6846. n = nd->next;
  6847. continue;
  6848. }
  6849. /* A float blockifies its box: Bootstrap floats inline
  6850. * anchors too (the navbar brand and its text links), and
  6851. * their padding must be honoured. */
  6852. if (!cs.float_left)
  6853. break;
  6854. if (nd->tag == BR_TAG_A && nd->href_off)
  6855. lk = (unsigned short)n;
  6856. right = cs.float_left == 2;
  6857. if (cs.width_kind == 2 || cs.width_kind == 3) {
  6858. colw = style_width_px(&cs, row_right - row_left);
  6859. } else if (cs.width_kind == 1) {
  6860. colw = (int)cs.width;
  6861. } else {
  6862. int base = row_right - row_left;
  6863. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  6864. mp_px(&cs, 7, base) +
  6865. mp_px(&cs, 5, base) +
  6866. mp_px(&cs, 3, base) +
  6867. mp_px(&cs, 1, base);
  6868. if (colw < 8)
  6869. colw = 8;
  6870. }
  6871. if (colw < 8)
  6872. colw = 8;
  6873. if (colw > row_right - row_left)
  6874. colw = row_right - row_left;
  6875. /* The float column width is already resolved. */
  6876. cs.width_kind = 0;
  6877. cs.max_width_kind = 0;
  6878. if (right) {
  6879. if (any && xr - colw < xl) {
  6880. row_top = row_bottom;
  6881. row_bottom = row_top;
  6882. xl = row_left;
  6883. xr = row_right;
  6884. }
  6885. if (xr - colw < xl)
  6886. colw = xr - xl;
  6887. if (colw < 8)
  6888. colw = 8;
  6889. l->left = xr - colw;
  6890. if (l->left < row_left)
  6891. l->left = row_left;
  6892. l->right = xr;
  6893. xr = l->left;
  6894. if (xr < fl_right)
  6895. fl_right = xr;
  6896. } else {
  6897. if (any && xl + colw > xr) {
  6898. row_top = row_bottom;
  6899. row_bottom = row_top;
  6900. xl = row_left;
  6901. xr = row_right;
  6902. }
  6903. l->left = xl;
  6904. l->right = xl + colw;
  6905. xl += colw;
  6906. if (xl > fl_left)
  6907. fl_left = xl;
  6908. }
  6909. if (l->right < l->left + 8)
  6910. l->right = l->left + 8;
  6911. l->y = row_top;
  6912. l->line_x = l->left;
  6913. l->run_x = l->left;
  6914. l->line_y = l->y;
  6915. l->line_h = 0;
  6916. l->nruns = 0;
  6917. l->space_pending = 0;
  6918. l->align = cs.align;
  6919. layout_block(l, n, &cs, depth + 1, lk);
  6920. if (l->y > row_bottom)
  6921. row_bottom = l->y;
  6922. if (l->y > fl_bottom)
  6923. fl_bottom = l->y;
  6924. any = 1;
  6925. n = nd->next;
  6926. }
  6927. l->left = row_left;
  6928. l->right = row_right;
  6929. if (n && any) {
  6930. struct br_node *nd = &doc.nodes[n];
  6931. int inline_next = 0;
  6932. if (nd->type == BR_NODE_TEXT) {
  6933. inline_next = 1;
  6934. } else if (nd->type == BR_NODE_ELEM) {
  6935. struct br_style cs;
  6936. br_style_for(&doc, n, pst, &cs);
  6937. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  6938. cs.display != BR_DISPLAY_NONE &&
  6939. !br_tag_is_block(nd->tag);
  6940. }
  6941. if (inline_next) {
  6942. if (l->float_active) {
  6943. if (l->float_left > fl_left)
  6944. fl_left = l->float_left;
  6945. if (l->float_right < fl_right)
  6946. fl_right = l->float_right;
  6947. if (l->float_bottom > fl_bottom)
  6948. fl_bottom = l->float_bottom;
  6949. }
  6950. l->float_active = 1;
  6951. l->float_left = fl_left;
  6952. l->float_right = fl_right;
  6953. l->float_bottom = fl_bottom;
  6954. l->y = row_top;
  6955. } else {
  6956. l->float_active = 0;
  6957. l->y = row_bottom;
  6958. }
  6959. } else {
  6960. l->float_active = 0;
  6961. l->y = row_bottom;
  6962. }
  6963. l->line_x = l->left;
  6964. l->run_x = l->left;
  6965. l->line_left = l->left;
  6966. l->line_right = l->right;
  6967. l->line_y = l->y;
  6968. l->line_h = 0;
  6969. l->nruns = 0;
  6970. l->space_pending = 0;
  6971. return n;
  6972. }
  6973. static int flex_item_width(struct lay *l, unsigned int n,
  6974. const struct br_style *cs, int avail)
  6975. {
  6976. struct br_node *nd = &doc.nodes[n];
  6977. (void)l;
  6978. int w;
  6979. if (cs->width_kind == 2 || cs->width_kind == 3)
  6980. w = style_width_px(cs, avail);
  6981. else if (cs->width_kind == 1)
  6982. w = (int)cs->width;
  6983. else if (nd->tag == BR_TAG_IMG) {
  6984. int idx = nd->img_index;
  6985. if (idx >= 0 && idx < image_count &&
  6986. images[idx].state == 1)
  6987. w = (int)images[idx].img.w;
  6988. else if (nd->width_attr)
  6989. w = (int)nd->width_attr;
  6990. else
  6991. w = 64;
  6992. } else {
  6993. w = intrinsic_width(l->ui, n, cs, 0, avail);
  6994. }
  6995. /* Explicit widths are content-box sizes; the flex item's outer width
  6996. * must include padding, borders and margins. */
  6997. w += mp_px(cs, 7, avail);
  6998. w += mp_px(cs, 5, avail);
  6999. w += mp_px(cs, 3, avail);
  7000. w += mp_px(cs, 1, avail);
  7001. w += cs->border_w[1] + cs->border_w[3];
  7002. if (w < 24)
  7003. w = 24;
  7004. if (w > avail)
  7005. w = avail;
  7006. return w;
  7007. }
  7008. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  7009. * on one line, not one full-width block each. Place intrinsic widths from
  7010. * left to right and wrap when the row is full. */
  7011. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7012. const struct br_style *pst, int depth,
  7013. unsigned short link)
  7014. {
  7015. unsigned int n = first;
  7016. int row_left = l->left, row_right = l->right;
  7017. int avail = row_right - row_left;
  7018. int x = row_left, y = l->y, row_h = 0, any = 0;
  7019. flush_line(l);
  7020. y = l->y;
  7021. while (n) {
  7022. struct br_node *nd = &doc.nodes[n];
  7023. struct br_style cs;
  7024. unsigned short lk = link;
  7025. int colw, h;
  7026. if (nd->type == BR_NODE_TEXT) {
  7027. if (!text_node_blank(nd))
  7028. break;
  7029. if (any)
  7030. x += 4;
  7031. n = nd->next;
  7032. continue;
  7033. }
  7034. br_style_for(&doc, n, pst, &cs);
  7035. if (cs.display == BR_DISPLAY_NONE) {
  7036. n = nd->next;
  7037. continue;
  7038. }
  7039. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  7040. break;
  7041. if (nd->tag == BR_TAG_A && nd->href_off)
  7042. lk = (unsigned short)n;
  7043. colw = flex_item_width(l, n, &cs, avail);
  7044. /* A few pixels of slack keep a single long token (boot.S)
  7045. * from wrapping at the exact content width. */
  7046. colw += 8;
  7047. if (colw > avail)
  7048. colw = avail;
  7049. cs.width_kind = 0;
  7050. cs.max_width_kind = 0;
  7051. if (any && x + colw > row_right) {
  7052. y += row_h + 2;
  7053. x = row_left;
  7054. row_h = 0;
  7055. any = 0;
  7056. }
  7057. if (any && x > row_left)
  7058. x += 4;
  7059. l->left = x;
  7060. l->right = x + colw;
  7061. if (l->right < l->left + 8)
  7062. l->right = l->left + 8;
  7063. l->y = y;
  7064. l->line_x = l->left;
  7065. l->run_x = l->left;
  7066. l->line_y = l->y;
  7067. l->line_h = 0;
  7068. l->nruns = 0;
  7069. l->space_pending = 0;
  7070. l->align = cs.align;
  7071. layout_block(l, n, &cs, depth + 1, lk);
  7072. h = l->y - y;
  7073. if (h > row_h)
  7074. row_h = h;
  7075. x += colw;
  7076. any = 1;
  7077. n = nd->next;
  7078. }
  7079. if (any)
  7080. y += row_h;
  7081. l->left = row_left;
  7082. l->right = row_right;
  7083. l->y = y;
  7084. l->line_x = l->left;
  7085. l->run_x = l->left;
  7086. l->line_y = l->y;
  7087. l->line_h = 0;
  7088. l->nruns = 0;
  7089. l->space_pending = 0;
  7090. return n;
  7091. }
  7092. struct flex_item {
  7093. unsigned int node;
  7094. unsigned short link;
  7095. int w;
  7096. };
  7097. static void layout_flex_children(struct lay *l, unsigned int parent,
  7098. const struct br_style *pst, int depth,
  7099. unsigned short link)
  7100. {
  7101. struct flex_item it[32];
  7102. unsigned int c;
  7103. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  7104. int row_left = l->left, row_right = l->right;
  7105. int avail = row_right - row_left;
  7106. int idx, row_top;
  7107. if (avail < 160 || depth > 48) {
  7108. layout_children(l, parent, pst, depth, link);
  7109. return;
  7110. }
  7111. /* If direct text is not just whitespace, normal block flow handles it
  7112. * better than pretending it is a flex item. */
  7113. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7114. struct br_node *nd = &doc.nodes[c];
  7115. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7116. layout_children(l, parent, pst, depth, link);
  7117. return;
  7118. }
  7119. }
  7120. for (c = doc.nodes[parent].first;
  7121. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  7122. c = doc.nodes[c].next) {
  7123. struct br_node *nd = &doc.nodes[c];
  7124. struct br_style cs;
  7125. if (nd->type == BR_NODE_TEXT)
  7126. continue;
  7127. br_style_for(&doc, c, pst, &cs);
  7128. if (cs.display == BR_DISPLAY_NONE)
  7129. continue;
  7130. it[nitem].node = c;
  7131. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  7132. (unsigned short)c : link;
  7133. it[nitem].w = 0;
  7134. if (cs.flex_grow && !cs.width_kind)
  7135. grow_count++;
  7136. else
  7137. fixed += flex_item_width(l, c, &cs, avail);
  7138. nitem++;
  7139. }
  7140. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  7141. if (grow_w < 96)
  7142. grow_w = 96;
  7143. for (idx = 0; idx < nitem; idx++) {
  7144. struct br_style cs;
  7145. br_style_for(&doc, it[idx].node, pst, &cs);
  7146. if (cs.flex_grow && !cs.width_kind)
  7147. it[idx].w = grow_w;
  7148. else
  7149. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  7150. if (it[idx].w > avail)
  7151. it[idx].w = avail;
  7152. if (it[idx].w < 8)
  7153. it[idx].w = 8;
  7154. }
  7155. row_top = l->y;
  7156. idx = 0;
  7157. while (idx < nitem) {
  7158. int start = idx, count = 0, row_w = 0;
  7159. int free_w, x, extra = 0, row_h = 0, k;
  7160. while (idx < nitem) {
  7161. int add = it[idx].w + (count ? gap : 0);
  7162. /* CSS default is nowrap; only flex-wrap: wrap (1)
  7163. * starts a new row. */
  7164. if (count && pst->flex_wrap == 1 &&
  7165. row_w + add > avail)
  7166. break;
  7167. row_w += add;
  7168. count++;
  7169. idx++;
  7170. }
  7171. if (!count) {
  7172. count = 1;
  7173. row_w = it[start].w;
  7174. idx = start + 1;
  7175. }
  7176. free_w = avail - row_w;
  7177. if (free_w < 0)
  7178. free_w = 0;
  7179. x = row_left;
  7180. if (pst->justify == 1) {
  7181. x += free_w / 2;
  7182. } else if (pst->justify == 2) {
  7183. x += free_w;
  7184. } else if (pst->justify == 3) {
  7185. extra = count > 1 ? free_w / (count - 1) : 0;
  7186. } else if (pst->justify == 4) {
  7187. extra = count ? free_w / count : 0;
  7188. x += extra / 2;
  7189. } else if (pst->justify == 5) {
  7190. extra = count ? free_w / (count + 1) : 0;
  7191. x += extra;
  7192. }
  7193. for (k = 0; k < count; k++) {
  7194. int node = (int)it[start + k].node;
  7195. int h = block_h[node];
  7196. if (h > row_h)
  7197. row_h = h;
  7198. }
  7199. if (pst->height_kind) {
  7200. int hh = style_height_px(pst, avail);
  7201. if (hh > row_h)
  7202. row_h = hh;
  7203. }
  7204. for (k = 0; k < count; k++) {
  7205. struct br_style cs;
  7206. int node = (int)it[start + k].node;
  7207. int yoff = 0;
  7208. br_style_for(&doc, node, pst, &cs);
  7209. cs.width_kind = 0;
  7210. cs.max_width_kind = 0;
  7211. if (l->draw && pst->align_items &&
  7212. row_h > block_h[node]) {
  7213. if (pst->align_items == 1)
  7214. yoff = (row_h - block_h[node]) / 2;
  7215. else if (pst->align_items == 2)
  7216. yoff = row_h - block_h[node];
  7217. }
  7218. l->left = x;
  7219. l->right = x + it[start + k].w;
  7220. if (l->right < l->left + 8)
  7221. l->right = l->left + 8;
  7222. l->y = row_top + yoff;
  7223. l->line_x = l->left;
  7224. l->run_x = l->left;
  7225. l->line_y = l->y;
  7226. l->line_h = 0;
  7227. l->nruns = 0;
  7228. l->space_pending = 0;
  7229. l->align = cs.align;
  7230. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  7231. if (!l->draw) {
  7232. int h = l->y - row_top;
  7233. if (h > row_h)
  7234. row_h = h;
  7235. }
  7236. x += it[start + k].w;
  7237. if (k + 1 < count)
  7238. x += gap + extra;
  7239. }
  7240. row_top += row_h;
  7241. }
  7242. l->left = row_left;
  7243. l->right = row_right;
  7244. l->y = row_top;
  7245. l->line_x = l->left;
  7246. l->run_x = l->left;
  7247. l->line_y = l->y;
  7248. l->line_h = 0;
  7249. l->nruns = 0;
  7250. l->space_pending = 0;
  7251. }
  7252. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  7253. * plus the grid-area hints used by site shells (site notice/footer full
  7254. * width, column-start left, page-content right). Anything more elaborate
  7255. * falls back to normal block flow. */
  7256. static int grid_track_width(unsigned char kind, unsigned short val,
  7257. int avail, int other)
  7258. {
  7259. if (kind == 2)
  7260. return avail * (int)val / 100;
  7261. if (kind == 1)
  7262. return val;
  7263. return other;
  7264. }
  7265. static void layout_grid_children(struct lay *l, unsigned int parent,
  7266. const struct br_style *pst, int depth,
  7267. unsigned short link)
  7268. {
  7269. unsigned int n;
  7270. int row_left = l->left, row_right = l->right;
  7271. int avail = row_right - row_left;
  7272. int gap = pst->grid_gap;
  7273. int track_total = avail - gap;
  7274. int col0, col1, x0, x1;
  7275. int row_y, row_bottom, have_left = 0, have_right = 0;
  7276. unsigned int c;
  7277. if (avail < 32 || depth > 48)
  7278. return;
  7279. if (track_total < 16)
  7280. track_total = 16;
  7281. col0 = grid_track_width((unsigned char)(pst->width_kind),
  7282. pst->width, track_total, 0);
  7283. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  7284. pst->max_width, track_total, 0);
  7285. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  7286. int w0 = pst->width ? pst->width : 1;
  7287. int w1 = pst->max_width ? pst->max_width : 1;
  7288. col0 = track_total * w0 / (w0 + w1);
  7289. col1 = track_total - col0;
  7290. } else if (pst->width_kind == 3) {
  7291. col0 = track_total - col1;
  7292. if (col0 < 24)
  7293. col0 = 24;
  7294. } else if (pst->max_width_kind == 3) {
  7295. col1 = track_total - col0;
  7296. if (col1 < 24)
  7297. col1 = 24;
  7298. }
  7299. if (col0 < 24)
  7300. col0 = 24;
  7301. if (col1 < 24)
  7302. col1 = 24;
  7303. if (col0 + col1 > track_total) {
  7304. col1 = track_total - col0;
  7305. if (col1 < 24)
  7306. col1 = 24;
  7307. }
  7308. x0 = row_left;
  7309. x1 = row_left + col0 + gap;
  7310. /* Direct text makes a grid ambiguous; use block flow instead. */
  7311. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7312. struct br_node *nd = &doc.nodes[c];
  7313. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7314. layout_children(l, parent, pst, depth, link);
  7315. return;
  7316. }
  7317. }
  7318. row_y = row_bottom = l->y;
  7319. n = doc.nodes[parent].first;
  7320. while (n) {
  7321. struct br_node *nd = &doc.nodes[n];
  7322. struct br_style cs;
  7323. unsigned short lk = link;
  7324. int slot, x, w;
  7325. if (nd->type == BR_NODE_TEXT) {
  7326. n = nd->next;
  7327. continue;
  7328. }
  7329. br_style_for(&doc, n, pst, &cs);
  7330. if (cs.display == BR_DISPLAY_NONE) {
  7331. n = nd->next;
  7332. continue;
  7333. }
  7334. if (nd->tag == BR_TAG_A && nd->href_off)
  7335. lk = (unsigned short)n;
  7336. slot = cs.grid_slot;
  7337. if (!slot) {
  7338. if (!have_left)
  7339. slot = 2;
  7340. else if (!have_right)
  7341. slot = 3;
  7342. else
  7343. slot = 2;
  7344. }
  7345. if (slot == 1) {
  7346. if (have_left || have_right) {
  7347. row_y = row_bottom;
  7348. have_left = have_right = 0;
  7349. }
  7350. x = row_left;
  7351. w = avail;
  7352. } else if (slot == 2) {
  7353. if (have_left) {
  7354. row_y = row_bottom;
  7355. have_left = have_right = 0;
  7356. }
  7357. x = x0;
  7358. w = col0;
  7359. have_left = 1;
  7360. } else {
  7361. if (have_right) {
  7362. row_y = row_bottom;
  7363. have_left = have_right = 0;
  7364. }
  7365. x = x1;
  7366. w = col1;
  7367. have_right = 1;
  7368. }
  7369. cs.width_kind = 0;
  7370. cs.max_width_kind = 0;
  7371. l->left = x;
  7372. l->right = x + w;
  7373. if (l->right < l->left + 8)
  7374. l->right = l->left + 8;
  7375. l->y = row_y;
  7376. l->line_x = l->left;
  7377. l->run_x = l->left;
  7378. l->line_y = l->y;
  7379. l->line_h = 0;
  7380. l->nruns = 0;
  7381. l->space_pending = 0;
  7382. l->align = cs.align;
  7383. layout_block(l, n, &cs, depth + 1, lk);
  7384. if (l->y > row_bottom)
  7385. row_bottom = l->y;
  7386. n = nd->next;
  7387. }
  7388. l->left = row_left;
  7389. l->right = row_right;
  7390. l->y = row_bottom;
  7391. l->line_x = l->left;
  7392. l->run_x = l->left;
  7393. l->line_y = l->y;
  7394. l->line_h = 0;
  7395. l->nruns = 0;
  7396. l->space_pending = 0;
  7397. }
  7398. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  7399. * capped at four. Used by the project docs' card grids. */
  7400. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7401. const struct br_style *pst, int depth,
  7402. unsigned short link)
  7403. {
  7404. unsigned int n, c;
  7405. int row_left = l->left, row_right = l->right;
  7406. int avail = row_right - row_left;
  7407. int gap = pst->grid_gap;
  7408. int minw = pst->width_kind == 1 ? pst->width : 200;
  7409. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  7410. if (avail < 32 || depth > 48) {
  7411. layout_children(l, parent, pst, depth, link);
  7412. return;
  7413. }
  7414. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7415. struct br_node *nd = &doc.nodes[c];
  7416. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  7417. layout_children(l, parent, pst, depth, link);
  7418. return;
  7419. }
  7420. }
  7421. if (minw < 80)
  7422. minw = 80;
  7423. ncols = (avail + gap) / (minw + gap);
  7424. if (ncols < 1)
  7425. ncols = 1;
  7426. if (ncols > 4)
  7427. ncols = 4;
  7428. colw = (avail - gap * (ncols - 1)) / ncols;
  7429. if (colw < 24)
  7430. colw = 24;
  7431. x = row_left;
  7432. n = doc.nodes[parent].first;
  7433. while (n) {
  7434. struct br_node *nd = &doc.nodes[n];
  7435. struct br_style cs;
  7436. unsigned short lk = link;
  7437. int h;
  7438. if (nd->type == BR_NODE_TEXT) {
  7439. n = nd->next;
  7440. continue;
  7441. }
  7442. br_style_for(&doc, n, pst, &cs);
  7443. if (cs.display == BR_DISPLAY_NONE) {
  7444. n = nd->next;
  7445. continue;
  7446. }
  7447. if (nd->tag == BR_TAG_A && nd->href_off)
  7448. lk = (unsigned short)n;
  7449. cs.width_kind = 0;
  7450. cs.max_width_kind = 0;
  7451. l->left = x;
  7452. l->right = x + colw;
  7453. if (l->right < l->left + 8)
  7454. l->right = l->left + 8;
  7455. l->y = y;
  7456. l->line_x = l->left;
  7457. l->run_x = l->left;
  7458. l->line_y = l->y;
  7459. l->line_h = 0;
  7460. l->nruns = 0;
  7461. l->space_pending = 0;
  7462. l->align = cs.align;
  7463. layout_block(l, n, &cs, depth + 1, lk);
  7464. h = l->y - y;
  7465. if (h > row_h)
  7466. row_h = h;
  7467. col++;
  7468. n = nd->next;
  7469. if (col == ncols) {
  7470. y += row_h + gap;
  7471. x = row_left;
  7472. row_h = 0;
  7473. col = 0;
  7474. } else {
  7475. x += colw + gap;
  7476. }
  7477. }
  7478. if (col)
  7479. y += row_h;
  7480. else if (y > start_y)
  7481. y -= gap;
  7482. l->left = row_left;
  7483. l->right = row_right;
  7484. l->y = y;
  7485. l->line_x = l->left;
  7486. l->run_x = l->left;
  7487. l->line_y = l->y;
  7488. l->line_h = 0;
  7489. l->nruns = 0;
  7490. l->space_pending = 0;
  7491. }
  7492. /* Column widths are the widest cell in each column across every row, so all
  7493. * rows line up. The table model is still deliberately basic: no colspan,
  7494. * border-collapse or percentage columns. */
  7495. static void table_columns(struct lay *l, unsigned int table,
  7496. const struct br_style *pst, int avail,
  7497. int *raw, int maxcols, int *out_cols,
  7498. int *out_total)
  7499. {
  7500. unsigned int r, c;
  7501. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  7502. int fixed[12];
  7503. for (c = 0; c < (unsigned int)maxcols; c++) {
  7504. raw[c] = 0;
  7505. fixed[c] = 0;
  7506. }
  7507. /* Intrinsic widths of single-column cells. */
  7508. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7509. struct br_node *rn = &doc.nodes[r];
  7510. int col = 0;
  7511. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7512. continue;
  7513. for (c = rn->first; c; c = doc.nodes[c].next) {
  7514. struct br_node *cn = &doc.nodes[c];
  7515. struct br_style cs;
  7516. int w, span;
  7517. if (cn->type != BR_NODE_ELEM ||
  7518. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7519. continue;
  7520. span = cn->colspan ? cn->colspan : 1;
  7521. br_style_for(&doc, c, pst, &cs);
  7522. if (cs.display == BR_DISPLAY_NONE)
  7523. continue;
  7524. if (col + span > maxcols)
  7525. span = maxcols - col;
  7526. if (span < 1)
  7527. break;
  7528. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  7529. mp_px(&cs, 7, avail) +
  7530. mp_px(&cs, 5, avail) +
  7531. mp_px(&cs, 3, avail) +
  7532. mp_px(&cs, 1, avail) +
  7533. cs.border_w[0] + cs.border_w[1] +
  7534. cs.border_w[2] + cs.border_w[3];
  7535. if (w < 24)
  7536. w = 24;
  7537. if (span == 1) {
  7538. if (w > raw[col])
  7539. raw[col] = w;
  7540. }
  7541. if (col + span > cols)
  7542. cols = col + span;
  7543. col += span;
  7544. }
  7545. }
  7546. /* A colspan cell only has to be as wide as the sum of its columns. */
  7547. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7548. struct br_node *rn = &doc.nodes[r];
  7549. int col = 0;
  7550. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7551. continue;
  7552. for (c = rn->first; c; c = doc.nodes[c].next) {
  7553. struct br_node *cn = &doc.nodes[c];
  7554. struct br_style cs;
  7555. int span, w, sum, i;
  7556. if (cn->type != BR_NODE_ELEM ||
  7557. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7558. continue;
  7559. span = cn->colspan ? cn->colspan : 1;
  7560. if (col + span > maxcols)
  7561. span = maxcols - col;
  7562. if (span < 1)
  7563. break;
  7564. if (span > 1) {
  7565. br_style_for(&doc, c, pst, &cs);
  7566. if (cs.display != BR_DISPLAY_NONE) {
  7567. w = intrinsic_width(l->ui, c, &cs,
  7568. 0, avail) +
  7569. mp_px(&cs, 7, avail) +
  7570. mp_px(&cs, 5, avail) +
  7571. mp_px(&cs, 3, avail) +
  7572. mp_px(&cs, 1, avail) +
  7573. cs.border_w[0] + cs.border_w[1] +
  7574. cs.border_w[2] + cs.border_w[3];
  7575. sum = 0;
  7576. for (i = 0; i < span; i++)
  7577. sum += raw[col + i];
  7578. if (w > sum)
  7579. raw[col + span - 1] += w - sum;
  7580. }
  7581. }
  7582. col += span;
  7583. }
  7584. }
  7585. /* Explicit and percentage widths override intrinsic widths. */
  7586. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7587. struct br_node *rn = &doc.nodes[r];
  7588. int col = 0;
  7589. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7590. continue;
  7591. for (c = rn->first; c; c = doc.nodes[c].next) {
  7592. struct br_node *cn = &doc.nodes[c];
  7593. struct br_style cs;
  7594. int span;
  7595. if (cn->type != BR_NODE_ELEM ||
  7596. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  7597. continue;
  7598. span = cn->colspan ? cn->colspan : 1;
  7599. if (col + span > maxcols)
  7600. span = maxcols - col;
  7601. if (span < 1)
  7602. break;
  7603. if (span == 1) {
  7604. br_style_for(&doc, c, pst, &cs);
  7605. if (cs.display != BR_DISPLAY_NONE) {
  7606. if (cs.width_kind == 1) {
  7607. raw[col] = cs.width;
  7608. fixed[col] = 1;
  7609. } else if (cs.width_kind == 2 ||
  7610. cs.width_kind == 3) {
  7611. raw[col] = style_width_px(&cs,
  7612. avail);
  7613. fixed[col] = 1;
  7614. }
  7615. }
  7616. }
  7617. col += span;
  7618. }
  7619. }
  7620. for (c = 0; c < (unsigned int)cols; c++) {
  7621. if (raw[c] < 8)
  7622. raw[c] = 8;
  7623. total += raw[c];
  7624. if (fixed[c])
  7625. fixed_sum += raw[c];
  7626. else {
  7627. free_raw += raw[c];
  7628. free_cols++;
  7629. }
  7630. }
  7631. if (fixed_sum > 0 && fixed_sum < avail) {
  7632. int free_avail = avail - fixed_sum;
  7633. int i;
  7634. if (free_raw > 0) {
  7635. for (i = 0; i < cols; i++)
  7636. if (!fixed[i])
  7637. raw[i] = free_avail * raw[i] /
  7638. free_raw;
  7639. } else if (free_cols > 0) {
  7640. for (i = 0; i < cols; i++)
  7641. if (!fixed[i])
  7642. raw[i] = free_avail / free_cols;
  7643. }
  7644. total = 0;
  7645. for (i = 0; i < cols; i++)
  7646. total += raw[i];
  7647. } else if (total < avail && total > 0) {
  7648. int i;
  7649. for (i = 0; i < cols; i++)
  7650. raw[i] = raw[i] * avail / total;
  7651. total = 0;
  7652. for (i = 0; i < cols; i++)
  7653. total += raw[i];
  7654. }
  7655. *out_cols = cols;
  7656. *out_total = total;
  7657. }
  7658. static void layout_table_row(struct lay *l, unsigned int row,
  7659. const struct br_style *pst, int depth,
  7660. unsigned short link)
  7661. {
  7662. unsigned int n, cell[12];
  7663. int raw[12], colstart[12], colspan[12];
  7664. int prefix[13];
  7665. int ncell = 0, total = 0, cols = 0, col = 0;
  7666. int row_left = l->left, row_right = l->right;
  7667. int avail = row_right - row_left;
  7668. int y = l->y, bottom = l->y;
  7669. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  7670. struct br_node *nd = &doc.nodes[n];
  7671. struct br_style cs;
  7672. int span;
  7673. if (nd->type == BR_NODE_TEXT) {
  7674. if (text_node_blank(nd))
  7675. continue;
  7676. layout_children(l, row, pst, depth, link);
  7677. return;
  7678. }
  7679. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  7680. layout_children(l, row, pst, depth, link);
  7681. return;
  7682. }
  7683. br_style_for(&doc, n, pst, &cs);
  7684. if (cs.display == BR_DISPLAY_NONE)
  7685. continue;
  7686. if (ncell >= 12) {
  7687. layout_children(l, row, pst, depth, link);
  7688. return;
  7689. }
  7690. span = nd->colspan ? nd->colspan : 1;
  7691. if (span > 12 - col)
  7692. span = 12 - col;
  7693. if (span < 1)
  7694. continue;
  7695. cell[ncell] = n;
  7696. colstart[ncell] = col;
  7697. colspan[ncell] = span;
  7698. col += span;
  7699. ncell++;
  7700. }
  7701. if (ncell < 1 || avail < 32) {
  7702. layout_children(l, row, pst, depth, link);
  7703. return;
  7704. }
  7705. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  7706. &total);
  7707. if (cols < 2 || total <= 0) {
  7708. int c;
  7709. total = 0;
  7710. for (c = 0; c < ncell; c++) {
  7711. struct br_style cs;
  7712. br_style_for(&doc, cell[c], pst, &cs);
  7713. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  7714. avail) +
  7715. mp_px(&cs, 7, avail) +
  7716. mp_px(&cs, 5, avail) +
  7717. mp_px(&cs, 3, avail) +
  7718. mp_px(&cs, 1, avail);
  7719. if (raw[c] < 24)
  7720. raw[c] = 24;
  7721. total += raw[c];
  7722. }
  7723. /* A one-column table still has to fill its own width; the
  7724. * intrinsic fallback above otherwise leaves the cell at its
  7725. * text width (HN's outer table and nested story table). */
  7726. if (total > 0 && total < avail) {
  7727. int c;
  7728. for (c = 0; c < ncell; c++)
  7729. raw[c] = raw[c] * avail / total;
  7730. total = avail;
  7731. }
  7732. }
  7733. prefix[0] = row_left;
  7734. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  7735. prefix[n + 1] = prefix[n] + raw[n];
  7736. for (n = 0; n < (unsigned int)ncell; n++) {
  7737. struct br_style cs;
  7738. int start = colstart[n];
  7739. int end = start + colspan[n];
  7740. int w;
  7741. if (end > cols)
  7742. end = cols;
  7743. if (start >= cols)
  7744. continue;
  7745. w = prefix[end] - prefix[start];
  7746. br_style_for(&doc, cell[n], pst, &cs);
  7747. /* The column width already reflects the cell's width property. */
  7748. cs.width_kind = 0;
  7749. cs.max_width_kind = 0;
  7750. if (w < 24)
  7751. w = 24;
  7752. if (w < 8)
  7753. w = 8;
  7754. l->left = prefix[start];
  7755. l->right = l->left + w;
  7756. l->y = y;
  7757. l->line_x = l->left;
  7758. l->run_x = l->left;
  7759. l->line_y = l->y;
  7760. l->line_h = 0;
  7761. l->nruns = 0;
  7762. l->space_pending = 0;
  7763. l->align = cs.align;
  7764. layout_block(l, cell[n], &cs, depth + 1, link);
  7765. if (l->y > bottom)
  7766. bottom = l->y;
  7767. }
  7768. l->left = row_left;
  7769. l->right = row_right;
  7770. l->y = bottom;
  7771. l->line_x = l->left;
  7772. l->run_x = l->left;
  7773. l->line_y = l->y;
  7774. l->line_h = 0;
  7775. l->nruns = 0;
  7776. l->space_pending = 0;
  7777. }
  7778. #define TBL_MAX_ROWS 32
  7779. #define TBL_MAX_COLS 12
  7780. #define TBL_MAX_CELLS 128
  7781. struct tbl_cell {
  7782. unsigned int node;
  7783. unsigned char row, col, rowspan, colspan;
  7784. int height;
  7785. };
  7786. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  7787. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  7788. static int table_active;
  7789. static int table_has_rowspan(unsigned int table)
  7790. {
  7791. unsigned int r, c;
  7792. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  7793. struct br_node *rn = &doc.nodes[r];
  7794. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  7795. continue;
  7796. for (c = rn->first; c; c = doc.nodes[c].next) {
  7797. struct br_node *cn = &doc.nodes[c];
  7798. if (cn->type == BR_NODE_ELEM &&
  7799. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  7800. cn->rowspan > 1)
  7801. return 1;
  7802. }
  7803. }
  7804. return 0;
  7805. }
  7806. static void table_cell_style(unsigned int row, unsigned int cell,
  7807. const struct br_style *st, struct br_style *out)
  7808. {
  7809. struct br_style trs;
  7810. br_style_for(&doc, row, st, &trs);
  7811. br_style_for(&doc, cell, &trs, out);
  7812. }
  7813. /* Tables that use rowspan need row heights before anything is painted. This
  7814. * path builds a small occupancy grid, measures the natural cell heights, then
  7815. * lays every cell out at its row/column position. Tables without rowspan
  7816. * keep the lighter per-row path in layout_table_row(). */
  7817. static void layout_table(struct lay *l, unsigned int table,
  7818. const struct br_style *st, int depth,
  7819. unsigned short link)
  7820. {
  7821. unsigned int rows[TBL_MAX_ROWS];
  7822. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  7823. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  7824. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  7825. int free_raw = 0, free_cols = 0;
  7826. int table_left = l->left, table_right = l->right;
  7827. int top = l->y, avail = table_right - table_left;
  7828. unsigned int r, c;
  7829. int i, rr, cc;
  7830. if (depth > 48 || table_active) {
  7831. layout_children(l, table, st, depth, link);
  7832. return;
  7833. }
  7834. table_active = 1;
  7835. for (r = doc.nodes[table].first;
  7836. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  7837. struct br_node *rn = &doc.nodes[r];
  7838. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  7839. rows[nrows++] = r;
  7840. }
  7841. if (!nrows) {
  7842. table_active = 0;
  7843. layout_children(l, table, st, depth, link);
  7844. return;
  7845. }
  7846. for (rr = 0; rr < nrows; rr++)
  7847. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  7848. tbl_at[rr][cc] = 0;
  7849. for (rr = 0; rr < nrows; rr++) {
  7850. int col = 0;
  7851. for (c = doc.nodes[rows[rr]].first; c;
  7852. c = doc.nodes[c].next) {
  7853. struct br_node *cn = &doc.nodes[c];
  7854. struct br_style cs;
  7855. int rs, csn;
  7856. if (cn->type != BR_NODE_ELEM ||
  7857. (cn->tag != BR_TAG_TD &&
  7858. cn->tag != BR_TAG_TH))
  7859. continue;
  7860. table_cell_style(rows[rr], c, st, &cs);
  7861. if (cs.display == BR_DISPLAY_NONE)
  7862. continue;
  7863. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  7864. col++;
  7865. if (col >= TBL_MAX_COLS)
  7866. break;
  7867. rs = cn->rowspan ? cn->rowspan : 1;
  7868. csn = cn->colspan ? cn->colspan : 1;
  7869. if (rr + rs > nrows)
  7870. rs = nrows - rr;
  7871. if (col + csn > TBL_MAX_COLS)
  7872. csn = TBL_MAX_COLS - col;
  7873. if (rs < 1 || csn < 1)
  7874. continue;
  7875. if (ncells >= TBL_MAX_CELLS)
  7876. break;
  7877. tbl_cells[ncells].node = c;
  7878. tbl_cells[ncells].row = (unsigned char)rr;
  7879. tbl_cells[ncells].col = (unsigned char)col;
  7880. tbl_cells[ncells].rowspan = (unsigned char)rs;
  7881. tbl_cells[ncells].colspan = (unsigned char)csn;
  7882. tbl_cells[ncells].height = 0;
  7883. for (i = rr; i < rr + rs; i++)
  7884. for (int j = col; j < col + csn; j++)
  7885. tbl_at[i][j] =
  7886. (unsigned short)(ncells + 1);
  7887. ncells++;
  7888. col += csn;
  7889. if (col > cols)
  7890. cols = col;
  7891. }
  7892. }
  7893. if (!ncells || cols < 1) {
  7894. table_active = 0;
  7895. layout_children(l, table, st, depth, link);
  7896. return;
  7897. }
  7898. for (i = 0; i < cols; i++) {
  7899. raw[i] = 0;
  7900. fixed[i] = 0;
  7901. }
  7902. /* Intrinsic widths of single-column cells. */
  7903. for (i = 0; i < ncells; i++) {
  7904. struct br_style cs;
  7905. int w;
  7906. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7907. st, &cs);
  7908. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  7909. mp_px(&cs, 7, avail) +
  7910. mp_px(&cs, 5, avail) +
  7911. mp_px(&cs, 3, avail) +
  7912. mp_px(&cs, 1, avail) +
  7913. cs.border_w[0] + cs.border_w[1] +
  7914. cs.border_w[2] + cs.border_w[3];
  7915. if (w < 24)
  7916. w = 24;
  7917. if (tbl_cells[i].colspan == 1) {
  7918. int col = tbl_cells[i].col;
  7919. if (w > raw[col])
  7920. raw[col] = w;
  7921. }
  7922. }
  7923. /* A spanning cell only needs the sum of its columns to be large
  7924. * enough; put the deficit in the last column. */
  7925. for (i = 0; i < ncells; i++) {
  7926. struct br_style cs;
  7927. int w, sum, col, span;
  7928. if (tbl_cells[i].colspan < 2)
  7929. continue;
  7930. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7931. st, &cs);
  7932. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  7933. mp_px(&cs, 7, avail) +
  7934. mp_px(&cs, 5, avail) +
  7935. mp_px(&cs, 3, avail) +
  7936. mp_px(&cs, 1, avail) +
  7937. cs.border_w[0] + cs.border_w[1] +
  7938. cs.border_w[2] + cs.border_w[3];
  7939. col = tbl_cells[i].col;
  7940. span = tbl_cells[i].colspan;
  7941. sum = 0;
  7942. for (int j = 0; j < span; j++)
  7943. sum += raw[col + j];
  7944. if (w > sum)
  7945. raw[col + span - 1] += w - sum;
  7946. }
  7947. /* Explicit/percentage widths, as in table_columns(). */
  7948. for (i = 0; i < ncells; i++) {
  7949. struct br_style cs;
  7950. int col;
  7951. if (tbl_cells[i].colspan != 1)
  7952. continue;
  7953. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  7954. st, &cs);
  7955. col = tbl_cells[i].col;
  7956. if (cs.width_kind == 1) {
  7957. raw[col] = cs.width;
  7958. fixed[col] = 1;
  7959. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  7960. raw[col] = style_width_px(&cs, avail);
  7961. fixed[col] = 1;
  7962. }
  7963. }
  7964. for (i = 0; i < cols; i++) {
  7965. if (raw[i] < 8)
  7966. raw[i] = 8;
  7967. total += raw[i];
  7968. if (fixed[i])
  7969. fixed_sum += raw[i];
  7970. else {
  7971. free_raw += raw[i];
  7972. free_cols++;
  7973. }
  7974. }
  7975. if (fixed_sum > 0 && fixed_sum < avail) {
  7976. int free_avail = avail - fixed_sum;
  7977. if (free_raw > 0) {
  7978. for (i = 0; i < cols; i++)
  7979. if (!fixed[i])
  7980. raw[i] = free_avail * raw[i] /
  7981. free_raw;
  7982. } else if (free_cols > 0) {
  7983. for (i = 0; i < cols; i++)
  7984. if (!fixed[i])
  7985. raw[i] = free_avail / free_cols;
  7986. }
  7987. } else if (total < avail && total > 0) {
  7988. for (i = 0; i < cols; i++)
  7989. raw[i] = raw[i] * avail / total;
  7990. }
  7991. prefix[0] = table_left;
  7992. for (i = 0; i < cols; i++)
  7993. prefix[i + 1] = prefix[i] + raw[i];
  7994. /* Measure natural cell heights with the column widths. */
  7995. for (i = 0; i < ncells; i++) {
  7996. struct br_style cs;
  7997. int col = tbl_cells[i].col;
  7998. int span = tbl_cells[i].colspan;
  7999. int w = prefix[col + span] - prefix[col];
  8000. int sl = l->left, sr = l->right, sy = l->y;
  8001. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8002. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8003. int sal = l->align, sdraw = l->draw;
  8004. struct ngui *sui = l->ui;
  8005. if (w < 8)
  8006. w = 8;
  8007. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  8008. st, &cs);
  8009. cs.width_kind = 0;
  8010. cs.max_width_kind = 0;
  8011. l->draw = 0;
  8012. l->ui = 0;
  8013. l->left = prefix[col];
  8014. l->right = l->left + w;
  8015. l->y = 0;
  8016. l->line_x = l->left;
  8017. l->run_x = l->left;
  8018. l->line_y = 0;
  8019. l->line_h = 0;
  8020. l->nruns = 0;
  8021. l->space_pending = 0;
  8022. l->align = cs.align;
  8023. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8024. tbl_cells[i].height = block_h[tbl_cells[i].node];
  8025. l->left = sl;
  8026. l->right = sr;
  8027. l->y = sy;
  8028. l->line_x = slx;
  8029. l->run_x = srx;
  8030. l->line_y = sly;
  8031. l->line_h = slh;
  8032. l->nruns = snr;
  8033. l->space_pending = ssp;
  8034. l->align = sal;
  8035. l->draw = sdraw;
  8036. l->ui = sui;
  8037. }
  8038. for (i = 0; i < nrows; i++)
  8039. rowh[i] = 0;
  8040. for (i = 0; i < ncells; i++) {
  8041. int row = tbl_cells[i].row;
  8042. if (tbl_cells[i].rowspan == 1) {
  8043. if (tbl_cells[i].height > rowh[row])
  8044. rowh[row] = tbl_cells[i].height;
  8045. }
  8046. }
  8047. for (i = 0; i < ncells; i++) {
  8048. int row = tbl_cells[i].row;
  8049. int span = tbl_cells[i].rowspan;
  8050. int sum = 0;
  8051. if (span < 2)
  8052. continue;
  8053. for (int j = 0; j < span; j++)
  8054. sum += rowh[row + j];
  8055. if (sum < tbl_cells[i].height)
  8056. rowh[row + span - 1] +=
  8057. tbl_cells[i].height - sum;
  8058. }
  8059. for (i = 0; i < nrows; i++)
  8060. if (rowh[i] < 8)
  8061. rowh[i] = 8;
  8062. rowy[0] = top;
  8063. for (i = 1; i < nrows; i++)
  8064. rowy[i] = rowy[i - 1] + rowh[i - 1];
  8065. if (!l->draw) {
  8066. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8067. table_active = 0;
  8068. return;
  8069. }
  8070. for (i = 0; i < ncells; i++) {
  8071. struct br_style cs;
  8072. int col = tbl_cells[i].col;
  8073. int span = tbl_cells[i].colspan;
  8074. int row = tbl_cells[i].row;
  8075. int rspan = tbl_cells[i].rowspan;
  8076. int w = prefix[col + span] - prefix[col];
  8077. int h = 0;
  8078. int sl = l->left, sr = l->right, sy = l->y;
  8079. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  8080. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  8081. int sal = l->align;
  8082. int deco;
  8083. for (int j = 0; j < rspan; j++)
  8084. h += rowh[row + j];
  8085. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  8086. cs.width_kind = 0;
  8087. cs.max_width_kind = 0;
  8088. cs.box_sizing = 0;
  8089. deco = mp_px(&cs, 4, avail) +
  8090. mp_px(&cs, 6, avail) +
  8091. cs.border_w[0] + cs.border_w[2];
  8092. cs.height_kind = 1;
  8093. cs.height = h > deco ? h - deco : 0;
  8094. /* The block painter reads block_h[] from the measure pass; make
  8095. * the table cell fill its row/rowspan, not just its content. */
  8096. if (h > 0 && h < 65536)
  8097. block_h[tbl_cells[i].node] = (unsigned short)h;
  8098. l->left = prefix[col];
  8099. l->right = l->left + w;
  8100. l->y = rowy[row];
  8101. l->line_x = l->left;
  8102. l->run_x = l->left;
  8103. l->line_y = l->y;
  8104. l->line_h = 0;
  8105. l->nruns = 0;
  8106. l->space_pending = 0;
  8107. l->align = cs.align;
  8108. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  8109. l->left = sl;
  8110. l->right = sr;
  8111. l->y = sy;
  8112. l->line_x = slx;
  8113. l->run_x = srx;
  8114. l->line_y = sly;
  8115. l->line_h = slh;
  8116. l->nruns = snr;
  8117. l->space_pending = ssp;
  8118. l->align = sal;
  8119. }
  8120. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  8121. table_active = 0;
  8122. }
  8123. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  8124. * flow so they sit above it, like CSS painting order. Their flow origin is
  8125. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  8126. struct br_deferred {
  8127. unsigned int node;
  8128. int flow_y, flow_left, flow_right;
  8129. unsigned short link;
  8130. signed short z_index;
  8131. unsigned char z_set;
  8132. unsigned int order;
  8133. };
  8134. /* Positioned boxes painted after the flow. News front pages have one or two
  8135. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  8136. * old 16 entries the rest fell back into the flow, so a hero image landed
  8137. * below its padding-top aspect box instead of on top of it. */
  8138. #define BR_MAX_DEFERRED 256
  8139. static struct br_deferred deferred[BR_MAX_DEFERRED];
  8140. static int ndeferred;
  8141. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  8142. * element's line. A block-level pseudo-element gets its own line; its box
  8143. * (margins, padding, background) is not drawn. */
  8144. static void emit_pseudo(struct lay *l, unsigned int node,
  8145. const struct br_style *st, int pe, unsigned short link)
  8146. {
  8147. char buf[160];
  8148. struct br_style ps;
  8149. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  8150. unsigned int i = 0;
  8151. int block, space_w;
  8152. if (!n)
  8153. return;
  8154. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  8155. if (block)
  8156. flush_line(l);
  8157. if (ps.uppercase)
  8158. for (i = 0; i < n; i++)
  8159. if (buf[i] >= 'a' && buf[i] <= 'z')
  8160. buf[i] = (char)(buf[i] - 'a' + 'A');
  8161. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  8162. if (space_w <= 0)
  8163. space_w = 8;
  8164. i = 0;
  8165. while (i < n) {
  8166. char word[28];
  8167. unsigned int k = 0;
  8168. int w;
  8169. if (buf[i] == ' ') {
  8170. l->space_pending = 1;
  8171. i++;
  8172. continue;
  8173. }
  8174. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  8175. word[k++] = buf[i++];
  8176. word[k] = '\0';
  8177. if (l->space_pending &&
  8178. (l->nruns > 0 || l->line_x > l->line_left) &&
  8179. l->line_x + space_w <= l->line_right)
  8180. l->line_x += space_w;
  8181. l->space_pending = 0;
  8182. w = (int)face_text_width(l->ui, &ps, word, k);
  8183. if (l->line_x + w > l->line_right &&
  8184. (l->nruns > 0 || l->line_x > l->line_left))
  8185. flush_line(l);
  8186. add_run(l, 0, 0, &ps, link, word);
  8187. }
  8188. if (block)
  8189. flush_line(l);
  8190. }
  8191. static void layout_children(struct lay *l, unsigned int parent,
  8192. const struct br_style *pst, int depth,
  8193. unsigned short link)
  8194. {
  8195. unsigned int n;
  8196. if (depth > 48)
  8197. return;
  8198. emit_pseudo(l, parent, pst, 1, link);
  8199. n = doc.nodes[parent].first;
  8200. while (n) {
  8201. struct br_node *nd = &doc.nodes[n];
  8202. struct br_style cs;
  8203. unsigned short lk = link;
  8204. if (nd->type == BR_NODE_TEXT) {
  8205. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  8206. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  8207. n = nd->next;
  8208. continue;
  8209. }
  8210. br_style_for(&doc, n, pst, &cs);
  8211. if (cs.display == BR_DISPLAY_NONE) {
  8212. n = nd->next;
  8213. continue;
  8214. }
  8215. if (cs.clear && l->float_active) {
  8216. flush_line(l);
  8217. if (l->y < l->float_bottom)
  8218. l->y = l->float_bottom;
  8219. l->float_active = 0;
  8220. l->line_x = l->left;
  8221. l->run_x = l->left;
  8222. l->line_left = l->left;
  8223. l->line_right = l->right;
  8224. l->line_y = l->y;
  8225. l->line_h = 0;
  8226. l->nruns = 0;
  8227. l->space_pending = 0;
  8228. }
  8229. if (nd->tag == BR_TAG_A && nd->href_off)
  8230. lk = (unsigned short)n;
  8231. if (cs.pos == 1 || cs.pos == 2 ||
  8232. (cs.pos == 3 && cs.z_set)) {
  8233. if (cs.pos == 3 && l->draw &&
  8234. ndeferred < BR_MAX_DEFERRED) {
  8235. /* Relative z-index: measure and advance the flow
  8236. * without painting, then paint it in the
  8237. * deferred (stacked) pass. */
  8238. int fy = l->y, fl = l->left, fr = l->right;
  8239. int save_draw = l->draw;
  8240. l->draw = 0;
  8241. layout_block(l, n, &cs, depth + 1, lk);
  8242. l->draw = save_draw;
  8243. deferred[ndeferred].node = n;
  8244. deferred[ndeferred].flow_y = fy;
  8245. deferred[ndeferred].flow_left = fl;
  8246. deferred[ndeferred].flow_right = fr;
  8247. deferred[ndeferred].link = lk;
  8248. deferred[ndeferred].z_index = cs.z_index;
  8249. deferred[ndeferred].z_set = cs.z_set;
  8250. deferred[ndeferred].order = (unsigned int)ndeferred;
  8251. ndeferred++;
  8252. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  8253. deferred[ndeferred].node = n;
  8254. deferred[ndeferred].flow_y =
  8255. cs.pos == 1 ? l->cb_top : l->y;
  8256. deferred[ndeferred].flow_left =
  8257. cs.pos == 1 ? l->cb_left : l->left;
  8258. deferred[ndeferred].flow_right =
  8259. cs.pos == 1 ? l->cb_right : l->right;
  8260. deferred[ndeferred].link = lk;
  8261. deferred[ndeferred].z_index = cs.z_index;
  8262. deferred[ndeferred].z_set = cs.z_set;
  8263. deferred[ndeferred].order = (unsigned int)ndeferred;
  8264. ndeferred++;
  8265. } else if (l->draw && cs.pos == 1) {
  8266. /* Deferred list full: paint in place, but still
  8267. * against the containing block, not the flow. */
  8268. int fy = l->y, fl = l->left, fr = l->right;
  8269. l->y = l->cb_top;
  8270. l->left = l->cb_left;
  8271. l->right = l->cb_right;
  8272. layout_block(l, n, &cs, depth + 1, lk);
  8273. l->y = fy;
  8274. l->left = fl;
  8275. l->right = fr;
  8276. } else {
  8277. layout_block(l, n, &cs, depth + 1, lk);
  8278. }
  8279. if (cs.pos == 1 && block_h[n] &&
  8280. doc.nodes[n].class_off) {
  8281. const char *cl = doc.attrs +
  8282. doc.nodes[n].class_off;
  8283. if ((contains_ci(cl, "poster-wrapper") ||
  8284. contains_ci(cl, "ts-picture")) &&
  8285. !has_skeleton_sibling(n))
  8286. l->y += block_h[n];
  8287. }
  8288. n = nd->next;
  8289. continue;
  8290. }
  8291. if (nd->tag == BR_TAG_BR) {
  8292. flush_line(l);
  8293. n = nd->next;
  8294. continue;
  8295. }
  8296. if (nd->tag == BR_TAG_HR) {
  8297. flush_line(l);
  8298. if (l->draw)
  8299. ngui_fill_rect(l->ui,
  8300. (struct ngui_rect){l->left, l->y + 2,
  8301. l->right - l->left, 1}, BR_GRAY);
  8302. l->y += 8;
  8303. n = nd->next;
  8304. continue;
  8305. }
  8306. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  8307. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  8308. if (!(nd->tag == BR_TAG_INPUT &&
  8309. s_eq(br_type(&doc, n), "hidden"))) {
  8310. form_fill_line = pst->display ==
  8311. BR_DISPLAY_FLEX &&
  8312. pst->flex_col;
  8313. add_form_run(l, n, &cs, lk);
  8314. form_fill_line = 0;
  8315. }
  8316. n = nd->next;
  8317. continue;
  8318. }
  8319. if (nd->tag == BR_TAG_IMG) {
  8320. add_image_run(l, n, &cs, lk);
  8321. n = nd->next;
  8322. continue;
  8323. }
  8324. if (nd->tag == BR_TAG_VIDEO) {
  8325. layout_block(l, n, &cs, depth + 1, lk);
  8326. n = nd->next;
  8327. continue;
  8328. }
  8329. if (cs.float_left) {
  8330. n = layout_float_group(l, n, pst, depth, lk);
  8331. continue;
  8332. }
  8333. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8334. n = layout_inline_blocks(l, n, pst, depth, link);
  8335. continue;
  8336. }
  8337. /* A flex container is block-level like any block box even when
  8338. * the element is an inline tag such as <a> (a link card with
  8339. * display:flex is common on news sites). Without the block box
  8340. * its children were laid out in the parent flow with a 0x0 box
  8341. * of their own. */
  8342. /* inline-flex around inline content only ("| mehr" link
  8343. * tails, icon+label pills) stays in the text line. */
  8344. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  8345. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  8346. !flex_wants_row(n, &cs)) {
  8347. layout_children(l, n, &cs, depth + 1, lk);
  8348. } else if (cs.display == BR_DISPLAY_BLOCK ||
  8349. cs.display == BR_DISPLAY_FLEX ||
  8350. br_tag_is_block(nd->tag))
  8351. layout_block(l, n, &cs, depth + 1, lk);
  8352. else {
  8353. layout_children(l, n, &cs, depth + 1, lk);
  8354. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  8355. l->space_pending = 1;
  8356. }
  8357. n = nd->next;
  8358. }
  8359. emit_pseudo(l, parent, pst, 2, link);
  8360. }
  8361. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  8362. * runs and a recursive page can otherwise overflow the stack. */
  8363. static struct lay layout_state;
  8364. static int measure_page(int left, int right)
  8365. {
  8366. struct lay *l = &layout_state;
  8367. struct br_style base = base_style();
  8368. unsigned int i;
  8369. for (i = 0; i < BR_MAX_NODES; i++) {
  8370. block_h[i] = 0;
  8371. img_top[i] = 0;
  8372. block_top[i] = 0;
  8373. img_h[i] = 0;
  8374. layout_boxes[i].valid = 0;
  8375. }
  8376. memset(li_marker, 0, sizeof(li_marker));
  8377. l->draw = 0;
  8378. l->ui = &ui;
  8379. l->left = left;
  8380. l->right = right;
  8381. l->y = 0;
  8382. l->line_x = left;
  8383. l->run_x = left;
  8384. l->line_left = left;
  8385. l->line_right = right;
  8386. l->line_y = 0;
  8387. l->line_h = 0;
  8388. l->align = BR_ALIGN_LEFT;
  8389. l->float_active = 0;
  8390. l->parent_top = 0;
  8391. l->cb_left = left;
  8392. l->cb_right = right;
  8393. l->cb_top = 0;
  8394. l->depth = 0;
  8395. l->nruns = 0;
  8396. l->space_pending = 0;
  8397. layout_children(l, doc.root, &base, 0, 0);
  8398. return l->y + 8;
  8399. }
  8400. static int deferred_cmp(const struct br_deferred *a,
  8401. const struct br_deferred *b)
  8402. {
  8403. int az = a->z_set ? a->z_index : 0;
  8404. int bz = b->z_set ? b->z_index : 0;
  8405. if (az != bz)
  8406. return az < bz ? -1 : 1;
  8407. if (a->order != b->order)
  8408. return a->order < b->order ? -1 : 1;
  8409. return 0;
  8410. }
  8411. static void sort_deferred(void)
  8412. {
  8413. int i;
  8414. for (i = 1; i < ndeferred; i++) {
  8415. struct br_deferred key = deferred[i];
  8416. int j = i;
  8417. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  8418. deferred[j] = deferred[j - 1];
  8419. j--;
  8420. }
  8421. deferred[j] = key;
  8422. }
  8423. }
  8424. static void render_page(int left, int right, int y0)
  8425. {
  8426. struct lay *l = &layout_state;
  8427. struct br_style base = base_style();
  8428. l->draw = 1;
  8429. l->ui = &ui;
  8430. l->left = left;
  8431. l->right = right;
  8432. l->y = y0;
  8433. l->line_x = left;
  8434. l->run_x = left;
  8435. l->line_left = left;
  8436. l->line_right = right;
  8437. l->line_y = y0;
  8438. l->line_h = 0;
  8439. l->align = BR_ALIGN_LEFT;
  8440. l->float_active = 0;
  8441. l->parent_top = 0;
  8442. l->cb_left = left;
  8443. l->cb_right = right;
  8444. l->cb_top = y0;
  8445. l->depth = 0;
  8446. l->nruns = 0;
  8447. l->space_pending = 0;
  8448. nhits = 0;
  8449. ndeferred = 0;
  8450. layout_children(l, doc.root, &base, 0, 0);
  8451. sort_deferred();
  8452. {
  8453. int i;
  8454. for (i = 0; i < ndeferred; i++) {
  8455. struct br_style st;
  8456. br_style_for(&doc, deferred[i].node, &base, &st);
  8457. if (st.display == BR_DISPLAY_NONE)
  8458. continue;
  8459. l->draw = 1;
  8460. l->left = deferred[i].flow_left;
  8461. l->right = deferred[i].flow_right;
  8462. l->y = deferred[i].flow_y;
  8463. l->line_x = l->left;
  8464. l->run_x = l->left;
  8465. l->line_y = l->y;
  8466. l->line_h = 0;
  8467. l->nruns = 0;
  8468. l->space_pending = 0;
  8469. l->align = st.align;
  8470. if (st.pos == 2 && block_h[deferred[i].node]) {
  8471. struct ngui_rect clip;
  8472. int ch = block_h[deferred[i].node] + 24;
  8473. clip.x = page_rect.x;
  8474. clip.y = page_rect.y;
  8475. clip.w = page_rect.w - 12;
  8476. if (ch > page_rect.h)
  8477. ch = page_rect.h;
  8478. clip.h = ch;
  8479. ngui_push_clip(&ui, clip);
  8480. if (st.has_bg)
  8481. ngui_fill_rect(&ui, clip, st.bg);
  8482. layout_block(l, deferred[i].node, &st, 0,
  8483. deferred[i].link);
  8484. ngui_pop_clip(&ui);
  8485. } else {
  8486. layout_block(l, deferred[i].node, &st, 0,
  8487. deferred[i].link);
  8488. }
  8489. }
  8490. }
  8491. }
  8492. /* ---- UI ---- */
  8493. static int find_hit(int x, int y)
  8494. {
  8495. int i;
  8496. for (i = nhits - 1; i >= 0; i--) {
  8497. struct hit *h = &hits[i];
  8498. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  8499. y < h->y + h->h)
  8500. return (int)h->node;
  8501. }
  8502. return 0;
  8503. }
  8504. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  8505. {
  8506. int x = r.x + 4, y = r.y + 4, h = 22;
  8507. int compact = r.w < 560;
  8508. int go_w = r.w < 420 ? 32 : 42;
  8509. int in_x, in_w, res;
  8510. ngui_fill_rect(&ui, r, ui.theme.panel);
  8511. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  8512. ui.theme.border);
  8513. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  8514. NGUI_ICON_CHEVRON_LEFT))
  8515. *action |= ACT_BACK;
  8516. x += 32;
  8517. if (!compact) {
  8518. if (ngui_icon_button(&ui, ID_FORWARD,
  8519. (struct ngui_rect){x, y, 28, h},
  8520. NGUI_ICON_CHEVRON_RIGHT))
  8521. *action |= ACT_FORWARD;
  8522. x += 32;
  8523. }
  8524. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  8525. NGUI_ICON_REFRESH))
  8526. *action |= ACT_RELOAD;
  8527. x += 32;
  8528. if (!compact) {
  8529. if (ngui_icon_button(&ui, ID_HOME,
  8530. (struct ngui_rect){x, y, 28, h},
  8531. NGUI_ICON_HOME))
  8532. *action |= ACT_HOME;
  8533. x += 32;
  8534. }
  8535. in_x = x + 2;
  8536. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  8537. if (in_w < 60)
  8538. in_w = 60;
  8539. res = ngui_text_input(&ui, ID_URL,
  8540. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  8541. if (res & NGUI_INPUT_SUBMIT)
  8542. *action |= ACT_NAV;
  8543. if (res & NGUI_INPUT_CANCEL)
  8544. ngui_set_focus(&ui, 0);
  8545. if (ngui_button(&ui, ID_GO,
  8546. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  8547. "Go"))
  8548. *action |= ACT_NAV;
  8549. }
  8550. static int page_hover_node(void)
  8551. {
  8552. if (!ui.inside)
  8553. return 0;
  8554. if (ui.mouse_x < page_rect.x ||
  8555. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  8556. ui.mouse_y < page_rect.y ||
  8557. ui.mouse_y >= page_rect.y + page_rect.h)
  8558. return 0;
  8559. return find_hit(ui.mouse_x, ui.mouse_y);
  8560. }
  8561. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  8562. {
  8563. int x, y, w = page.w, h = page.h;
  8564. if (!src || w <= 0 || h <= 0)
  8565. return;
  8566. for (y = 0; y < h; y++) {
  8567. unsigned short *s = src + (page.y + y) * sw + page.x;
  8568. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  8569. for (x = 0; x + 1 < w; x += 2) {
  8570. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  8571. }
  8572. if (x < w)
  8573. d[x] = s[x];
  8574. }
  8575. }
  8576. static void draw_page(struct ngui_rect page)
  8577. {
  8578. int left, right, ch;
  8579. int old_panel, old_dim;
  8580. unsigned short *saved_px;
  8581. unsigned short page_bg = ui.theme.bg;
  8582. int saved_w, saved_h, use_buf;
  8583. page_rect = page;
  8584. {
  8585. unsigned int root = doc.nnode > 1 ?
  8586. br_find_tag(&doc, BR_TAG_HTML) : 0;
  8587. unsigned int body = doc.nnode > 1 ?
  8588. br_find_tag(&doc, BR_TAG_BODY) : 0;
  8589. struct br_style bs;
  8590. if (root) {
  8591. style_for_node(root - 1, &bs);
  8592. if (bs.has_bg)
  8593. page_bg = bs.bg;
  8594. }
  8595. if (body) {
  8596. style_for_node(body - 1, &bs);
  8597. if (bs.has_bg)
  8598. page_bg = bs.bg;
  8599. }
  8600. }
  8601. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  8602. page_cache_valid && layout_valid &&
  8603. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  8604. !(ui.scroll_y &&
  8605. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  8606. page_scroll.offset == page_cache_scroll &&
  8607. page_cache_nnode == doc.nnode &&
  8608. page_cache_x == page.x && page_cache_y == page.y &&
  8609. page_cache_w == page.w && page_cache_h == page.h) {
  8610. blit_page(page, page_backbuf, pagebuf_w);
  8611. return;
  8612. }
  8613. ngui_fill_rect(&ui, page, page_bg);
  8614. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  8615. const char *s = page_loading ? "Loading..." : "No page";
  8616. int w = (int)ngui_text_width_ui(&ui, s);
  8617. ngui_text(&ui, page.x + (page.w - w) / 2,
  8618. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  8619. page_scroll.content_h = 0;
  8620. page_scroll.view_h = page.h;
  8621. page_cache_valid = 0;
  8622. return;
  8623. }
  8624. if (page.w < 40 || page.h < 40) {
  8625. page_cache_valid = 0;
  8626. return;
  8627. }
  8628. saved_px = ui.px;
  8629. saved_w = ui.w;
  8630. saved_h = ui.h;
  8631. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  8632. if (use_buf) {
  8633. ui.px = page_backbuf;
  8634. ui.w = pagebuf_w;
  8635. ui.h = pagebuf_h;
  8636. ngui_fill_rect(&ui, page, page_bg);
  8637. }
  8638. left = page.x + 8;
  8639. right = page.x + page.w - 16;
  8640. if (!layout_valid || left != layout_left || right != layout_right ||
  8641. layout_nnode != doc.nnode) {
  8642. layout_content_h = measure_page(left, right);
  8643. layout_valid = 1;
  8644. layout_left = left;
  8645. layout_right = right;
  8646. layout_nnode = doc.nnode;
  8647. }
  8648. ch = layout_content_h;
  8649. page_scroll.content_h = ch;
  8650. page_scroll.view_h = page.h;
  8651. ngui_scroll_begin(&ui, page, &page_scroll);
  8652. ngui_scroll_wheel(&ui, page, &page_scroll);
  8653. render_page(left, right, page.y + 4 - page_scroll.offset);
  8654. old_panel = ui.theme.panel_alt;
  8655. old_dim = ui.theme.text_dim;
  8656. ui.theme.panel_alt = 0xC618;
  8657. ui.theme.text_dim = 0x8410;
  8658. ngui_scroll_end(&ui, page, &page_scroll);
  8659. ui.theme.panel_alt = old_panel;
  8660. ui.theme.text_dim = old_dim;
  8661. if (use_buf) {
  8662. ui.px = saved_px;
  8663. ui.w = saved_w;
  8664. ui.h = saved_h;
  8665. blit_page(page, page_backbuf, pagebuf_w);
  8666. page_cache_valid = 1;
  8667. page_cache_scroll = page_scroll.offset;
  8668. page_cache_nnode = doc.nnode;
  8669. page_cache_x = page.x;
  8670. page_cache_y = page.y;
  8671. page_cache_w = page.w;
  8672. page_cache_h = page.h;
  8673. } else {
  8674. page_cache_valid = 0;
  8675. }
  8676. }
  8677. static void draw_status(struct ngui_rect r)
  8678. {
  8679. char msg[BR_URL_MAX + 32];
  8680. unsigned int n = 0;
  8681. int hover = page_hover_node();
  8682. unsigned short color;
  8683. const char *kind;
  8684. ngui_fill_rect(&ui, r, ui.theme.panel);
  8685. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  8686. ui.theme.border);
  8687. if (hover) {
  8688. const char *href = br_href(&doc, (unsigned int)hover);
  8689. char url[BR_URL_MAX];
  8690. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  8691. s_append(msg, &n, "Link: ", sizeof(msg));
  8692. s_append(msg, &n, url, sizeof(msg));
  8693. } else {
  8694. s_copy(msg, "Link", sizeof(msg));
  8695. }
  8696. color = ui.theme.accent;
  8697. } else if (status_text[0]) {
  8698. s_copy(msg, status_text, sizeof(msg));
  8699. color = status_error ? ui.theme.error : ui.theme.text;
  8700. } else if (page_title[0]) {
  8701. s_copy(msg, page_title, sizeof(msg));
  8702. color = ui.theme.text;
  8703. } else {
  8704. s_copy(msg, "Ready", sizeof(msg));
  8705. color = ui.theme.text_dim;
  8706. }
  8707. kind = s_eq(page_url, "about:home") ? "HOME" :
  8708. page_is_local ? "FILE" :
  8709. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  8710. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  8711. {
  8712. int kw = (int)ngui_text_width_ui(&ui, kind);
  8713. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  8714. ui.theme.text_dim);
  8715. }
  8716. }
  8717. static void draw(unsigned int *action)
  8718. {
  8719. struct ngui_rect r = {0, 0, ui.w, ui.h};
  8720. struct ngui_rect toolbar, status, page;
  8721. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  8722. status = ngui_cut_bottom(&r, BR_STATUS_H);
  8723. page = r;
  8724. draw_toolbar(toolbar, action);
  8725. draw_page(page);
  8726. draw_status(status);
  8727. }
  8728. static void redraw_now(void)
  8729. {
  8730. unsigned int action = 0;
  8731. ngui_begin(&ui);
  8732. draw(&action);
  8733. ngui_end(&ui);
  8734. }
  8735. static void handle_keys(unsigned int *action)
  8736. {
  8737. int k, scrolled = 0;
  8738. if (form_focus >= doc.nnode)
  8739. form_focus = 0;
  8740. if (form_focus && !ngui_focus(&ui)) {
  8741. while ((k = ngui_key(&ui)) != 0)
  8742. form_key(k);
  8743. return;
  8744. }
  8745. /* Batch queued page keys: a slow full-page render must not make a
  8746. * held Page Down advance only once every few frames. */
  8747. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  8748. scrolled++;
  8749. if (scrolled)
  8750. ngui_invalidate(&ui);
  8751. if (ngui_focus(&ui))
  8752. return;
  8753. while ((k = ngui_key(&ui)) != 0) {
  8754. switch (k) {
  8755. case NGUI_KEY_ESC:
  8756. *action |= ACT_CLOSE;
  8757. break;
  8758. case NGUI_KEY_TAB:
  8759. case 0x0C: /* Ctrl+L */
  8760. ngui_set_focus(&ui, ID_URL);
  8761. break;
  8762. case 0x12: /* Ctrl+R */
  8763. *action |= ACT_RELOAD;
  8764. break;
  8765. case NGUI_KEY_BACKSPACE:
  8766. *action |= ACT_BACK;
  8767. break;
  8768. case NGUI_KEY_UP:
  8769. ngui_scroll_to(&page_scroll,
  8770. page_scroll.offset - 24);
  8771. ngui_invalidate(&ui);
  8772. break;
  8773. case NGUI_KEY_DOWN:
  8774. ngui_scroll_to(&page_scroll,
  8775. page_scroll.offset + 24);
  8776. ngui_invalidate(&ui);
  8777. break;
  8778. case NGUI_KEY_HOME:
  8779. ngui_scroll_to(&page_scroll, 0);
  8780. ngui_invalidate(&ui);
  8781. break;
  8782. case NGUI_KEY_END:
  8783. ngui_scroll_to(&page_scroll,
  8784. page_scroll.content_h -
  8785. page_scroll.view_h);
  8786. ngui_invalidate(&ui);
  8787. break;
  8788. default:
  8789. break;
  8790. }
  8791. }
  8792. }
  8793. static unsigned int form_ancestor(unsigned int node)
  8794. {
  8795. unsigned int p = node;
  8796. while (p && p < doc.nnode) {
  8797. if (doc.nodes[p].tag == BR_TAG_FORM &&
  8798. doc.nodes[p].type == BR_NODE_ELEM)
  8799. return p;
  8800. p = doc.nodes[p].parent;
  8801. }
  8802. return 0;
  8803. }
  8804. static int form_descendant(unsigned int node, unsigned int form)
  8805. {
  8806. unsigned int p = node;
  8807. while (p && p < doc.nnode) {
  8808. if (p == form)
  8809. return 1;
  8810. p = doc.nodes[p].parent;
  8811. }
  8812. return 0;
  8813. }
  8814. static void form_reset_form(unsigned int form)
  8815. {
  8816. unsigned int i;
  8817. for (i = 0; i < FORM_MAX; i++)
  8818. if (form_states[i].used &&
  8819. form_descendant(form_states[i].node, form))
  8820. form_states[i].used = 0;
  8821. form_focus = 0;
  8822. }
  8823. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  8824. const char *s)
  8825. {
  8826. static const char hex[] = "0123456789ABCDEF";
  8827. while (s && *s && *n + 1 < cap) {
  8828. unsigned char c = (unsigned char)*s++;
  8829. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  8830. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  8831. c == '.' || c == '~') {
  8832. dst[(*n)++] = (char)c;
  8833. } else if (c == ' ') {
  8834. dst[(*n)++] = '+';
  8835. } else if (*n + 3 < cap) {
  8836. dst[(*n)++] = '%';
  8837. dst[(*n)++] = hex[c >> 4];
  8838. dst[(*n)++] = hex[c & 15];
  8839. }
  8840. }
  8841. dst[*n] = '\0';
  8842. }
  8843. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  8844. const char *name, const char *value, int *first)
  8845. {
  8846. if (!name || !name[0])
  8847. return;
  8848. if (!*first && *n + 1 < cap)
  8849. dst[(*n)++] = '&';
  8850. *first = 0;
  8851. form_url_append(dst, n, cap, name);
  8852. if (*n + 1 < cap)
  8853. dst[(*n)++] = '=';
  8854. form_url_append(dst, n, cap, value ? value : "");
  8855. dst[*n] = '\0';
  8856. }
  8857. static int form_submit_form(unsigned int node, int fire_event)
  8858. {
  8859. unsigned int form = form_ancestor(node);
  8860. char action[BR_URL_MAX], query[2048];
  8861. unsigned int qn = 0, i;
  8862. int first = 1, is_post = 0;
  8863. const char *a, *method;
  8864. if (!form)
  8865. return 0;
  8866. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  8867. return 0;
  8868. method = br_find_attr(&doc, form, "method");
  8869. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  8870. is_post = 1;
  8871. a = br_find_attr(&doc, form, "action");
  8872. if (a && a[0]) {
  8873. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  8874. return 0;
  8875. } else {
  8876. s_copy(action, page_url, sizeof(action));
  8877. }
  8878. query[0] = '\0';
  8879. for (i = 0; i < doc.nnode; i++) {
  8880. struct br_node *nd = &doc.nodes[i];
  8881. struct form_state *fs;
  8882. const char *name;
  8883. const char *value = "";
  8884. if (nd->type != BR_NODE_ELEM || i == form ||
  8885. !form_descendant(i, form))
  8886. continue;
  8887. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  8888. nd->tag != BR_TAG_SELECT)
  8889. continue;
  8890. if (form_disabled(i))
  8891. continue;
  8892. name = br_find_attr(&doc, i, "name");
  8893. if (!name || !name[0])
  8894. continue;
  8895. fs = form_get(i, 1);
  8896. if (!fs)
  8897. continue;
  8898. if (nd->tag == BR_TAG_SELECT) {
  8899. char opt[64];
  8900. if (!form_option_text(i, fs->selected, opt,
  8901. sizeof(opt)))
  8902. s_copy(opt, "", sizeof(opt));
  8903. value = opt;
  8904. {
  8905. unsigned int c, oi = 0;
  8906. for (c = nd->first; c;
  8907. c = doc.nodes[c].next) {
  8908. if (doc.nodes[c].type != BR_NODE_ELEM ||
  8909. doc.nodes[c].tag != BR_TAG_OPTION)
  8910. continue;
  8911. if (oi == fs->selected) {
  8912. const char *v =
  8913. br_value(&doc, c);
  8914. if (v && v[0])
  8915. value = v;
  8916. break;
  8917. }
  8918. oi++;
  8919. }
  8920. }
  8921. } else if (nd->tag == BR_TAG_INPUT) {
  8922. int kind = form_kind_of(i);
  8923. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  8924. if (!fs->checked)
  8925. continue;
  8926. value = br_value(&doc, i);
  8927. if (!value || !value[0])
  8928. value = "on";
  8929. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  8930. kind == FORM_BUTTON) {
  8931. if (i != node)
  8932. continue;
  8933. value = fs->value;
  8934. } else {
  8935. value = fs->value;
  8936. }
  8937. } else {
  8938. value = fs->value;
  8939. }
  8940. form_add_param(query, &qn, sizeof(query), name, value, &first);
  8941. }
  8942. if (is_post) {
  8943. if (action[0] == '/') {
  8944. set_status("POST forms need an HTTP action URL", 1, 4000);
  8945. ngui_invalidate(&ui);
  8946. return 0;
  8947. }
  8948. if (qn >= sizeof(pending_post))
  8949. qn = sizeof(pending_post) - 1;
  8950. if (qn)
  8951. memcpy(pending_post, query, qn);
  8952. pending_post[qn] = '\0';
  8953. pending_post_len = qn;
  8954. pending_post_is = 1;
  8955. } else {
  8956. pending_post_len = 0;
  8957. pending_post_is = 0;
  8958. if (qn) {
  8959. unsigned int an = s_len(action);
  8960. if (an + qn + 2 < sizeof(action)) {
  8961. action[an++] = strchr(action, '?') ? '&' : '?';
  8962. action[an] = '\0';
  8963. s_copy(action + an, query,
  8964. sizeof(action) - an);
  8965. }
  8966. }
  8967. }
  8968. s_copy(pending_url, action, sizeof(pending_url));
  8969. pending_action |= ACT_NAV;
  8970. cancel_fetch = 1;
  8971. ngui_invalidate(&ui);
  8972. return 1;
  8973. }
  8974. static void form_reset_event(unsigned int form)
  8975. {
  8976. if (form && !js_browser_event(form, "reset", 1, 1))
  8977. return;
  8978. if (form)
  8979. form_reset_form(form);
  8980. else
  8981. form_reset_state();
  8982. form_dirty = 0;
  8983. layout_valid = 0;
  8984. ngui_invalidate(&ui);
  8985. }
  8986. static void form_blur(void)
  8987. {
  8988. unsigned int node = form_focus;
  8989. form_focus = 0;
  8990. if (node && form_dirty) {
  8991. form_dirty = 0;
  8992. js_browser_event(node, "change", 1, 0);
  8993. }
  8994. }
  8995. static void form_click(unsigned int node)
  8996. {
  8997. struct form_state *fs;
  8998. int kind, changed = 0;
  8999. if (!form_is_control(node) || form_disabled(node))
  9000. return;
  9001. if (form_focus != node)
  9002. form_blur();
  9003. if (!js_browser_event(node, "click", 1, 1))
  9004. return;
  9005. fs = form_get(node, 1);
  9006. if (!fs)
  9007. return;
  9008. kind = form_kind_of(node);
  9009. form_focus = node;
  9010. form_dirty = 0;
  9011. if (kind == FORM_CHECKBOX) {
  9012. fs->checked = !fs->checked;
  9013. changed = 1;
  9014. } else if (kind == FORM_RADIO) {
  9015. const char *name = br_find_attr(&doc, node, "name");
  9016. unsigned int i;
  9017. fs->checked = 1;
  9018. changed = 1;
  9019. if (name) {
  9020. for (i = 0; i < FORM_MAX; i++) {
  9021. struct form_state *o = &form_states[i];
  9022. if (!o->used || o->node == node)
  9023. continue;
  9024. if (form_kind_of(o->node) == FORM_RADIO) {
  9025. const char *on = br_find_attr(&doc,
  9026. o->node,
  9027. "name");
  9028. if (on && s_eq(on, name))
  9029. o->checked = 0;
  9030. }
  9031. }
  9032. }
  9033. } else if (kind == FORM_SELECT) {
  9034. unsigned int n = form_option_count(node);
  9035. if (n) {
  9036. fs->selected = (unsigned char)
  9037. ((fs->selected + 1) % n);
  9038. changed = 1;
  9039. }
  9040. } else if (kind == FORM_SUBMIT) {
  9041. form_submit_form(node, 1);
  9042. return;
  9043. } else if (kind == FORM_RESET) {
  9044. form_reset_event(form_ancestor(node));
  9045. return;
  9046. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  9047. kind == FORM_TEXTAREA) {
  9048. fs->caret = fs->len;
  9049. }
  9050. if (changed) {
  9051. js_browser_event(node, "input", 1, 0);
  9052. js_browser_event(node, "change", 1, 0);
  9053. }
  9054. layout_valid = 0;
  9055. ngui_invalidate(&ui);
  9056. }
  9057. static void form_focus_next(void)
  9058. {
  9059. unsigned int start = form_focus ? form_focus + 1 : 0;
  9060. unsigned int i;
  9061. form_blur();
  9062. for (i = start; i < doc.nnode; i++) {
  9063. if (form_is_control(i) && !form_disabled(i) &&
  9064. !s_eq(br_type(&doc, i), "hidden")) {
  9065. form_focus = i;
  9066. layout_valid = 0;
  9067. ngui_invalidate(&ui);
  9068. return;
  9069. }
  9070. }
  9071. form_focus = 0;
  9072. layout_valid = 0;
  9073. ngui_invalidate(&ui);
  9074. }
  9075. static void form_key(int k)
  9076. {
  9077. struct form_state *fs;
  9078. int kind;
  9079. if (!form_focus || form_focus >= doc.nnode) {
  9080. form_focus = 0;
  9081. return;
  9082. }
  9083. fs = form_get(form_focus, 1);
  9084. if (!fs || form_disabled(form_focus))
  9085. return;
  9086. kind = form_kind_of(form_focus);
  9087. if (kind == FORM_SELECT) {
  9088. unsigned int n = form_option_count(form_focus);
  9089. int changed = 0;
  9090. if (k == NGUI_KEY_UP && n) {
  9091. fs->selected = (unsigned char)
  9092. ((fs->selected + n - 1) % n);
  9093. changed = 1;
  9094. } else if (k == NGUI_KEY_DOWN && n) {
  9095. fs->selected = (unsigned char)
  9096. ((fs->selected + 1) % n);
  9097. changed = 1;
  9098. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9099. form_blur();
  9100. layout_valid = 0;
  9101. ngui_invalidate(&ui);
  9102. return;
  9103. } else {
  9104. return;
  9105. }
  9106. if (changed) {
  9107. js_browser_event(form_focus, "input", 1, 0);
  9108. js_browser_event(form_focus, "change", 1, 0);
  9109. }
  9110. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  9111. if (k == ' ') {
  9112. form_click(form_focus);
  9113. return;
  9114. }
  9115. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  9116. form_blur();
  9117. layout_valid = 0;
  9118. ngui_invalidate(&ui);
  9119. }
  9120. return;
  9121. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  9122. kind == FORM_RESET) {
  9123. if (k == NGUI_KEY_ESC) {
  9124. form_blur();
  9125. layout_valid = 0;
  9126. ngui_invalidate(&ui);
  9127. } else if (k == '\r' || k == '\n' || k == ' ') {
  9128. form_click(form_focus);
  9129. }
  9130. return;
  9131. } else if (k == NGUI_KEY_TAB) {
  9132. form_focus_next();
  9133. return;
  9134. } else if (k == NGUI_KEY_ESC) {
  9135. form_blur();
  9136. layout_valid = 0;
  9137. ngui_invalidate(&ui);
  9138. return;
  9139. } else if (k == '\r' || k == '\n') {
  9140. unsigned int node = form_focus;
  9141. form_blur();
  9142. if (form_ancestor(node))
  9143. form_submit_form(node, 1);
  9144. layout_valid = 0;
  9145. ngui_invalidate(&ui);
  9146. return;
  9147. } else if (k == NGUI_KEY_BACKSPACE) {
  9148. if (fs->caret) {
  9149. unsigned int i = --fs->caret;
  9150. for (; i < fs->len; i++)
  9151. fs->value[i] = fs->value[i + 1];
  9152. if (fs->len)
  9153. fs->len--;
  9154. form_dirty = 1;
  9155. js_browser_event(form_focus, "input", 1, 0);
  9156. }
  9157. } else if (k == NGUI_KEY_DELETE) {
  9158. if (fs->caret < fs->len) {
  9159. unsigned int i;
  9160. for (i = fs->caret; i < fs->len; i++)
  9161. fs->value[i] = fs->value[i + 1];
  9162. fs->len--;
  9163. form_dirty = 1;
  9164. js_browser_event(form_focus, "input", 1, 0);
  9165. }
  9166. } else if (k == NGUI_KEY_LEFT) {
  9167. if (fs->caret)
  9168. fs->caret--;
  9169. } else if (k == NGUI_KEY_RIGHT) {
  9170. if (fs->caret < fs->len)
  9171. fs->caret++;
  9172. } else if (k == NGUI_KEY_HOME) {
  9173. fs->caret = 0;
  9174. } else if (k == NGUI_KEY_END) {
  9175. fs->caret = fs->len;
  9176. } else if (k >= 32 && k < 127) {
  9177. if (fs->len < FORM_VALUE_MAX) {
  9178. unsigned int i;
  9179. for (i = fs->len; i > fs->caret; i--)
  9180. fs->value[i] = fs->value[i - 1];
  9181. fs->value[fs->caret++] = (char)k;
  9182. fs->len++;
  9183. form_dirty = 1;
  9184. js_browser_event(form_focus, "input", 1, 0);
  9185. }
  9186. } else {
  9187. return;
  9188. }
  9189. fs->value[fs->len] = '\0';
  9190. layout_valid = 0;
  9191. ngui_invalidate(&ui);
  9192. }
  9193. /* The innermost laid-out box under a screen point: the smallest valid box
  9194. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  9195. * Used to deliver clicks to elements that are neither links nor controls
  9196. * (a Vue <div role="button">, a card with a click listener). */
  9197. static unsigned int find_box_hit(int x, int y)
  9198. {
  9199. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  9200. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  9201. const struct br_layout_box *b = &layout_boxes[i];
  9202. unsigned int area;
  9203. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  9204. x < b->x || y < b->y || x >= b->x + b->w ||
  9205. y >= b->y + b->h)
  9206. continue;
  9207. area = (unsigned int)b->w * (unsigned int)b->h;
  9208. if (area <= best_area) {
  9209. best = i;
  9210. best_area = area;
  9211. }
  9212. }
  9213. return best;
  9214. }
  9215. static void handle_page_click(unsigned int *action)
  9216. {
  9217. int node;
  9218. char url[BR_URL_MAX];
  9219. if (!ui.pressed)
  9220. return;
  9221. if (ui.press_x < page_rect.x ||
  9222. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  9223. ui.press_y < page_rect.y ||
  9224. ui.press_y >= page_rect.y + page_rect.h)
  9225. return;
  9226. node = find_hit(ui.press_x, ui.press_y);
  9227. if (!node) {
  9228. unsigned int box;
  9229. if (!js_browser_active())
  9230. return;
  9231. box = find_box_hit(ui.press_x, ui.press_y);
  9232. if (box) {
  9233. form_blur();
  9234. js_browser_event(box, "click", 1, 1);
  9235. }
  9236. return;
  9237. }
  9238. if (form_is_control((unsigned int)node)) {
  9239. form_click((unsigned int)node);
  9240. return;
  9241. }
  9242. form_blur();
  9243. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  9244. return;
  9245. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  9246. sizeof(url)) != 0)
  9247. return;
  9248. s_copy(click_url, url, sizeof(click_url));
  9249. *action |= ACT_NAV;
  9250. }
  9251. void _start(const char *arg)
  9252. {
  9253. struct win_info wi;
  9254. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  9255. u_win_create(960, 640, "Browser", &wi) != 0 &&
  9256. u_win_create(780, 540, "Browser", &wi) != 0) {
  9257. u_puts("browser: no graphics window\n");
  9258. u_exit(1);
  9259. }
  9260. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  9261. url_in.placeholder = "http://...";
  9262. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  9263. ui.theme.accent);
  9264. br_set_viewport(wi.width);
  9265. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  9266. s_copy(cwd, "/", sizeof(cwd));
  9267. heap_clear();
  9268. origin_cache_load();
  9269. css_cache_init();
  9270. script_cache_init();
  9271. page_scroll.offset = 0;
  9272. page_scroll.content_h = 0;
  9273. if (arg && arg[0]) {
  9274. navigate(arg, 1);
  9275. } else {
  9276. load_home(1);
  9277. /* Start ready to type: keep the home page, but leave the address
  9278. * bar empty instead of showing "about:home". */
  9279. ngui_input_set(&url_in, "");
  9280. ngui_set_focus(&ui, ID_URL);
  9281. }
  9282. for (;;) {
  9283. unsigned int action = 0;
  9284. unsigned int now;
  9285. click_url[0] = '\0';
  9286. if (pending_action) {
  9287. action |= pending_action & ACT_WAIT_NAV;
  9288. if (pending_url[0])
  9289. s_copy(click_url, pending_url, sizeof(click_url));
  9290. pending_action = 0;
  9291. pending_url[0] = '\0';
  9292. cancel_fetch = 0;
  9293. } else if (preload_active) {
  9294. if (preload_wait)
  9295. preload_wait = 0;
  9296. else
  9297. preload_step();
  9298. } else if ((preload_pending &&
  9299. page_scroll.offset != preload_scroll) ||
  9300. (preload_rescan && layout_valid)) {
  9301. preload_scroll = page_scroll.offset;
  9302. preload_rescan = 0;
  9303. preload_pending = 0;
  9304. preload_node = 0;
  9305. preload_active = 1;
  9306. }
  9307. js_browser_tick();
  9308. if (pending_action)
  9309. continue;
  9310. now = u_ticks_ms();
  9311. if (status_until && (int)(now - status_until) >= 0) {
  9312. status_text[0] = '\0';
  9313. status_until = 0;
  9314. status_error = 0;
  9315. ngui_invalidate(&ui);
  9316. }
  9317. if (!ngui_begin(&ui)) {
  9318. /* A queued navigation (e.g. Enter in the URL bar during
  9319. * a slow fetch) must be handled even when this frame
  9320. * needs no redraw. */
  9321. if (!action) {
  9322. fetch_workers_stop_if_unfocused();
  9323. u_sleep_ms(10);
  9324. continue;
  9325. }
  9326. } else {
  9327. draw(&action);
  9328. handle_keys(&action);
  9329. handle_page_click(&action);
  9330. ngui_end(&ui);
  9331. }
  9332. if (action & ACT_NAV) {
  9333. if (click_url[0]) {
  9334. navigate(click_url, 1);
  9335. click_url[0] = '\0';
  9336. } else {
  9337. navigate(url_in.text, 1);
  9338. }
  9339. }
  9340. if (action & ACT_BACK) {
  9341. if (hist_pos > 0) {
  9342. hist_pos--;
  9343. navigate(history[hist_pos], 0);
  9344. }
  9345. }
  9346. if (action & ACT_FORWARD) {
  9347. if (hist_pos + 1 < hist_len) {
  9348. hist_pos++;
  9349. navigate(history[hist_pos], 0);
  9350. }
  9351. }
  9352. if (action & ACT_RELOAD) {
  9353. if (s_eq(page_url, "about:home"))
  9354. load_home(0);
  9355. else
  9356. navigate(page_url, 0);
  9357. }
  9358. if (action & ACT_HOME)
  9359. load_home(1);
  9360. if (action & ACT_CLOSE)
  9361. quit = 1;
  9362. if (quit)
  9363. break;
  9364. if (pending_action)
  9365. continue;
  9366. fetch_workers_stop_if_unfocused();
  9367. u_sleep_ms(10);
  9368. }
  9369. fetch_workers_stop_all();
  9370. u_win_close();
  9371. u_exit(0);
  9372. }