browser.c 191 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Inline JavaScript runs through the vendored MuJS engine (console.log,
  5. * alert, document.getElementById(...).textContent and location.href); forms
  6. * are not supported. External CSS is loaded over uhttp, and images are
  7. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  8. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  9. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  10. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  11. */
  12. #include <stdlib.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <math.h>
  16. #include <ucmd_heap.h>
  17. #include "ucmd_lib.h"
  18. #include "ngui.h"
  19. #include "browser_html.h"
  20. #include "js_browser.h"
  21. #include "uhttp.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. /* Start wide enough for the desktop nav; smaller screens fall back to
  26. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  27. #define BR_W 1100
  28. #define BR_H 700
  29. #define BR_TOOLBAR_H 30
  30. #define BR_STATUS_H 18
  31. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  32. #define BR_IMG_FILE_MAX (512u * 1024u)
  33. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  34. #define BR_MAX_IMAGES 16
  35. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  36. #define BR_IMG_LAYOUT_W 1000
  37. #define BR_CSS_MAX (832u * 1024u)
  38. #define BR_CSS_COMP_MAX (192u * 1024u)
  39. #define BR_SCRIPT_MAX (512u * 1024u)
  40. #define FETCH_ABORT (-2)
  41. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  42. #define CSS_CACHE_MAX 16
  43. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  44. #define CSS_CACHE_PREFIX "bcss-"
  45. #define SCRIPT_CACHE_MAX 16
  46. #define SCRIPT_CACHE_FILE_MAX (512u * 1024u)
  47. #define SCRIPT_CACHE_PREFIX "bjs-"
  48. #define BR_MAX_SHEETS 6
  49. #define BR_HISTORY 16
  50. #define BR_URL_MAX 512
  51. #define BR_STATUS_MAX 200
  52. #define BR_IMG_RGB565(r, g, b) \
  53. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  54. #define BR_GRAY 0x8410
  55. enum {
  56. ID_URL = 1,
  57. ID_GO,
  58. ID_BACK,
  59. ID_FORWARD,
  60. ID_RELOAD,
  61. ID_HOME
  62. };
  63. #define ACT_NAV (1u << 0)
  64. #define ACT_BACK (1u << 1)
  65. #define ACT_FORWARD (1u << 2)
  66. #define ACT_RELOAD (1u << 3)
  67. #define ACT_HOME (1u << 4)
  68. #define ACT_CLOSE (1u << 5)
  69. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  70. ACT_HOME | ACT_CLOSE)
  71. struct br_image {
  72. int state; /* 0 empty, 1 ready */
  73. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  74. int native_w, native_h;
  75. char err[32];
  76. };
  77. static struct ngui ui;
  78. static struct ngui_input url_in;
  79. static struct ngui_scroll page_scroll;
  80. static struct br_doc doc;
  81. static struct br_image images[BR_MAX_IMAGES];
  82. static int image_count;
  83. /* Painted border boxes, in page/screen coordinates (layout starts at
  84. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  85. struct br_layout_box {
  86. int x, y;
  87. int w, h;
  88. unsigned char valid;
  89. };
  90. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  91. /* Images are loaded one per main-loop iteration so the parsed page stays
  92. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  93. static int preload_active;
  94. static int preload_pending;
  95. static int preload_wait;
  96. static unsigned int preload_node;
  97. static int preload_loaded;
  98. static int preload_scroll;
  99. static char post_status_text[BR_STATUS_MAX];
  100. static int post_status_error;
  101. static unsigned int post_status_ttl;
  102. /* Content-relative position/height of each <img>, recorded by the measure
  103. * pass so image loading can be deferred until it is near the viewport. */
  104. static unsigned short img_top[BR_MAX_NODES];
  105. static unsigned short img_h[BR_MAX_NODES];
  106. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  107. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  108. * body. Decode arenas are allocated per image instead of living here. */
  109. static unsigned char *image_io_buf;
  110. static struct ufont_face *font_faces[BR_MAX_FACES];
  111. #define image_file_buf (image_io_buf)
  112. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  113. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  114. static struct inflate image_inflate_ws;
  115. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  116. #error "CSS scratch must fit in image_io_buf"
  117. #endif
  118. static char page_url[BR_URL_MAX];
  119. static char page_title[BR_TITLE_MAX];
  120. static char cwd[64];
  121. static int page_is_local;
  122. static int page_loading;
  123. static char status_text[BR_STATUS_MAX];
  124. static unsigned int status_until;
  125. static int status_error;
  126. static char history[BR_HISTORY][BR_URL_MAX];
  127. static int hist_len, hist_pos;
  128. static char click_url[BR_URL_MAX];
  129. static char pending_url[BR_URL_MAX];
  130. #define BR_POST_MAX 4096
  131. static char pending_post[BR_POST_MAX];
  132. static unsigned int pending_post_len;
  133. static unsigned int pending_action;
  134. static int cancel_fetch;
  135. static int quit;
  136. static struct ngui_rect page_rect;
  137. static unsigned short *page_backbuf;
  138. static int pagebuf_w, pagebuf_h;
  139. static int page_cache_valid;
  140. static int page_cache_scroll;
  141. static unsigned int page_cache_nnode;
  142. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  143. static int layout_valid, layout_left, layout_right;
  144. static unsigned int layout_nnode;
  145. static int layout_content_h;
  146. /* layout output */
  147. struct lay_run {
  148. unsigned short off, len;
  149. unsigned short gap;
  150. unsigned short color;
  151. unsigned short href;
  152. char lit[28];
  153. short img;
  154. signed short dy; /* inline image vertical offset */
  155. unsigned short iw, ih;
  156. unsigned short w;
  157. unsigned char font_px, bold, italic, mono, underline, font_face;
  158. unsigned char transform_scale;
  159. unsigned char origin_x_kind, origin_y_kind;
  160. signed short scale_x, scale_y, rotate_x100;
  161. signed short origin_x, origin_y;
  162. unsigned char has_lit;
  163. unsigned int form; /* node + 1, 0 = not a control */
  164. unsigned char form_kind;
  165. unsigned char form_disabled;
  166. };
  167. struct lay {
  168. int draw;
  169. struct ngui *ui;
  170. int left, right;
  171. int y;
  172. int line_x, line_y, line_h;
  173. int line_left, line_right;
  174. int parent_top;
  175. int run_x;
  176. int align;
  177. int depth;
  178. int space_pending;
  179. unsigned char float_active;
  180. int float_left, float_right, float_bottom;
  181. struct lay_run runs[96];
  182. int nruns;
  183. };
  184. struct hit {
  185. int x, y, w, h;
  186. unsigned short node;
  187. };
  188. /* Live form state; the DOM attributes stay the initial/default value. */
  189. #define FORM_MAX 64
  190. #define FORM_VALUE_MAX 63
  191. enum {
  192. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  193. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  194. };
  195. struct form_state {
  196. unsigned int node;
  197. char value[FORM_VALUE_MAX + 1];
  198. unsigned char len, caret, checked, selected, used;
  199. };
  200. static struct form_state form_states[FORM_MAX];
  201. static unsigned int form_focus;
  202. static unsigned int form_dirty;
  203. static int form_descendant(unsigned int node, unsigned int form);
  204. static int form_submit_form(unsigned int node, int fire_event);
  205. static void form_reset_event(unsigned int form);
  206. static unsigned int s_len(const char *s);
  207. static int s_eq(const char *a, const char *b);
  208. static void form_key(int k);
  209. static void form_click(unsigned int node);
  210. static void style_for_node(unsigned int node, struct br_style *out);
  211. static int form_disabled(unsigned int node)
  212. {
  213. struct br_node *n = &doc.nodes[node];
  214. if (n->attr_flags & BR_ATTR_DISABLED)
  215. return 1;
  216. return br_find_attr(&doc, node, "disabled") != 0;
  217. }
  218. static int form_kind_of(unsigned int node)
  219. {
  220. const char *type = br_type(&doc, node);
  221. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  222. return FORM_TEXTAREA;
  223. if (doc.nodes[node].tag == BR_TAG_SELECT)
  224. return FORM_SELECT;
  225. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  226. if (s_eq(type, "reset"))
  227. return FORM_RESET;
  228. if (s_eq(type, "button"))
  229. return FORM_BUTTON;
  230. return FORM_SUBMIT;
  231. }
  232. if (s_eq(type, "password"))
  233. return FORM_PASSWORD;
  234. if (s_eq(type, "checkbox"))
  235. return FORM_CHECKBOX;
  236. if (s_eq(type, "radio"))
  237. return FORM_RADIO;
  238. if (s_eq(type, "submit"))
  239. return FORM_SUBMIT;
  240. if (s_eq(type, "reset"))
  241. return FORM_RESET;
  242. if (s_eq(type, "button"))
  243. return FORM_BUTTON;
  244. return FORM_TEXT;
  245. }
  246. static unsigned int form_option_count(unsigned int node)
  247. {
  248. unsigned int c, n = 0;
  249. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  250. if (doc.nodes[c].type == BR_NODE_ELEM &&
  251. doc.nodes[c].tag == BR_TAG_OPTION)
  252. n++;
  253. return n;
  254. }
  255. static unsigned int form_option_selected(unsigned int node)
  256. {
  257. unsigned int c, i = 0;
  258. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  259. if (doc.nodes[c].type != BR_NODE_ELEM ||
  260. doc.nodes[c].tag != BR_TAG_OPTION)
  261. continue;
  262. if (br_find_attr(&doc, c, "selected"))
  263. return i;
  264. i++;
  265. }
  266. return 0;
  267. }
  268. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  269. char *out, unsigned int cap)
  270. {
  271. unsigned int c, i = 0;
  272. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  273. if (doc.nodes[c].type != BR_NODE_ELEM ||
  274. doc.nodes[c].tag != BR_TAG_OPTION)
  275. continue;
  276. if (i == idx)
  277. return br_text_content(&doc, c, out, cap);
  278. i++;
  279. }
  280. return 0;
  281. }
  282. static struct form_state *form_get(unsigned int node, int create)
  283. {
  284. struct form_state *slot = 0;
  285. unsigned int i;
  286. for (i = 0; i < FORM_MAX; i++) {
  287. if (form_states[i].used) {
  288. if (form_states[i].node == node)
  289. return &form_states[i];
  290. } else if (!slot) {
  291. slot = &form_states[i];
  292. }
  293. }
  294. if (!create || !slot)
  295. return 0;
  296. slot->node = node;
  297. slot->len = 0;
  298. slot->caret = 0;
  299. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  300. slot->selected = form_option_selected(node);
  301. slot->used = 1;
  302. {
  303. unsigned int n = 0;
  304. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  305. n = br_text_content(&doc, node, slot->value,
  306. FORM_VALUE_MAX + 1);
  307. } else {
  308. const char *v = br_value(&doc, node);
  309. if (v) {
  310. n = s_len(v);
  311. if (n > FORM_VALUE_MAX)
  312. n = FORM_VALUE_MAX;
  313. for (unsigned int j = 0; j < n; j++)
  314. slot->value[j] = v[j];
  315. }
  316. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  317. n = br_text_content(&doc, node, slot->value,
  318. FORM_VALUE_MAX + 1);
  319. }
  320. if (n > FORM_VALUE_MAX)
  321. n = FORM_VALUE_MAX;
  322. slot->value[n] = '\0';
  323. slot->len = (unsigned char)n;
  324. slot->caret = (unsigned char)n;
  325. }
  326. return slot;
  327. }
  328. static void form_reset_state(void)
  329. {
  330. unsigned int i;
  331. for (i = 0; i < FORM_MAX; i++)
  332. form_states[i].used = 0;
  333. form_focus = 0;
  334. }
  335. static int form_is_control(unsigned int node)
  336. {
  337. unsigned int tag;
  338. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  339. return 0;
  340. tag = doc.nodes[node].tag;
  341. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  342. tag == BR_TAG_SELECT || tag == BR_TAG_BUTTON;
  343. }
  344. #define HIT_MAX 96
  345. static struct hit hits[HIT_MAX];
  346. static int nhits;
  347. static unsigned short block_h[BR_MAX_NODES];
  348. static char li_marker[BR_MAX_NODES][6];
  349. /* one connection object; the browser fetches one resource at a time */
  350. /* ---- tiny strings ---- */
  351. static unsigned int s_len(const char *s)
  352. {
  353. unsigned int n = 0;
  354. while (s && s[n])
  355. n++;
  356. return n;
  357. }
  358. static void s_copy(char *d, const char *s, unsigned int cap)
  359. {
  360. unsigned int i = 0;
  361. if (!cap)
  362. return;
  363. while (s && s[i] && i + 1 < cap) {
  364. d[i] = s[i];
  365. i++;
  366. }
  367. d[i] = '\0';
  368. }
  369. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  370. {
  371. while (s && *s && *n + 1 < cap)
  372. d[(*n)++] = *s++;
  373. d[*n] = '\0';
  374. }
  375. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  376. unsigned int cap)
  377. {
  378. char tmp[12];
  379. unsigned int i = 0, j;
  380. do {
  381. tmp[i++] = (char)('0' + v % 10);
  382. v /= 10;
  383. } while (v && i < sizeof(tmp));
  384. for (j = 0; j < i && *n + 1 < cap; j++)
  385. d[(*n)++] = tmp[i - 1 - j];
  386. d[*n] = '\0';
  387. }
  388. static int s_eq(const char *a, const char *b)
  389. {
  390. while (*a && *b) {
  391. if (*a != *b)
  392. return 0;
  393. a++;
  394. b++;
  395. }
  396. return *a == *b;
  397. }
  398. static int starts_with(const char *s, const char *p)
  399. {
  400. unsigned int i = 0;
  401. while (p[i]) {
  402. if (s[i] != p[i])
  403. return 0;
  404. i++;
  405. }
  406. return 1;
  407. }
  408. static int contains_ci(const char *s, const char *p)
  409. {
  410. unsigned int i, j;
  411. for (i = 0; s[i]; i++) {
  412. for (j = 0; p[j]; j++) {
  413. char a = s[i + j];
  414. if (a >= 'A' && a <= 'Z')
  415. a = (char)(a - 'A' + 'a');
  416. if (a != p[j])
  417. break;
  418. }
  419. if (!p[j])
  420. return 1;
  421. }
  422. return 0;
  423. }
  424. static char *trim(char *s)
  425. {
  426. unsigned int n;
  427. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  428. s++;
  429. n = s_len(s);
  430. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  431. s[n - 1] == '\r' || s[n - 1] == '\n'))
  432. s[--n] = '\0';
  433. return s;
  434. }
  435. /* ---- per-process heap ---- */
  436. static int heap_start(void)
  437. {
  438. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  439. if (!image_io_buf)
  440. return -1;
  441. page_backbuf = (unsigned short *)malloc(
  442. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  443. pagebuf_w = page_backbuf ? ui.w : 0;
  444. pagebuf_h = page_backbuf ? ui.h : 0;
  445. page_cache_valid = 0;
  446. return 0;
  447. }
  448. static void heap_clear(void)
  449. {
  450. memset(font_faces, 0, sizeof(font_faces));
  451. ngui_font_detach(&ui);
  452. heap_reset();
  453. image_io_buf = 0;
  454. page_backbuf = 0;
  455. pagebuf_w = pagebuf_h = 0;
  456. page_cache_valid = 0;
  457. }
  458. static void browser_rules_alloc(void)
  459. {
  460. struct br_rule *rules;
  461. rules = (struct br_rule *)malloc(
  462. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  463. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  464. }
  465. /* ---- status ---- */
  466. static void set_status(const char *s, int err, unsigned int ttl_ms)
  467. {
  468. s_copy(status_text, s, sizeof(status_text));
  469. status_error = err;
  470. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  471. ngui_invalidate(&ui);
  472. }
  473. /* ---- JavaScript ---- */
  474. static int resolve_link(const char *base, const char *href, char *out,
  475. unsigned int cap);
  476. static char js_last_status[BR_STATUS_MAX];
  477. static int js_last_error;
  478. static void js_host_status(const char *msg, int error)
  479. {
  480. s_copy(js_last_status, msg, sizeof(js_last_status));
  481. js_last_error = error;
  482. set_status(msg, error, 6000);
  483. }
  484. static void js_host_report(const char *msg)
  485. {
  486. u_puts("[js] ");
  487. u_puts(msg);
  488. u_putc('\n');
  489. s_copy(js_last_status, msg, sizeof(js_last_status));
  490. js_last_error = 1;
  491. set_status(msg, 1, 8000);
  492. }
  493. static void js_host_navigate(const char *url)
  494. {
  495. char resolved[BR_URL_MAX];
  496. if (!url || !url[0])
  497. return;
  498. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  499. return;
  500. s_copy(pending_url, resolved, sizeof(pending_url));
  501. pending_action |= ACT_NAV;
  502. cancel_fetch = 1;
  503. }
  504. static void js_host_changed(void)
  505. {
  506. /* Class/style/attribute mutations change computed styles, not just the
  507. * text: drop the per-node style cache before the next layout. */
  508. br_reset_styles(&doc);
  509. layout_valid = 0;
  510. ngui_invalidate(&ui);
  511. }
  512. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  513. {
  514. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  515. return 0;
  516. *x = layout_boxes[node].x - page_rect.x;
  517. *y = layout_boxes[node].y - page_rect.y;
  518. *w = layout_boxes[node].w;
  519. *h = layout_boxes[node].h;
  520. return 1;
  521. }
  522. static void form_copy_out(const char *s, char *buf, int cap)
  523. {
  524. int i = 0;
  525. if (!buf || cap <= 0)
  526. return;
  527. while (s && s[i] && i + 1 < cap) {
  528. buf[i] = s[i];
  529. i++;
  530. }
  531. buf[i] = '\0';
  532. }
  533. static int js_host_form_value(unsigned int node, char *buf, int cap)
  534. {
  535. struct form_state *fs;
  536. int kind;
  537. if (!form_is_control(node))
  538. return 0;
  539. kind = form_kind_of(node);
  540. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  541. return 0;
  542. if (kind == FORM_SELECT) {
  543. char opt[64] = "";
  544. unsigned int c, i = 0;
  545. fs = form_get(node, 1);
  546. if (!fs)
  547. return 0;
  548. form_option_text(node, fs->selected, opt, sizeof(opt));
  549. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  550. if (doc.nodes[c].type != BR_NODE_ELEM ||
  551. doc.nodes[c].tag != BR_TAG_OPTION)
  552. continue;
  553. if (i == fs->selected) {
  554. const char *v = br_value(&doc, c);
  555. if (v && v[0])
  556. form_copy_out(v, buf, cap);
  557. else
  558. form_copy_out(opt, buf, cap);
  559. return 1;
  560. }
  561. i++;
  562. }
  563. form_copy_out(opt, buf, cap);
  564. return 1;
  565. }
  566. fs = form_get(node, 1);
  567. if (!fs)
  568. return 0;
  569. form_copy_out(fs->value, buf, cap);
  570. return 1;
  571. }
  572. static int js_host_form_checked(unsigned int node)
  573. {
  574. struct form_state *fs;
  575. int kind;
  576. if (!form_is_control(node))
  577. return -1;
  578. kind = form_kind_of(node);
  579. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  580. return -1;
  581. fs = form_get(node, 1);
  582. return fs ? fs->checked : 0;
  583. }
  584. static int js_host_form_selected(unsigned int node)
  585. {
  586. struct form_state *fs;
  587. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  588. return -1;
  589. fs = form_get(node, 1);
  590. return fs ? fs->selected : 0;
  591. }
  592. static int js_host_form_set_value(unsigned int node, const char *value)
  593. {
  594. struct form_state *fs;
  595. unsigned int n;
  596. if (!form_is_control(node))
  597. return 0;
  598. fs = form_get(node, 1);
  599. if (!fs)
  600. return 0;
  601. n = s_len(value ? value : "");
  602. if (n > FORM_VALUE_MAX)
  603. n = FORM_VALUE_MAX;
  604. for (unsigned int i = 0; i < n; i++)
  605. fs->value[i] = value[i];
  606. fs->value[n] = '\0';
  607. fs->len = (unsigned char)n;
  608. fs->caret = (unsigned char)n;
  609. layout_valid = 0;
  610. ngui_invalidate(&ui);
  611. return 1;
  612. }
  613. static int js_host_form_set_checked(unsigned int node, int checked)
  614. {
  615. struct form_state *fs;
  616. int kind;
  617. if (!form_is_control(node))
  618. return 0;
  619. kind = form_kind_of(node);
  620. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  621. return 0;
  622. fs = form_get(node, 1);
  623. if (!fs)
  624. return 0;
  625. fs->checked = (unsigned char)(checked != 0);
  626. layout_valid = 0;
  627. ngui_invalidate(&ui);
  628. return 1;
  629. }
  630. static int js_host_form_set_selected(unsigned int node, int index)
  631. {
  632. struct form_state *fs;
  633. unsigned int n;
  634. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  635. return 0;
  636. fs = form_get(node, 1);
  637. if (!fs)
  638. return 0;
  639. n = form_option_count(node);
  640. if (index < 0)
  641. index = 0;
  642. if (n && (unsigned int)index >= n)
  643. index = (int)n - 1;
  644. fs->selected = (unsigned char)index;
  645. layout_valid = 0;
  646. ngui_invalidate(&ui);
  647. return 1;
  648. }
  649. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  650. {
  651. unsigned int i;
  652. int n = 0;
  653. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  654. doc.nodes[form].tag != BR_TAG_FORM)
  655. return 0;
  656. for (i = 0; i < doc.nnode && n < cap; i++) {
  657. struct br_node *nd = &doc.nodes[i];
  658. if (i == form || nd->type != BR_NODE_ELEM)
  659. continue;
  660. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  661. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  662. continue;
  663. if (!form_descendant(i, form))
  664. continue;
  665. out[n++] = i;
  666. }
  667. return n;
  668. }
  669. static int js_host_form_submit(unsigned int form)
  670. {
  671. form_submit_form(form, 0);
  672. return 1;
  673. }
  674. static int js_host_form_reset(unsigned int form)
  675. {
  676. form_reset_event(form);
  677. return 1;
  678. }
  679. static void css_computed_name(const char *p, char *out, int cap)
  680. {
  681. int n = 0;
  682. for (; p && *p && n + 2 < cap; p++) {
  683. char c = *p;
  684. if (c >= 'A' && c <= 'Z') {
  685. out[n++] = '-';
  686. c = (char)(c - 'A' + 'a');
  687. } else if (c == '_') {
  688. c = '-';
  689. } else if (c >= 'a' && c <= 'z') {
  690. /* keep */
  691. }
  692. out[n++] = c;
  693. }
  694. out[n] = '\0';
  695. if (!strcmp(out, "css-float"))
  696. strcpy(out, "float");
  697. }
  698. static void css_rgb(unsigned short c, char *buf, int cap)
  699. {
  700. int r = ((c >> 11) & 31) * 255 / 31;
  701. int g = ((c >> 5) & 63) * 255 / 63;
  702. int b = (c & 31) * 255 / 31;
  703. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  704. }
  705. static void css_mp_value(char *buf, int cap, int raw, int unit, int px)
  706. {
  707. if (unit == 4) {
  708. snprintf(buf, cap, "auto");
  709. } else if (unit == 0) {
  710. snprintf(buf, cap, "%dpx", raw);
  711. } else if (unit == 1) {
  712. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  713. } else if (unit == 2) {
  714. snprintf(buf, cap, "%d.%02dem", raw / 100, raw % 100);
  715. } else if (unit == 3) {
  716. snprintf(buf, cap, "%d.%02drem", raw / 100, raw % 100);
  717. } else {
  718. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  719. raw / 100, raw % 100, px);
  720. }
  721. }
  722. static int js_host_computed(unsigned int node, const char *property,
  723. char *buf, int cap)
  724. {
  725. struct br_style st;
  726. char name[40];
  727. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  728. return 0;
  729. buf[0] = '\0';
  730. css_computed_name(property, name, sizeof(name));
  731. style_for_node(node, &st);
  732. if (!strcmp(name, "display")) {
  733. const char *v = "inline";
  734. if (st.display == BR_DISPLAY_BLOCK)
  735. v = "block";
  736. else if (st.display == BR_DISPLAY_NONE)
  737. v = "none";
  738. else if (st.display == BR_DISPLAY_FLEX)
  739. v = "flex";
  740. else if (st.display == BR_DISPLAY_GRID)
  741. v = "grid";
  742. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  743. v = "inline-block";
  744. snprintf(buf, cap, "%s", v);
  745. } else if (!strcmp(name, "position")) {
  746. static const char *pos[] = {
  747. "static", "absolute", "fixed", "relative", "sticky"
  748. };
  749. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  750. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  751. int is_w = name[0] == 'w';
  752. int kind = is_w ? st.width_kind : st.height_kind;
  753. int val = is_w ? st.width : st.height;
  754. if (kind == 3) {
  755. if (is_w)
  756. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  757. st.width_calc_pct / 100,
  758. st.width_calc_pct % 100,
  759. st.width_calc_px);
  760. else
  761. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  762. st.height_calc_pct / 100,
  763. st.height_calc_pct % 100,
  764. st.height_calc_px);
  765. } else if (kind == 1) {
  766. snprintf(buf, cap, "%dpx", val);
  767. } else if (kind == 2) {
  768. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  769. } else {
  770. snprintf(buf, cap, "auto");
  771. }
  772. } else if (!strcmp(name, "color") ||
  773. !strcmp(name, "background-color")) {
  774. if (!strcmp(name, "background-color") && !st.has_bg)
  775. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  776. else
  777. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  778. } else if (!strcmp(name, "font-size")) {
  779. snprintf(buf, cap, "%dpx", st.font_px);
  780. } else if (!strcmp(name, "font-weight")) {
  781. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  782. } else if (!strcmp(name, "font-style")) {
  783. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  784. } else if (!strcmp(name, "font-family")) {
  785. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  786. br_font_face_family(st.font_face)[0])
  787. snprintf(buf, cap, "%s",
  788. br_font_face_family(st.font_face));
  789. else
  790. snprintf(buf, cap, "%s",
  791. st.mono ? "monospace" : "sans-serif");
  792. } else if (!strcmp(name, "text-align")) {
  793. static const char *al[] = { "left", "center", "right", "justify" };
  794. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  795. } else if (!strcmp(name, "float")) {
  796. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  797. st.float_left == 2 ? "right" : "none");
  798. } else if (!strcmp(name, "clear")) {
  799. static const char *cl[] = { "none", "left", "right", "both" };
  800. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  801. } else if (!strcmp(name, "opacity")) {
  802. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  803. } else if (!strcmp(name, "visibility")) {
  804. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  805. } else if (!strcmp(name, "overflow")) {
  806. snprintf(buf, cap, "%s",
  807. st.overflow_hidden ? "hidden" : "visible");
  808. } else if (!strcmp(name, "white-space")) {
  809. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  810. } else if (!strcmp(name, "text-transform")) {
  811. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  812. } else if (!strcmp(name, "box-sizing")) {
  813. snprintf(buf, cap, "%s",
  814. st.box_sizing ? "border-box" : "content-box");
  815. } else if (!strcmp(name, "line-height")) {
  816. if (st.line_h_px)
  817. snprintf(buf, cap, "%dpx", st.line_h_px);
  818. else if (st.line_h_pct)
  819. snprintf(buf, cap, "%d%%", st.line_h_pct);
  820. else
  821. snprintf(buf, cap, "normal");
  822. } else if (!strcmp(name, "z-index")) {
  823. if (st.z_set)
  824. snprintf(buf, cap, "%d", st.z_index);
  825. else
  826. snprintf(buf, cap, "auto");
  827. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  828. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  829. int set = name[0] == 't' ? st.top_set :
  830. name[0] == 'l' ? st.left_set :
  831. name[0] == 'r' ? st.right_set : st.bottom_set;
  832. int v = name[0] == 't' ? st.top :
  833. name[0] == 'l' ? st.left :
  834. name[0] == 'r' ? st.right : st.bottom;
  835. if (set)
  836. snprintf(buf, cap, "%dpx", v);
  837. else
  838. snprintf(buf, cap, "auto");
  839. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  840. !strcmp(name, "margin-bottom") ||
  841. !strcmp(name, "margin-left") ||
  842. !strcmp(name, "padding-top") ||
  843. !strcmp(name, "padding-right") ||
  844. !strcmp(name, "padding-bottom") ||
  845. !strcmp(name, "padding-left")) {
  846. int is_pad = name[0] == 'p';
  847. int side = name[strlen(name) - 1] == 'p' ? 0 :
  848. name[strlen(name) - 1] == 't' ? 1 :
  849. name[strlen(name) - 1] == 'm' ? 2 : 3;
  850. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  851. if (!strcmp(name, "margin-right") ||
  852. !strcmp(name, "padding-right"))
  853. side = 1;
  854. else if (!strcmp(name, "margin-bottom") ||
  855. !strcmp(name, "padding-bottom"))
  856. side = 2;
  857. else if (!strcmp(name, "margin-left") ||
  858. !strcmp(name, "padding-left"))
  859. side = 3;
  860. else
  861. side = 0;
  862. side += is_pad ? 4 : 0;
  863. css_mp_value(buf, cap,
  864. side == 0 ? st.mt : side == 1 ? st.mr :
  865. side == 2 ? st.mb : side == 3 ? st.ml :
  866. side == 4 ? st.pt : side == 5 ? st.pr :
  867. side == 6 ? st.pb : st.pl,
  868. st.mp_unit[side], st.mp_calc_px[side]);
  869. } else if (!strcmp(name, "border-top-width") ||
  870. !strcmp(name, "border-right-width") ||
  871. !strcmp(name, "border-bottom-width") ||
  872. !strcmp(name, "border-left-width")) {
  873. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  874. name[7] == 'b' ? 2 : 3;
  875. snprintf(buf, cap, "%dpx", st.border_w[side]);
  876. } else if (!strcmp(name, "border-top-color") ||
  877. !strcmp(name, "border-right-color") ||
  878. !strcmp(name, "border-bottom-color") ||
  879. !strcmp(name, "border-left-color")) {
  880. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  881. name[7] == 'b' ? 2 : 3;
  882. if (st.border_w[side])
  883. css_rgb(st.border_c[side], buf, cap);
  884. else
  885. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  886. } else if (!strcmp(name, "background-image")) {
  887. if (st.bg_image)
  888. snprintf(buf, cap, "url(\"%s\")",
  889. br_bg_image_url(st.bg_image - 1));
  890. else
  891. snprintf(buf, cap, "none");
  892. } else if (!strcmp(name, "background-repeat")) {
  893. static const char *rp[] = {
  894. "repeat", "no-repeat", "repeat-x", "repeat-y"
  895. };
  896. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  897. st.bg_repeat : 0]);
  898. } else if (!strcmp(name, "background-position")) {
  899. if (st.bg_pos_x_kind == 1)
  900. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  901. st.bg_pos_y);
  902. else
  903. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  904. st.bg_pos_y);
  905. } else if (!strcmp(name, "background-size")) {
  906. if (st.bg_size_kind == 3)
  907. snprintf(buf, cap, "cover");
  908. else if (st.bg_size_kind == 4)
  909. snprintf(buf, cap, "contain");
  910. else if (st.bg_size_kind == 1)
  911. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  912. st.bg_size_h);
  913. else if (st.bg_size_kind == 2)
  914. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  915. st.bg_size_h);
  916. else
  917. snprintf(buf, cap, "auto");
  918. } else if (!strcmp(name, "transform")) {
  919. char tmp[128];
  920. unsigned int n = 0;
  921. if (!st.transform_set) {
  922. snprintf(buf, cap, "none");
  923. } else {
  924. tmp[0] = '\0';
  925. if (st.tx || st.ty) {
  926. snprintf(tmp + n, sizeof(tmp) - n,
  927. "translate(%dpx, %dpx)", st.tx, st.ty);
  928. n = (unsigned int)strlen(tmp);
  929. }
  930. if (st.transform_scale) {
  931. snprintf(tmp + n, sizeof(tmp) - n,
  932. "%sscale(%d.%02d, %d.%02d)",
  933. n ? " " : "", st.scale_x / 100,
  934. st.scale_x % 100, st.scale_y / 100,
  935. st.scale_y % 100);
  936. n = (unsigned int)strlen(tmp);
  937. if (st.rotate_x100) {
  938. snprintf(tmp + n, sizeof(tmp) - n,
  939. " rotate(%d.%02ddeg)",
  940. st.rotate_x100 / 100,
  941. st.rotate_x100 % 100);
  942. }
  943. } else if (st.rotate_x100) {
  944. snprintf(tmp + n, sizeof(tmp) - n,
  945. "%srotate(%d.%02ddeg)",
  946. n ? " " : "", st.rotate_x100 / 100,
  947. st.rotate_x100 % 100);
  948. }
  949. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  950. }
  951. } else {
  952. return 0;
  953. }
  954. return buf[0] != '\0';
  955. }
  956. static int js_host_click(unsigned int node)
  957. {
  958. char url[BR_URL_MAX];
  959. const char *href;
  960. if (node >= doc.nnode)
  961. return 0;
  962. if (form_is_control(node)) {
  963. form_click(node);
  964. return 1;
  965. }
  966. href = br_href(&doc, node);
  967. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  968. return 0;
  969. s_copy(pending_url, url, sizeof(pending_url));
  970. pending_action |= ACT_NAV;
  971. cancel_fetch = 1;
  972. ngui_invalidate(&ui);
  973. return 1;
  974. }
  975. static int fetch_script_text(const char *url, unsigned char **out,
  976. unsigned int *outlen, char *err,
  977. unsigned int errcap);
  978. static void script_error(const char *what, const char *url, const char *why)
  979. {
  980. char msg[192];
  981. unsigned int n = 0;
  982. s_append(msg, &n, what, sizeof(msg));
  983. if (url && url[0]) {
  984. s_append(msg, &n, " ", sizeof(msg));
  985. s_append(msg, &n, url, sizeof(msg));
  986. }
  987. if (why && why[0]) {
  988. s_append(msg, &n, ": ", sizeof(msg));
  989. s_append(msg, &n, why, sizeof(msg));
  990. }
  991. js_host_report(msg);
  992. }
  993. /* Run the page's scripts in document order: external <script src> bodies are
  994. * fetched, inline bodies are copied because MuJS needs NUL-terminated text. */
  995. static void run_page_scripts(void)
  996. {
  997. struct js_browser_host host;
  998. unsigned int i;
  999. if (!doc.nscripts)
  1000. return;
  1001. host.status = js_host_status;
  1002. host.report = js_host_report;
  1003. host.navigate = js_host_navigate;
  1004. host.changed = js_host_changed;
  1005. host.rect = js_host_rect;
  1006. host.form_value = js_host_form_value;
  1007. host.form_checked = js_host_form_checked;
  1008. host.form_selected = js_host_form_selected;
  1009. host.form_set_value = js_host_form_set_value;
  1010. host.form_set_checked = js_host_form_set_checked;
  1011. host.form_set_selected = js_host_form_set_selected;
  1012. host.form_elements = js_host_form_elements;
  1013. host.form_submit = js_host_form_submit;
  1014. host.form_reset = js_host_form_reset;
  1015. host.click = js_host_click;
  1016. host.computed = js_host_computed;
  1017. host.page_url = page_url;
  1018. host.width = ui.w;
  1019. host.height = ui.h;
  1020. if (js_browser_start(&doc, &host) != 0) {
  1021. js_host_status("JavaScript: out of memory", 1);
  1022. return;
  1023. }
  1024. for (i = 0; i < doc.nscripts; i++) {
  1025. struct br_script *script = &doc.scripts[i];
  1026. if (script->src_off) {
  1027. const char *src_attr = doc.attrs + script->src_off;
  1028. char url[BR_URL_MAX];
  1029. unsigned char *data;
  1030. unsigned int len;
  1031. char err[64];
  1032. int rv;
  1033. if (!src_attr[0])
  1034. continue;
  1035. if (resolve_link(page_url, src_attr, url,
  1036. sizeof(url)) != 0) {
  1037. script_error("Cannot load script", src_attr,
  1038. "unsupported URL");
  1039. continue;
  1040. }
  1041. set_status("Loading script...", 0, 0);
  1042. rv = fetch_script_text(url, &data, &len, err,
  1043. sizeof(err));
  1044. if (rv == FETCH_ABORT)
  1045. break;
  1046. if (rv != 0) {
  1047. script_error("Cannot load script", url, err);
  1048. continue;
  1049. }
  1050. js_browser_run((const char *)data, url);
  1051. free(data);
  1052. } else {
  1053. unsigned int off = script->off;
  1054. unsigned int len = script->len;
  1055. unsigned int k;
  1056. char *src = (char *)malloc(len + 1);
  1057. if (!src) {
  1058. js_host_status("JavaScript: out of memory", 1);
  1059. break;
  1060. }
  1061. for (k = 0; k < len; k++)
  1062. src[k] = doc.script_src[off + k];
  1063. src[len] = '\0';
  1064. js_browser_run(src, page_url);
  1065. free(src);
  1066. }
  1067. if (pending_action)
  1068. break;
  1069. }
  1070. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1071. * load_home() stop it before the next navigation. */
  1072. if (doc.scripts_truncated && !js_last_error)
  1073. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1074. 1);
  1075. }
  1076. /* ---- images ---- */
  1077. static void image_reset(void)
  1078. {
  1079. int i;
  1080. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1081. images[i].state = 0;
  1082. images[i].native_w = images[i].native_h = 0;
  1083. images[i].err[0] = '\0';
  1084. }
  1085. image_count = 0;
  1086. preload_active = 0;
  1087. preload_pending = 0;
  1088. preload_wait = 0;
  1089. preload_node = 0;
  1090. preload_loaded = 0;
  1091. }
  1092. /* Decode into the shared arena, then copy/scale the result into a display
  1093. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  1094. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  1095. * pixels. Transparent edges are composited over white. */
  1096. static int decode_image_data(const unsigned char *data, unsigned int len,
  1097. struct br_image *bi)
  1098. {
  1099. struct img_info info;
  1100. struct img_options opt;
  1101. struct img_mem mem;
  1102. struct img_image decoded;
  1103. unsigned char *arena;
  1104. unsigned int est, bytes, i;
  1105. unsigned short *px;
  1106. unsigned char *alpha = 0;
  1107. int dw, dh, r;
  1108. if (img_sniff(data, len, &info) != 0) {
  1109. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  1110. return -1;
  1111. }
  1112. est = img_estimate(&info);
  1113. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  1114. s_copy(bi->err, "image too large", sizeof(bi->err));
  1115. return -1;
  1116. }
  1117. arena = (unsigned char *)malloc(est);
  1118. if (!arena) {
  1119. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1120. return -1;
  1121. }
  1122. img_mem_init(&mem, arena, est);
  1123. opt.max_pixels = BR_IMG_PIX_MAX;
  1124. r = img_decode(data, len, &opt, &mem, &decoded);
  1125. if (r != 0) {
  1126. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  1127. goto fail;
  1128. }
  1129. if (decoded.w == 0 || decoded.h == 0) {
  1130. s_copy(bi->err, "empty image", sizeof(bi->err));
  1131. goto fail;
  1132. }
  1133. bi->native_w = (int)decoded.w;
  1134. bi->native_h = (int)decoded.h;
  1135. dw = (int)decoded.w;
  1136. dh = (int)decoded.h;
  1137. if (dw > BR_IMG_LAYOUT_W) {
  1138. dh = (int)((unsigned int)decoded.h * BR_IMG_LAYOUT_W /
  1139. decoded.w);
  1140. dw = BR_IMG_LAYOUT_W;
  1141. }
  1142. if (dh < 1)
  1143. dh = 1;
  1144. if (dw < 1)
  1145. dw = 1;
  1146. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  1147. px = (unsigned short *)malloc(bytes);
  1148. if (!px) {
  1149. s_copy(bi->err, "out of memory", sizeof(bi->err));
  1150. goto fail;
  1151. }
  1152. /* Keep the alpha plane for the scaled image so transparent logos and
  1153. * icons composite over the page instead of the browser's dark theme
  1154. * background. Very large alpha images stay flattened to bound the
  1155. * heap use. */
  1156. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  1157. alpha = (unsigned char *)malloc((unsigned int)dw *
  1158. (unsigned int)dh);
  1159. if (alpha) {
  1160. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1161. alpha[i] = 255;
  1162. }
  1163. }
  1164. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  1165. px[i] = ui.theme.bg;
  1166. {
  1167. struct img_blit b;
  1168. b.dst = px;
  1169. b.dst_w = dw;
  1170. b.dst_h = dh;
  1171. b.clip_x = 0;
  1172. b.clip_y = 0;
  1173. b.clip_w = dw;
  1174. b.clip_h = dh;
  1175. b.x = 0;
  1176. b.y = 0;
  1177. b.scale = ((unsigned int)dw << 16) / decoded.w;
  1178. b.bg = ui.theme.bg;
  1179. b.bg2 = ui.theme.bg;
  1180. b.dst_a = alpha;
  1181. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  1182. img_draw(&decoded, &b);
  1183. }
  1184. bi->img.format = decoded.format;
  1185. bi->img.w = (unsigned int)dw;
  1186. bi->img.h = (unsigned int)dh;
  1187. bi->img.px = px;
  1188. bi->img.alpha = alpha;
  1189. bi->img.flags = 0;
  1190. bi->state = 1;
  1191. free(arena);
  1192. return 0;
  1193. fail:
  1194. free(arena);
  1195. return -1;
  1196. }
  1197. /* ---- URL / local path handling ---- */
  1198. static int is_http(const char *s)
  1199. {
  1200. return starts_with(s, "http://") || starts_with(s, "https://");
  1201. }
  1202. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  1203. static int normalize_abs(const char *in, char *out, unsigned int cap)
  1204. {
  1205. char seg[64];
  1206. unsigned int i = 0, o = 1;
  1207. int depth = 0;
  1208. int trailing;
  1209. if (!in || in[0] != '/' || cap < 2)
  1210. return -1;
  1211. trailing = 0;
  1212. {
  1213. unsigned int n = s_len(in);
  1214. if (n > 1 && in[n - 1] == '/')
  1215. trailing = 1;
  1216. }
  1217. out[0] = '/';
  1218. while (in[i]) {
  1219. unsigned int n = 0;
  1220. while (in[i] == '/')
  1221. i++;
  1222. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  1223. if (n + 1 < sizeof(seg))
  1224. seg[n++] = in[i];
  1225. i++;
  1226. }
  1227. seg[n] = '\0';
  1228. if (n == 0)
  1229. break;
  1230. if (s_eq(seg, "."))
  1231. continue;
  1232. if (s_eq(seg, "..")) {
  1233. if (depth > 0) {
  1234. while (o > 1 && out[o - 1] != '/')
  1235. o--;
  1236. if (o > 1)
  1237. o--;
  1238. depth--;
  1239. }
  1240. continue;
  1241. }
  1242. if (o > 1) {
  1243. if (o + 1 >= cap)
  1244. return -1;
  1245. out[o++] = '/';
  1246. }
  1247. if (o + n + 1 >= cap)
  1248. return -1;
  1249. {
  1250. unsigned int j;
  1251. for (j = 0; j < n; j++)
  1252. out[o++] = seg[j];
  1253. }
  1254. depth++;
  1255. }
  1256. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  1257. if (o + 1 >= cap)
  1258. return -1;
  1259. out[o++] = '/';
  1260. }
  1261. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  1262. if (in[i] == '?' || in[i] == '#') {
  1263. while (in[i]) {
  1264. if (o + 1 >= cap)
  1265. return -1;
  1266. out[o++] = in[i++];
  1267. }
  1268. }
  1269. out[o] = '\0';
  1270. return 0;
  1271. }
  1272. static void make_abs_local(const char *in, char *out, unsigned int cap)
  1273. {
  1274. char joined[BR_URL_MAX];
  1275. if (!in || !in[0]) {
  1276. s_copy(out, cwd[0] ? cwd : "/", cap);
  1277. return;
  1278. }
  1279. if (in[0] == '/') {
  1280. if (normalize_abs(in, out, cap) != 0)
  1281. s_copy(out, in, cap);
  1282. return;
  1283. }
  1284. {
  1285. unsigned int n = 0;
  1286. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  1287. s_append(joined, &n, "/", sizeof(joined));
  1288. s_append(joined, &n, in, sizeof(joined));
  1289. }
  1290. if (normalize_abs(joined, out, cap) != 0)
  1291. s_copy(out, joined, cap);
  1292. }
  1293. /* ---- canonical origin cache ---- *
  1294. *
  1295. * Sites commonly redirect http://host to https://host and then to
  1296. * https://www.host. Remember the final scheme/host of the last navigation so
  1297. * a bare domain typed again goes straight there instead of paying for two
  1298. * more connections and TLS handshakes. Only default-port requests are
  1299. * rewritten; explicit ports are left alone. */
  1300. #define ORIGIN_CACHE_MAX 8
  1301. #define ORIGIN_FILE "/share/borigins"
  1302. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  1303. UHTTP_HOST_MAX + 2))
  1304. struct origin_cache_entry {
  1305. char host[UHTTP_HOST_MAX];
  1306. char origin[UHTTP_HOST_MAX + 16];
  1307. };
  1308. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  1309. static int origin_count;
  1310. static char origin_buf[ORIGIN_BUF_SIZE];
  1311. static int default_port(const struct uhttp_url *u)
  1312. {
  1313. return u->secure ? u->port == 443 : u->port == 80;
  1314. }
  1315. static void url_origin(const struct uhttp_url *u, char *out,
  1316. unsigned int cap)
  1317. {
  1318. unsigned int n = 0;
  1319. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  1320. s_append(out, &n, u->host, cap);
  1321. if (!default_port(u)) {
  1322. s_append(out, &n, ":", cap);
  1323. s_append_dec(out, &n, u->port, cap);
  1324. }
  1325. }
  1326. static void origin_cache_apply(char *url, unsigned int cap)
  1327. {
  1328. struct uhttp_url u;
  1329. char out[BR_URL_MAX];
  1330. unsigned int n = 0;
  1331. int i;
  1332. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  1333. return;
  1334. for (i = 0; i < origin_count; i++) {
  1335. if (!s_eq(u.host, origins[i].host))
  1336. continue;
  1337. s_append(out, &n, origins[i].origin, sizeof(out));
  1338. s_append(out, &n, u.path, sizeof(out));
  1339. s_copy(url, out, cap);
  1340. return;
  1341. }
  1342. }
  1343. static void origin_cache_save(void)
  1344. {
  1345. unsigned int n = 0;
  1346. int i;
  1347. for (i = 0; i < origin_count; i++) {
  1348. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  1349. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  1350. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  1351. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  1352. }
  1353. if (n)
  1354. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  1355. (int)origin_buf, (int)n);
  1356. }
  1357. static void origin_cache_load(void)
  1358. {
  1359. char *p;
  1360. int rn;
  1361. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  1362. (int)(sizeof(origin_buf) - 1));
  1363. if (rn <= 0)
  1364. return;
  1365. origin_buf[rn] = '\0';
  1366. p = origin_buf;
  1367. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  1368. char *line = p, *origin;
  1369. while (*p && *p != '\n')
  1370. p++;
  1371. if (*p)
  1372. *p++ = '\0';
  1373. if (!line[0])
  1374. continue;
  1375. origin = line;
  1376. while (*origin && *origin != ' ')
  1377. origin++;
  1378. if (!*origin)
  1379. continue;
  1380. *origin++ = '\0';
  1381. if (!line[0] || !is_http(origin))
  1382. continue;
  1383. {
  1384. struct uhttp_url uo;
  1385. if (uhttp_parse_url(origin, &uo) != 0 ||
  1386. !s_eq(uo.path, "/"))
  1387. continue;
  1388. }
  1389. s_copy(origins[origin_count].host, line,
  1390. sizeof(origins[origin_count].host));
  1391. s_copy(origins[origin_count].origin, origin,
  1392. sizeof(origins[origin_count].origin));
  1393. origin_count++;
  1394. }
  1395. }
  1396. static int host_is_www_of(const char *host, const char *base)
  1397. {
  1398. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  1399. host[3] == '.' && s_eq(host + 4, base);
  1400. }
  1401. static void origin_cache_learn(const char *requested, const char *final)
  1402. {
  1403. struct uhttp_url from, to;
  1404. char origin[UHTTP_HOST_MAX + 16];
  1405. int i;
  1406. if (!is_http(requested) || !is_http(final))
  1407. return;
  1408. if (uhttp_parse_url(requested, &from) != 0 ||
  1409. uhttp_parse_url(final, &to) != 0)
  1410. return;
  1411. if (!default_port(&from))
  1412. return;
  1413. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  1414. from.port == to.port)
  1415. return;
  1416. /* Only remember origin-level canonicalisation: the same path, and
  1417. * either the same host or its www./apex sibling. A path- or
  1418. * host-specific redirect (a shortener, a login page) must not poison
  1419. * every request to the typed host. */
  1420. if (!s_eq(from.path, to.path))
  1421. return;
  1422. if (!s_eq(from.host, to.host) &&
  1423. !host_is_www_of(to.host, from.host) &&
  1424. !host_is_www_of(from.host, to.host))
  1425. return;
  1426. url_origin(&to, origin, sizeof(origin));
  1427. for (i = 0; i < origin_count; i++) {
  1428. if (s_eq(origins[i].host, from.host)) {
  1429. if (!s_eq(origins[i].origin, origin)) {
  1430. s_copy(origins[i].origin, origin,
  1431. sizeof(origins[i].origin));
  1432. origin_cache_save();
  1433. }
  1434. return;
  1435. }
  1436. }
  1437. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  1438. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  1439. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  1440. origin_cache_save();
  1441. }
  1442. static int path_dir(const char *path, char *out, unsigned int cap)
  1443. {
  1444. unsigned int i, last = 0;
  1445. for (i = 0; path[i]; i++)
  1446. if (path[i] == '/')
  1447. last = i;
  1448. if (last == 0) {
  1449. if (cap < 2)
  1450. return -1;
  1451. out[0] = '/';
  1452. out[1] = '\0';
  1453. return 0;
  1454. }
  1455. if (last + 1 >= cap)
  1456. return -1;
  1457. {
  1458. unsigned int j;
  1459. for (j = 0; j < last; j++)
  1460. out[j] = path[j];
  1461. out[last] = '\0';
  1462. }
  1463. return 0;
  1464. }
  1465. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  1466. static int resolve_link(const char *base, const char *href, char *out,
  1467. unsigned int cap)
  1468. {
  1469. char joined[BR_URL_MAX];
  1470. if (!href || !href[0] || href[0] == '#')
  1471. return -1;
  1472. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  1473. starts_with(href, "data:") || starts_with(href, "tel:"))
  1474. return -1;
  1475. if (starts_with(href, "about:")) {
  1476. s_copy(out, href, cap);
  1477. return 0;
  1478. }
  1479. if (is_http(href)) {
  1480. s_copy(out, href, cap);
  1481. return 0;
  1482. }
  1483. if (starts_with(href, "//")) {
  1484. if (is_http(base)) {
  1485. unsigned int n = 0;
  1486. s_append(out, &n, starts_with(base, "https:") ?
  1487. "https:" : "http:", cap);
  1488. s_append(out, &n, href, cap);
  1489. return 0;
  1490. }
  1491. return -1;
  1492. }
  1493. if (is_http(base)) {
  1494. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  1495. }
  1496. /* local page */
  1497. if (href[0] == '/') {
  1498. if (normalize_abs(href, out, cap) != 0)
  1499. return -1;
  1500. return 0;
  1501. }
  1502. {
  1503. char dir[BR_URL_MAX];
  1504. unsigned int n = 0;
  1505. if (s_eq(base, "about:home"))
  1506. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  1507. else if (path_dir(base, dir, sizeof(dir)) != 0)
  1508. s_copy(dir, "/", sizeof(dir));
  1509. s_append(joined, &n, dir, sizeof(joined));
  1510. if (n == 0 || joined[n - 1] != '/')
  1511. s_append(joined, &n, "/", sizeof(joined));
  1512. s_append(joined, &n, href, sizeof(joined));
  1513. }
  1514. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  1515. }
  1516. /* Best-effort decompression: keep the first `cap` bytes and discard the
  1517. * rest instead of failing when a page or stylesheet is larger than the
  1518. * buffer. The stream is still walked to the end, so a normal page is
  1519. * verified; a truncated compressed input still returns whatever was decoded
  1520. * so far. */
  1521. struct trunc_buf {
  1522. unsigned char *dst;
  1523. unsigned int cap, pos;
  1524. int full;
  1525. };
  1526. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  1527. {
  1528. struct trunc_buf *m = (struct trunc_buf *)ctx;
  1529. if (len > m->cap - m->pos) {
  1530. unsigned int room = m->cap - m->pos;
  1531. if (room) {
  1532. unsigned int i;
  1533. for (i = 0; i < room; i++)
  1534. m->dst[m->pos + i] = data[i];
  1535. m->pos += room;
  1536. }
  1537. m->full = 1;
  1538. return 0;
  1539. }
  1540. {
  1541. unsigned int i;
  1542. for (i = 0; i < len; i++)
  1543. m->dst[m->pos + i] = data[i];
  1544. }
  1545. m->pos += len;
  1546. return 0;
  1547. }
  1548. static void worker_wait_ui(void);
  1549. static void inflate_ui_pump(void *ctx)
  1550. {
  1551. static unsigned int last;
  1552. unsigned int now = u_ticks_ms();
  1553. (void)ctx;
  1554. if ((int)(now - last) >= 50) {
  1555. last = now;
  1556. worker_wait_ui();
  1557. }
  1558. }
  1559. static int inflate_trunc(const unsigned char *src, unsigned int len,
  1560. unsigned char *dst, unsigned int cap,
  1561. unsigned int *outlen, int gzip, int *truncated)
  1562. {
  1563. struct inflate_src in;
  1564. struct inflate_sink sink;
  1565. struct trunc_buf m;
  1566. unsigned int got = 0;
  1567. int r;
  1568. in.p = src;
  1569. in.len = len;
  1570. in.more = 0;
  1571. in.ctx = 0;
  1572. m.dst = dst;
  1573. m.cap = cap;
  1574. m.pos = 0;
  1575. m.full = 0;
  1576. sink.write = trunc_write;
  1577. sink.ctx = &m;
  1578. inflate_init(&image_inflate_ws, &in, &sink);
  1579. image_inflate_ws.progress = inflate_ui_pump;
  1580. image_inflate_ws.progress_ctx = 0;
  1581. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  1582. inflate_zlib(&image_inflate_ws, &got);
  1583. *outlen = m.pos;
  1584. *truncated = m.full || r != 0;
  1585. if (r != 0 && m.pos == 0)
  1586. return -1;
  1587. return 0;
  1588. }
  1589. /* ---- headless fetch helper ------------------------------------------- *
  1590. *
  1591. * Network I/O runs in a separate ring-3 process (`curl __fetch`): it writes
  1592. * the raw response and a small metadata file under /share. While it works,
  1593. * the browser keeps drawing and scrolling its own window, so a slow DNS/TLS
  1594. * handshake or a multi-megabyte body never freezes the UI.
  1595. */
  1596. #define FETCH_REQ "/share/bfreq"
  1597. #define FETCH_BODY "/share/bfbody"
  1598. #define FETCH_META "/share/bfmeta"
  1599. #define FETCH_DONE "/share/bfdone"
  1600. #define FETCH_POST "/share/bfpost"
  1601. struct fetch_meta {
  1602. int status;
  1603. int error;
  1604. int trunc;
  1605. unsigned int len;
  1606. char encoding[16];
  1607. char ctype[64];
  1608. char final[BR_URL_MAX];
  1609. };
  1610. static void draw(unsigned int *action);
  1611. static void handle_keys(unsigned int *action);
  1612. static void handle_page_click(unsigned int *action);
  1613. static int fetch_helper_tty = -2;
  1614. static int fetch_helper_pid = -1;
  1615. static unsigned int fetch_seq;
  1616. static struct fetch_meta fetch_meta;
  1617. static unsigned int meta_uint(char **pp)
  1618. {
  1619. char *p = *pp;
  1620. unsigned int v = 0;
  1621. while (*p >= '0' && *p <= '9') {
  1622. v = v * 10 + (unsigned int)(*p - '0');
  1623. p++;
  1624. }
  1625. while (*p && *p != '\n')
  1626. p++;
  1627. if (*p == '\n')
  1628. p++;
  1629. *pp = p;
  1630. return v;
  1631. }
  1632. static void meta_str(char **pp, char *out, unsigned int cap)
  1633. {
  1634. char *p = *pp;
  1635. unsigned int n = 0;
  1636. while (*p && *p != '\n' && n + 1 < cap)
  1637. out[n++] = *p++;
  1638. out[n] = '\0';
  1639. while (*p && *p != '\n')
  1640. p++;
  1641. if (*p == '\n')
  1642. p++;
  1643. *pp = p;
  1644. }
  1645. static void worker_wait_ui(void)
  1646. {
  1647. unsigned int action = 0;
  1648. if (!ngui_begin(&ui))
  1649. return;
  1650. draw(&action);
  1651. handle_keys(&action);
  1652. handle_page_click(&action);
  1653. if (action & ACT_WAIT_NAV) {
  1654. pending_action |= action & ACT_WAIT_NAV;
  1655. if ((action & ACT_NAV) && click_url[0])
  1656. s_copy(pending_url, click_url, sizeof(pending_url));
  1657. click_url[0] = '\0';
  1658. cancel_fetch = 1;
  1659. }
  1660. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  1661. ngui_invalidate(&ui);
  1662. ngui_end(&ui);
  1663. }
  1664. static void fetch_helper_stop(void)
  1665. {
  1666. int i;
  1667. if (fetch_helper_pid > 0) {
  1668. u_kill((unsigned int)fetch_helper_pid);
  1669. for (i = 0; i < 40 && u_alive((unsigned int)fetch_helper_pid); i++)
  1670. u_sleep_ms(5);
  1671. /* Let the reaper release the NIC before the next request. */
  1672. u_sleep_ms(10);
  1673. }
  1674. fetch_helper_pid = -1;
  1675. }
  1676. static int fetch_helper_start(char *err, unsigned int errcap)
  1677. {
  1678. if (fetch_helper_pid > 0 &&
  1679. u_alive((unsigned int)fetch_helper_pid))
  1680. return 0;
  1681. fetch_helper_pid = -1;
  1682. if (fetch_helper_tty == -2) {
  1683. int t = u_tty_create();
  1684. fetch_helper_tty = t > 0 ? t : 0;
  1685. }
  1686. fetch_helper_pid = u_spawn("/ramfs/bin/curl", "__serve",
  1687. fetch_helper_tty, "/");
  1688. if (fetch_helper_pid <= 0) {
  1689. fetch_helper_pid = -1;
  1690. s_copy(err, "cannot start network helper", errcap);
  1691. return -1;
  1692. }
  1693. return 0;
  1694. }
  1695. static int worker_fetch(const char *url, unsigned int cap,
  1696. const char *post, unsigned int post_len,
  1697. struct fetch_meta *m, char *err, unsigned int errcap)
  1698. {
  1699. static char req[768], meta[1024], done[24];
  1700. char *p;
  1701. unsigned int n = 0, deadline;
  1702. int rn, mseq, retried = 0;
  1703. struct sys_stat st;
  1704. if (cancel_fetch || pending_action)
  1705. return FETCH_ABORT;
  1706. if (u_stat("/share", &st) != 0 || !st.is_dir ||
  1707. u_stat("/ramfs/bin/curl", &st) != 0) {
  1708. s_copy(err, "network helper unavailable", errcap);
  1709. return -1;
  1710. }
  1711. fetch_seq++;
  1712. if (!fetch_seq)
  1713. fetch_seq = 1;
  1714. s_append_dec(req, &n, fetch_seq, sizeof(req));
  1715. s_append(req, &n, " ", sizeof(req));
  1716. s_append_dec(req, &n, cap, sizeof(req));
  1717. s_append(req, &n, " ", sizeof(req));
  1718. if (post_len) {
  1719. s_append(req, &n, "POST ", sizeof(req));
  1720. s_append_dec(req, &n, post_len, sizeof(req));
  1721. s_append(req, &n, " ", sizeof(req));
  1722. }
  1723. s_append(req, &n, url, sizeof(req));
  1724. s_append(req, &n, "\n", sizeof(req));
  1725. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)FETCH_POST,
  1726. (int)post, (int)post_len) < 0) {
  1727. s_copy(err, "cannot queue form body", errcap);
  1728. return -1;
  1729. }
  1730. u_syscall1(SYS_UNLINK, (int)FETCH_DONE);
  1731. u_syscall1(SYS_UNLINK, (int)FETCH_META);
  1732. if (u_syscall3(SYS_WRITE_FILE, (int)FETCH_REQ, (int)req, (int)n) < 0) {
  1733. s_copy(err, "cannot queue network request", errcap);
  1734. return -1;
  1735. }
  1736. if (fetch_helper_start(err, errcap) != 0)
  1737. return -1;
  1738. deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  1739. for (;;) {
  1740. worker_wait_ui();
  1741. if (cancel_fetch || pending_action) {
  1742. fetch_helper_stop();
  1743. return FETCH_ABORT;
  1744. }
  1745. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_DONE, (int)done,
  1746. (int)(sizeof(done) - 1));
  1747. if (rn > 0) {
  1748. done[rn] = '\0';
  1749. p = done;
  1750. mseq = (int)meta_uint(&p);
  1751. if (mseq == (int)fetch_seq)
  1752. break;
  1753. }
  1754. if (!u_alive((unsigned int)fetch_helper_pid)) {
  1755. fetch_helper_pid = -1;
  1756. if (!retried && fetch_helper_start(err, errcap) == 0) {
  1757. retried = 1;
  1758. continue;
  1759. }
  1760. s_copy(err, "network helper stopped", errcap);
  1761. return -1;
  1762. }
  1763. if ((int)(u_ticks_ms() - deadline) >= 0) {
  1764. fetch_helper_stop();
  1765. s_copy(err, "network request timed out", errcap);
  1766. return -1;
  1767. }
  1768. u_sleep_ms(20);
  1769. }
  1770. if (cancel_fetch || pending_action)
  1771. return FETCH_ABORT;
  1772. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_META, (int)meta,
  1773. (int)(sizeof(meta) - 1));
  1774. if (rn <= 0) {
  1775. s_copy(err, "network helper failed", errcap);
  1776. return -1;
  1777. }
  1778. meta[rn] = '\0';
  1779. p = meta;
  1780. mseq = (int)meta_uint(&p);
  1781. if (mseq != (int)fetch_seq) {
  1782. s_copy(err, "stale network response", errcap);
  1783. return -1;
  1784. }
  1785. m->status = (int)meta_uint(&p);
  1786. m->error = (int)meta_uint(&p);
  1787. m->trunc = (int)meta_uint(&p);
  1788. meta_str(&p, m->encoding, sizeof(m->encoding));
  1789. meta_str(&p, m->ctype, sizeof(m->ctype));
  1790. meta_str(&p, m->final, sizeof(m->final));
  1791. m->len = meta_uint(&p);
  1792. if (m->error) {
  1793. s_copy(err, uhttp_error_string(m->error), errcap);
  1794. return -1;
  1795. }
  1796. return 0;
  1797. }
  1798. static int fetch_remote(const char *url, unsigned int cap,
  1799. const char *post, unsigned int post_len,
  1800. unsigned char *plain, unsigned int plaincap,
  1801. unsigned char *comp, unsigned int compcap,
  1802. struct fetch_meta *m, int *truncated,
  1803. char *err, unsigned int errcap)
  1804. {
  1805. int rv, zr, was_trunc;
  1806. rv = worker_fetch(url, cap, post, post_len, m, err, errcap);
  1807. if (rv == FETCH_ABORT)
  1808. return FETCH_ABORT;
  1809. if (rv != 0)
  1810. return -1;
  1811. if (contains_ci(m->encoding, "gzip") ||
  1812. contains_ci(m->encoding, "deflate")) {
  1813. unsigned int comp_len = 0, plen = 0;
  1814. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)comp,
  1815. (int)compcap);
  1816. if (rv < 0) {
  1817. s_copy(err, "empty response", errcap);
  1818. return -1;
  1819. }
  1820. comp_len = (unsigned int)rv;
  1821. if (comp_len < m->len) {
  1822. s_copy(err, "compressed response is too large", errcap);
  1823. return -1;
  1824. }
  1825. if (contains_ci(m->encoding, "deflate"))
  1826. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  1827. &plen, 0, &was_trunc);
  1828. else
  1829. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  1830. &plen, 1, &was_trunc);
  1831. if (zr != 0) {
  1832. s_copy(err, "compressed response is corrupt", errcap);
  1833. return -1;
  1834. }
  1835. *truncated = m->trunc || was_trunc;
  1836. return (cancel_fetch || pending_action) ? FETCH_ABORT :
  1837. (int)plen;
  1838. }
  1839. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)plain,
  1840. (int)plaincap);
  1841. if (rv < 0) {
  1842. s_copy(err, "empty response", errcap);
  1843. return -1;
  1844. }
  1845. *truncated = m->trunc || ((unsigned int)rv < m->len);
  1846. return (cancel_fetch || pending_action) ? FETCH_ABORT : rv;
  1847. }
  1848. /* ---- HTTP / file fetch ---- */
  1849. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  1850. unsigned int *outlen, int *is_local, char *ctype,
  1851. unsigned int ctcap, char *final, unsigned int finalcap,
  1852. char *err, unsigned int errcap, int *truncated,
  1853. const char *post, unsigned int post_len)
  1854. {
  1855. unsigned char *buf;
  1856. unsigned int len;
  1857. int tr = 0;
  1858. int rv;
  1859. *out = 0;
  1860. *outlen = 0;
  1861. *truncated = 0;
  1862. if (final && finalcap)
  1863. final[0] = '\0';
  1864. if (ctype && ctcap)
  1865. ctype[0] = '\0';
  1866. if (url[0] == '/') {
  1867. char pathbuf[BR_URL_MAX];
  1868. const char *open_url = url;
  1869. unsigned int i = 0;
  1870. /* A local form GET keeps ?query in the address bar but the
  1871. * file lookup uses the path alone, like a real browser. */
  1872. while (url[i] && url[i] != '?' && url[i] != '#')
  1873. i++;
  1874. if (url[i]) {
  1875. s_copy(pathbuf, url, i + 1);
  1876. open_url = pathbuf;
  1877. }
  1878. buf = (unsigned char *)malloc(cap);
  1879. if (!buf) {
  1880. s_copy(err, "out of memory", errcap);
  1881. return -1;
  1882. }
  1883. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  1884. if (rv < 0) {
  1885. free(buf);
  1886. s_copy(err, "file not found", errcap);
  1887. return -1;
  1888. }
  1889. *out = buf;
  1890. *outlen = (unsigned int)rv;
  1891. *is_local = 1;
  1892. if (ctype)
  1893. s_copy(ctype, "text/html", ctcap);
  1894. if (final)
  1895. s_copy(final, url, finalcap);
  1896. if ((unsigned int)rv == cap)
  1897. *truncated = 1;
  1898. return 0;
  1899. }
  1900. buf = (unsigned char *)malloc(cap);
  1901. if (!buf) {
  1902. s_copy(err, "out of memory", errcap);
  1903. return -1;
  1904. }
  1905. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  1906. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  1907. if (rv == FETCH_ABORT) {
  1908. free(buf);
  1909. return FETCH_ABORT;
  1910. }
  1911. if (rv < 0) {
  1912. free(buf);
  1913. return -1;
  1914. }
  1915. len = (unsigned int)rv;
  1916. if (len == 0) {
  1917. free(buf);
  1918. s_copy(err, "empty response", errcap);
  1919. return -1;
  1920. }
  1921. if (ctype)
  1922. s_copy(ctype, fetch_meta.ctype, ctcap);
  1923. if (final && fetch_meta.final[0])
  1924. s_copy(final, fetch_meta.final, finalcap);
  1925. *is_local = 0;
  1926. *out = buf;
  1927. *outlen = len;
  1928. *truncated = tr;
  1929. return 0;
  1930. }
  1931. /* Load every @font-face the parser registered. Local files go through
  1932. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  1933. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  1934. * to the built-in regular/bold/italic/mono set. */
  1935. static void load_font_faces(void)
  1936. {
  1937. unsigned int i;
  1938. memset(font_faces, 0, sizeof(font_faces));
  1939. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  1940. i <= BR_MAX_FACES; i++) {
  1941. const char *url = br_font_face_url((int)i);
  1942. const char *base = br_font_face_base((int)i);
  1943. char abs[BR_URL_MAX];
  1944. if (!url || !url[0])
  1945. continue;
  1946. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  1947. sizeof(abs)) != 0)
  1948. continue;
  1949. if (abs[0] == '/') {
  1950. font_faces[i - 1] = ufont_face_open_path(abs);
  1951. } else if (is_http(abs)) {
  1952. unsigned char *buf;
  1953. char err[64];
  1954. int rv, tr = 0;
  1955. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  1956. if (!buf)
  1957. continue;
  1958. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  1959. UFONT_MAX_FILE, image_io_buf,
  1960. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  1961. err, sizeof(err));
  1962. if (rv > 0)
  1963. font_faces[i - 1] = ufont_face_open_mem(buf,
  1964. rv);
  1965. free(buf);
  1966. }
  1967. }
  1968. }
  1969. /* Remote scripts are cached under /share for the current boot, like the
  1970. * stylesheet cache, so reloads and later visits skip the network. */
  1971. static int script_cache_count;
  1972. static unsigned int script_cache_hash(const char *s)
  1973. {
  1974. unsigned int h = 2166136261u;
  1975. while (*s) {
  1976. h ^= (unsigned char)*s++;
  1977. h *= 16777619u;
  1978. }
  1979. return h;
  1980. }
  1981. static void script_cache_path(const char *url, char *out, unsigned int cap)
  1982. {
  1983. unsigned int n = 0;
  1984. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  1985. s_append_dec(out, &n, script_cache_hash(url), cap);
  1986. }
  1987. static void script_cache_clear(void)
  1988. {
  1989. struct sys_dirent d;
  1990. char path[96];
  1991. for (;;) {
  1992. int i, found = 0;
  1993. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  1994. (int)&d) == 1; i++) {
  1995. unsigned int n = 0;
  1996. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  1997. continue;
  1998. s_append(path, &n, "/share/", sizeof(path));
  1999. s_append(path, &n, d.name, sizeof(path));
  2000. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2001. return;
  2002. found = 1;
  2003. break;
  2004. }
  2005. if (!found)
  2006. break;
  2007. }
  2008. script_cache_count = 0;
  2009. }
  2010. static void script_cache_init(void)
  2011. {
  2012. struct sys_dirent d;
  2013. int i, count = 0;
  2014. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2015. (int)&d) == 1; i++)
  2016. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  2017. count++;
  2018. if (count >= SCRIPT_CACHE_MAX) {
  2019. script_cache_clear();
  2020. return;
  2021. }
  2022. script_cache_count = count;
  2023. }
  2024. static int script_cache_get(const char *url, unsigned char **out,
  2025. unsigned int *outlen)
  2026. {
  2027. char path[96];
  2028. struct sys_stat st;
  2029. unsigned char *buf;
  2030. int rn;
  2031. script_cache_path(url, path, sizeof(path));
  2032. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  2033. st.size >= SCRIPT_CACHE_FILE_MAX)
  2034. return 0;
  2035. buf = (unsigned char *)malloc(st.size + 1);
  2036. if (!buf)
  2037. return 0;
  2038. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  2039. if (rn != (int)st.size) {
  2040. free(buf);
  2041. return 0;
  2042. }
  2043. buf[st.size] = '\0';
  2044. *out = buf;
  2045. *outlen = st.size;
  2046. return 1;
  2047. }
  2048. static void script_cache_put(const char *url, const unsigned char *data,
  2049. unsigned int len)
  2050. {
  2051. char path[96];
  2052. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  2053. len >= SCRIPT_CACHE_FILE_MAX)
  2054. return;
  2055. script_cache_path(url, path, sizeof(path));
  2056. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2057. (int)len) >= 0)
  2058. script_cache_count++;
  2059. }
  2060. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  2061. static int fetch_script_text(const char *url, unsigned char **out,
  2062. unsigned int *outlen, char *err,
  2063. unsigned int errcap)
  2064. {
  2065. unsigned char *buf;
  2066. unsigned int len;
  2067. int local, truncated = 0;
  2068. char ctype[64], final[BR_URL_MAX];
  2069. int rv;
  2070. *out = 0;
  2071. *outlen = 0;
  2072. if (url[0] != '/' && script_cache_get(url, out, outlen))
  2073. return 0;
  2074. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  2075. sizeof(ctype), final, sizeof(final), err, errcap,
  2076. &truncated, 0, 0);
  2077. if (rv != 0)
  2078. return rv;
  2079. if (truncated || len >= BR_SCRIPT_MAX) {
  2080. free(buf);
  2081. s_copy(err, "script is too large", errcap);
  2082. return -1;
  2083. }
  2084. buf[len] = '\0';
  2085. if (!local)
  2086. script_cache_put(url, buf, len);
  2087. *out = buf;
  2088. *outlen = len;
  2089. return 0;
  2090. }
  2091. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  2092. * the heap, so images must not allocate their file body from it as well. */
  2093. static int fetch_image(const char *url, unsigned int cap,
  2094. unsigned char **out, unsigned int *outlen,
  2095. char *err, unsigned int errcap)
  2096. {
  2097. unsigned int len;
  2098. int tr = 0;
  2099. int rv;
  2100. *out = 0;
  2101. *outlen = 0;
  2102. if (cap > BR_IMG_FILE_MAX)
  2103. cap = BR_IMG_FILE_MAX;
  2104. if (url[0] == '/') {
  2105. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  2106. (int)cap);
  2107. if (rv < 0) {
  2108. s_copy(err, "file not found", errcap);
  2109. return -1;
  2110. }
  2111. *out = image_file_buf;
  2112. *outlen = (unsigned int)rv;
  2113. return 0;
  2114. }
  2115. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  2116. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  2117. if (rv == FETCH_ABORT)
  2118. return FETCH_ABORT;
  2119. if (rv < 0)
  2120. return -1;
  2121. len = (unsigned int)rv;
  2122. if (len == 0) {
  2123. s_copy(err, "empty image", errcap);
  2124. return -1;
  2125. }
  2126. *out = image_file_buf;
  2127. *outlen = len;
  2128. return 0;
  2129. }
  2130. /* Remote stylesheets are immutable enough for the current boot: keep
  2131. * successful responses under /share so a reload, a second visit or a fresh
  2132. * browser launch does not fetch the same five sheets over the network again.
  2133. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  2134. static int css_cache_count;
  2135. static unsigned int css_cache_hash(const char *s)
  2136. {
  2137. unsigned int h = 2166136261u;
  2138. while (*s) {
  2139. h ^= (unsigned char)*s++;
  2140. h *= 16777619u;
  2141. }
  2142. return h;
  2143. }
  2144. static void css_cache_path(const char *url, char *out, unsigned int cap)
  2145. {
  2146. unsigned int n = 0;
  2147. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  2148. s_append_dec(out, &n, css_cache_hash(url), cap);
  2149. }
  2150. static void css_cache_clear(void)
  2151. {
  2152. struct sys_dirent d;
  2153. char path[96];
  2154. for (;;) {
  2155. int i, found = 0;
  2156. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2157. (int)&d) == 1; i++) {
  2158. unsigned int n = 0;
  2159. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  2160. continue;
  2161. s_append(path, &n, "/share/", sizeof(path));
  2162. s_append(path, &n, d.name, sizeof(path));
  2163. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  2164. return;
  2165. found = 1;
  2166. break;
  2167. }
  2168. if (!found)
  2169. break;
  2170. }
  2171. css_cache_count = 0;
  2172. }
  2173. static void css_cache_init(void)
  2174. {
  2175. struct sys_dirent d;
  2176. int i, count = 0;
  2177. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  2178. (int)&d) == 1; i++)
  2179. if (starts_with(d.name, CSS_CACHE_PREFIX))
  2180. count++;
  2181. if (count >= CSS_CACHE_MAX) {
  2182. css_cache_clear();
  2183. return;
  2184. }
  2185. css_cache_count = count;
  2186. }
  2187. static int css_cache_get(const char *url, unsigned char **out,
  2188. unsigned int *outlen)
  2189. {
  2190. char path[96];
  2191. int rn;
  2192. css_cache_path(url, path, sizeof(path));
  2193. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  2194. (int)CSS_CACHE_FILE_MAX);
  2195. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  2196. return 0;
  2197. *out = image_io_buf;
  2198. *outlen = (unsigned int)rn;
  2199. return 1;
  2200. }
  2201. static void css_cache_put(const char *url, const unsigned char *data,
  2202. unsigned int len)
  2203. {
  2204. char path[96];
  2205. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  2206. len >= CSS_CACHE_FILE_MAX)
  2207. return;
  2208. css_cache_path(url, path, sizeof(path));
  2209. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  2210. (int)len) >= 0)
  2211. css_cache_count++;
  2212. }
  2213. /* Read one stylesheet into the shared static buffer. CSS is parsed
  2214. * immediately, so it does not need the page heap; this leaves the heap for
  2215. * the 2 MB page body, the rules and the scaled image bitmaps. */
  2216. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  2217. char *err, unsigned int errcap)
  2218. {
  2219. unsigned int len;
  2220. int tr = 0;
  2221. int rv;
  2222. *out = 0;
  2223. *outlen = 0;
  2224. if (url[0] == '/') {
  2225. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  2226. (int)BR_CSS_MAX);
  2227. if (rv < 0) {
  2228. s_copy(err, "stylesheet not found", errcap);
  2229. return -1;
  2230. }
  2231. *out = image_io_buf;
  2232. *outlen = (unsigned int)rv;
  2233. return 0;
  2234. }
  2235. if (css_cache_get(url, out, outlen))
  2236. return 0;
  2237. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  2238. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  2239. &fetch_meta, &tr, err, errcap);
  2240. if (rv == FETCH_ABORT)
  2241. return FETCH_ABORT;
  2242. if (rv < 0)
  2243. return -1;
  2244. len = (unsigned int)rv;
  2245. if (len == 0) {
  2246. s_copy(err, "empty stylesheet", errcap);
  2247. return -1;
  2248. }
  2249. *out = image_io_buf;
  2250. *outlen = len;
  2251. css_cache_put(url, image_io_buf, len);
  2252. return 0;
  2253. }
  2254. static void redraw_now(void);
  2255. static char error_page[1024];
  2256. static void show_error(const char *title, const char *detail)
  2257. {
  2258. char *page = error_page;
  2259. unsigned int n = 0;
  2260. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  2261. s_append(page, &n, title, sizeof(error_page));
  2262. s_append(page, &n, "</h2><p>", sizeof(error_page));
  2263. {
  2264. const char *p = detail;
  2265. while (*p && n + 1 < sizeof(error_page)) {
  2266. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  2267. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  2268. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  2269. else page[n++] = *p;
  2270. p++;
  2271. }
  2272. }
  2273. page[n] = '\0';
  2274. s_append(page, &n, "</p><p>", sizeof(error_page));
  2275. s_append(page, &n, page_url, sizeof(error_page));
  2276. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  2277. sizeof(error_page));
  2278. br_parse(&doc, page, n);
  2279. layout_valid = 0;
  2280. preload_active = 0;
  2281. preload_pending = 0;
  2282. preload_wait = 0;
  2283. s_copy(page_title, title, sizeof(page_title));
  2284. page_loading = 0;
  2285. set_status(title, 1, 0);
  2286. ngui_invalidate(&ui);
  2287. }
  2288. static int decode_direct_image(const unsigned char *data, unsigned int len,
  2289. unsigned int node)
  2290. {
  2291. if (image_count >= BR_MAX_IMAGES)
  2292. return -1;
  2293. if (decode_image_data(data, len, &images[0]) != 0)
  2294. return -1;
  2295. doc.nodes[node].img_index = 0;
  2296. image_count = 1;
  2297. return 0;
  2298. }
  2299. static int ancestor_is(unsigned int node, unsigned int tag)
  2300. {
  2301. unsigned int p = doc.nodes[node].parent;
  2302. while (p) {
  2303. if (doc.nodes[p].tag == tag)
  2304. return 1;
  2305. p = doc.nodes[p].parent;
  2306. }
  2307. return 0;
  2308. }
  2309. static int load_stylesheets(void)
  2310. {
  2311. static char seen[BR_MAX_SHEETS][BR_URL_MAX];
  2312. unsigned int i, sheets = 0, nseen = 0;
  2313. for (i = 0; i < doc.nnode && sheets < BR_MAX_SHEETS; i++) {
  2314. struct br_node *nd = &doc.nodes[i];
  2315. const char *rel, *href;
  2316. char url[BR_URL_MAX];
  2317. unsigned char *data;
  2318. unsigned int len;
  2319. char err[64];
  2320. int rv;
  2321. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  2322. continue;
  2323. rel = br_rel(&doc, i);
  2324. if (!contains_ci(rel, "stylesheet"))
  2325. continue;
  2326. href = br_href(&doc, i);
  2327. if (!href[0])
  2328. continue;
  2329. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  2330. continue;
  2331. {
  2332. unsigned int k;
  2333. int dup = 0;
  2334. for (k = 0; k < nseen; k++)
  2335. if (s_eq(seen[k], url)) {
  2336. dup = 1;
  2337. break;
  2338. }
  2339. if (dup)
  2340. continue;
  2341. if (nseen < BR_MAX_SHEETS) {
  2342. s_copy(seen[nseen], url, BR_URL_MAX);
  2343. nseen++;
  2344. }
  2345. }
  2346. rv = fetch_css(url, &data, &len, err, sizeof(err));
  2347. if (rv == FETCH_ABORT)
  2348. return FETCH_ABORT;
  2349. if (rv != 0)
  2350. continue;
  2351. if (len) {
  2352. br_set_font_base(url);
  2353. br_parse_css_text(&doc, (const char *)data, len);
  2354. }
  2355. sheets++;
  2356. }
  2357. br_set_font_base(page_url);
  2358. br_parse_inline_css(&doc);
  2359. load_font_faces();
  2360. br_reset_styles(&doc);
  2361. layout_valid = 0;
  2362. return 0;
  2363. }
  2364. static void preload_begin(void)
  2365. {
  2366. preload_active = 1;
  2367. preload_pending = 0;
  2368. preload_wait = 1;
  2369. preload_node = 0;
  2370. preload_loaded = 0;
  2371. preload_scroll = 0;
  2372. }
  2373. /* Styles are computed top-down during layout, but images inside a hidden
  2374. * menu/carousel are never visited and keep img_top == 0. Without this check
  2375. * the preloader walks the DOM in node order and spends the whole image
  2376. * budget on logos and off-canvas thumbnails the reader cannot see. */
  2377. static int node_hidden(unsigned int node)
  2378. {
  2379. unsigned int path[32], n = 0, p = node, i;
  2380. struct br_style st, parent;
  2381. while (p && n < sizeof(path) / sizeof(path[0])) {
  2382. path[n++] = p;
  2383. p = doc.nodes[p].parent;
  2384. }
  2385. parent = (struct br_style){0};
  2386. parent.font_px = 16;
  2387. parent.display = BR_DISPLAY_BLOCK;
  2388. for (i = n; i > 0; i--) {
  2389. br_style_for(&doc, path[i - 1], &parent, &st);
  2390. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  2391. st.opacity_hidden)
  2392. return 1;
  2393. parent = st;
  2394. }
  2395. return 0;
  2396. }
  2397. static struct br_style base_style(void);
  2398. static void style_for_node(unsigned int node, struct br_style *out)
  2399. {
  2400. unsigned int p = doc.nodes[node].parent;
  2401. struct br_style parent;
  2402. if (p) {
  2403. style_for_node(p, &parent);
  2404. br_style_for(&doc, node, &parent, out);
  2405. } else {
  2406. parent = base_style();
  2407. br_style_for(&doc, node, &parent, out);
  2408. }
  2409. }
  2410. /* Load at most one image per call. Images below the current viewport are
  2411. * left pending until the page is scrolled; this keeps a long article with
  2412. * many 4K screenshots from stalling on content the user cannot see yet. */
  2413. static void preload_step(void)
  2414. {
  2415. unsigned int batch = 0;
  2416. while (preload_active && preload_node < doc.nnode) {
  2417. unsigned int i = preload_node;
  2418. struct br_node *nd = &doc.nodes[i];
  2419. const char *src;
  2420. char url[BR_URL_MAX];
  2421. unsigned char *data;
  2422. unsigned int len;
  2423. char err[64];
  2424. char msg[64];
  2425. unsigned int n = 0;
  2426. int rv;
  2427. if (nd->type != BR_NODE_ELEM) {
  2428. preload_node++;
  2429. continue;
  2430. }
  2431. if (nd->tag != BR_TAG_IMG) {
  2432. if (nd->bg_img_index == -1) {
  2433. struct br_style bs;
  2434. style_for_node(i, &bs);
  2435. if (bs.display != BR_DISPLAY_NONE &&
  2436. !bs.vis_hidden && bs.bg_image) {
  2437. const char *bsrc =
  2438. br_bg_image_url(bs.bg_image - 1);
  2439. if (bsrc[0] &&
  2440. !contains_ci(bsrc, ".svg") &&
  2441. !starts_with(bsrc, "data:") &&
  2442. resolve_link(page_url, bsrc, url,
  2443. sizeof(url)) == 0) {
  2444. if (image_count >=
  2445. BR_MAX_IMAGES) {
  2446. preload_node =
  2447. doc.nnode;
  2448. break;
  2449. }
  2450. preload_node = i + 1;
  2451. data = 0;
  2452. len = 0;
  2453. rv = fetch_image(url,
  2454. BR_IMG_FILE_MAX,
  2455. &data, &len,
  2456. err, sizeof(err));
  2457. if (rv == FETCH_ABORT) {
  2458. preload_active = 0;
  2459. preload_pending = 0;
  2460. return;
  2461. }
  2462. if (rv == 0 &&
  2463. decode_image_data(
  2464. data, len,
  2465. &images[image_count]) == 0) {
  2466. nd->bg_img_index =
  2467. (short)image_count;
  2468. image_count++;
  2469. preload_loaded++;
  2470. layout_valid = 0;
  2471. } else {
  2472. nd->bg_img_index = -2;
  2473. }
  2474. ngui_invalidate(&ui);
  2475. if (++batch >= 4)
  2476. return;
  2477. continue;
  2478. }
  2479. }
  2480. nd->bg_img_index = -2;
  2481. }
  2482. preload_node++;
  2483. continue;
  2484. }
  2485. if (nd->img_index != -1) {
  2486. preload_node++;
  2487. continue;
  2488. }
  2489. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  2490. preload_node++;
  2491. continue;
  2492. }
  2493. src = br_src(&doc, i);
  2494. if (!src[0] || contains_ci(src, ".svg") ||
  2495. starts_with(src, "data:")) {
  2496. preload_node++;
  2497. continue;
  2498. }
  2499. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  2500. preload_node++;
  2501. continue;
  2502. }
  2503. if (image_count >= BR_MAX_IMAGES) {
  2504. preload_node = doc.nnode;
  2505. break;
  2506. }
  2507. /* Do not stop at the first below-fold image: DOM order is
  2508. * not visual order, and a footer/ad image early in the DOM
  2509. * used to hide every later article image from the loader. */
  2510. if (img_top[i] >
  2511. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  2512. preload_pending = 1;
  2513. preload_node++;
  2514. continue;
  2515. }
  2516. preload_node = i + 1;
  2517. s_append(msg, &n, "Loading images ", sizeof(msg));
  2518. s_append_dec(msg, &n, (unsigned int)preload_loaded + 1,
  2519. sizeof(msg));
  2520. s_append(msg, &n, "...", sizeof(msg));
  2521. set_status(msg, 0, 0);
  2522. ngui_invalidate(&ui);
  2523. data = 0;
  2524. len = 0;
  2525. rv = fetch_image(url, BR_IMG_FILE_MAX, &data, &len, err,
  2526. sizeof(err));
  2527. if (rv == FETCH_ABORT) {
  2528. preload_active = 0;
  2529. preload_pending = 0;
  2530. return;
  2531. }
  2532. if (rv == 0 &&
  2533. decode_image_data(data, len, &images[image_count]) == 0) {
  2534. nd->img_index = (short)image_count;
  2535. image_count++;
  2536. preload_loaded++;
  2537. layout_valid = 0;
  2538. } else {
  2539. /* Remember failures so a scroll does not retry an
  2540. * unreachable tracking/ad image with the full network
  2541. * timeout on every pass. */
  2542. nd->img_index = -2;
  2543. }
  2544. ngui_invalidate(&ui);
  2545. /* A full page layout after every image dominates loading on a
  2546. * long page. Decode a small batch, then let the main loop draw
  2547. * once for the whole batch. */
  2548. if (++batch >= 4)
  2549. return;
  2550. }
  2551. preload_active = 0;
  2552. if (preload_pending)
  2553. preload_scroll = page_scroll.offset;
  2554. else
  2555. preload_pending = 0;
  2556. set_status(post_status_text, post_status_error, post_status_ttl);
  2557. ngui_invalidate(&ui);
  2558. }
  2559. static void history_push(const char *url)
  2560. {
  2561. if (!url || !url[0])
  2562. return;
  2563. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  2564. s_eq(history[hist_pos], url))
  2565. return;
  2566. if (hist_len > 0 && hist_pos + 1 < hist_len)
  2567. hist_len = hist_pos + 1;
  2568. if (hist_len < BR_HISTORY) {
  2569. s_copy(history[hist_len], url, BR_URL_MAX);
  2570. hist_pos = hist_len;
  2571. hist_len++;
  2572. } else {
  2573. int i;
  2574. for (i = 1; i < BR_HISTORY; i++)
  2575. s_copy(history[i - 1], history[i], BR_URL_MAX);
  2576. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  2577. hist_pos = BR_HISTORY - 1;
  2578. }
  2579. }
  2580. static void load_page(const char *url, int local, int push)
  2581. {
  2582. unsigned char *body = 0;
  2583. unsigned int len = 0;
  2584. int truncated = 0;
  2585. struct img_info image_info;
  2586. char ctype[64];
  2587. char final[BR_URL_MAX];
  2588. char err[80];
  2589. const char *detail = 0;
  2590. const char *post = pending_post_len ? pending_post : 0;
  2591. unsigned int post_len = pending_post_len;
  2592. int rv;
  2593. final[0] = '\0';
  2594. pending_post_len = 0;
  2595. cancel_fetch = 0;
  2596. preload_active = 0;
  2597. preload_pending = 0;
  2598. js_browser_stop();
  2599. js_last_status[0] = '\0';
  2600. js_last_error = 0;
  2601. heap_clear();
  2602. image_reset();
  2603. form_reset_state();
  2604. layout_valid = 0;
  2605. page_scroll.offset = 0;
  2606. page_scroll.dragging = 0;
  2607. br_parse_plain(&doc, "", 0); /* blank while loading */
  2608. page_title[0] = '\0';
  2609. page_loading = 1;
  2610. page_is_local = local;
  2611. s_copy(page_url, url, sizeof(page_url));
  2612. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2613. url_in.len = s_len(url_in.text);
  2614. url_in.cursor = url_in.len;
  2615. url_in.scroll = 0;
  2616. ngui_set_focus(&ui, 0);
  2617. if (final[0])
  2618. final[0] = '\0';
  2619. if (push)
  2620. history_push(url);
  2621. set_status("Loading...", 0, 0);
  2622. ngui_invalidate(&ui);
  2623. /* heap_clear() detaches the fonts, so attach them again before the
  2624. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  2625. if (heap_start() != 0) {
  2626. show_error("Out of memory", "Cannot allocate the page buffer");
  2627. return;
  2628. }
  2629. ngui_font_attach(&ui);
  2630. redraw_now();
  2631. browser_rules_alloc();
  2632. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  2633. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  2634. &truncated, post, post_len);
  2635. if (rv == FETCH_ABORT)
  2636. return;
  2637. if (rv != 0) {
  2638. detail = err;
  2639. show_error("Cannot load this page", detail);
  2640. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2641. url_in.len = s_len(url_in.text);
  2642. url_in.cursor = url_in.len;
  2643. url_in.scroll = 0;
  2644. return;
  2645. }
  2646. if (!local)
  2647. origin_cache_learn(url, final[0] ? final : url);
  2648. page_is_local = local;
  2649. if (final[0]) {
  2650. s_copy(page_url, final, sizeof(page_url));
  2651. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2652. url_in.len = s_len(url_in.text);
  2653. url_in.cursor = url_in.len;
  2654. url_in.scroll = 0;
  2655. }
  2656. if (contains_ci(ctype, "text/plain")) {
  2657. br_parse_plain(&doc, (const char *)body, len);
  2658. } else if (contains_ci(ctype, "image/") ||
  2659. (!contains_ci(ctype, "text/html") &&
  2660. img_sniff(body, len, &image_info) == 0)) {
  2661. unsigned int node = br_parse_image_doc(&doc, page_url);
  2662. if (node)
  2663. decode_direct_image(body, len, node);
  2664. s_copy(page_title, "Image", sizeof(page_title));
  2665. } else {
  2666. br_set_viewport(ui.w);
  2667. br_parse(&doc, (const char *)body, len);
  2668. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  2669. sizeof(page_title));
  2670. if (load_stylesheets() == FETCH_ABORT)
  2671. return;
  2672. if (pending_action)
  2673. return;
  2674. }
  2675. preload_begin();
  2676. page_loading = 0;
  2677. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2678. url_in.len = s_len(url_in.text);
  2679. url_in.cursor = url_in.len;
  2680. url_in.scroll = 0;
  2681. ngui_set_focus(&ui, 0);
  2682. /* Paint the parsed page before fetching/running scripts. A slow
  2683. * remote <script src> then does not hide the page behind the loading
  2684. * screen; the fetch helper pumps this UI while it waits. */
  2685. set_status("Loading scripts...", 0, 0);
  2686. redraw_now();
  2687. run_page_scripts();
  2688. if (pending_action)
  2689. return;
  2690. post_status_text[0] = '\0';
  2691. post_status_error = 0;
  2692. post_status_ttl = 0;
  2693. if (js_last_status[0]) {
  2694. s_copy(post_status_text, js_last_status,
  2695. sizeof(post_status_text));
  2696. post_status_error = js_last_error;
  2697. post_status_ttl = 8000;
  2698. } else if (truncated) {
  2699. s_copy(post_status_text, "Page truncated at the buffer limit",
  2700. sizeof(post_status_text));
  2701. post_status_ttl = 6000;
  2702. } else if (doc.truncated) {
  2703. s_copy(post_status_text, "Page truncated by the parser",
  2704. sizeof(post_status_text));
  2705. post_status_ttl = 6000;
  2706. } else if (starts_with(page_url, "https://")) {
  2707. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  2708. sizeof(post_status_text));
  2709. post_status_ttl = 6000;
  2710. }
  2711. set_status(post_status_text, post_status_error, post_status_ttl);
  2712. ngui_invalidate(&ui);
  2713. }
  2714. static void load_home(int push)
  2715. {
  2716. pending_post_len = 0;
  2717. cancel_fetch = 0;
  2718. preload_active = 0;
  2719. preload_pending = 0;
  2720. js_browser_stop();
  2721. js_last_status[0] = '\0';
  2722. js_last_error = 0;
  2723. heap_clear();
  2724. image_reset();
  2725. form_reset_state();
  2726. layout_valid = 0;
  2727. page_scroll.offset = 0;
  2728. page_scroll.dragging = 0;
  2729. br_parse_plain(&doc, "", 0);
  2730. page_loading = 1;
  2731. page_is_local = 0;
  2732. s_copy(page_url, "about:home", sizeof(page_url));
  2733. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2734. url_in.len = s_len(url_in.text);
  2735. url_in.cursor = url_in.len;
  2736. url_in.scroll = 0;
  2737. ngui_set_focus(&ui, 0);
  2738. if (push)
  2739. history_push(page_url);
  2740. ngui_invalidate(&ui);
  2741. /* See load_page(): reattach the fonts before the first redraw. */
  2742. if (heap_start() != 0) {
  2743. show_error("Out of memory", "Cannot allocate the browser heap");
  2744. return;
  2745. }
  2746. ngui_font_attach(&ui);
  2747. redraw_now();
  2748. browser_rules_alloc();
  2749. {
  2750. static const char home[] =
  2751. "<html><head><title>NebOS Browser</title><style>"
  2752. "body { margin: 10px; color: #e4e6f0; }"
  2753. "h1 { color: #7fb0ff; }"
  2754. ".box { background-color: #262b3a; margin: 12px; "
  2755. "padding: 10px; }"
  2756. "a { color: #7fb0ff; }"
  2757. "pre { background-color: #32384a; }"
  2758. "</style></head><body>"
  2759. "<h1>NebOS Browser</h1>"
  2760. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  2761. "shared HTTP client and the image library.</p>"
  2762. "<div class=\"box\"><b>Try:</b>"
  2763. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  2764. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  2765. "<li><a href=\"/floppy1/JS.HTM\">/"
  2766. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  2767. "<li><a href=\"http://10.0.2.2:8000/\">"
  2768. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  2769. "<li><a href=\"https://example.com/\">"
  2770. "https://example.com/</a> (TLS, not verified)</li>"
  2771. "</ul></div>"
  2772. "<p>Type a URL in the bar above. Esc closes the "
  2773. "window, Ctrl+L focuses the address bar.</p>"
  2774. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  2775. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  2776. "</body></html>";
  2777. br_set_viewport(ui.w);
  2778. br_parse(&doc, home, sizeof(home) - 1);
  2779. br_parse_inline_css(&doc);
  2780. br_reset_styles(&doc);
  2781. s_copy(page_title, doc.title, sizeof(page_title));
  2782. }
  2783. post_status_text[0] = '\0';
  2784. post_status_error = 0;
  2785. post_status_ttl = 0;
  2786. page_loading = 0;
  2787. set_status("", 0, 0);
  2788. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  2789. url_in.len = s_len(url_in.text);
  2790. url_in.cursor = url_in.len;
  2791. url_in.scroll = 0;
  2792. ngui_set_focus(&ui, 0);
  2793. ngui_invalidate(&ui);
  2794. }
  2795. /* Extensions the browser opens from the local filesystem. A dotted input
  2796. * with one of these still resolves relative to the cwd. */
  2797. static int local_file_ext(const char *s)
  2798. {
  2799. static const char *const exts[] = {
  2800. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  2801. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  2802. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  2803. "cfg", "conf", 0
  2804. };
  2805. unsigned int i = 0, start = 0, len = 0, e;
  2806. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  2807. s[i] != '#') {
  2808. if (s[i] == '.') {
  2809. start = i + 1;
  2810. len = 0;
  2811. } else if (start) {
  2812. len++;
  2813. }
  2814. i++;
  2815. }
  2816. if (!len)
  2817. return 0;
  2818. for (e = 0; exts[e]; e++) {
  2819. const char *x = exts[e];
  2820. unsigned int xn = s_len(x), k;
  2821. if (xn != len)
  2822. continue;
  2823. for (k = 0; k < len; k++) {
  2824. char a = s[start + k];
  2825. if (a >= 'A' && a <= 'Z')
  2826. a = (char)(a - 'A' + 'a');
  2827. if (a != x[k])
  2828. break;
  2829. }
  2830. if (k == len)
  2831. return 1;
  2832. }
  2833. return 0;
  2834. }
  2835. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  2836. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  2837. * Enter to the first network request. */
  2838. static int looks_like_host(const char *s)
  2839. {
  2840. unsigned int i = 0;
  2841. int dot = 0;
  2842. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  2843. s[i] != ':') {
  2844. char c = s[i];
  2845. if (c == '.') {
  2846. dot = 1;
  2847. } else if (!((c >= 'a' && c <= 'z') ||
  2848. (c >= 'A' && c <= 'Z') ||
  2849. (c >= '0' && c <= '9') ||
  2850. c == '-' || c == '_')) {
  2851. return 0;
  2852. }
  2853. i++;
  2854. }
  2855. return dot && i > 0 && !local_file_ext(s);
  2856. }
  2857. static void load_remote(const char *url, int push)
  2858. {
  2859. char canon[BR_URL_MAX];
  2860. s_copy(canon, url, sizeof(canon));
  2861. origin_cache_apply(canon, sizeof(canon));
  2862. load_page(canon, 0, push);
  2863. }
  2864. static void navigate(const char *input, int push)
  2865. {
  2866. char target[BR_URL_MAX];
  2867. char *t;
  2868. if (!input)
  2869. return;
  2870. s_copy(target, input, sizeof(target));
  2871. t = trim(target);
  2872. if (!t[0])
  2873. return;
  2874. if (s_eq(t, "about:home")) {
  2875. load_home(push);
  2876. return;
  2877. }
  2878. if (starts_with(t, "file://")) {
  2879. make_abs_local(t + 7, target, sizeof(target));
  2880. load_page(target, 1, push);
  2881. return;
  2882. }
  2883. if (is_http(t)) {
  2884. load_remote(t, push);
  2885. return;
  2886. }
  2887. if (t[0] == '/') {
  2888. make_abs_local(t, target, sizeof(target));
  2889. load_page(target, 1, push);
  2890. return;
  2891. }
  2892. if (!looks_like_host(t)) {
  2893. struct sys_stat st;
  2894. if (u_stat(t, &st) == 0 && !st.is_dir) {
  2895. make_abs_local(t, target, sizeof(target));
  2896. load_page(target, 1, push);
  2897. return;
  2898. }
  2899. }
  2900. {
  2901. char with_scheme[BR_URL_MAX];
  2902. unsigned int n = 0;
  2903. s_append(with_scheme, &n, "http://", sizeof(with_scheme));
  2904. s_append(with_scheme, &n, t, sizeof(with_scheme));
  2905. load_remote(with_scheme, push);
  2906. }
  2907. }
  2908. /* ---- layout ---- */
  2909. static struct ufont_face *style_face(const struct br_style *st)
  2910. {
  2911. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  2912. return font_faces[st->font_face - 1];
  2913. return 0;
  2914. }
  2915. static struct ufont_face *run_face(const struct lay_run *r)
  2916. {
  2917. if (r->font_face && r->font_face <= BR_MAX_FACES)
  2918. return font_faces[r->font_face - 1];
  2919. return 0;
  2920. }
  2921. static unsigned int face_text_width(struct ngui *gui,
  2922. const struct br_style *st,
  2923. const char *s, unsigned int n)
  2924. {
  2925. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  2926. st->bold, st->italic, st->mono);
  2927. }
  2928. static int face_line_height(struct ngui *gui, const struct br_style *st)
  2929. {
  2930. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  2931. st->mono);
  2932. }
  2933. static unsigned int run_text_width(struct ngui *gui,
  2934. const struct lay_run *r,
  2935. const char *s, unsigned int n)
  2936. {
  2937. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  2938. r->bold, r->italic, r->mono);
  2939. }
  2940. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  2941. {
  2942. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  2943. r->mono);
  2944. }
  2945. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  2946. {
  2947. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  2948. }
  2949. static struct br_style base_style(void)
  2950. {
  2951. struct br_style s = { 0 };
  2952. s.color = ui.theme.text;
  2953. s.bg = ui.theme.bg;
  2954. s.has_bg = 0;
  2955. for (int i = 0; i < 4; i++) {
  2956. s.border_c[i] = 0;
  2957. s.border_w[i] = 0;
  2958. }
  2959. s.font_px = 16;
  2960. s.bold = 0;
  2961. s.italic = 0;
  2962. s.mono = 0;
  2963. s.underline = 0;
  2964. s.align = BR_ALIGN_LEFT;
  2965. s.display = BR_DISPLAY_BLOCK;
  2966. s.no_bullet = 0;
  2967. s.uppercase = 0;
  2968. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  2969. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  2970. s.width = s.max_width = s.min_width = 0;
  2971. s.height = s.min_height = s.max_height = 0;
  2972. s.box_sizing = 0;
  2973. s.ml_auto = s.mr_auto = 0;
  2974. s.line_h_pct = 0;
  2975. s.line_h_px = 0;
  2976. s.mt = s.mb = s.ml = s.mr = 0;
  2977. s.pt = s.pb = s.pl = s.pr = 0;
  2978. return s;
  2979. }
  2980. /* Resolve a margin/padding raw value. Percentages use the containing
  2981. * block width for all four sides, as CSS specifies. */
  2982. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  2983. {
  2984. if (unit == 1)
  2985. return base * v / 10000;
  2986. if (unit == 2)
  2987. return st->font_px * v / 100;
  2988. if (unit == 3)
  2989. return (int)br_root_font_px() * v / 100;
  2990. if (unit == 4)
  2991. return 0;
  2992. return v;
  2993. }
  2994. static int mp_px(const struct br_style *st, int side, int base)
  2995. {
  2996. int raw;
  2997. switch (side) {
  2998. case 0: raw = st->mt; break;
  2999. case 1: raw = st->mr; break;
  3000. case 2: raw = st->mb; break;
  3001. case 3: raw = st->ml; break;
  3002. case 4: raw = st->pt; break;
  3003. case 5: raw = st->pr; break;
  3004. case 6: raw = st->pb; break;
  3005. default: raw = st->pl; break;
  3006. }
  3007. if (st->mp_unit[side] == 5)
  3008. return base * raw / 100 + st->mp_calc_px[side];
  3009. return css_mp_px(st, raw, st->mp_unit[side], base);
  3010. }
  3011. static int style_width_px(const struct br_style *st, int base)
  3012. {
  3013. if (st->width_kind == 1)
  3014. return st->width;
  3015. if (st->width_kind == 2)
  3016. return base * (int)st->width / 100;
  3017. if (st->width_kind == 3)
  3018. return base * st->width_calc_pct / 100 + st->width_calc_px;
  3019. return 0;
  3020. }
  3021. static int style_height_px(const struct br_style *st, int base)
  3022. {
  3023. if (st->height_kind == 1)
  3024. return st->height;
  3025. if (st->height_kind == 2)
  3026. return base * (int)st->height / 100;
  3027. if (st->height_kind == 3)
  3028. return base * st->height_calc_pct / 100 + st->height_calc_px;
  3029. return 0;
  3030. }
  3031. static int css_size(unsigned char kind, int val, int base)
  3032. {
  3033. if (kind == 1)
  3034. return val;
  3035. if (kind == 2)
  3036. return base * val / 100;
  3037. return -1;
  3038. }
  3039. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  3040. const struct br_style *st)
  3041. {
  3042. int top = st->border_w[0], right = st->border_w[1];
  3043. int bottom = st->border_w[2], left = st->border_w[3];
  3044. if (r.w <= 0 || r.h <= 0)
  3045. return;
  3046. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  3047. int i;
  3048. for (i = 0; i < 4; i++)
  3049. if (st->border_w[i]) {
  3050. ngui_fill_rect(ui, r, st->border_c[i]);
  3051. break;
  3052. }
  3053. return;
  3054. }
  3055. if (top)
  3056. ngui_fill_rect(ui, (struct ngui_rect){r.x, r.y, r.w, top},
  3057. st->border_c[0]);
  3058. if (bottom)
  3059. ngui_fill_rect(ui, (struct ngui_rect){r.x,
  3060. r.y + r.h - bottom,
  3061. r.w, bottom},
  3062. st->border_c[2]);
  3063. if (left)
  3064. ngui_fill_rect(ui, (struct ngui_rect){r.x, r.y + top, left,
  3065. r.h - top - bottom},
  3066. st->border_c[3]);
  3067. if (right)
  3068. ngui_fill_rect(ui, (struct ngui_rect){r.x + r.w - right,
  3069. r.y + top, right,
  3070. r.h - top - bottom},
  3071. st->border_c[1]);
  3072. }
  3073. static void transform_origin(const struct br_style *st, int w, int h,
  3074. int *ox, int *oy)
  3075. {
  3076. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  3077. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  3078. }
  3079. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  3080. unsigned int a)
  3081. {
  3082. unsigned int dr, dg, db, sr, sg, sb;
  3083. if (a >= 255)
  3084. return s;
  3085. dr = (d >> 11) & 31;
  3086. dg = (d >> 5) & 63;
  3087. db = d & 31;
  3088. sr = (s >> 11) & 31;
  3089. sg = (s >> 5) & 63;
  3090. sb = s & 31;
  3091. dr = (dr * (255 - a) + sr * a) / 255;
  3092. dg = (dg * (255 - a) + sg * a) / 255;
  3093. db = (db * (255 - a) + sb * a) / 255;
  3094. return (unsigned short)((dr << 11) | (dg << 5) | db);
  3095. }
  3096. /* Paint a solid box through scale()/rotate() around transform-origin. This
  3097. * transforms the element's own background box; text and descendants keep
  3098. * their layout (documented approximation). */
  3099. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  3100. unsigned short color,
  3101. const struct br_style *st)
  3102. {
  3103. double sx = st->scale_x / 100.0;
  3104. double sy = st->scale_y / 100.0;
  3105. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  3106. double c = cos(th), sn = sin(th);
  3107. int ox, oy, minx, miny, maxx, maxy, x, y;
  3108. double ax, ay;
  3109. double px[4], py[4];
  3110. int cx1, cy1, cx2, cy2, i;
  3111. if (sx == 0)
  3112. sx = 0.01;
  3113. if (sy == 0)
  3114. sy = 0.01;
  3115. transform_origin(st, box.w, box.h, &ox, &oy);
  3116. ax = box.x + ox;
  3117. ay = box.y + oy;
  3118. px[0] = -ox; py[0] = -oy;
  3119. px[1] = box.w - ox; py[1] = -oy;
  3120. px[2] = box.w - ox; py[2] = box.h - oy;
  3121. px[3] = -ox; py[3] = box.h - oy;
  3122. minx = miny = 1000000;
  3123. maxx = maxy = -1000000;
  3124. for (i = 0; i < 4; i++) {
  3125. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  3126. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  3127. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3128. if (dx < minx) minx = dx;
  3129. if (dx > maxx) maxx = dx;
  3130. if (dy < miny) miny = dy;
  3131. if (dy > maxy) maxy = dy;
  3132. }
  3133. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3134. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3135. cx2 = page_rect.x + page_rect.w - 12;
  3136. cy2 = page_rect.y + page_rect.h;
  3137. if (cx2 > gui->w) cx2 = gui->w;
  3138. if (cy2 > gui->h) cy2 = gui->h;
  3139. if (minx < cx1) minx = cx1;
  3140. if (miny < cy1) miny = cy1;
  3141. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3142. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3143. for (y = miny; y <= maxy; y++) {
  3144. for (x = minx; x <= maxx; x++) {
  3145. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  3146. double rx = dx * c + dy * sn;
  3147. double ry = -dx * sn + dy * c;
  3148. double bx = rx / sx + ox;
  3149. double by = ry / sy + oy;
  3150. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  3151. gui->px[y * gui->w + x] = color;
  3152. }
  3153. }
  3154. }
  3155. static void draw_image_transformed(struct ngui *gui,
  3156. const struct img_image *im,
  3157. int x, int y, int w, int h,
  3158. int sx100, int sy100, int rot100,
  3159. int origin_x, int origin_y,
  3160. int origin_x_kind, int origin_y_kind)
  3161. {
  3162. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  3163. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  3164. double c = cos(th), sn = sin(th);
  3165. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  3166. double ax, ay;
  3167. double bx[4], by[4];
  3168. int cx1, cy1, cx2, cy2;
  3169. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  3170. return;
  3171. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  3172. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  3173. ax = x + ox;
  3174. ay = y + oy;
  3175. bx[0] = -ox; by[0] = -oy;
  3176. bx[1] = w - ox; by[1] = -oy;
  3177. bx[2] = w - ox; by[2] = h - oy;
  3178. bx[3] = -ox; by[3] = h - oy;
  3179. minx = miny = 1000000;
  3180. maxx = maxy = -1000000;
  3181. for (i = 0; i < 4; i++) {
  3182. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  3183. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  3184. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  3185. if (dx < minx) minx = dx;
  3186. if (dx > maxx) maxx = dx;
  3187. if (dy < miny) miny = dy;
  3188. if (dy > maxy) maxy = dy;
  3189. }
  3190. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  3191. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  3192. cx2 = page_rect.x + page_rect.w - 12;
  3193. cy2 = page_rect.y + page_rect.h;
  3194. if (cx2 > gui->w) cx2 = gui->w;
  3195. if (cy2 > gui->h) cy2 = gui->h;
  3196. if (minx < cx1) minx = cx1;
  3197. if (miny < cy1) miny = cy1;
  3198. if (maxx > cx2 - 1) maxx = cx2 - 1;
  3199. if (maxy > cy2 - 1) maxy = cy2 - 1;
  3200. for (py = miny; py <= maxy; py++) {
  3201. for (px = minx; px <= maxx; px++) {
  3202. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  3203. double rx = dx * c + dy * sn;
  3204. double ry = -dx * sn + dy * c;
  3205. double fx = rx / sx + ox;
  3206. double fy = ry / sy + oy;
  3207. int ix, iy;
  3208. unsigned int si, a;
  3209. unsigned short src;
  3210. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  3211. continue;
  3212. ix = (int)(fx * (double)im->w / w);
  3213. iy = (int)(fy * (double)im->h / h);
  3214. if (ix < 0 || ix >= (int)im->w ||
  3215. iy < 0 || iy >= (int)im->h)
  3216. continue;
  3217. si = (unsigned int)iy * im->w + (unsigned int)ix;
  3218. src = im->px[si];
  3219. a = im->alpha ? im->alpha[si] : 255;
  3220. gui->px[py * gui->w + px] =
  3221. a >= 255 ? src :
  3222. blend_rgb565(gui->px[py * gui->w + px],
  3223. src, a);
  3224. }
  3225. }
  3226. }
  3227. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  3228. unsigned int node, const struct br_style *st)
  3229. {
  3230. struct br_image *bi;
  3231. struct img_blit b;
  3232. int tw, th, x, y, rep_x, rep_y, posx, posy;
  3233. unsigned int scale = 65536;
  3234. int legacy, tiles = 0, rows = 0;
  3235. int cx1, cy1, cx2, cy2;
  3236. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  3237. return;
  3238. if (doc.nodes[node].bg_img_index < 0 ||
  3239. doc.nodes[node].bg_img_index >= image_count)
  3240. return;
  3241. bi = &images[doc.nodes[node].bg_img_index];
  3242. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  3243. return;
  3244. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  3245. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  3246. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  3247. if (legacy) {
  3248. scale = ((unsigned int)box.w << 16) / bi->img.w;
  3249. tw = box.w;
  3250. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  3251. x = box.x;
  3252. y = box.y;
  3253. rep_x = rep_y = 0;
  3254. } else {
  3255. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  3256. unsigned int sx = ((unsigned int)box.w << 16) /
  3257. bi->img.w;
  3258. unsigned int sy = ((unsigned int)box.h << 16) /
  3259. bi->img.h;
  3260. scale = st->bg_size_kind == 3 ?
  3261. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  3262. } else if (st->bg_size_kind == 1 ||
  3263. st->bg_size_kind == 2) {
  3264. int w = st->bg_size_w;
  3265. int h = st->bg_size_h;
  3266. if (st->bg_size_kind == 2) {
  3267. if (w)
  3268. w = box.w * w / 100;
  3269. if (h)
  3270. h = box.h * h / 100;
  3271. }
  3272. if (w)
  3273. scale = ((unsigned int)w << 16) / bi->img.w;
  3274. else if (h)
  3275. scale = ((unsigned int)h << 16) / bi->img.h;
  3276. }
  3277. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  3278. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  3279. if (tw < 1)
  3280. tw = 1;
  3281. if (th < 1)
  3282. th = 1;
  3283. posx = st->bg_pos_x_kind == 1 ?
  3284. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  3285. posy = st->bg_pos_y_kind == 1 ?
  3286. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  3287. x = box.x + posx;
  3288. y = box.y + posy;
  3289. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  3290. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  3291. if (rep_x) {
  3292. int m = (x - box.x) % tw;
  3293. if (m > 0)
  3294. m -= tw;
  3295. x = box.x + m;
  3296. }
  3297. if (rep_y) {
  3298. int m = (y - box.y) % th;
  3299. if (m > 0)
  3300. m -= th;
  3301. y = box.y + m;
  3302. }
  3303. }
  3304. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  3305. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  3306. cx2 = box.x + box.w;
  3307. cy2 = box.y + box.h;
  3308. if (cx2 > page_rect.x + page_rect.w - 12)
  3309. cx2 = page_rect.x + page_rect.w - 12;
  3310. if (cy2 > page_rect.y + page_rect.h)
  3311. cy2 = page_rect.y + page_rect.h;
  3312. if (cx1 >= cx2 || cy1 >= cy2)
  3313. return;
  3314. b.dst = l->ui->px;
  3315. b.dst_w = l->ui->w;
  3316. b.dst_h = l->ui->h;
  3317. b.clip_x = cx1;
  3318. b.clip_y = cy1;
  3319. b.clip_w = cx2 - cx1;
  3320. b.clip_h = cy2 - cy1;
  3321. b.scale = scale;
  3322. b.bg = ui.theme.bg;
  3323. b.bg2 = ui.theme.bg;
  3324. b.flags = IMG_BLIT_OVER_DST;
  3325. {
  3326. int row_x = x;
  3327. for (;;) {
  3328. for (;;) {
  3329. b.x = x;
  3330. b.y = y;
  3331. img_draw(&bi->img, &b);
  3332. if (!rep_x || ++tiles > 512)
  3333. break;
  3334. x += tw;
  3335. if (x >= box.x + box.w)
  3336. break;
  3337. }
  3338. if (!rep_y || ++rows > 64)
  3339. break;
  3340. y += th;
  3341. if (y >= box.y + box.h)
  3342. break;
  3343. x = row_x;
  3344. }
  3345. }
  3346. }
  3347. static int run_width(const struct lay_run *r)
  3348. {
  3349. if (r->img >= 0)
  3350. return r->iw;
  3351. if (r->img == -2)
  3352. return r->iw;
  3353. return (int)r->w;
  3354. }
  3355. static void start_line(struct lay *l, const struct br_style *st)
  3356. {
  3357. (void)st;
  3358. if (l->nruns == 0) {
  3359. l->line_y = l->y;
  3360. l->line_h = 0;
  3361. }
  3362. l->line_left = l->left;
  3363. l->line_right = l->right;
  3364. if (l->float_active && l->line_y < l->float_bottom) {
  3365. if (l->float_left > l->line_left)
  3366. l->line_left = l->float_left;
  3367. if (l->float_right < l->line_right)
  3368. l->line_right = l->float_right;
  3369. }
  3370. if (l->line_right < l->line_left + 8)
  3371. l->line_right = l->line_left + 8;
  3372. l->line_x = l->line_left;
  3373. l->run_x = l->line_left;
  3374. }
  3375. static void flush_line(struct lay *l)
  3376. {
  3377. int total, x, i, vis;
  3378. if (!l->nruns && l->line_x == l->line_left) {
  3379. l->line_h = 0;
  3380. return;
  3381. }
  3382. total = l->line_x - l->line_left;
  3383. x = l->line_left;
  3384. vis = 1;
  3385. if (l->draw) {
  3386. int lh = l->line_h ? l->line_h : 16;
  3387. vis = l->line_y + lh >= page_rect.y &&
  3388. l->line_y <= page_rect.y + page_rect.h;
  3389. }
  3390. if (l->align == BR_ALIGN_CENTER)
  3391. x += (l->line_right - l->line_left - total) / 2;
  3392. else if (l->align == BR_ALIGN_RIGHT)
  3393. x = l->line_right - total;
  3394. if (x < l->line_left)
  3395. x = l->line_left;
  3396. for (i = 0; i < l->nruns; i++) {
  3397. struct lay_run *r = &l->runs[i];
  3398. int w = run_width(r);
  3399. int ry = l->line_y + r->dy;
  3400. x += r->gap;
  3401. if (l->draw && vis) {
  3402. if (r->form) {
  3403. unsigned int node = r->form - 1;
  3404. struct form_state *fs = form_get(node, 1);
  3405. int hh = r->ih ? r->ih : 20;
  3406. int focused = form_focus == node;
  3407. int disabled = r->form_disabled;
  3408. unsigned short bg = l->ui->theme.panel_alt;
  3409. unsigned short fg = disabled ? 0x8410 : r->color;
  3410. struct ngui_rect box = {x, ry, w, hh};
  3411. if (r->form_kind == FORM_CHECKBOX ||
  3412. r->form_kind == FORM_RADIO) {
  3413. ngui_fill_rect(l->ui, box, bg);
  3414. ngui_frame(l->ui, box,
  3415. focused ? l->ui->theme.accent :
  3416. l->ui->theme.border);
  3417. if (fs && fs->checked) {
  3418. struct ngui_rect dot = {
  3419. x + 4, ry + 4,
  3420. w > 8 ? w - 8 : 1,
  3421. hh > 8 ? hh - 8 : 1
  3422. };
  3423. if (r->form_kind == FORM_RADIO)
  3424. ngui_fill_round_rect(
  3425. l->ui, dot, 4,
  3426. 4, 4, 4,
  3427. l->ui->theme.accent);
  3428. else
  3429. ngui_fill_rect(l->ui,
  3430. dot,
  3431. l->ui->theme.accent);
  3432. }
  3433. } else {
  3434. ngui_fill_rect(l->ui, box, bg);
  3435. ngui_frame(l->ui, box,
  3436. focused ? l->ui->theme.accent :
  3437. l->ui->theme.border);
  3438. ngui_text_px_face(l->ui, run_face(r),
  3439. x + 6, ry + 2,
  3440. r->lit, s_len(r->lit),
  3441. fg, r->font_px, r->bold,
  3442. r->italic, r->mono);
  3443. if (focused && fs &&
  3444. (r->form_kind == FORM_TEXT ||
  3445. r->form_kind == FORM_PASSWORD ||
  3446. r->form_kind == FORM_TEXTAREA)) {
  3447. int cw = 0;
  3448. if (fs->len && fs->caret)
  3449. cw = (int)run_text_width(
  3450. l->ui, r, r->lit,
  3451. fs->caret < fs->len ?
  3452. fs->caret : fs->len);
  3453. ngui_fill_rect(l->ui,
  3454. (struct ngui_rect){
  3455. x + 6 + cw,
  3456. ry + 4, 1,
  3457. hh > 8 ? hh - 8 : 1
  3458. },
  3459. l->ui->theme.accent);
  3460. }
  3461. if (r->form_kind == FORM_SELECT) {
  3462. ngui_text_px(l->ui, x + w - 12,
  3463. ry + 2, "v", 1, fg,
  3464. r->font_px, 0, 0, 0);
  3465. }
  3466. }
  3467. } else if (r->img == -2) {
  3468. int hh = r->ih ? r->ih : 20;
  3469. ngui_fill_rect(l->ui,
  3470. (struct ngui_rect){x, ry, w, hh},
  3471. l->ui->theme.panel_alt);
  3472. ngui_frame(l->ui,
  3473. (struct ngui_rect){x, ry, w, hh},
  3474. l->ui->theme.border);
  3475. ngui_text_px_face(l->ui, run_face(r),
  3476. x + 6, ry + 2, r->lit,
  3477. s_len(r->lit), r->color,
  3478. r->font_px, r->bold, r->italic,
  3479. r->mono);
  3480. } else if (r->img >= 0) {
  3481. struct br_image *bi = &images[r->img];
  3482. if (bi->state == 1 && r->transform_scale) {
  3483. draw_image_transformed(l->ui, &bi->img,
  3484. x, ry, r->iw, r->ih,
  3485. r->scale_x, r->scale_y,
  3486. r->rotate_x100, r->origin_x,
  3487. r->origin_y, r->origin_x_kind,
  3488. r->origin_y_kind);
  3489. } else if (bi->state == 1) {
  3490. struct img_blit b;
  3491. b.dst = l->ui->px;
  3492. b.dst_w = l->ui->w;
  3493. b.dst_h = l->ui->h;
  3494. b.clip_x = page_rect.x;
  3495. b.clip_y = page_rect.y;
  3496. b.clip_w = page_rect.w - 12;
  3497. b.clip_h = page_rect.h;
  3498. b.x = x;
  3499. b.y = ry;
  3500. b.scale = ((unsigned int)r->iw << 16) /
  3501. bi->img.w;
  3502. b.bg = ui.theme.bg;
  3503. b.bg2 = ui.theme.bg;
  3504. b.flags = IMG_BLIT_OVER_DST;
  3505. img_draw(&bi->img, &b);
  3506. }
  3507. } else {
  3508. const char *s = r->has_lit ? r->lit :
  3509. doc.text + r->off;
  3510. unsigned int n = r->has_lit ? s_len(r->lit) :
  3511. r->len;
  3512. ngui_text_px_face(l->ui, run_face(r), x, ry,
  3513. s, n, r->color, r->font_px,
  3514. r->bold, r->italic, r->mono);
  3515. if (r->underline)
  3516. ngui_fill_rect(l->ui,
  3517. (struct ngui_rect){x,
  3518. ry + run_ascent(l->ui, r) + 2,
  3519. w, 1}, r->color);
  3520. }
  3521. if (r->form || r->href) {
  3522. if (nhits < HIT_MAX) {
  3523. struct hit *h = &hits[nhits];
  3524. unsigned int target = r->form ?
  3525. r->form - 1 : r->href;
  3526. int hh = (r->form || r->img >= 0) ?
  3527. r->ih :
  3528. run_line_height(l->ui, r);
  3529. int merge = nhits > 0 &&
  3530. hits[nhits - 1].node == target &&
  3531. hits[nhits - 1].y == ry &&
  3532. hits[nhits - 1].h == hh &&
  3533. x <= hits[nhits - 1].x +
  3534. hits[nhits - 1].w + 2;
  3535. if (merge) {
  3536. struct hit *p = &hits[nhits - 1];
  3537. int end = x + w;
  3538. if (end > p->x + p->w)
  3539. p->w = end - p->x;
  3540. } else {
  3541. h->x = x;
  3542. h->y = ry;
  3543. h->w = w;
  3544. h->h = hh;
  3545. h->node = (unsigned short)target;
  3546. nhits++;
  3547. }
  3548. }
  3549. }
  3550. }
  3551. x += w;
  3552. }
  3553. l->y += l->line_h + 2;
  3554. if (l->float_active && l->y >= l->float_bottom)
  3555. l->float_active = 0;
  3556. l->nruns = 0;
  3557. l->line_x = l->left;
  3558. l->run_x = l->left;
  3559. l->line_left = l->left;
  3560. l->line_right = l->right;
  3561. l->line_h = 0;
  3562. l->space_pending = 0;
  3563. }
  3564. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  3565. const struct br_style *st, unsigned short href,
  3566. const char *lit)
  3567. {
  3568. unsigned int n = lit ? s_len(lit) : len;
  3569. const char *tp = lit ? lit : doc.text + off;
  3570. int w = (int)face_text_width(l->ui, st, tp, n);
  3571. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  3572. flush_line(l);
  3573. if (l->nruns == 0) {
  3574. l->line_y = l->y;
  3575. l->line_h = 0;
  3576. start_line(l, st);
  3577. }
  3578. {
  3579. struct lay_run *r = &l->runs[l->nruns++];
  3580. int gap = l->line_x - l->run_x;
  3581. if (gap < 0)
  3582. gap = 0;
  3583. r->gap = (unsigned short)gap;
  3584. r->off = off;
  3585. r->len = len;
  3586. r->color = st->color;
  3587. r->href = href;
  3588. r->dy = 0;
  3589. r->has_lit = 0;
  3590. r->form = 0;
  3591. r->form_kind = 0;
  3592. r->form_disabled = 0;
  3593. r->lit[0] = '\0';
  3594. if (lit && lit[0]) {
  3595. unsigned int i;
  3596. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  3597. r->lit[i] = lit[i];
  3598. r->lit[i] = '\0';
  3599. r->has_lit = 1;
  3600. }
  3601. r->img = -1;
  3602. r->iw = r->ih = 0;
  3603. r->font_px = st->font_px;
  3604. r->bold = st->bold;
  3605. r->italic = st->italic;
  3606. r->mono = st->mono;
  3607. r->font_face = st->font_face;
  3608. /* A control with its own background is a button, not body copy;
  3609. * an inherited link underline would strike through the fill. */
  3610. r->underline = st->underline && !st->has_bg;
  3611. r->w = (unsigned short)w;
  3612. if (r->has_lit)
  3613. r->w = (unsigned short)run_text_width(
  3614. l->ui, r, r->lit, s_len(r->lit));
  3615. w = r->w;
  3616. }
  3617. l->line_x += w;
  3618. l->run_x = l->line_x;
  3619. {
  3620. int lh = face_line_height(l->ui, st);
  3621. if (st->line_h_px)
  3622. lh = st->line_h_px;
  3623. else if (st->line_h_pct)
  3624. lh = st->font_px * st->line_h_pct / 100;
  3625. if (lh < face_line_height(l->ui, st))
  3626. lh = face_line_height(l->ui, st);
  3627. if (l->line_h < lh)
  3628. l->line_h = lh;
  3629. }
  3630. }
  3631. static void add_image_run(struct lay *l, unsigned int node,
  3632. const struct br_style *st, unsigned short href)
  3633. {
  3634. struct br_image *bi = 0;
  3635. int idx = doc.nodes[node].img_index;
  3636. int dw, dh, maxw;
  3637. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  3638. bi = &images[idx];
  3639. if (l->nruns == 0)
  3640. start_line(l, st);
  3641. if (l->space_pending &&
  3642. (l->nruns > 0 || l->line_x > l->line_left)) {
  3643. int sp = (int)face_text_width(l->ui, st, " ", 1);
  3644. if (l->line_x + sp <= l->line_right)
  3645. l->line_x += sp;
  3646. }
  3647. l->space_pending = 0;
  3648. if (!bi) {
  3649. const char *alt = br_alt(&doc, node);
  3650. struct br_style gs = *st;
  3651. char tmp[96];
  3652. unsigned int n = 0;
  3653. int w;
  3654. gs.color = BR_GRAY;
  3655. gs.underline = 0;
  3656. s_append(tmp, &n, "[", sizeof(tmp));
  3657. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  3658. s_append(tmp, &n, "]", sizeof(tmp));
  3659. w = (int)face_text_width(l->ui, &gs, tmp, n);
  3660. if (l->line_x + w > l->line_right &&
  3661. (l->nruns > 0 || l->line_x > l->line_left))
  3662. flush_line(l);
  3663. add_run(l, 0, 0, &gs, href, tmp);
  3664. if (!l->draw) {
  3665. int t = l->line_y < 0 ? 0 : l->line_y;
  3666. int hh = face_line_height(l->ui, &gs);
  3667. if (t > 65535)
  3668. t = 65535;
  3669. if (hh > 65535)
  3670. hh = 65535;
  3671. img_top[node] = (unsigned short)t;
  3672. img_h[node] = (unsigned short)hh;
  3673. }
  3674. return;
  3675. }
  3676. maxw = l->line_right - l->line_left;
  3677. if (maxw < 8)
  3678. maxw = 8;
  3679. {
  3680. int iw = bi->native_w, ih = bi->native_h;
  3681. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  3682. if (iw <= 0 || ih <= 0) {
  3683. iw = (int)bi->img.w;
  3684. ih = (int)bi->img.h;
  3685. }
  3686. dw = iw;
  3687. dh = ih;
  3688. if (doc.nodes[node].width_attr) {
  3689. int want = doc.nodes[node].width_attr;
  3690. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  3691. have_w = 1;
  3692. }
  3693. if (doc.nodes[node].height_attr) {
  3694. int want = doc.nodes[node].height_attr;
  3695. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  3696. have_h = 1;
  3697. }
  3698. if (have_w && !have_h)
  3699. dh = ih ? ih * dw / iw : 0;
  3700. if (have_h && !have_w)
  3701. dw = iw ? iw * dh / ih : 0;
  3702. if (st->width_kind) {
  3703. css_w = 1;
  3704. if (st->width_kind == 3)
  3705. dw = maxw * st->width_calc_pct / 100 +
  3706. st->width_calc_px;
  3707. else
  3708. dw = st->width_kind == 2 ?
  3709. maxw * (int)st->width / 100 :
  3710. (int)st->width;
  3711. }
  3712. if (st->height_kind) {
  3713. css_h = 1;
  3714. if (st->height_kind == 3)
  3715. dh = maxw * st->height_calc_pct / 100 +
  3716. st->height_calc_px;
  3717. else
  3718. dh = st->height_kind == 2 ?
  3719. maxw * (int)st->height / 100 :
  3720. (int)st->height;
  3721. }
  3722. if (css_w && !css_h)
  3723. dh = ih ? ih * dw / iw : 0;
  3724. if (css_h && !css_w)
  3725. dw = iw ? iw * dh / ih : 0;
  3726. if (st->max_width_kind) {
  3727. int mw = st->max_width_kind == 3 ?
  3728. maxw * st->max_width_calc_pct / 100 +
  3729. st->max_width_calc_px :
  3730. st->max_width_kind == 2 ?
  3731. maxw * (int)st->max_width / 100 :
  3732. (int)st->max_width;
  3733. if (mw > 0 && dw > mw) {
  3734. dh = iw ? ih * mw / iw : 0;
  3735. dw = mw;
  3736. }
  3737. }
  3738. }
  3739. if (dw < 8)
  3740. dw = 8;
  3741. if (dh < 8)
  3742. dh = 8;
  3743. if (dw > maxw) {
  3744. dh = dw ? dh * maxw / dw : dh;
  3745. dw = maxw;
  3746. }
  3747. if (!l->draw) {
  3748. int t = l->line_y < 0 ? 0 : l->line_y;
  3749. if (t > 65535)
  3750. t = 65535;
  3751. if (dh > 65535)
  3752. dh = 65535;
  3753. img_top[node] = (unsigned short)t;
  3754. img_h[node] = (unsigned short)dh;
  3755. }
  3756. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  3757. l->line_x > l->line_left))
  3758. flush_line(l);
  3759. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  3760. flush_line(l);
  3761. if (l->nruns == 0) {
  3762. l->line_y = l->y;
  3763. l->line_h = 0;
  3764. start_line(l, st);
  3765. }
  3766. {
  3767. struct lay_run *r = &l->runs[l->nruns++];
  3768. int gap = l->line_x - l->run_x;
  3769. if (gap < 0)
  3770. gap = 0;
  3771. r->gap = (unsigned short)gap;
  3772. r->off = 0;
  3773. r->len = 0;
  3774. r->color = 0;
  3775. r->href = href;
  3776. r->form = 0;
  3777. r->form_kind = 0;
  3778. r->form_disabled = 0;
  3779. /* Inline replaced elements honour their vertical margins; this
  3780. * is how Bootstrap's negative logo margins centre the wordmark. */
  3781. {
  3782. int idy = mp_px(st, 0, l->right - l->left);
  3783. if (idy < -2048)
  3784. idy = -2048;
  3785. if (idy > 2048)
  3786. idy = 2048;
  3787. r->dy = (signed short)idy;
  3788. }
  3789. r->has_lit = 0;
  3790. r->lit[0] = '\0';
  3791. r->img = (short)idx;
  3792. r->iw = (unsigned short)dw;
  3793. r->ih = (unsigned short)dh;
  3794. r->w = (unsigned short)dw;
  3795. r->font_px = st->font_px;
  3796. r->bold = st->bold;
  3797. r->italic = st->italic;
  3798. r->mono = st->mono;
  3799. r->font_face = st->font_face;
  3800. r->transform_scale = st->transform_scale;
  3801. r->scale_x = st->scale_x;
  3802. r->scale_y = st->scale_y;
  3803. r->rotate_x100 = st->rotate_x100;
  3804. r->origin_x = st->origin_x;
  3805. r->origin_y = st->origin_y;
  3806. r->origin_x_kind = st->origin_x_kind;
  3807. r->origin_y_kind = st->origin_y_kind;
  3808. r->underline = 0;
  3809. }
  3810. if (node < BR_MAX_NODES) {
  3811. layout_boxes[node].x = l->line_x;
  3812. layout_boxes[node].y = l->line_y +
  3813. mp_px(st, 0, l->right - l->left);
  3814. layout_boxes[node].w = dw;
  3815. layout_boxes[node].h = dh;
  3816. layout_boxes[node].valid = 1;
  3817. }
  3818. l->line_x += dw;
  3819. l->run_x = l->line_x;
  3820. if (l->line_h < dh)
  3821. l->line_h = dh;
  3822. }
  3823. static int text_width(struct lay *l, const char *s, unsigned int n,
  3824. const struct br_style *st)
  3825. {
  3826. return (int)face_text_width(l->ui, st, s, n);
  3827. }
  3828. /* Longest prefix that fits in maxw, at least one byte. */
  3829. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  3830. const struct br_style *st, int maxw)
  3831. {
  3832. unsigned int take = 0;
  3833. while (take < n) {
  3834. if (text_width(l, s, take + 1, st) > maxw)
  3835. break;
  3836. take++;
  3837. }
  3838. return take ? take : 1;
  3839. }
  3840. static void emit_word(struct lay *l, const char *s, unsigned int start,
  3841. unsigned int n, unsigned int base,
  3842. const struct br_style *st, unsigned short href)
  3843. {
  3844. int avail;
  3845. int w = text_width(l, s + start, n, st);
  3846. unsigned int off = start;
  3847. if (l->nruns == 0)
  3848. start_line(l, st);
  3849. avail = l->line_right - l->line_left;
  3850. if (st->nowrap) {
  3851. if (n)
  3852. add_run(l, (unsigned short)(base + start),
  3853. (unsigned short)n, st, href, 0);
  3854. return;
  3855. }
  3856. if (l->line_x + w > l->line_right &&
  3857. (l->nruns > 0 || l->line_x > l->line_left)) {
  3858. flush_line(l);
  3859. start_line(l, st);
  3860. avail = l->line_right - l->line_left;
  3861. }
  3862. if (w <= avail) {
  3863. if (n)
  3864. add_run(l, (unsigned short)(base + start),
  3865. (unsigned short)n, st, href, 0);
  3866. return;
  3867. }
  3868. while (n > 0) {
  3869. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  3870. add_run(l, (unsigned short)(base + off),
  3871. (unsigned short)take, st, href, 0);
  3872. off += take;
  3873. n -= take;
  3874. if (n) {
  3875. flush_line(l);
  3876. start_line(l, st);
  3877. avail = l->line_right - l->line_left;
  3878. }
  3879. }
  3880. }
  3881. static void emit_text(struct lay *l, const char *s, unsigned int len,
  3882. const struct br_style *st, unsigned short href, int pre)
  3883. {
  3884. unsigned int i = 0;
  3885. unsigned int base;
  3886. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  3887. if (!s || !len)
  3888. return;
  3889. if (space_w <= 0)
  3890. space_w = 8;
  3891. if (l->nruns == 0)
  3892. start_line(l, st);
  3893. base = (unsigned int)(s - doc.text);
  3894. if (st->uppercase) {
  3895. char *p = (char *)s;
  3896. unsigned int j;
  3897. for (j = 0; j < len; j++)
  3898. if (p[j] >= 'a' && p[j] <= 'z')
  3899. p[j] = (char)(p[j] - 'a' + 'A');
  3900. }
  3901. if (pre) {
  3902. while (i < len) {
  3903. unsigned int start;
  3904. if (s[i] == '\n') {
  3905. flush_line(l);
  3906. start_line(l, st);
  3907. i++;
  3908. continue;
  3909. }
  3910. if (s[i] == ' ') {
  3911. if (l->line_x + space_w > l->line_right &&
  3912. (l->nruns > 0 || l->line_x > l->line_left)) {
  3913. flush_line(l);
  3914. start_line(l, st);
  3915. } else {
  3916. l->line_x += space_w;
  3917. }
  3918. i++;
  3919. continue;
  3920. }
  3921. start = i;
  3922. while (i < len && s[i] != ' ' && s[i] != '\n')
  3923. i++;
  3924. emit_word(l, s, start, i - start, base, st, href);
  3925. }
  3926. return;
  3927. }
  3928. while (i < len) {
  3929. unsigned int start, n;
  3930. if (s[i] == ' ') {
  3931. l->space_pending = 1;
  3932. i++;
  3933. continue;
  3934. }
  3935. start = i;
  3936. while (i < len && s[i] != ' ')
  3937. i++;
  3938. n = i - start;
  3939. if (l->space_pending &&
  3940. (l->nruns > 0 || l->line_x > l->line_left)) {
  3941. if (st->nowrap ||
  3942. l->line_x + space_w <= l->line_right)
  3943. l->line_x += space_w;
  3944. }
  3945. l->space_pending = 0;
  3946. emit_word(l, s, start, n, base, st, href);
  3947. }
  3948. }
  3949. static int list_index(unsigned int parent, unsigned int node)
  3950. {
  3951. unsigned int n = 0, i;
  3952. for (i = doc.nodes[parent].first; i && i != node;
  3953. i = doc.nodes[i].next)
  3954. if (doc.nodes[i].tag == BR_TAG_LI)
  3955. n++;
  3956. return (int)n + 1;
  3957. }
  3958. static void add_form_run(struct lay *l, unsigned int node,
  3959. const struct br_style *st, unsigned short href)
  3960. {
  3961. struct form_state *fs = form_get(node, 1);
  3962. char shown[FORM_VALUE_MAX + 1];
  3963. char opt[64];
  3964. const char *text = "";
  3965. struct lay_run *r;
  3966. int kind = form_kind_of(node);
  3967. int disabled = form_disabled(node);
  3968. int tw, w = 120, h = 20, i;
  3969. if (!fs)
  3970. return;
  3971. if (l->nruns == 0)
  3972. start_line(l, st);
  3973. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  3974. text = "";
  3975. w = 16;
  3976. h = 16;
  3977. } else if (kind == FORM_SELECT) {
  3978. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  3979. s_copy(opt, "Select", sizeof(opt));
  3980. text = opt;
  3981. w = 120;
  3982. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  3983. kind == FORM_RESET) {
  3984. if (fs->len)
  3985. text = fs->value;
  3986. else
  3987. text = kind == FORM_SUBMIT ? "Submit" :
  3988. kind == FORM_RESET ? "Reset" : "Button";
  3989. } else if (kind == FORM_PASSWORD) {
  3990. for (i = 0; i < fs->len; i++)
  3991. shown[i] = '*';
  3992. shown[fs->len] = '\0';
  3993. text = fs->len ? shown : br_placeholder(&doc, node);
  3994. } else {
  3995. if (fs->len)
  3996. text = fs->value;
  3997. else
  3998. text = br_placeholder(&doc, node);
  3999. if (kind == FORM_TEXTAREA) {
  4000. w = 180;
  4001. h = 40;
  4002. }
  4003. }
  4004. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  4005. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  4006. w = tw + 18;
  4007. if (w < 64)
  4008. w = 64;
  4009. h = 22;
  4010. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  4011. w = st->width_kind == 1 ? st->width : 120;
  4012. } else if (kind == FORM_SELECT) {
  4013. w = st->width_kind == 1 ? st->width : 120;
  4014. }
  4015. if (w > l->line_right - l->line_left)
  4016. w = l->line_right - l->line_left;
  4017. if (w < 8)
  4018. w = 8;
  4019. if (l->line_x + w > l->line_right &&
  4020. (l->nruns > 0 || l->line_x > l->line_left))
  4021. flush_line(l);
  4022. if (l->nruns >= 96)
  4023. return;
  4024. if (l->nruns == 0) {
  4025. l->line_y = l->y;
  4026. l->line_h = 0;
  4027. start_line(l, st);
  4028. }
  4029. r = &l->runs[l->nruns++];
  4030. r->gap = (unsigned short)(l->line_x - l->run_x);
  4031. r->off = r->len = 0;
  4032. r->color = st->color;
  4033. r->href = href;
  4034. r->dy = 0;
  4035. r->has_lit = 1;
  4036. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  4037. r->lit[i] = text[i];
  4038. r->lit[i] = '\0';
  4039. r->img = -2;
  4040. r->iw = (unsigned short)w;
  4041. r->ih = (unsigned short)h;
  4042. r->w = (unsigned short)w;
  4043. r->font_px = st->font_px;
  4044. r->bold = st->bold;
  4045. r->italic = st->italic;
  4046. r->mono = st->mono;
  4047. r->font_face = st->font_face;
  4048. r->underline = 0;
  4049. r->form = node + 1;
  4050. r->form_kind = (unsigned char)kind;
  4051. r->form_disabled = (unsigned char)disabled;
  4052. if (node < BR_MAX_NODES) {
  4053. layout_boxes[node].x = l->line_x;
  4054. layout_boxes[node].y = l->line_y;
  4055. layout_boxes[node].w = w;
  4056. layout_boxes[node].h = h;
  4057. layout_boxes[node].valid = 1;
  4058. }
  4059. l->line_x += w;
  4060. l->run_x = l->line_x;
  4061. if (l->line_h < h)
  4062. l->line_h = h;
  4063. }
  4064. /* A poster wrapper is absolutely positioned over the media slot; the
  4065. * measured height of its picture is normally added back to the flow. When a
  4066. * loading-skeleton sibling already reserves that slot, adding both doubles
  4067. * the media height and pushes the article text a full screen down. */
  4068. static int has_skeleton_sibling(unsigned int node)
  4069. {
  4070. unsigned int p = doc.nodes[node].parent, c;
  4071. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  4072. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  4073. continue;
  4074. if (doc.nodes[c].class_off &&
  4075. contains_ci(doc.attrs + doc.nodes[c].class_off,
  4076. "skeleton"))
  4077. return 1;
  4078. }
  4079. return 0;
  4080. }
  4081. static void layout_children(struct lay *l, unsigned int parent,
  4082. const struct br_style *pst, int depth,
  4083. unsigned short link);
  4084. static void layout_flex_children(struct lay *l, unsigned int parent,
  4085. const struct br_style *pst, int depth,
  4086. unsigned short link);
  4087. static void layout_grid_children(struct lay *l, unsigned int parent,
  4088. const struct br_style *pst, int depth,
  4089. unsigned short link);
  4090. static void layout_grid_auto(struct lay *l, unsigned int parent,
  4091. const struct br_style *pst, int depth,
  4092. unsigned short link);
  4093. static int flex_item_width(struct lay *l, unsigned int n,
  4094. const struct br_style *cs, int avail);
  4095. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  4096. const struct br_style *pst, int depth,
  4097. unsigned short link);
  4098. static void layout_table_row(struct lay *l, unsigned int row,
  4099. const struct br_style *pst, int depth,
  4100. unsigned short link);
  4101. static int table_has_rowspan(unsigned int table);
  4102. static void layout_table(struct lay *l, unsigned int table,
  4103. const struct br_style *st, int depth,
  4104. unsigned short link);
  4105. /* A flex container whose items are only inline spans is usually just a
  4106. * heading/icon pair. Our flex row positions such items without emitting
  4107. * their inline text in some deep page contexts; normal inline flow renders
  4108. * the same content correctly. */
  4109. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  4110. {
  4111. unsigned int c;
  4112. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  4113. struct br_node *nd = &doc.nodes[c];
  4114. struct br_style cs;
  4115. if (nd->type == BR_NODE_TEXT)
  4116. continue;
  4117. br_style_for(&doc, c, pst, &cs);
  4118. if (cs.display == BR_DISPLAY_NONE)
  4119. continue;
  4120. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  4121. cs.width_kind || cs.has_bg ||
  4122. cs.border_w[0] || cs.border_w[1] ||
  4123. cs.border_w[2] || cs.border_w[3] ||
  4124. nd->tag == BR_TAG_IMG)
  4125. return 1;
  4126. }
  4127. return 0;
  4128. }
  4129. static int css_radius(const struct br_style *st, int corner,
  4130. int w, int h)
  4131. {
  4132. int r = st->radius[corner];
  4133. if (r <= 0)
  4134. return 0;
  4135. if (r > w / 2)
  4136. r = w / 2;
  4137. if (r > h / 2)
  4138. r = h / 2;
  4139. return r;
  4140. }
  4141. static void svg_viewbox(unsigned node, int *vw, int *vh)
  4142. {
  4143. struct br_node *nd = &doc.nodes[node];
  4144. if (nd->width_attr && nd->height_attr) {
  4145. *vw = nd->width_attr;
  4146. *vh = nd->height_attr;
  4147. } else {
  4148. *vw = 300;
  4149. *vh = 150;
  4150. }
  4151. if (*vw < 1)
  4152. *vw = 1;
  4153. if (*vh < 1)
  4154. *vh = 1;
  4155. }
  4156. static int svg_num(const char **pp)
  4157. {
  4158. const char *p = *pp;
  4159. int neg = 0, v = 0, frac = 0, scale = 1;
  4160. while (*p == ' ' || *p == ',' || *p == '\t' ||
  4161. *p == '\n' || *p == '\r')
  4162. p++;
  4163. if (*p == '-') {
  4164. neg = 1;
  4165. p++;
  4166. } else if (*p == '+') {
  4167. p++;
  4168. }
  4169. while (*p >= '0' && *p <= '9') {
  4170. v = v * 10 + (*p - '0');
  4171. p++;
  4172. }
  4173. if (*p == '.') {
  4174. p++;
  4175. while (*p >= '0' && *p <= '9' && scale < 1000) {
  4176. frac = frac * 10 + (*p - '0');
  4177. scale *= 10;
  4178. p++;
  4179. }
  4180. }
  4181. v += frac / scale;
  4182. *pp = p;
  4183. return neg ? -v : v;
  4184. }
  4185. static void svg_path(struct ngui *ui, const char *d,
  4186. int ox, int oy, int dw, int dh, int vw, int vh,
  4187. unsigned short color)
  4188. {
  4189. int cx = 0, cy = 0, sx = 0, sy = 0;
  4190. char cmd = 0;
  4191. const char *p = d;
  4192. while (p && *p) {
  4193. int rel, nx, ny;
  4194. char c;
  4195. while (*p == ' ' || *p == ',' || *p == '\t' ||
  4196. *p == '\n' || *p == '\r')
  4197. p++;
  4198. if (!*p)
  4199. break;
  4200. if ((*p >= 'A' && *p <= 'Z') ||
  4201. (*p >= 'a' && *p <= 'z'))
  4202. cmd = *p++;
  4203. else if (!cmd) {
  4204. p++;
  4205. continue;
  4206. }
  4207. rel = cmd >= 'a' && cmd <= 'z';
  4208. c = rel ? (char)(cmd - 'a' + 'A') : cmd;
  4209. if (c == 'Z') {
  4210. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  4211. ox + sx * dw / vw, oy + sy * dh / vh,
  4212. color);
  4213. cx = sx;
  4214. cy = sy;
  4215. cmd = 0;
  4216. continue;
  4217. }
  4218. if (c == 'H' || c == 'V') {
  4219. const char *save = p;
  4220. int a = svg_num(&p);
  4221. if (p == save) {
  4222. p++;
  4223. continue;
  4224. }
  4225. nx = cx;
  4226. ny = cy;
  4227. if (c == 'H')
  4228. nx = rel ? cx + a : a;
  4229. else
  4230. ny = rel ? cy + a : a;
  4231. } else {
  4232. const char *save = p;
  4233. int a = svg_num(&p);
  4234. int b = svg_num(&p);
  4235. if (p == save) {
  4236. p++;
  4237. continue;
  4238. }
  4239. if (c == 'M') {
  4240. nx = rel ? cx + a : a;
  4241. ny = rel ? cy + b : b;
  4242. cx = sx = nx;
  4243. cy = sy = ny;
  4244. cmd = rel ? 'l' : 'L';
  4245. continue;
  4246. }
  4247. if (c != 'L')
  4248. break;
  4249. nx = rel ? cx + a : a;
  4250. ny = rel ? cy + b : b;
  4251. }
  4252. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  4253. ox + nx * dw / vw, oy + ny * dh / vh, color);
  4254. cx = nx;
  4255. cy = ny;
  4256. }
  4257. }
  4258. static void draw_svg(struct ngui *ui, unsigned node,
  4259. int ox, int oy, int dw, int dh, int vw, int vh,
  4260. const struct br_style *pst)
  4261. {
  4262. unsigned int c;
  4263. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  4264. struct br_node *nd = &doc.nodes[c];
  4265. struct br_style st;
  4266. const char *nm;
  4267. if (nd->type != BR_NODE_ELEM || !nd->name_off)
  4268. continue;
  4269. nm = doc.attrs + nd->name_off;
  4270. br_style_for(&doc, c, pst, &st);
  4271. if (s_eq(nm, "rect")) {
  4272. struct ngui_rect r;
  4273. int rx = (int)nd->svg_rx * dw / vw;
  4274. r.x = ox + (int)nd->svg_x * dw / vw;
  4275. r.y = oy + (int)nd->svg_y * dh / vh;
  4276. r.w = (int)nd->width_attr * dw / vw;
  4277. r.h = (int)nd->height_attr * dh / vh;
  4278. if (r.w < 1)
  4279. r.w = 1;
  4280. if (r.h < 1)
  4281. r.h = 1;
  4282. if (rx > r.w / 2)
  4283. rx = r.w / 2;
  4284. if (rx > r.h / 2)
  4285. rx = r.h / 2;
  4286. if (st.has_bg) {
  4287. if (rx)
  4288. ngui_fill_round_rect(ui, r, rx, rx,
  4289. rx, rx, st.bg);
  4290. else
  4291. ngui_fill_rect(ui, r, st.bg);
  4292. }
  4293. if (st.border_w[0]) {
  4294. if (rx)
  4295. ngui_frame_round(ui, r, rx, rx, rx, rx,
  4296. st.border_w[0],
  4297. st.border_c[0]);
  4298. else
  4299. draw_border_box(ui, r, &st);
  4300. }
  4301. } else if (s_eq(nm, "line")) {
  4302. if (st.border_w[0])
  4303. ngui_line(ui,
  4304. ox + (int)nd->svg_x * dw / vw,
  4305. oy + (int)nd->svg_y * dh / vh,
  4306. ox + (int)nd->width_attr * dw / vw,
  4307. oy + (int)nd->height_attr * dh / vh,
  4308. st.border_c[0]);
  4309. } else if (s_eq(nm, "path")) {
  4310. if (st.border_w[0] && nd->src_off)
  4311. svg_path(ui, doc.attrs + nd->src_off,
  4312. ox, oy, dw, dh, vw, vh,
  4313. st.border_c[0]);
  4314. } else if (s_eq(nm, "text")) {
  4315. unsigned int t = nd->first;
  4316. const char *s;
  4317. unsigned int n, tw;
  4318. int px = st.font_px ? st.font_px : 16;
  4319. int tx, ty, anchor;
  4320. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  4321. continue;
  4322. s = doc.text + doc.nodes[t].text_off;
  4323. n = doc.nodes[t].text_len;
  4324. tw = face_text_width(ui, &st, s, n);
  4325. tx = ox + (int)nd->svg_x * dw / vw;
  4326. ty = oy + (int)nd->svg_y * dh / vh -
  4327. ngui_text_ascent_face(ui, style_face(&st), px,
  4328. st.mono);
  4329. anchor = st.align;
  4330. if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  4331. anchor = BR_ALIGN_CENTER;
  4332. else if (nd->attr_flags & BR_ATTR_ANCHOR_END)
  4333. anchor = BR_ALIGN_RIGHT;
  4334. if (anchor == BR_ALIGN_CENTER)
  4335. tx -= (int)tw / 2;
  4336. else if (anchor == BR_ALIGN_RIGHT)
  4337. tx -= (int)tw;
  4338. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  4339. st.color, px, st.bold, st.italic,
  4340. st.mono);
  4341. }
  4342. }
  4343. }
  4344. static void layout_block(struct lay *l, unsigned int node,
  4345. const struct br_style *st, int depth,
  4346. unsigned short link)
  4347. {
  4348. int old_left = l->left, old_right = l->right, old_align = l->align;
  4349. int saved_parent_top = l->parent_top;
  4350. int top, l0, r0;
  4351. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  4352. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  4353. int deco_w, deco_h, content_w, content_h, box_h;
  4354. int definite_w = 0;
  4355. int normal_top = 0;
  4356. int rel_dx = 0, rel_dy = 0;
  4357. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  4358. return;
  4359. flow_y = l->y;
  4360. flow_left = l->left;
  4361. flow_right = l->right;
  4362. positioned = st->pos == 1 || st->pos == 2;
  4363. relative = st->pos == 3;
  4364. sticky = st->pos == 4;
  4365. shifted = relative || sticky || st->transform_set;
  4366. if (positioned) {
  4367. int def_w = st->width_kind == 1 ? st->width : -1;
  4368. if (st->pos == 2) {
  4369. int avail_w = page_rect.w - 12;
  4370. if (st->right_set && def_w >= 0)
  4371. l->left = page_rect.x + avail_w - st->right -
  4372. def_w;
  4373. else
  4374. l->left = page_rect.x +
  4375. (st->left_set ? st->left : 0);
  4376. l->right = def_w >= 0 ? l->left + def_w :
  4377. page_rect.x + avail_w;
  4378. if (st->bottom_set && st->height_kind)
  4379. l->y = page_rect.y + page_rect.h -
  4380. st->bottom -
  4381. style_height_px(st, page_rect.w);
  4382. else
  4383. l->y = page_rect.y +
  4384. (st->top_set ? st->top : 0);
  4385. } else {
  4386. int left = flow_left + (st->left_set ? st->left : 0);
  4387. unsigned int parent = doc.nodes[node].parent;
  4388. if (st->right_set && def_w >= 0)
  4389. left = flow_right - st->right - def_w;
  4390. l->left = left;
  4391. l->right = def_w >= 0 ? left + def_w :
  4392. flow_right +
  4393. (st->left_set ? st->left : 0);
  4394. l->y = flow_y + (st->top_set ? st->top : 0);
  4395. if (st->bottom_set && st->height_kind &&
  4396. parent < BR_MAX_NODES && block_h[parent] > 0)
  4397. l->y = flow_y + block_h[parent] - st->bottom -
  4398. style_height_px(st, old_right - old_left);
  4399. }
  4400. old_left = l->left;
  4401. old_right = l->right;
  4402. } else if (relative) {
  4403. rel_dx = st->left_set ? st->left :
  4404. (st->right_set ? -st->right : 0);
  4405. rel_dy = st->top_set ? st->top :
  4406. (st->bottom_set ? -st->bottom : 0);
  4407. }
  4408. if (st->transform_set) {
  4409. rel_dx += st->tx;
  4410. rel_dy += st->ty;
  4411. }
  4412. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  4413. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  4414. doc.nodes[node].tag == BR_TAG_SELECT ||
  4415. doc.nodes[node].tag == BR_TAG_BUTTON) {
  4416. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  4417. s_eq(br_type(&doc, node), "hidden"))
  4418. return;
  4419. add_form_run(l, node, st, link);
  4420. l->y += doc.nodes[node].tag == BR_TAG_TEXTAREA ? 40 :
  4421. doc.nodes[node].tag == BR_TAG_BUTTON ? 22 : 20;
  4422. return;
  4423. }
  4424. flush_line(l);
  4425. cbw = old_right - old_left;
  4426. if (cbw < 8)
  4427. cbw = 8;
  4428. l->y += mp_px(st, 0, cbw);
  4429. top = l->y;
  4430. ml = mp_px(st, 3, cbw);
  4431. mr = mp_px(st, 1, cbw);
  4432. bl = st->border_w[3];
  4433. br = st->border_w[1];
  4434. pl = mp_px(st, 7, cbw);
  4435. pr = mp_px(st, 5, cbw);
  4436. bt = st->border_w[0];
  4437. bb = st->border_w[2];
  4438. pt = mp_px(st, 4, cbw);
  4439. pb = mp_px(st, 6, cbw);
  4440. deco_w = bl + br + pl + pr;
  4441. deco_h = bt + bb + pt + pb;
  4442. if (st->width_kind) {
  4443. int w;
  4444. if (st->width_kind == 3)
  4445. w = cbw * st->width_calc_pct / 100 +
  4446. st->width_calc_px;
  4447. else
  4448. w = css_size(st->width_kind, st->width, cbw);
  4449. if (w < 0)
  4450. w = 0;
  4451. content_w = st->box_sizing ? w - deco_w : w;
  4452. definite_w = 1;
  4453. } else {
  4454. content_w = cbw - ml - mr - deco_w;
  4455. }
  4456. if (content_w < 0)
  4457. content_w = 0;
  4458. if (st->max_width_kind) {
  4459. int mw = st->max_width_kind == 3 ?
  4460. cbw * st->max_width_calc_pct / 100 +
  4461. st->max_width_calc_px :
  4462. css_size(st->max_width_kind, st->max_width, cbw);
  4463. int max_box = st->box_sizing ? mw : mw + deco_w;
  4464. if (content_w + deco_w > max_box)
  4465. content_w = max_box - deco_w;
  4466. }
  4467. if (st->min_width_kind) {
  4468. int mw = st->min_width_kind == 3 ?
  4469. cbw * st->min_width_calc_pct / 100 +
  4470. st->min_width_calc_px :
  4471. css_size(st->min_width_kind, st->min_width, cbw);
  4472. int min_box = st->box_sizing ? mw : mw + deco_w;
  4473. if (content_w + deco_w < min_box) {
  4474. content_w = min_box - deco_w;
  4475. definite_w = 1;
  4476. }
  4477. }
  4478. if (content_w < 8)
  4479. content_w = 8;
  4480. if (definite_w) {
  4481. int free_w = cbw - ml - mr - deco_w - content_w;
  4482. if (free_w < 0)
  4483. free_w = 0;
  4484. if (st->ml_auto && st->mr_auto) {
  4485. ml = free_w / 2;
  4486. mr = free_w - ml;
  4487. } else if (st->ml_auto) {
  4488. ml = free_w;
  4489. } else if (st->mr_auto) {
  4490. mr = free_w;
  4491. }
  4492. }
  4493. l0 = old_left + ml;
  4494. r0 = l0 + deco_w + content_w;
  4495. if (r0 < l0 + 8)
  4496. r0 = l0 + 8;
  4497. normal_top = top;
  4498. if (sticky) {
  4499. if (st->top_set) {
  4500. int stick = page_rect.y + 4 + st->top;
  4501. if (normal_top < stick)
  4502. rel_dy += stick - normal_top;
  4503. } else if (st->bottom_set && block_h[node]) {
  4504. int stick = page_rect.y + page_rect.h - st->bottom -
  4505. block_h[node];
  4506. if (normal_top > stick)
  4507. rel_dy += stick - normal_top;
  4508. }
  4509. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  4510. block_h[doc.nodes[node].parent]) {
  4511. unsigned int p = doc.nodes[node].parent;
  4512. int ptop = l->parent_top;
  4513. int pbottom = ptop + block_h[p];
  4514. int eh = block_h[node];
  4515. int moved_top = normal_top + rel_dy;
  4516. int moved_bottom = moved_top + eh;
  4517. if (moved_bottom > pbottom)
  4518. rel_dy -= moved_bottom - pbottom;
  4519. moved_top = normal_top + rel_dy;
  4520. if (moved_top < ptop)
  4521. rel_dy += ptop - moved_top;
  4522. }
  4523. }
  4524. if (shifted && l->draw) {
  4525. top += rel_dy;
  4526. l0 += rel_dx;
  4527. r0 += rel_dx;
  4528. }
  4529. l->parent_top = top;
  4530. if (l->draw && block_h[node] &&
  4531. top < page_rect.y + page_rect.h &&
  4532. top + block_h[node] > page_rect.y) {
  4533. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  4534. int rtl = css_radius(st, 0, box.w, box.h);
  4535. int rtr = css_radius(st, 1, box.w, box.h);
  4536. int rbr = css_radius(st, 2, box.w, box.h);
  4537. int rbl = css_radius(st, 3, box.w, box.h);
  4538. if (st->transform_scale) {
  4539. if (st->has_bg)
  4540. fill_transformed_rect(l->ui, box, st->bg, st);
  4541. } else if (rtl || rtr || rbr || rbl) {
  4542. if (st->has_bg) {
  4543. int bw = st->border_w[0];
  4544. if (bw > 0 && st->border_c[0] != st->bg &&
  4545. box.w > bw * 2 && box.h > bw * 2) {
  4546. struct ngui_rect inner = {
  4547. box.x + bw, box.y + bw,
  4548. box.w - bw * 2, box.h - bw * 2
  4549. };
  4550. int itl = rtl > bw ? rtl - bw : 0;
  4551. int itr = rtr > bw ? rtr - bw : 0;
  4552. int ibr = rbr > bw ? rbr - bw : 0;
  4553. int ibl = rbl > bw ? rbl - bw : 0;
  4554. ngui_fill_round_rect(l->ui, box, rtl,
  4555. rtr, rbr, rbl,
  4556. st->border_c[0]);
  4557. ngui_fill_round_rect(l->ui, inner,
  4558. itl, itr, ibr,
  4559. ibl, st->bg);
  4560. } else {
  4561. ngui_fill_round_rect(l->ui, box, rtl,
  4562. rtr, rbr, rbl,
  4563. st->bg);
  4564. }
  4565. } else if (st->border_w[0]) {
  4566. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  4567. rbl, st->border_w[0],
  4568. st->border_c[0]);
  4569. }
  4570. } else {
  4571. if (st->has_bg)
  4572. ngui_fill_rect(l->ui, box, st->bg);
  4573. if (st->bg_image)
  4574. draw_bg_image(l, box, node, st);
  4575. if (st->border_w[0] || st->border_w[1] ||
  4576. st->border_w[2] || st->border_w[3])
  4577. draw_border_box(l->ui, box, st);
  4578. }
  4579. }
  4580. l->left = l0 + bl + pl;
  4581. l->right = l->left + content_w;
  4582. if (l->right < l->left + 8)
  4583. l->right = l->left + 8;
  4584. l->align = st->align;
  4585. l->line_left = l->left;
  4586. l->line_right = l->right;
  4587. l->y = top + bt + pt;
  4588. if (doc.nodes[node].tag == BR_TAG_HR) {
  4589. if (l->draw)
  4590. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  4591. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  4592. l->y += 8;
  4593. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  4594. int vw = l->right - l->left;
  4595. int vh;
  4596. if (doc.nodes[node].width_pct)
  4597. vw = vw * doc.nodes[node].width_attr / 100;
  4598. else if (doc.nodes[node].width_attr)
  4599. vw = doc.nodes[node].width_attr;
  4600. if (vw > l->right - l->left)
  4601. vw = l->right - l->left;
  4602. if (vw < 8)
  4603. vw = 8;
  4604. vh = vw * 9 / 16;
  4605. if (vh > 240)
  4606. vh = 240;
  4607. if (vh < 80)
  4608. vh = 80;
  4609. if (l->draw) {
  4610. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  4611. vw, vh}, 0xD69A);
  4612. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  4613. vw, vh}, 0x8410);
  4614. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  4615. 0x4208);
  4616. }
  4617. l->y += vh + 4;
  4618. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  4619. int vw, vh, dw = l->right - l->left;
  4620. int dh;
  4621. svg_viewbox(node, &vw, &vh);
  4622. if (dw < 8)
  4623. dw = 8;
  4624. dh = dw * vh / vw;
  4625. if (dh < 8)
  4626. dh = 8;
  4627. if (dh > 1400)
  4628. dh = 1400;
  4629. if (l->draw) {
  4630. struct ngui_rect clip = {l->left, l->y, dw, dh};
  4631. ngui_push_clip(l->ui, clip);
  4632. draw_svg(l->ui, node, l->left, l->y, dw, dh,
  4633. vw, vh, st);
  4634. ngui_pop_clip(l->ui);
  4635. }
  4636. l->y += dh;
  4637. } else {
  4638. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  4639. !st->no_bullet) {
  4640. char *m = li_marker[node];
  4641. if (!m[0]) {
  4642. unsigned int parent = doc.nodes[node].parent;
  4643. if (parent &&
  4644. doc.nodes[parent].tag == BR_TAG_OL) {
  4645. int idx = list_index(parent, node);
  4646. unsigned int n = 0;
  4647. s_append_dec(m, &n, (unsigned int)idx, 6);
  4648. s_append(m, &n, ".", 6);
  4649. } else {
  4650. s_copy(m, "-", 6);
  4651. }
  4652. }
  4653. if (l->draw) {
  4654. int mw = (int)ngui_text_width_ui(l->ui, m);
  4655. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  4656. st->color);
  4657. }
  4658. }
  4659. if (doc.nodes[node].tag == BR_TAG_TR)
  4660. layout_table_row(l, node, st, depth + 1, link);
  4661. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  4662. table_has_rowspan(node))
  4663. layout_table(l, node, st, depth + 1, link);
  4664. else if (st->grid_auto)
  4665. layout_grid_auto(l, node, st, depth + 1, link);
  4666. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  4667. st->grid_gap > 0)
  4668. layout_grid_children(l, node, st, depth + 1, link);
  4669. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  4670. flex_wants_row(node, st))
  4671. layout_flex_children(l, node, st, depth + 1, link);
  4672. else
  4673. layout_children(l, node, st, depth + 1, link);
  4674. }
  4675. flush_line(l);
  4676. if (l->float_active) {
  4677. if (l->y < l->float_bottom)
  4678. l->y = l->float_bottom;
  4679. l->float_active = 0;
  4680. }
  4681. if (st->height_kind) {
  4682. content_h = style_height_px(st, cbw);
  4683. if (st->box_sizing)
  4684. content_h -= deco_h;
  4685. } else {
  4686. content_h = l->y - (top + bt + pt);
  4687. }
  4688. if (content_h < 0)
  4689. content_h = 0;
  4690. if (st->max_height_kind) {
  4691. int mh = st->max_height_kind == 3 ?
  4692. cbw * st->max_height_calc_pct / 100 +
  4693. st->max_height_calc_px :
  4694. css_size(st->max_height_kind, st->max_height, cbw);
  4695. int max_box = st->box_sizing ? mh : mh + deco_h;
  4696. if (content_h + deco_h > max_box)
  4697. content_h = max_box - deco_h;
  4698. }
  4699. if (st->min_height_kind) {
  4700. int mh = st->min_height_kind == 3 ?
  4701. cbw * st->min_height_calc_pct / 100 +
  4702. st->min_height_calc_px :
  4703. css_size(st->min_height_kind, st->min_height, cbw);
  4704. int min_box = st->box_sizing ? mh : mh + deco_h;
  4705. if (content_h + deco_h < min_box)
  4706. content_h = min_box - deco_h;
  4707. }
  4708. if (content_h < 0)
  4709. content_h = 0;
  4710. box_h = deco_h + content_h;
  4711. if (box_h < 0)
  4712. box_h = 0;
  4713. l->y = (shifted ? normal_top : top) + box_h;
  4714. if (node < BR_MAX_NODES) {
  4715. layout_boxes[node].x = l0;
  4716. layout_boxes[node].y = top;
  4717. layout_boxes[node].w = r0 - l0;
  4718. layout_boxes[node].h = box_h;
  4719. layout_boxes[node].valid = r0 > l0;
  4720. }
  4721. l->left = old_left;
  4722. l->right = old_right;
  4723. l->align = old_align;
  4724. l->y += mp_px(st, 2, cbw);
  4725. if (!l->draw) {
  4726. if (box_h > 65535)
  4727. box_h = 65535;
  4728. block_h[node] = (unsigned short)box_h;
  4729. }
  4730. if (positioned) {
  4731. l->y = flow_y;
  4732. l->left = flow_left;
  4733. l->right = flow_right;
  4734. }
  4735. l->parent_top = saved_parent_top;
  4736. }
  4737. static int text_node_blank(const struct br_node *nd)
  4738. {
  4739. const char *t = doc.text + nd->text_off;
  4740. unsigned int i;
  4741. for (i = 0; i < nd->text_len; i++)
  4742. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  4743. t[i] != '\r')
  4744. return 0;
  4745. return 1;
  4746. }
  4747. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  4748. * text/image widths in the subtree, plus padding and margins. This keeps
  4749. * Bootstrap's floated nav items on one line instead of giving each the whole
  4750. * row. */
  4751. static int text_space(char c)
  4752. {
  4753. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  4754. }
  4755. static int intrinsic_width(struct ngui *ui, unsigned int node,
  4756. const struct br_style *pst, int depth, int base)
  4757. {
  4758. unsigned int c;
  4759. int w = 0;
  4760. if (depth > 12)
  4761. return 0;
  4762. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  4763. struct br_node *nd = &doc.nodes[c];
  4764. struct br_style cs;
  4765. if (nd->type == BR_NODE_TEXT) {
  4766. const char *t = doc.text + nd->text_off;
  4767. unsigned int tn = nd->text_len;
  4768. if (doc.nodes[node].tag == BR_TAG_PRE) {
  4769. w += (int)face_text_width(ui, pst, t, tn);
  4770. } else {
  4771. unsigned int ti = 0;
  4772. int first = 1;
  4773. int lead = w > 0 && tn > 0 && text_space(t[0]);
  4774. int sp = (int)face_text_width(ui, pst, " ", 1);
  4775. while (ti < tn) {
  4776. unsigned int ts;
  4777. while (ti < tn && text_space(t[ti]))
  4778. ti++;
  4779. ts = ti;
  4780. while (ti < tn && !text_space(t[ti]))
  4781. ti++;
  4782. if (ti == ts)
  4783. break;
  4784. if (!first || lead)
  4785. w += sp;
  4786. lead = 0;
  4787. w += (int)face_text_width(ui, pst,
  4788. t + ts, ti - ts);
  4789. first = 0;
  4790. }
  4791. }
  4792. continue;
  4793. }
  4794. br_style_for(&doc, c, pst, &cs);
  4795. if (cs.display == BR_DISPLAY_NONE)
  4796. continue;
  4797. if (nd->tag == BR_TAG_BR) {
  4798. w += 8;
  4799. continue;
  4800. }
  4801. if (nd->tag == BR_TAG_IMG) {
  4802. /* Measure the image as layout will draw it: a CSS or
  4803. * attribute height keeps the intrinsic aspect ratio, and
  4804. * a CSS width overrides the native pixel width. Bootstrap
  4805. * sizes the Cloudron logo with height:40px only. */
  4806. int idx = nd->img_index;
  4807. int iw = 0, ih = 0;
  4808. if (idx >= 0 && idx < image_count &&
  4809. images[idx].state == 1) {
  4810. iw = (int)images[idx].native_w;
  4811. ih = (int)images[idx].native_h;
  4812. if (iw <= 0 || ih <= 0) {
  4813. iw = (int)images[idx].img.w;
  4814. ih = (int)images[idx].img.h;
  4815. }
  4816. }
  4817. if (cs.width_kind) {
  4818. int ww = style_width_px(&cs, base);
  4819. w += ww > 0 ? ww : 64;
  4820. } else if (nd->width_attr) {
  4821. w += nd->width_attr;
  4822. } else if (nd->height_attr && iw && ih) {
  4823. w += iw * (int)nd->height_attr / ih;
  4824. } else if (cs.height_kind && iw && ih) {
  4825. int hh = style_height_px(&cs, base);
  4826. w += hh > 0 ? iw * hh / ih : iw;
  4827. } else if (iw) {
  4828. w += iw;
  4829. } else {
  4830. w += 64;
  4831. }
  4832. continue;
  4833. }
  4834. w += mp_px(&cs, 7, base) +
  4835. mp_px(&cs, 5, base) +
  4836. mp_px(&cs, 3, base) +
  4837. mp_px(&cs, 1, base);
  4838. w += intrinsic_width(ui, c, &cs, depth + 1, base);
  4839. if (w > 4096)
  4840. break;
  4841. }
  4842. return w;
  4843. }
  4844. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  4845. * the main user: .row > .col-md-* with float:left and a percentage width.
  4846. * Each column is laid out with its own left/right edge and the row advances
  4847. * to the tallest column. Returns the first child not consumed. */
  4848. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  4849. const struct br_style *pst, int depth,
  4850. unsigned short link)
  4851. {
  4852. unsigned int n = first;
  4853. int row_left = l->left, row_right = l->right;
  4854. int row_top, row_bottom, xl, xr, any = 0;
  4855. int fl_left = row_left, fl_right = row_right, fl_bottom;
  4856. flush_line(l);
  4857. row_top = l->y;
  4858. row_bottom = l->y;
  4859. fl_bottom = row_top;
  4860. xl = row_left;
  4861. xr = row_right;
  4862. while (n) {
  4863. struct br_node *nd = &doc.nodes[n];
  4864. struct br_style cs;
  4865. unsigned short lk = link;
  4866. int colw, right;
  4867. if (nd->type == BR_NODE_TEXT) {
  4868. if (text_node_blank(nd)) {
  4869. n = nd->next;
  4870. continue;
  4871. }
  4872. break;
  4873. }
  4874. br_style_for(&doc, n, pst, &cs);
  4875. if (cs.display == BR_DISPLAY_NONE) {
  4876. n = nd->next;
  4877. continue;
  4878. }
  4879. /* A float blockifies its box: Bootstrap floats inline
  4880. * anchors too (the navbar brand and its text links), and
  4881. * their padding must be honoured. */
  4882. if (!cs.float_left)
  4883. break;
  4884. if (nd->tag == BR_TAG_A && nd->href_off)
  4885. lk = (unsigned short)n;
  4886. right = cs.float_left == 2;
  4887. if (cs.width_kind == 2 || cs.width_kind == 3) {
  4888. colw = style_width_px(&cs, row_right - row_left);
  4889. } else if (cs.width_kind == 1) {
  4890. colw = (int)cs.width;
  4891. } else {
  4892. int base = row_right - row_left;
  4893. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  4894. mp_px(&cs, 7, base) +
  4895. mp_px(&cs, 5, base) +
  4896. mp_px(&cs, 3, base) +
  4897. mp_px(&cs, 1, base);
  4898. if (colw < 8)
  4899. colw = 8;
  4900. }
  4901. if (colw < 8)
  4902. colw = 8;
  4903. if (colw > row_right - row_left)
  4904. colw = row_right - row_left;
  4905. /* The float column width is already resolved. */
  4906. cs.width_kind = 0;
  4907. cs.max_width_kind = 0;
  4908. if (right) {
  4909. if (any && xr - colw < xl) {
  4910. row_top = row_bottom;
  4911. row_bottom = row_top;
  4912. xl = row_left;
  4913. xr = row_right;
  4914. }
  4915. if (xr - colw < xl)
  4916. colw = xr - xl;
  4917. if (colw < 8)
  4918. colw = 8;
  4919. l->left = xr - colw;
  4920. if (l->left < row_left)
  4921. l->left = row_left;
  4922. l->right = xr;
  4923. xr = l->left;
  4924. if (xr < fl_right)
  4925. fl_right = xr;
  4926. } else {
  4927. if (any && xl + colw > xr) {
  4928. row_top = row_bottom;
  4929. row_bottom = row_top;
  4930. xl = row_left;
  4931. xr = row_right;
  4932. }
  4933. l->left = xl;
  4934. l->right = xl + colw;
  4935. xl += colw;
  4936. if (xl > fl_left)
  4937. fl_left = xl;
  4938. }
  4939. if (l->right < l->left + 8)
  4940. l->right = l->left + 8;
  4941. l->y = row_top;
  4942. l->line_x = l->left;
  4943. l->run_x = l->left;
  4944. l->line_y = l->y;
  4945. l->line_h = 0;
  4946. l->nruns = 0;
  4947. l->space_pending = 0;
  4948. l->align = cs.align;
  4949. layout_block(l, n, &cs, depth + 1, lk);
  4950. if (l->y > row_bottom)
  4951. row_bottom = l->y;
  4952. if (l->y > fl_bottom)
  4953. fl_bottom = l->y;
  4954. any = 1;
  4955. n = nd->next;
  4956. }
  4957. l->left = row_left;
  4958. l->right = row_right;
  4959. if (n && any) {
  4960. struct br_node *nd = &doc.nodes[n];
  4961. int inline_next = 0;
  4962. if (nd->type == BR_NODE_TEXT) {
  4963. inline_next = 1;
  4964. } else if (nd->type == BR_NODE_ELEM) {
  4965. struct br_style cs;
  4966. br_style_for(&doc, n, pst, &cs);
  4967. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  4968. cs.display != BR_DISPLAY_NONE &&
  4969. !br_tag_is_block(nd->tag);
  4970. }
  4971. if (inline_next) {
  4972. if (l->float_active) {
  4973. if (l->float_left > fl_left)
  4974. fl_left = l->float_left;
  4975. if (l->float_right < fl_right)
  4976. fl_right = l->float_right;
  4977. if (l->float_bottom > fl_bottom)
  4978. fl_bottom = l->float_bottom;
  4979. }
  4980. l->float_active = 1;
  4981. l->float_left = fl_left;
  4982. l->float_right = fl_right;
  4983. l->float_bottom = fl_bottom;
  4984. l->y = row_top;
  4985. } else {
  4986. l->float_active = 0;
  4987. l->y = row_bottom;
  4988. }
  4989. } else {
  4990. l->float_active = 0;
  4991. l->y = row_bottom;
  4992. }
  4993. l->line_x = l->left;
  4994. l->run_x = l->left;
  4995. l->line_left = l->left;
  4996. l->line_right = l->right;
  4997. l->line_y = l->y;
  4998. l->line_h = 0;
  4999. l->nruns = 0;
  5000. l->space_pending = 0;
  5001. return n;
  5002. }
  5003. static int flex_item_width(struct lay *l, unsigned int n,
  5004. const struct br_style *cs, int avail)
  5005. {
  5006. struct br_node *nd = &doc.nodes[n];
  5007. (void)l;
  5008. int w;
  5009. if (cs->width_kind == 2 || cs->width_kind == 3)
  5010. w = style_width_px(cs, avail);
  5011. else if (cs->width_kind == 1)
  5012. w = (int)cs->width;
  5013. else if (nd->tag == BR_TAG_IMG) {
  5014. int idx = nd->img_index;
  5015. if (idx >= 0 && idx < image_count &&
  5016. images[idx].state == 1)
  5017. w = (int)images[idx].img.w;
  5018. else if (nd->width_attr)
  5019. w = (int)nd->width_attr;
  5020. else
  5021. w = 64;
  5022. } else {
  5023. w = intrinsic_width(l->ui, n, cs, 0, avail);
  5024. w += mp_px(cs, 7, avail);
  5025. w += mp_px(cs, 5, avail);
  5026. w += mp_px(cs, 3, avail);
  5027. w += mp_px(cs, 1, avail);
  5028. }
  5029. if (w < 24)
  5030. w = 24;
  5031. if (w > avail)
  5032. w = avail;
  5033. return w;
  5034. }
  5035. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  5036. * on one line, not one full-width block each. Place intrinsic widths from
  5037. * left to right and wrap when the row is full. */
  5038. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  5039. const struct br_style *pst, int depth,
  5040. unsigned short link)
  5041. {
  5042. unsigned int n = first;
  5043. int row_left = l->left, row_right = l->right;
  5044. int avail = row_right - row_left;
  5045. int x = row_left, y = l->y, row_h = 0, any = 0;
  5046. flush_line(l);
  5047. y = l->y;
  5048. while (n) {
  5049. struct br_node *nd = &doc.nodes[n];
  5050. struct br_style cs;
  5051. unsigned short lk = link;
  5052. int colw, h;
  5053. if (nd->type == BR_NODE_TEXT) {
  5054. if (!text_node_blank(nd))
  5055. break;
  5056. if (any)
  5057. x += 4;
  5058. n = nd->next;
  5059. continue;
  5060. }
  5061. br_style_for(&doc, n, pst, &cs);
  5062. if (cs.display == BR_DISPLAY_NONE) {
  5063. n = nd->next;
  5064. continue;
  5065. }
  5066. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  5067. break;
  5068. if (nd->tag == BR_TAG_A && nd->href_off)
  5069. lk = (unsigned short)n;
  5070. colw = flex_item_width(l, n, &cs, avail);
  5071. /* A few pixels of slack keep a single long token (boot.S)
  5072. * from wrapping at the exact content width. */
  5073. colw += 8;
  5074. if (colw > avail)
  5075. colw = avail;
  5076. cs.width_kind = 0;
  5077. cs.max_width_kind = 0;
  5078. if (any && x + colw > row_right) {
  5079. y += row_h + 2;
  5080. x = row_left;
  5081. row_h = 0;
  5082. any = 0;
  5083. }
  5084. if (any && x > row_left)
  5085. x += 4;
  5086. l->left = x;
  5087. l->right = x + colw;
  5088. if (l->right < l->left + 8)
  5089. l->right = l->left + 8;
  5090. l->y = y;
  5091. l->line_x = l->left;
  5092. l->run_x = l->left;
  5093. l->line_y = l->y;
  5094. l->line_h = 0;
  5095. l->nruns = 0;
  5096. l->space_pending = 0;
  5097. l->align = cs.align;
  5098. layout_block(l, n, &cs, depth + 1, lk);
  5099. h = l->y - y;
  5100. if (h > row_h)
  5101. row_h = h;
  5102. x += colw;
  5103. any = 1;
  5104. n = nd->next;
  5105. }
  5106. if (any)
  5107. y += row_h;
  5108. l->left = row_left;
  5109. l->right = row_right;
  5110. l->y = y;
  5111. l->line_x = l->left;
  5112. l->run_x = l->left;
  5113. l->line_y = l->y;
  5114. l->line_h = 0;
  5115. l->nruns = 0;
  5116. l->space_pending = 0;
  5117. return n;
  5118. }
  5119. struct flex_item {
  5120. unsigned int node;
  5121. unsigned short link;
  5122. int w;
  5123. };
  5124. static void layout_flex_children(struct lay *l, unsigned int parent,
  5125. const struct br_style *pst, int depth,
  5126. unsigned short link)
  5127. {
  5128. struct flex_item it[32];
  5129. unsigned int c;
  5130. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  5131. int row_left = l->left, row_right = l->right;
  5132. int avail = row_right - row_left;
  5133. int idx, row_top;
  5134. if (avail < 160 || depth > 24) {
  5135. layout_children(l, parent, pst, depth, link);
  5136. return;
  5137. }
  5138. /* If direct text is not just whitespace, normal block flow handles it
  5139. * better than pretending it is a flex item. */
  5140. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5141. struct br_node *nd = &doc.nodes[c];
  5142. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  5143. layout_children(l, parent, pst, depth, link);
  5144. return;
  5145. }
  5146. }
  5147. for (c = doc.nodes[parent].first;
  5148. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  5149. c = doc.nodes[c].next) {
  5150. struct br_node *nd = &doc.nodes[c];
  5151. struct br_style cs;
  5152. if (nd->type == BR_NODE_TEXT)
  5153. continue;
  5154. br_style_for(&doc, c, pst, &cs);
  5155. if (cs.display == BR_DISPLAY_NONE)
  5156. continue;
  5157. it[nitem].node = c;
  5158. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  5159. (unsigned short)c : link;
  5160. it[nitem].w = 0;
  5161. if (cs.flex_grow && !cs.width_kind)
  5162. grow_count++;
  5163. else
  5164. fixed += flex_item_width(l, c, &cs, avail);
  5165. nitem++;
  5166. }
  5167. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  5168. if (grow_w < 96)
  5169. grow_w = 96;
  5170. for (idx = 0; idx < nitem; idx++) {
  5171. struct br_style cs;
  5172. br_style_for(&doc, it[idx].node, pst, &cs);
  5173. if (cs.flex_grow && !cs.width_kind)
  5174. it[idx].w = grow_w;
  5175. else
  5176. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  5177. if (it[idx].w > avail)
  5178. it[idx].w = avail;
  5179. if (it[idx].w < 8)
  5180. it[idx].w = 8;
  5181. }
  5182. row_top = l->y;
  5183. idx = 0;
  5184. while (idx < nitem) {
  5185. int start = idx, count = 0, row_w = 0;
  5186. int free_w, x, extra = 0, row_h = 0, k;
  5187. while (idx < nitem) {
  5188. int add = it[idx].w + (count ? gap : 0);
  5189. if (count && pst->flex_wrap != 2 &&
  5190. row_w + add > avail)
  5191. break;
  5192. row_w += add;
  5193. count++;
  5194. idx++;
  5195. }
  5196. if (!count) {
  5197. count = 1;
  5198. row_w = it[start].w;
  5199. idx = start + 1;
  5200. }
  5201. free_w = avail - row_w;
  5202. if (free_w < 0)
  5203. free_w = 0;
  5204. x = row_left;
  5205. if (pst->justify == 1) {
  5206. x += free_w / 2;
  5207. } else if (pst->justify == 2) {
  5208. x += free_w;
  5209. } else if (pst->justify == 3) {
  5210. extra = count > 1 ? free_w / (count - 1) : 0;
  5211. } else if (pst->justify == 4) {
  5212. extra = count ? free_w / count : 0;
  5213. x += extra / 2;
  5214. }
  5215. for (k = 0; k < count; k++) {
  5216. int node = (int)it[start + k].node;
  5217. int h = block_h[node];
  5218. if (h > row_h)
  5219. row_h = h;
  5220. }
  5221. if (pst->height_kind) {
  5222. int hh = style_height_px(pst, avail);
  5223. if (hh > row_h)
  5224. row_h = hh;
  5225. }
  5226. for (k = 0; k < count; k++) {
  5227. struct br_style cs;
  5228. int node = (int)it[start + k].node;
  5229. int yoff = 0;
  5230. br_style_for(&doc, node, pst, &cs);
  5231. cs.width_kind = 0;
  5232. cs.max_width_kind = 0;
  5233. if (l->draw && pst->align_items &&
  5234. row_h > block_h[node]) {
  5235. if (pst->align_items == 1)
  5236. yoff = (row_h - block_h[node]) / 2;
  5237. else if (pst->align_items == 2)
  5238. yoff = row_h - block_h[node];
  5239. }
  5240. l->left = x;
  5241. l->right = x + it[start + k].w;
  5242. if (l->right < l->left + 8)
  5243. l->right = l->left + 8;
  5244. l->y = row_top + yoff;
  5245. l->line_x = l->left;
  5246. l->run_x = l->left;
  5247. l->line_y = l->y;
  5248. l->line_h = 0;
  5249. l->nruns = 0;
  5250. l->space_pending = 0;
  5251. l->align = cs.align;
  5252. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  5253. if (!l->draw) {
  5254. int h = l->y - row_top;
  5255. if (h > row_h)
  5256. row_h = h;
  5257. }
  5258. x += it[start + k].w;
  5259. if (k + 1 < count)
  5260. x += gap + extra;
  5261. }
  5262. row_top += row_h;
  5263. }
  5264. l->left = row_left;
  5265. l->right = row_right;
  5266. l->y = row_top;
  5267. l->line_x = l->left;
  5268. l->run_x = l->left;
  5269. l->line_y = l->y;
  5270. l->line_h = 0;
  5271. l->nruns = 0;
  5272. l->space_pending = 0;
  5273. }
  5274. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  5275. * plus the grid-area hints used by site shells (site notice/footer full
  5276. * width, column-start left, page-content right). Anything more elaborate
  5277. * falls back to normal block flow. */
  5278. static int grid_track_width(unsigned char kind, unsigned short val,
  5279. int avail, int other)
  5280. {
  5281. if (kind == 2)
  5282. return avail * (int)val / 100;
  5283. if (kind == 1)
  5284. return val;
  5285. return other;
  5286. }
  5287. static void layout_grid_children(struct lay *l, unsigned int parent,
  5288. const struct br_style *pst, int depth,
  5289. unsigned short link)
  5290. {
  5291. unsigned int n;
  5292. int row_left = l->left, row_right = l->right;
  5293. int avail = row_right - row_left;
  5294. int gap = pst->grid_gap;
  5295. int track_total = avail - gap;
  5296. int col0, col1, x0, x1;
  5297. int row_y, row_bottom, have_left = 0, have_right = 0;
  5298. unsigned int c;
  5299. if (avail < 32 || depth > 24)
  5300. return;
  5301. if (track_total < 16)
  5302. track_total = 16;
  5303. col0 = grid_track_width((unsigned char)(pst->width_kind),
  5304. pst->width, track_total, 0);
  5305. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  5306. pst->max_width, track_total, 0);
  5307. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  5308. int w0 = pst->width ? pst->width : 1;
  5309. int w1 = pst->max_width ? pst->max_width : 1;
  5310. col0 = track_total * w0 / (w0 + w1);
  5311. col1 = track_total - col0;
  5312. } else if (pst->width_kind == 3) {
  5313. col0 = track_total - col1;
  5314. if (col0 < 24)
  5315. col0 = 24;
  5316. } else if (pst->max_width_kind == 3) {
  5317. col1 = track_total - col0;
  5318. if (col1 < 24)
  5319. col1 = 24;
  5320. }
  5321. if (col0 < 24)
  5322. col0 = 24;
  5323. if (col1 < 24)
  5324. col1 = 24;
  5325. if (col0 + col1 > track_total) {
  5326. col1 = track_total - col0;
  5327. if (col1 < 24)
  5328. col1 = 24;
  5329. }
  5330. x0 = row_left;
  5331. x1 = row_left + col0 + gap;
  5332. /* Direct text makes a grid ambiguous; use block flow instead. */
  5333. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5334. struct br_node *nd = &doc.nodes[c];
  5335. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  5336. layout_children(l, parent, pst, depth, link);
  5337. return;
  5338. }
  5339. }
  5340. row_y = row_bottom = l->y;
  5341. n = doc.nodes[parent].first;
  5342. while (n) {
  5343. struct br_node *nd = &doc.nodes[n];
  5344. struct br_style cs;
  5345. unsigned short lk = link;
  5346. int slot, x, w;
  5347. if (nd->type == BR_NODE_TEXT) {
  5348. n = nd->next;
  5349. continue;
  5350. }
  5351. br_style_for(&doc, n, pst, &cs);
  5352. if (cs.display == BR_DISPLAY_NONE) {
  5353. n = nd->next;
  5354. continue;
  5355. }
  5356. if (nd->tag == BR_TAG_A && nd->href_off)
  5357. lk = (unsigned short)n;
  5358. slot = cs.grid_slot;
  5359. if (!slot) {
  5360. if (!have_left)
  5361. slot = 2;
  5362. else if (!have_right)
  5363. slot = 3;
  5364. else
  5365. slot = 2;
  5366. }
  5367. if (slot == 1) {
  5368. if (have_left || have_right) {
  5369. row_y = row_bottom;
  5370. have_left = have_right = 0;
  5371. }
  5372. x = row_left;
  5373. w = avail;
  5374. } else if (slot == 2) {
  5375. if (have_left) {
  5376. row_y = row_bottom;
  5377. have_left = have_right = 0;
  5378. }
  5379. x = x0;
  5380. w = col0;
  5381. have_left = 1;
  5382. } else {
  5383. if (have_right) {
  5384. row_y = row_bottom;
  5385. have_left = have_right = 0;
  5386. }
  5387. x = x1;
  5388. w = col1;
  5389. have_right = 1;
  5390. }
  5391. cs.width_kind = 0;
  5392. cs.max_width_kind = 0;
  5393. l->left = x;
  5394. l->right = x + w;
  5395. if (l->right < l->left + 8)
  5396. l->right = l->left + 8;
  5397. l->y = row_y;
  5398. l->line_x = l->left;
  5399. l->run_x = l->left;
  5400. l->line_y = l->y;
  5401. l->line_h = 0;
  5402. l->nruns = 0;
  5403. l->space_pending = 0;
  5404. l->align = cs.align;
  5405. layout_block(l, n, &cs, depth + 1, lk);
  5406. if (l->y > row_bottom)
  5407. row_bottom = l->y;
  5408. n = nd->next;
  5409. }
  5410. l->left = row_left;
  5411. l->right = row_right;
  5412. l->y = row_bottom;
  5413. l->line_x = l->left;
  5414. l->run_x = l->left;
  5415. l->line_y = l->y;
  5416. l->line_h = 0;
  5417. l->nruns = 0;
  5418. l->space_pending = 0;
  5419. }
  5420. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  5421. * capped at four. Used by the project docs' card grids. */
  5422. static void layout_grid_auto(struct lay *l, unsigned int parent,
  5423. const struct br_style *pst, int depth,
  5424. unsigned short link)
  5425. {
  5426. unsigned int n, c;
  5427. int row_left = l->left, row_right = l->right;
  5428. int avail = row_right - row_left;
  5429. int gap = pst->grid_gap;
  5430. int minw = pst->width_kind == 1 ? pst->width : 200;
  5431. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  5432. if (avail < 32 || depth > 24) {
  5433. layout_children(l, parent, pst, depth, link);
  5434. return;
  5435. }
  5436. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  5437. struct br_node *nd = &doc.nodes[c];
  5438. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  5439. layout_children(l, parent, pst, depth, link);
  5440. return;
  5441. }
  5442. }
  5443. if (minw < 80)
  5444. minw = 80;
  5445. ncols = (avail + gap) / (minw + gap);
  5446. if (ncols < 1)
  5447. ncols = 1;
  5448. if (ncols > 4)
  5449. ncols = 4;
  5450. colw = (avail - gap * (ncols - 1)) / ncols;
  5451. if (colw < 24)
  5452. colw = 24;
  5453. x = row_left;
  5454. n = doc.nodes[parent].first;
  5455. while (n) {
  5456. struct br_node *nd = &doc.nodes[n];
  5457. struct br_style cs;
  5458. unsigned short lk = link;
  5459. int h;
  5460. if (nd->type == BR_NODE_TEXT) {
  5461. n = nd->next;
  5462. continue;
  5463. }
  5464. br_style_for(&doc, n, pst, &cs);
  5465. if (cs.display == BR_DISPLAY_NONE) {
  5466. n = nd->next;
  5467. continue;
  5468. }
  5469. if (nd->tag == BR_TAG_A && nd->href_off)
  5470. lk = (unsigned short)n;
  5471. cs.width_kind = 0;
  5472. cs.max_width_kind = 0;
  5473. l->left = x;
  5474. l->right = x + colw;
  5475. if (l->right < l->left + 8)
  5476. l->right = l->left + 8;
  5477. l->y = y;
  5478. l->line_x = l->left;
  5479. l->run_x = l->left;
  5480. l->line_y = l->y;
  5481. l->line_h = 0;
  5482. l->nruns = 0;
  5483. l->space_pending = 0;
  5484. l->align = cs.align;
  5485. layout_block(l, n, &cs, depth + 1, lk);
  5486. h = l->y - y;
  5487. if (h > row_h)
  5488. row_h = h;
  5489. col++;
  5490. n = nd->next;
  5491. if (col == ncols) {
  5492. y += row_h + gap;
  5493. x = row_left;
  5494. row_h = 0;
  5495. col = 0;
  5496. } else {
  5497. x += colw + gap;
  5498. }
  5499. }
  5500. if (col)
  5501. y += row_h;
  5502. else if (y > start_y)
  5503. y -= gap;
  5504. l->left = row_left;
  5505. l->right = row_right;
  5506. l->y = y;
  5507. l->line_x = l->left;
  5508. l->run_x = l->left;
  5509. l->line_y = l->y;
  5510. l->line_h = 0;
  5511. l->nruns = 0;
  5512. l->space_pending = 0;
  5513. }
  5514. /* Column widths are the widest cell in each column across every row, so all
  5515. * rows line up. The table model is still deliberately basic: no colspan,
  5516. * border-collapse or percentage columns. */
  5517. static void table_columns(struct lay *l, unsigned int table,
  5518. const struct br_style *pst, int avail,
  5519. int *raw, int maxcols, int *out_cols,
  5520. int *out_total)
  5521. {
  5522. unsigned int r, c;
  5523. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  5524. int fixed[12];
  5525. for (c = 0; c < (unsigned int)maxcols; c++) {
  5526. raw[c] = 0;
  5527. fixed[c] = 0;
  5528. }
  5529. /* Intrinsic widths of single-column cells. */
  5530. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  5531. struct br_node *rn = &doc.nodes[r];
  5532. int col = 0;
  5533. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  5534. continue;
  5535. for (c = rn->first; c; c = doc.nodes[c].next) {
  5536. struct br_node *cn = &doc.nodes[c];
  5537. struct br_style cs;
  5538. int w, span;
  5539. if (cn->type != BR_NODE_ELEM ||
  5540. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  5541. continue;
  5542. span = cn->colspan ? cn->colspan : 1;
  5543. br_style_for(&doc, c, pst, &cs);
  5544. if (cs.display == BR_DISPLAY_NONE)
  5545. continue;
  5546. if (col + span > maxcols)
  5547. span = maxcols - col;
  5548. if (span < 1)
  5549. break;
  5550. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  5551. mp_px(&cs, 7, avail) +
  5552. mp_px(&cs, 5, avail) +
  5553. mp_px(&cs, 3, avail) +
  5554. mp_px(&cs, 1, avail) +
  5555. cs.border_w[0] + cs.border_w[1] +
  5556. cs.border_w[2] + cs.border_w[3];
  5557. if (w < 24)
  5558. w = 24;
  5559. if (span == 1) {
  5560. if (w > raw[col])
  5561. raw[col] = w;
  5562. }
  5563. if (col + span > cols)
  5564. cols = col + span;
  5565. col += span;
  5566. }
  5567. }
  5568. /* A colspan cell only has to be as wide as the sum of its columns. */
  5569. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  5570. struct br_node *rn = &doc.nodes[r];
  5571. int col = 0;
  5572. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  5573. continue;
  5574. for (c = rn->first; c; c = doc.nodes[c].next) {
  5575. struct br_node *cn = &doc.nodes[c];
  5576. struct br_style cs;
  5577. int span, w, sum, i;
  5578. if (cn->type != BR_NODE_ELEM ||
  5579. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  5580. continue;
  5581. span = cn->colspan ? cn->colspan : 1;
  5582. if (col + span > maxcols)
  5583. span = maxcols - col;
  5584. if (span < 1)
  5585. break;
  5586. if (span > 1) {
  5587. br_style_for(&doc, c, pst, &cs);
  5588. if (cs.display != BR_DISPLAY_NONE) {
  5589. w = intrinsic_width(l->ui, c, &cs,
  5590. 0, avail) +
  5591. mp_px(&cs, 7, avail) +
  5592. mp_px(&cs, 5, avail) +
  5593. mp_px(&cs, 3, avail) +
  5594. mp_px(&cs, 1, avail) +
  5595. cs.border_w[0] + cs.border_w[1] +
  5596. cs.border_w[2] + cs.border_w[3];
  5597. sum = 0;
  5598. for (i = 0; i < span; i++)
  5599. sum += raw[col + i];
  5600. if (w > sum)
  5601. raw[col + span - 1] += w - sum;
  5602. }
  5603. }
  5604. col += span;
  5605. }
  5606. }
  5607. /* Explicit and percentage widths override intrinsic widths. */
  5608. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  5609. struct br_node *rn = &doc.nodes[r];
  5610. int col = 0;
  5611. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  5612. continue;
  5613. for (c = rn->first; c; c = doc.nodes[c].next) {
  5614. struct br_node *cn = &doc.nodes[c];
  5615. struct br_style cs;
  5616. int span;
  5617. if (cn->type != BR_NODE_ELEM ||
  5618. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  5619. continue;
  5620. span = cn->colspan ? cn->colspan : 1;
  5621. if (col + span > maxcols)
  5622. span = maxcols - col;
  5623. if (span < 1)
  5624. break;
  5625. if (span == 1) {
  5626. br_style_for(&doc, c, pst, &cs);
  5627. if (cs.display != BR_DISPLAY_NONE) {
  5628. if (cs.width_kind == 1) {
  5629. raw[col] = cs.width;
  5630. fixed[col] = 1;
  5631. } else if (cs.width_kind == 2 ||
  5632. cs.width_kind == 3) {
  5633. raw[col] = style_width_px(&cs,
  5634. avail);
  5635. fixed[col] = 1;
  5636. }
  5637. }
  5638. }
  5639. col += span;
  5640. }
  5641. }
  5642. for (c = 0; c < (unsigned int)cols; c++) {
  5643. if (raw[c] < 8)
  5644. raw[c] = 8;
  5645. total += raw[c];
  5646. if (fixed[c])
  5647. fixed_sum += raw[c];
  5648. else {
  5649. free_raw += raw[c];
  5650. free_cols++;
  5651. }
  5652. }
  5653. if (fixed_sum > 0 && fixed_sum < avail) {
  5654. int free_avail = avail - fixed_sum;
  5655. int i;
  5656. if (free_raw > 0) {
  5657. for (i = 0; i < cols; i++)
  5658. if (!fixed[i])
  5659. raw[i] = free_avail * raw[i] /
  5660. free_raw;
  5661. } else if (free_cols > 0) {
  5662. for (i = 0; i < cols; i++)
  5663. if (!fixed[i])
  5664. raw[i] = free_avail / free_cols;
  5665. }
  5666. total = 0;
  5667. for (i = 0; i < cols; i++)
  5668. total += raw[i];
  5669. } else if (total < avail && total > 0) {
  5670. int i;
  5671. for (i = 0; i < cols; i++)
  5672. raw[i] = raw[i] * avail / total;
  5673. total = 0;
  5674. for (i = 0; i < cols; i++)
  5675. total += raw[i];
  5676. }
  5677. *out_cols = cols;
  5678. *out_total = total;
  5679. }
  5680. static void layout_table_row(struct lay *l, unsigned int row,
  5681. const struct br_style *pst, int depth,
  5682. unsigned short link)
  5683. {
  5684. unsigned int n, cell[12];
  5685. int raw[12], colstart[12], colspan[12];
  5686. int prefix[13];
  5687. int ncell = 0, total = 0, cols = 0, col = 0;
  5688. int row_left = l->left, row_right = l->right;
  5689. int avail = row_right - row_left;
  5690. int y = l->y, bottom = l->y;
  5691. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  5692. struct br_node *nd = &doc.nodes[n];
  5693. struct br_style cs;
  5694. int span;
  5695. if (nd->type == BR_NODE_TEXT) {
  5696. if (text_node_blank(nd))
  5697. continue;
  5698. layout_children(l, row, pst, depth, link);
  5699. return;
  5700. }
  5701. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  5702. layout_children(l, row, pst, depth, link);
  5703. return;
  5704. }
  5705. br_style_for(&doc, n, pst, &cs);
  5706. if (cs.display == BR_DISPLAY_NONE)
  5707. continue;
  5708. if (ncell >= 12) {
  5709. layout_children(l, row, pst, depth, link);
  5710. return;
  5711. }
  5712. span = nd->colspan ? nd->colspan : 1;
  5713. if (span > 12 - col)
  5714. span = 12 - col;
  5715. if (span < 1)
  5716. continue;
  5717. cell[ncell] = n;
  5718. colstart[ncell] = col;
  5719. colspan[ncell] = span;
  5720. col += span;
  5721. ncell++;
  5722. }
  5723. if (ncell < 1 || avail < 32) {
  5724. layout_children(l, row, pst, depth, link);
  5725. return;
  5726. }
  5727. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  5728. &total);
  5729. if (cols < 2 || total <= 0) {
  5730. int c;
  5731. for (c = 0; c < ncell; c++) {
  5732. struct br_style cs;
  5733. br_style_for(&doc, cell[c], pst, &cs);
  5734. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  5735. avail) +
  5736. mp_px(&cs, 7, avail) +
  5737. mp_px(&cs, 5, avail) +
  5738. mp_px(&cs, 3, avail) +
  5739. mp_px(&cs, 1, avail);
  5740. if (raw[c] < 24)
  5741. raw[c] = 24;
  5742. total += raw[c];
  5743. }
  5744. }
  5745. prefix[0] = row_left;
  5746. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  5747. prefix[n + 1] = prefix[n] + raw[n];
  5748. for (n = 0; n < (unsigned int)ncell; n++) {
  5749. struct br_style cs;
  5750. int start = colstart[n];
  5751. int end = start + colspan[n];
  5752. int w;
  5753. if (end > cols)
  5754. end = cols;
  5755. if (start >= cols)
  5756. continue;
  5757. w = prefix[end] - prefix[start];
  5758. br_style_for(&doc, cell[n], pst, &cs);
  5759. /* The column width already reflects the cell's width property. */
  5760. cs.width_kind = 0;
  5761. cs.max_width_kind = 0;
  5762. if (w < 24)
  5763. w = 24;
  5764. if (w < 8)
  5765. w = 8;
  5766. l->left = prefix[start];
  5767. l->right = l->left + w;
  5768. l->y = y;
  5769. l->line_x = l->left;
  5770. l->run_x = l->left;
  5771. l->line_y = l->y;
  5772. l->line_h = 0;
  5773. l->nruns = 0;
  5774. l->space_pending = 0;
  5775. l->align = cs.align;
  5776. layout_block(l, cell[n], &cs, depth + 1, link);
  5777. if (l->y > bottom)
  5778. bottom = l->y;
  5779. }
  5780. l->left = row_left;
  5781. l->right = row_right;
  5782. l->y = bottom;
  5783. l->line_x = l->left;
  5784. l->run_x = l->left;
  5785. l->line_y = l->y;
  5786. l->line_h = 0;
  5787. l->nruns = 0;
  5788. l->space_pending = 0;
  5789. }
  5790. #define TBL_MAX_ROWS 32
  5791. #define TBL_MAX_COLS 12
  5792. #define TBL_MAX_CELLS 128
  5793. struct tbl_cell {
  5794. unsigned int node;
  5795. unsigned char row, col, rowspan, colspan;
  5796. int height;
  5797. };
  5798. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  5799. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  5800. static int table_active;
  5801. static int table_has_rowspan(unsigned int table)
  5802. {
  5803. unsigned int r, c;
  5804. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  5805. struct br_node *rn = &doc.nodes[r];
  5806. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  5807. continue;
  5808. for (c = rn->first; c; c = doc.nodes[c].next) {
  5809. struct br_node *cn = &doc.nodes[c];
  5810. if (cn->type == BR_NODE_ELEM &&
  5811. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  5812. cn->rowspan > 1)
  5813. return 1;
  5814. }
  5815. }
  5816. return 0;
  5817. }
  5818. static void table_cell_style(unsigned int row, unsigned int cell,
  5819. const struct br_style *st, struct br_style *out)
  5820. {
  5821. struct br_style trs;
  5822. br_style_for(&doc, row, st, &trs);
  5823. br_style_for(&doc, cell, &trs, out);
  5824. }
  5825. /* Tables that use rowspan need row heights before anything is painted. This
  5826. * path builds a small occupancy grid, measures the natural cell heights, then
  5827. * lays every cell out at its row/column position. Tables without rowspan
  5828. * keep the lighter per-row path in layout_table_row(). */
  5829. static void layout_table(struct lay *l, unsigned int table,
  5830. const struct br_style *st, int depth,
  5831. unsigned short link)
  5832. {
  5833. unsigned int rows[TBL_MAX_ROWS];
  5834. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  5835. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  5836. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  5837. int free_raw = 0, free_cols = 0;
  5838. int table_left = l->left, table_right = l->right;
  5839. int top = l->y, avail = table_right - table_left;
  5840. unsigned int r, c;
  5841. int i, rr, cc;
  5842. if (depth > 24 || table_active) {
  5843. layout_children(l, table, st, depth, link);
  5844. return;
  5845. }
  5846. table_active = 1;
  5847. for (r = doc.nodes[table].first;
  5848. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  5849. struct br_node *rn = &doc.nodes[r];
  5850. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  5851. rows[nrows++] = r;
  5852. }
  5853. if (!nrows) {
  5854. table_active = 0;
  5855. layout_children(l, table, st, depth, link);
  5856. return;
  5857. }
  5858. for (rr = 0; rr < nrows; rr++)
  5859. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  5860. tbl_at[rr][cc] = 0;
  5861. for (rr = 0; rr < nrows; rr++) {
  5862. int col = 0;
  5863. for (c = doc.nodes[rows[rr]].first; c;
  5864. c = doc.nodes[c].next) {
  5865. struct br_node *cn = &doc.nodes[c];
  5866. struct br_style cs;
  5867. int rs, csn;
  5868. if (cn->type != BR_NODE_ELEM ||
  5869. (cn->tag != BR_TAG_TD &&
  5870. cn->tag != BR_TAG_TH))
  5871. continue;
  5872. table_cell_style(rows[rr], c, st, &cs);
  5873. if (cs.display == BR_DISPLAY_NONE)
  5874. continue;
  5875. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  5876. col++;
  5877. if (col >= TBL_MAX_COLS)
  5878. break;
  5879. rs = cn->rowspan ? cn->rowspan : 1;
  5880. csn = cn->colspan ? cn->colspan : 1;
  5881. if (rr + rs > nrows)
  5882. rs = nrows - rr;
  5883. if (col + csn > TBL_MAX_COLS)
  5884. csn = TBL_MAX_COLS - col;
  5885. if (rs < 1 || csn < 1)
  5886. continue;
  5887. if (ncells >= TBL_MAX_CELLS)
  5888. break;
  5889. tbl_cells[ncells].node = c;
  5890. tbl_cells[ncells].row = (unsigned char)rr;
  5891. tbl_cells[ncells].col = (unsigned char)col;
  5892. tbl_cells[ncells].rowspan = (unsigned char)rs;
  5893. tbl_cells[ncells].colspan = (unsigned char)csn;
  5894. tbl_cells[ncells].height = 0;
  5895. for (i = rr; i < rr + rs; i++)
  5896. for (int j = col; j < col + csn; j++)
  5897. tbl_at[i][j] =
  5898. (unsigned short)(ncells + 1);
  5899. ncells++;
  5900. col += csn;
  5901. if (col > cols)
  5902. cols = col;
  5903. }
  5904. }
  5905. if (!ncells || cols < 1) {
  5906. table_active = 0;
  5907. layout_children(l, table, st, depth, link);
  5908. return;
  5909. }
  5910. for (i = 0; i < cols; i++) {
  5911. raw[i] = 0;
  5912. fixed[i] = 0;
  5913. }
  5914. /* Intrinsic widths of single-column cells. */
  5915. for (i = 0; i < ncells; i++) {
  5916. struct br_style cs;
  5917. int w;
  5918. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  5919. st, &cs);
  5920. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  5921. mp_px(&cs, 7, avail) +
  5922. mp_px(&cs, 5, avail) +
  5923. mp_px(&cs, 3, avail) +
  5924. mp_px(&cs, 1, avail) +
  5925. cs.border_w[0] + cs.border_w[1] +
  5926. cs.border_w[2] + cs.border_w[3];
  5927. if (w < 24)
  5928. w = 24;
  5929. if (tbl_cells[i].colspan == 1) {
  5930. int col = tbl_cells[i].col;
  5931. if (w > raw[col])
  5932. raw[col] = w;
  5933. }
  5934. }
  5935. /* A spanning cell only needs the sum of its columns to be large
  5936. * enough; put the deficit in the last column. */
  5937. for (i = 0; i < ncells; i++) {
  5938. struct br_style cs;
  5939. int w, sum, col, span;
  5940. if (tbl_cells[i].colspan < 2)
  5941. continue;
  5942. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  5943. st, &cs);
  5944. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  5945. mp_px(&cs, 7, avail) +
  5946. mp_px(&cs, 5, avail) +
  5947. mp_px(&cs, 3, avail) +
  5948. mp_px(&cs, 1, avail) +
  5949. cs.border_w[0] + cs.border_w[1] +
  5950. cs.border_w[2] + cs.border_w[3];
  5951. col = tbl_cells[i].col;
  5952. span = tbl_cells[i].colspan;
  5953. sum = 0;
  5954. for (int j = 0; j < span; j++)
  5955. sum += raw[col + j];
  5956. if (w > sum)
  5957. raw[col + span - 1] += w - sum;
  5958. }
  5959. /* Explicit/percentage widths, as in table_columns(). */
  5960. for (i = 0; i < ncells; i++) {
  5961. struct br_style cs;
  5962. int col;
  5963. if (tbl_cells[i].colspan != 1)
  5964. continue;
  5965. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  5966. st, &cs);
  5967. col = tbl_cells[i].col;
  5968. if (cs.width_kind == 1) {
  5969. raw[col] = cs.width;
  5970. fixed[col] = 1;
  5971. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  5972. raw[col] = style_width_px(&cs, avail);
  5973. fixed[col] = 1;
  5974. }
  5975. }
  5976. for (i = 0; i < cols; i++) {
  5977. if (raw[i] < 8)
  5978. raw[i] = 8;
  5979. total += raw[i];
  5980. if (fixed[i])
  5981. fixed_sum += raw[i];
  5982. else {
  5983. free_raw += raw[i];
  5984. free_cols++;
  5985. }
  5986. }
  5987. if (fixed_sum > 0 && fixed_sum < avail) {
  5988. int free_avail = avail - fixed_sum;
  5989. if (free_raw > 0) {
  5990. for (i = 0; i < cols; i++)
  5991. if (!fixed[i])
  5992. raw[i] = free_avail * raw[i] /
  5993. free_raw;
  5994. } else if (free_cols > 0) {
  5995. for (i = 0; i < cols; i++)
  5996. if (!fixed[i])
  5997. raw[i] = free_avail / free_cols;
  5998. }
  5999. } else if (total < avail && total > 0) {
  6000. for (i = 0; i < cols; i++)
  6001. raw[i] = raw[i] * avail / total;
  6002. }
  6003. prefix[0] = table_left;
  6004. for (i = 0; i < cols; i++)
  6005. prefix[i + 1] = prefix[i] + raw[i];
  6006. /* Measure natural cell heights with the column widths. */
  6007. for (i = 0; i < ncells; i++) {
  6008. struct br_style cs;
  6009. int col = tbl_cells[i].col;
  6010. int span = tbl_cells[i].colspan;
  6011. int w = prefix[col + span] - prefix[col];
  6012. int sl = l->left, sr = l->right, sy = l->y;
  6013. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  6014. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  6015. int sal = l->align, sdraw = l->draw;
  6016. struct ngui *sui = l->ui;
  6017. if (w < 8)
  6018. w = 8;
  6019. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  6020. st, &cs);
  6021. cs.width_kind = 0;
  6022. cs.max_width_kind = 0;
  6023. l->draw = 0;
  6024. l->ui = 0;
  6025. l->left = prefix[col];
  6026. l->right = l->left + w;
  6027. l->y = 0;
  6028. l->line_x = l->left;
  6029. l->run_x = l->left;
  6030. l->line_y = 0;
  6031. l->line_h = 0;
  6032. l->nruns = 0;
  6033. l->space_pending = 0;
  6034. l->align = cs.align;
  6035. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  6036. tbl_cells[i].height = block_h[tbl_cells[i].node];
  6037. l->left = sl;
  6038. l->right = sr;
  6039. l->y = sy;
  6040. l->line_x = slx;
  6041. l->run_x = srx;
  6042. l->line_y = sly;
  6043. l->line_h = slh;
  6044. l->nruns = snr;
  6045. l->space_pending = ssp;
  6046. l->align = sal;
  6047. l->draw = sdraw;
  6048. l->ui = sui;
  6049. }
  6050. for (i = 0; i < nrows; i++)
  6051. rowh[i] = 0;
  6052. for (i = 0; i < ncells; i++) {
  6053. int row = tbl_cells[i].row;
  6054. if (tbl_cells[i].rowspan == 1) {
  6055. if (tbl_cells[i].height > rowh[row])
  6056. rowh[row] = tbl_cells[i].height;
  6057. }
  6058. }
  6059. for (i = 0; i < ncells; i++) {
  6060. int row = tbl_cells[i].row;
  6061. int span = tbl_cells[i].rowspan;
  6062. int sum = 0;
  6063. if (span < 2)
  6064. continue;
  6065. for (int j = 0; j < span; j++)
  6066. sum += rowh[row + j];
  6067. if (sum < tbl_cells[i].height)
  6068. rowh[row + span - 1] +=
  6069. tbl_cells[i].height - sum;
  6070. }
  6071. for (i = 0; i < nrows; i++)
  6072. if (rowh[i] < 8)
  6073. rowh[i] = 8;
  6074. rowy[0] = top;
  6075. for (i = 1; i < nrows; i++)
  6076. rowy[i] = rowy[i - 1] + rowh[i - 1];
  6077. if (!l->draw) {
  6078. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  6079. table_active = 0;
  6080. return;
  6081. }
  6082. for (i = 0; i < ncells; i++) {
  6083. struct br_style cs;
  6084. int col = tbl_cells[i].col;
  6085. int span = tbl_cells[i].colspan;
  6086. int row = tbl_cells[i].row;
  6087. int rspan = tbl_cells[i].rowspan;
  6088. int w = prefix[col + span] - prefix[col];
  6089. int h = 0;
  6090. int sl = l->left, sr = l->right, sy = l->y;
  6091. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  6092. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  6093. int sal = l->align;
  6094. int deco;
  6095. for (int j = 0; j < rspan; j++)
  6096. h += rowh[row + j];
  6097. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  6098. cs.width_kind = 0;
  6099. cs.max_width_kind = 0;
  6100. cs.box_sizing = 0;
  6101. deco = mp_px(&cs, 4, avail) +
  6102. mp_px(&cs, 6, avail) +
  6103. cs.border_w[0] + cs.border_w[2];
  6104. cs.height_kind = 1;
  6105. cs.height = h > deco ? h - deco : 0;
  6106. /* The block painter reads block_h[] from the measure pass; make
  6107. * the table cell fill its row/rowspan, not just its content. */
  6108. if (h > 0 && h < 65536)
  6109. block_h[tbl_cells[i].node] = (unsigned short)h;
  6110. l->left = prefix[col];
  6111. l->right = l->left + w;
  6112. l->y = rowy[row];
  6113. l->line_x = l->left;
  6114. l->run_x = l->left;
  6115. l->line_y = l->y;
  6116. l->line_h = 0;
  6117. l->nruns = 0;
  6118. l->space_pending = 0;
  6119. l->align = cs.align;
  6120. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  6121. l->left = sl;
  6122. l->right = sr;
  6123. l->y = sy;
  6124. l->line_x = slx;
  6125. l->run_x = srx;
  6126. l->line_y = sly;
  6127. l->line_h = slh;
  6128. l->nruns = snr;
  6129. l->space_pending = ssp;
  6130. l->align = sal;
  6131. }
  6132. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  6133. table_active = 0;
  6134. }
  6135. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  6136. * flow so they sit above it, like CSS painting order. Their flow origin is
  6137. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  6138. struct br_deferred {
  6139. unsigned int node;
  6140. int flow_y, flow_left, flow_right;
  6141. unsigned short link;
  6142. signed short z_index;
  6143. unsigned char z_set;
  6144. unsigned int order;
  6145. };
  6146. static struct br_deferred deferred[16];
  6147. static int ndeferred;
  6148. static void layout_children(struct lay *l, unsigned int parent,
  6149. const struct br_style *pst, int depth,
  6150. unsigned short link)
  6151. {
  6152. unsigned int n;
  6153. if (depth > 24)
  6154. return;
  6155. n = doc.nodes[parent].first;
  6156. while (n) {
  6157. struct br_node *nd = &doc.nodes[n];
  6158. struct br_style cs;
  6159. unsigned short lk = link;
  6160. if (nd->type == BR_NODE_TEXT) {
  6161. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  6162. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  6163. n = nd->next;
  6164. continue;
  6165. }
  6166. br_style_for(&doc, n, pst, &cs);
  6167. if (cs.display == BR_DISPLAY_NONE) {
  6168. n = nd->next;
  6169. continue;
  6170. }
  6171. if (cs.clear && l->float_active) {
  6172. flush_line(l);
  6173. if (l->y < l->float_bottom)
  6174. l->y = l->float_bottom;
  6175. l->float_active = 0;
  6176. l->line_x = l->left;
  6177. l->run_x = l->left;
  6178. l->line_left = l->left;
  6179. l->line_right = l->right;
  6180. l->line_y = l->y;
  6181. l->line_h = 0;
  6182. l->nruns = 0;
  6183. l->space_pending = 0;
  6184. }
  6185. if (nd->tag == BR_TAG_A && nd->href_off)
  6186. lk = (unsigned short)n;
  6187. if (cs.pos == 1 || cs.pos == 2) {
  6188. if (l->draw && ndeferred < 16) {
  6189. deferred[ndeferred].node = n;
  6190. deferred[ndeferred].flow_y = l->y;
  6191. deferred[ndeferred].flow_left = l->left;
  6192. deferred[ndeferred].flow_right = l->right;
  6193. deferred[ndeferred].link = lk;
  6194. deferred[ndeferred].z_index = cs.z_index;
  6195. deferred[ndeferred].z_set = cs.z_set;
  6196. deferred[ndeferred].order = (unsigned int)ndeferred;
  6197. ndeferred++;
  6198. } else {
  6199. layout_block(l, n, &cs, depth + 1, lk);
  6200. }
  6201. if (cs.pos == 1 && block_h[n] &&
  6202. doc.nodes[n].class_off) {
  6203. const char *cl = doc.attrs +
  6204. doc.nodes[n].class_off;
  6205. if ((contains_ci(cl, "poster-wrapper") ||
  6206. contains_ci(cl, "ts-picture")) &&
  6207. !has_skeleton_sibling(n))
  6208. l->y += block_h[n];
  6209. }
  6210. n = nd->next;
  6211. continue;
  6212. }
  6213. if (nd->tag == BR_TAG_BR) {
  6214. flush_line(l);
  6215. n = nd->next;
  6216. continue;
  6217. }
  6218. if (nd->tag == BR_TAG_HR) {
  6219. flush_line(l);
  6220. if (l->draw)
  6221. ngui_fill_rect(l->ui,
  6222. (struct ngui_rect){l->left, l->y + 2,
  6223. l->right - l->left, 1}, BR_GRAY);
  6224. l->y += 8;
  6225. n = nd->next;
  6226. continue;
  6227. }
  6228. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  6229. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
  6230. if (!(nd->tag == BR_TAG_INPUT &&
  6231. s_eq(br_type(&doc, n), "hidden")))
  6232. add_form_run(l, n, &cs, lk);
  6233. n = nd->next;
  6234. continue;
  6235. }
  6236. if (nd->tag == BR_TAG_IMG) {
  6237. add_image_run(l, n, &cs, lk);
  6238. n = nd->next;
  6239. continue;
  6240. }
  6241. if (nd->tag == BR_TAG_VIDEO) {
  6242. layout_block(l, n, &cs, depth + 1, lk);
  6243. n = nd->next;
  6244. continue;
  6245. }
  6246. if (cs.float_left) {
  6247. n = layout_float_group(l, n, pst, depth, lk);
  6248. continue;
  6249. }
  6250. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  6251. n = layout_inline_blocks(l, n, pst, depth, link);
  6252. continue;
  6253. }
  6254. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  6255. layout_block(l, n, &cs, depth + 1, lk);
  6256. else {
  6257. layout_children(l, n, &cs, depth + 1, lk);
  6258. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  6259. l->space_pending = 1;
  6260. }
  6261. n = nd->next;
  6262. }
  6263. }
  6264. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  6265. * runs and a recursive page can otherwise overflow the stack. */
  6266. static struct lay layout_state;
  6267. static int measure_page(int left, int right)
  6268. {
  6269. struct lay *l = &layout_state;
  6270. struct br_style base = base_style();
  6271. unsigned int i;
  6272. for (i = 0; i < BR_MAX_NODES; i++) {
  6273. block_h[i] = 0;
  6274. img_top[i] = 0;
  6275. img_h[i] = 0;
  6276. layout_boxes[i].valid = 0;
  6277. }
  6278. l->draw = 0;
  6279. l->ui = 0;
  6280. l->left = left;
  6281. l->right = right;
  6282. l->y = 0;
  6283. l->line_x = left;
  6284. l->run_x = left;
  6285. l->line_left = left;
  6286. l->line_right = right;
  6287. l->line_y = 0;
  6288. l->line_h = 0;
  6289. l->align = BR_ALIGN_LEFT;
  6290. l->float_active = 0;
  6291. l->parent_top = 0;
  6292. l->depth = 0;
  6293. l->nruns = 0;
  6294. l->space_pending = 0;
  6295. layout_children(l, doc.root, &base, 0, 0);
  6296. return l->y + 8;
  6297. }
  6298. static int deferred_cmp(const struct br_deferred *a,
  6299. const struct br_deferred *b)
  6300. {
  6301. int az = a->z_set ? a->z_index : 0;
  6302. int bz = b->z_set ? b->z_index : 0;
  6303. if (az != bz)
  6304. return az < bz ? -1 : 1;
  6305. if (a->order != b->order)
  6306. return a->order < b->order ? -1 : 1;
  6307. return 0;
  6308. }
  6309. static void sort_deferred(void)
  6310. {
  6311. int i;
  6312. for (i = 1; i < ndeferred; i++) {
  6313. struct br_deferred key = deferred[i];
  6314. int j = i;
  6315. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  6316. deferred[j] = deferred[j - 1];
  6317. j--;
  6318. }
  6319. deferred[j] = key;
  6320. }
  6321. }
  6322. static void render_page(int left, int right, int y0)
  6323. {
  6324. struct lay *l = &layout_state;
  6325. struct br_style base = base_style();
  6326. l->draw = 1;
  6327. l->ui = &ui;
  6328. l->left = left;
  6329. l->right = right;
  6330. l->y = y0;
  6331. l->line_x = left;
  6332. l->run_x = left;
  6333. l->line_left = left;
  6334. l->line_right = right;
  6335. l->line_y = y0;
  6336. l->line_h = 0;
  6337. l->align = BR_ALIGN_LEFT;
  6338. l->float_active = 0;
  6339. l->parent_top = 0;
  6340. l->depth = 0;
  6341. l->nruns = 0;
  6342. l->space_pending = 0;
  6343. nhits = 0;
  6344. ndeferred = 0;
  6345. layout_children(l, doc.root, &base, 0, 0);
  6346. sort_deferred();
  6347. {
  6348. int i;
  6349. for (i = 0; i < ndeferred; i++) {
  6350. struct br_style st;
  6351. br_style_for(&doc, deferred[i].node, &base, &st);
  6352. if (st.display == BR_DISPLAY_NONE)
  6353. continue;
  6354. l->draw = 1;
  6355. l->left = deferred[i].flow_left;
  6356. l->right = deferred[i].flow_right;
  6357. l->y = deferred[i].flow_y;
  6358. l->line_x = l->left;
  6359. l->run_x = l->left;
  6360. l->line_y = l->y;
  6361. l->line_h = 0;
  6362. l->nruns = 0;
  6363. l->space_pending = 0;
  6364. l->align = st.align;
  6365. if (st.pos == 2 && block_h[deferred[i].node]) {
  6366. struct ngui_rect clip;
  6367. int ch = block_h[deferred[i].node] + 24;
  6368. clip.x = page_rect.x;
  6369. clip.y = page_rect.y;
  6370. clip.w = page_rect.w - 12;
  6371. if (ch > page_rect.h)
  6372. ch = page_rect.h;
  6373. clip.h = ch;
  6374. ngui_push_clip(&ui, clip);
  6375. if (st.has_bg)
  6376. ngui_fill_rect(&ui, clip, st.bg);
  6377. layout_block(l, deferred[i].node, &st, 0,
  6378. deferred[i].link);
  6379. ngui_pop_clip(&ui);
  6380. } else {
  6381. layout_block(l, deferred[i].node, &st, 0,
  6382. deferred[i].link);
  6383. }
  6384. }
  6385. }
  6386. }
  6387. /* ---- UI ---- */
  6388. static int find_hit(int x, int y)
  6389. {
  6390. int i;
  6391. for (i = nhits - 1; i >= 0; i--) {
  6392. struct hit *h = &hits[i];
  6393. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  6394. y < h->y + h->h)
  6395. return (int)h->node;
  6396. }
  6397. return 0;
  6398. }
  6399. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  6400. {
  6401. int x = r.x + 4, y = r.y + 4, h = 22;
  6402. int compact = r.w < 560;
  6403. int go_w = r.w < 420 ? 32 : 42;
  6404. int in_x, in_w, res;
  6405. ngui_fill_rect(&ui, r, ui.theme.panel);
  6406. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  6407. ui.theme.border);
  6408. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  6409. NGUI_ICON_CHEVRON_LEFT))
  6410. *action |= ACT_BACK;
  6411. x += 32;
  6412. if (!compact) {
  6413. if (ngui_icon_button(&ui, ID_FORWARD,
  6414. (struct ngui_rect){x, y, 28, h},
  6415. NGUI_ICON_CHEVRON_RIGHT))
  6416. *action |= ACT_FORWARD;
  6417. x += 32;
  6418. }
  6419. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  6420. NGUI_ICON_REFRESH))
  6421. *action |= ACT_RELOAD;
  6422. x += 32;
  6423. if (!compact) {
  6424. if (ngui_icon_button(&ui, ID_HOME,
  6425. (struct ngui_rect){x, y, 28, h},
  6426. NGUI_ICON_HOME))
  6427. *action |= ACT_HOME;
  6428. x += 32;
  6429. }
  6430. in_x = x + 2;
  6431. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  6432. if (in_w < 60)
  6433. in_w = 60;
  6434. res = ngui_text_input(&ui, ID_URL,
  6435. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  6436. if (res & NGUI_INPUT_SUBMIT)
  6437. *action |= ACT_NAV;
  6438. if (res & NGUI_INPUT_CANCEL)
  6439. ngui_set_focus(&ui, 0);
  6440. if (ngui_button(&ui, ID_GO,
  6441. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  6442. "Go"))
  6443. *action |= ACT_NAV;
  6444. }
  6445. static int page_hover_node(void)
  6446. {
  6447. if (!ui.inside)
  6448. return 0;
  6449. if (ui.mouse_x < page_rect.x ||
  6450. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  6451. ui.mouse_y < page_rect.y ||
  6452. ui.mouse_y >= page_rect.y + page_rect.h)
  6453. return 0;
  6454. return find_hit(ui.mouse_x, ui.mouse_y);
  6455. }
  6456. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  6457. {
  6458. int x, y, w = page.w, h = page.h;
  6459. if (!src || w <= 0 || h <= 0)
  6460. return;
  6461. for (y = 0; y < h; y++) {
  6462. unsigned short *s = src + (page.y + y) * sw + page.x;
  6463. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  6464. for (x = 0; x + 1 < w; x += 2) {
  6465. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  6466. }
  6467. if (x < w)
  6468. d[x] = s[x];
  6469. }
  6470. }
  6471. static void draw_page(struct ngui_rect page)
  6472. {
  6473. int left, right, ch;
  6474. int old_panel, old_dim;
  6475. unsigned short *saved_px;
  6476. int saved_w, saved_h, use_buf;
  6477. page_rect = page;
  6478. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  6479. page_cache_valid && layout_valid &&
  6480. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  6481. page_scroll.offset == page_cache_scroll &&
  6482. page_cache_nnode == doc.nnode &&
  6483. page_cache_x == page.x && page_cache_y == page.y &&
  6484. page_cache_w == page.w && page_cache_h == page.h) {
  6485. blit_page(page, page_backbuf, pagebuf_w);
  6486. return;
  6487. }
  6488. ngui_fill_rect(&ui, page, ui.theme.bg);
  6489. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  6490. const char *s = page_loading ? "Loading..." : "No page";
  6491. int w = (int)ngui_text_width_ui(&ui, s);
  6492. ngui_text(&ui, page.x + (page.w - w) / 2,
  6493. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  6494. page_scroll.content_h = 0;
  6495. page_scroll.view_h = page.h;
  6496. page_cache_valid = 0;
  6497. return;
  6498. }
  6499. if (page.w < 40 || page.h < 40) {
  6500. page_cache_valid = 0;
  6501. return;
  6502. }
  6503. saved_px = ui.px;
  6504. saved_w = ui.w;
  6505. saved_h = ui.h;
  6506. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  6507. if (use_buf) {
  6508. ui.px = page_backbuf;
  6509. ui.w = pagebuf_w;
  6510. ui.h = pagebuf_h;
  6511. ngui_fill_rect(&ui, page, ui.theme.bg);
  6512. }
  6513. left = page.x + 8;
  6514. right = page.x + page.w - 16;
  6515. if (!layout_valid || left != layout_left || right != layout_right ||
  6516. layout_nnode != doc.nnode) {
  6517. layout_content_h = measure_page(left, right);
  6518. layout_valid = 1;
  6519. layout_left = left;
  6520. layout_right = right;
  6521. layout_nnode = doc.nnode;
  6522. }
  6523. ch = layout_content_h;
  6524. page_scroll.content_h = ch;
  6525. page_scroll.view_h = page.h;
  6526. ngui_scroll_begin(&ui, page, &page_scroll);
  6527. render_page(left, right, page.y + 4 - page_scroll.offset);
  6528. old_panel = ui.theme.panel_alt;
  6529. old_dim = ui.theme.text_dim;
  6530. ui.theme.panel_alt = 0xC618;
  6531. ui.theme.text_dim = 0x8410;
  6532. ngui_scroll_end(&ui, page, &page_scroll);
  6533. ui.theme.panel_alt = old_panel;
  6534. ui.theme.text_dim = old_dim;
  6535. if (use_buf) {
  6536. ui.px = saved_px;
  6537. ui.w = saved_w;
  6538. ui.h = saved_h;
  6539. blit_page(page, page_backbuf, pagebuf_w);
  6540. page_cache_valid = 1;
  6541. page_cache_scroll = page_scroll.offset;
  6542. page_cache_nnode = doc.nnode;
  6543. page_cache_x = page.x;
  6544. page_cache_y = page.y;
  6545. page_cache_w = page.w;
  6546. page_cache_h = page.h;
  6547. } else {
  6548. page_cache_valid = 0;
  6549. }
  6550. }
  6551. static void draw_status(struct ngui_rect r)
  6552. {
  6553. char msg[BR_URL_MAX + 32];
  6554. unsigned int n = 0;
  6555. int hover = page_hover_node();
  6556. unsigned short color;
  6557. const char *kind;
  6558. ngui_fill_rect(&ui, r, ui.theme.panel);
  6559. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  6560. ui.theme.border);
  6561. if (hover) {
  6562. const char *href = br_href(&doc, (unsigned int)hover);
  6563. char url[BR_URL_MAX];
  6564. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  6565. s_append(msg, &n, "Link: ", sizeof(msg));
  6566. s_append(msg, &n, url, sizeof(msg));
  6567. } else {
  6568. s_copy(msg, "Link", sizeof(msg));
  6569. }
  6570. color = ui.theme.accent;
  6571. } else if (status_text[0]) {
  6572. s_copy(msg, status_text, sizeof(msg));
  6573. color = status_error ? ui.theme.error : ui.theme.text;
  6574. } else if (page_title[0]) {
  6575. s_copy(msg, page_title, sizeof(msg));
  6576. color = ui.theme.text;
  6577. } else {
  6578. s_copy(msg, "Ready", sizeof(msg));
  6579. color = ui.theme.text_dim;
  6580. }
  6581. kind = s_eq(page_url, "about:home") ? "HOME" :
  6582. page_is_local ? "FILE" :
  6583. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  6584. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  6585. {
  6586. int kw = (int)ngui_text_width_ui(&ui, kind);
  6587. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  6588. ui.theme.text_dim);
  6589. }
  6590. }
  6591. static void draw(unsigned int *action)
  6592. {
  6593. struct ngui_rect r = {0, 0, ui.w, ui.h};
  6594. struct ngui_rect toolbar, status, page;
  6595. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  6596. status = ngui_cut_bottom(&r, BR_STATUS_H);
  6597. page = r;
  6598. draw_toolbar(toolbar, action);
  6599. draw_page(page);
  6600. draw_status(status);
  6601. }
  6602. static void redraw_now(void)
  6603. {
  6604. unsigned int action = 0;
  6605. ngui_begin(&ui);
  6606. draw(&action);
  6607. ngui_end(&ui);
  6608. }
  6609. static void handle_keys(unsigned int *action)
  6610. {
  6611. int k, scrolled = 0;
  6612. if (form_focus >= doc.nnode)
  6613. form_focus = 0;
  6614. if (form_focus && !ngui_focus(&ui)) {
  6615. while ((k = ngui_key(&ui)) != 0)
  6616. form_key(k);
  6617. return;
  6618. }
  6619. /* Batch queued page keys: a slow full-page render must not make a
  6620. * held Page Down advance only once every few frames. */
  6621. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  6622. scrolled++;
  6623. if (scrolled)
  6624. ngui_invalidate(&ui);
  6625. if (ngui_focus(&ui))
  6626. return;
  6627. while ((k = ngui_key(&ui)) != 0) {
  6628. switch (k) {
  6629. case NGUI_KEY_ESC:
  6630. *action |= ACT_CLOSE;
  6631. break;
  6632. case NGUI_KEY_TAB:
  6633. case 0x0C: /* Ctrl+L */
  6634. ngui_set_focus(&ui, ID_URL);
  6635. break;
  6636. case 0x12: /* Ctrl+R */
  6637. *action |= ACT_RELOAD;
  6638. break;
  6639. case NGUI_KEY_BACKSPACE:
  6640. *action |= ACT_BACK;
  6641. break;
  6642. case NGUI_KEY_UP:
  6643. ngui_scroll_to(&page_scroll,
  6644. page_scroll.offset - 24);
  6645. ngui_invalidate(&ui);
  6646. break;
  6647. case NGUI_KEY_DOWN:
  6648. ngui_scroll_to(&page_scroll,
  6649. page_scroll.offset + 24);
  6650. ngui_invalidate(&ui);
  6651. break;
  6652. case NGUI_KEY_HOME:
  6653. ngui_scroll_to(&page_scroll, 0);
  6654. ngui_invalidate(&ui);
  6655. break;
  6656. case NGUI_KEY_END:
  6657. ngui_scroll_to(&page_scroll,
  6658. page_scroll.content_h -
  6659. page_scroll.view_h);
  6660. ngui_invalidate(&ui);
  6661. break;
  6662. default:
  6663. break;
  6664. }
  6665. }
  6666. }
  6667. static unsigned int form_ancestor(unsigned int node)
  6668. {
  6669. unsigned int p = node;
  6670. while (p && p < doc.nnode) {
  6671. if (doc.nodes[p].tag == BR_TAG_FORM &&
  6672. doc.nodes[p].type == BR_NODE_ELEM)
  6673. return p;
  6674. p = doc.nodes[p].parent;
  6675. }
  6676. return 0;
  6677. }
  6678. static int form_descendant(unsigned int node, unsigned int form)
  6679. {
  6680. unsigned int p = node;
  6681. while (p && p < doc.nnode) {
  6682. if (p == form)
  6683. return 1;
  6684. p = doc.nodes[p].parent;
  6685. }
  6686. return 0;
  6687. }
  6688. static void form_reset_form(unsigned int form)
  6689. {
  6690. unsigned int i;
  6691. for (i = 0; i < FORM_MAX; i++)
  6692. if (form_states[i].used &&
  6693. form_descendant(form_states[i].node, form))
  6694. form_states[i].used = 0;
  6695. form_focus = 0;
  6696. }
  6697. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  6698. const char *s)
  6699. {
  6700. static const char hex[] = "0123456789ABCDEF";
  6701. while (s && *s && *n + 1 < cap) {
  6702. unsigned char c = (unsigned char)*s++;
  6703. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  6704. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  6705. c == '.' || c == '~') {
  6706. dst[(*n)++] = (char)c;
  6707. } else if (c == ' ') {
  6708. dst[(*n)++] = '+';
  6709. } else if (*n + 3 < cap) {
  6710. dst[(*n)++] = '%';
  6711. dst[(*n)++] = hex[c >> 4];
  6712. dst[(*n)++] = hex[c & 15];
  6713. }
  6714. }
  6715. dst[*n] = '\0';
  6716. }
  6717. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  6718. const char *name, const char *value, int *first)
  6719. {
  6720. if (!name || !name[0])
  6721. return;
  6722. if (!*first && *n + 1 < cap)
  6723. dst[(*n)++] = '&';
  6724. *first = 0;
  6725. form_url_append(dst, n, cap, name);
  6726. if (*n + 1 < cap)
  6727. dst[(*n)++] = '=';
  6728. form_url_append(dst, n, cap, value ? value : "");
  6729. dst[*n] = '\0';
  6730. }
  6731. static int form_submit_form(unsigned int node, int fire_event)
  6732. {
  6733. unsigned int form = form_ancestor(node);
  6734. char action[BR_URL_MAX], query[2048];
  6735. unsigned int qn = 0, i;
  6736. int first = 1, is_post = 0;
  6737. const char *a, *method;
  6738. if (!form)
  6739. return 0;
  6740. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  6741. return 0;
  6742. method = br_find_attr(&doc, form, "method");
  6743. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  6744. is_post = 1;
  6745. a = br_find_attr(&doc, form, "action");
  6746. if (a && a[0]) {
  6747. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  6748. return 0;
  6749. } else {
  6750. s_copy(action, page_url, sizeof(action));
  6751. }
  6752. query[0] = '\0';
  6753. for (i = 0; i < doc.nnode; i++) {
  6754. struct br_node *nd = &doc.nodes[i];
  6755. struct form_state *fs;
  6756. const char *name;
  6757. const char *value = "";
  6758. if (nd->type != BR_NODE_ELEM || i == form ||
  6759. !form_descendant(i, form))
  6760. continue;
  6761. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  6762. nd->tag != BR_TAG_SELECT)
  6763. continue;
  6764. if (form_disabled(i))
  6765. continue;
  6766. name = br_find_attr(&doc, i, "name");
  6767. if (!name || !name[0])
  6768. continue;
  6769. fs = form_get(i, 1);
  6770. if (!fs)
  6771. continue;
  6772. if (nd->tag == BR_TAG_SELECT) {
  6773. char opt[64];
  6774. if (!form_option_text(i, fs->selected, opt,
  6775. sizeof(opt)))
  6776. s_copy(opt, "", sizeof(opt));
  6777. value = opt;
  6778. {
  6779. unsigned int c, oi = 0;
  6780. for (c = nd->first; c;
  6781. c = doc.nodes[c].next) {
  6782. if (doc.nodes[c].type != BR_NODE_ELEM ||
  6783. doc.nodes[c].tag != BR_TAG_OPTION)
  6784. continue;
  6785. if (oi == fs->selected) {
  6786. const char *v =
  6787. br_value(&doc, c);
  6788. if (v && v[0])
  6789. value = v;
  6790. break;
  6791. }
  6792. oi++;
  6793. }
  6794. }
  6795. } else if (nd->tag == BR_TAG_INPUT) {
  6796. int kind = form_kind_of(i);
  6797. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6798. if (!fs->checked)
  6799. continue;
  6800. value = br_value(&doc, i);
  6801. if (!value || !value[0])
  6802. value = "on";
  6803. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  6804. kind == FORM_BUTTON) {
  6805. if (i != node)
  6806. continue;
  6807. value = fs->value;
  6808. } else {
  6809. value = fs->value;
  6810. }
  6811. } else {
  6812. value = fs->value;
  6813. }
  6814. form_add_param(query, &qn, sizeof(query), name, value, &first);
  6815. }
  6816. if (is_post) {
  6817. if (action[0] == '/') {
  6818. set_status("POST forms need an HTTP action URL", 1, 4000);
  6819. ngui_invalidate(&ui);
  6820. return 0;
  6821. }
  6822. if (qn >= sizeof(pending_post))
  6823. qn = sizeof(pending_post) - 1;
  6824. if (qn)
  6825. memcpy(pending_post, query, qn);
  6826. pending_post[qn] = '\0';
  6827. pending_post_len = qn;
  6828. } else {
  6829. pending_post_len = 0;
  6830. if (qn) {
  6831. unsigned int an = s_len(action);
  6832. if (an + qn + 2 < sizeof(action)) {
  6833. action[an++] = strchr(action, '?') ? '&' : '?';
  6834. action[an] = '\0';
  6835. s_copy(action + an, query,
  6836. sizeof(action) - an);
  6837. }
  6838. }
  6839. }
  6840. s_copy(pending_url, action, sizeof(pending_url));
  6841. pending_action |= ACT_NAV;
  6842. cancel_fetch = 1;
  6843. ngui_invalidate(&ui);
  6844. return 1;
  6845. }
  6846. static void form_reset_event(unsigned int form)
  6847. {
  6848. if (form && !js_browser_event(form, "reset", 1, 1))
  6849. return;
  6850. if (form)
  6851. form_reset_form(form);
  6852. else
  6853. form_reset_state();
  6854. form_dirty = 0;
  6855. layout_valid = 0;
  6856. ngui_invalidate(&ui);
  6857. }
  6858. static void form_blur(void)
  6859. {
  6860. unsigned int node = form_focus;
  6861. form_focus = 0;
  6862. if (node && form_dirty) {
  6863. form_dirty = 0;
  6864. js_browser_event(node, "change", 1, 0);
  6865. }
  6866. }
  6867. static void form_click(unsigned int node)
  6868. {
  6869. struct form_state *fs;
  6870. int kind, changed = 0;
  6871. if (!form_is_control(node) || form_disabled(node))
  6872. return;
  6873. if (form_focus != node)
  6874. form_blur();
  6875. if (!js_browser_event(node, "click", 1, 1))
  6876. return;
  6877. fs = form_get(node, 1);
  6878. if (!fs)
  6879. return;
  6880. kind = form_kind_of(node);
  6881. form_focus = node;
  6882. form_dirty = 0;
  6883. if (kind == FORM_CHECKBOX) {
  6884. fs->checked = !fs->checked;
  6885. changed = 1;
  6886. } else if (kind == FORM_RADIO) {
  6887. const char *name = br_find_attr(&doc, node, "name");
  6888. unsigned int i;
  6889. fs->checked = 1;
  6890. changed = 1;
  6891. if (name) {
  6892. for (i = 0; i < FORM_MAX; i++) {
  6893. struct form_state *o = &form_states[i];
  6894. if (!o->used || o->node == node)
  6895. continue;
  6896. if (form_kind_of(o->node) == FORM_RADIO) {
  6897. const char *on = br_find_attr(&doc,
  6898. o->node,
  6899. "name");
  6900. if (on && s_eq(on, name))
  6901. o->checked = 0;
  6902. }
  6903. }
  6904. }
  6905. } else if (kind == FORM_SELECT) {
  6906. unsigned int n = form_option_count(node);
  6907. if (n) {
  6908. fs->selected = (unsigned char)
  6909. ((fs->selected + 1) % n);
  6910. changed = 1;
  6911. }
  6912. } else if (kind == FORM_SUBMIT) {
  6913. form_submit_form(node, 1);
  6914. return;
  6915. } else if (kind == FORM_RESET) {
  6916. form_reset_event(form_ancestor(node));
  6917. return;
  6918. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  6919. kind == FORM_TEXTAREA) {
  6920. fs->caret = fs->len;
  6921. }
  6922. if (changed) {
  6923. js_browser_event(node, "input", 1, 0);
  6924. js_browser_event(node, "change", 1, 0);
  6925. }
  6926. layout_valid = 0;
  6927. ngui_invalidate(&ui);
  6928. }
  6929. static void form_focus_next(void)
  6930. {
  6931. unsigned int start = form_focus ? form_focus + 1 : 0;
  6932. unsigned int i;
  6933. form_blur();
  6934. for (i = start; i < doc.nnode; i++) {
  6935. if (form_is_control(i) && !form_disabled(i) &&
  6936. !s_eq(br_type(&doc, i), "hidden")) {
  6937. form_focus = i;
  6938. layout_valid = 0;
  6939. ngui_invalidate(&ui);
  6940. return;
  6941. }
  6942. }
  6943. form_focus = 0;
  6944. layout_valid = 0;
  6945. ngui_invalidate(&ui);
  6946. }
  6947. static void form_key(int k)
  6948. {
  6949. struct form_state *fs;
  6950. int kind;
  6951. if (!form_focus || form_focus >= doc.nnode) {
  6952. form_focus = 0;
  6953. return;
  6954. }
  6955. fs = form_get(form_focus, 1);
  6956. if (!fs || form_disabled(form_focus))
  6957. return;
  6958. kind = form_kind_of(form_focus);
  6959. if (kind == FORM_SELECT) {
  6960. unsigned int n = form_option_count(form_focus);
  6961. int changed = 0;
  6962. if (k == NGUI_KEY_UP && n) {
  6963. fs->selected = (unsigned char)
  6964. ((fs->selected + n - 1) % n);
  6965. changed = 1;
  6966. } else if (k == NGUI_KEY_DOWN && n) {
  6967. fs->selected = (unsigned char)
  6968. ((fs->selected + 1) % n);
  6969. changed = 1;
  6970. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  6971. form_blur();
  6972. layout_valid = 0;
  6973. ngui_invalidate(&ui);
  6974. return;
  6975. } else {
  6976. return;
  6977. }
  6978. if (changed) {
  6979. js_browser_event(form_focus, "input", 1, 0);
  6980. js_browser_event(form_focus, "change", 1, 0);
  6981. }
  6982. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6983. if (k == ' ') {
  6984. form_click(form_focus);
  6985. return;
  6986. }
  6987. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  6988. form_blur();
  6989. layout_valid = 0;
  6990. ngui_invalidate(&ui);
  6991. }
  6992. return;
  6993. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6994. kind == FORM_RESET) {
  6995. if (k == NGUI_KEY_ESC) {
  6996. form_blur();
  6997. layout_valid = 0;
  6998. ngui_invalidate(&ui);
  6999. } else if (k == '\r' || k == '\n' || k == ' ') {
  7000. form_click(form_focus);
  7001. }
  7002. return;
  7003. } else if (k == NGUI_KEY_TAB) {
  7004. form_focus_next();
  7005. return;
  7006. } else if (k == NGUI_KEY_ESC) {
  7007. form_blur();
  7008. layout_valid = 0;
  7009. ngui_invalidate(&ui);
  7010. return;
  7011. } else if (k == '\r' || k == '\n') {
  7012. unsigned int node = form_focus;
  7013. form_blur();
  7014. if (form_ancestor(node))
  7015. form_submit_form(node, 1);
  7016. layout_valid = 0;
  7017. ngui_invalidate(&ui);
  7018. return;
  7019. } else if (k == NGUI_KEY_BACKSPACE) {
  7020. if (fs->caret) {
  7021. unsigned int i = --fs->caret;
  7022. for (; i < fs->len; i++)
  7023. fs->value[i] = fs->value[i + 1];
  7024. if (fs->len)
  7025. fs->len--;
  7026. form_dirty = 1;
  7027. js_browser_event(form_focus, "input", 1, 0);
  7028. }
  7029. } else if (k == NGUI_KEY_DELETE) {
  7030. if (fs->caret < fs->len) {
  7031. unsigned int i;
  7032. for (i = fs->caret; i < fs->len; i++)
  7033. fs->value[i] = fs->value[i + 1];
  7034. fs->len--;
  7035. form_dirty = 1;
  7036. js_browser_event(form_focus, "input", 1, 0);
  7037. }
  7038. } else if (k == NGUI_KEY_LEFT) {
  7039. if (fs->caret)
  7040. fs->caret--;
  7041. } else if (k == NGUI_KEY_RIGHT) {
  7042. if (fs->caret < fs->len)
  7043. fs->caret++;
  7044. } else if (k == NGUI_KEY_HOME) {
  7045. fs->caret = 0;
  7046. } else if (k == NGUI_KEY_END) {
  7047. fs->caret = fs->len;
  7048. } else if (k >= 32 && k < 127) {
  7049. if (fs->len < FORM_VALUE_MAX) {
  7050. unsigned int i;
  7051. for (i = fs->len; i > fs->caret; i--)
  7052. fs->value[i] = fs->value[i - 1];
  7053. fs->value[fs->caret++] = (char)k;
  7054. fs->len++;
  7055. form_dirty = 1;
  7056. js_browser_event(form_focus, "input", 1, 0);
  7057. }
  7058. } else {
  7059. return;
  7060. }
  7061. fs->value[fs->len] = '\0';
  7062. layout_valid = 0;
  7063. ngui_invalidate(&ui);
  7064. }
  7065. static void handle_page_click(unsigned int *action)
  7066. {
  7067. int node;
  7068. char url[BR_URL_MAX];
  7069. if (!ui.pressed)
  7070. return;
  7071. if (ui.press_x < page_rect.x ||
  7072. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  7073. ui.press_y < page_rect.y ||
  7074. ui.press_y >= page_rect.y + page_rect.h)
  7075. return;
  7076. node = find_hit(ui.press_x, ui.press_y);
  7077. if (!node)
  7078. return;
  7079. if (form_is_control((unsigned int)node)) {
  7080. form_click((unsigned int)node);
  7081. return;
  7082. }
  7083. form_blur();
  7084. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  7085. return;
  7086. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  7087. sizeof(url)) != 0)
  7088. return;
  7089. s_copy(click_url, url, sizeof(click_url));
  7090. *action |= ACT_NAV;
  7091. }
  7092. void _start(const char *arg)
  7093. {
  7094. struct win_info wi;
  7095. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  7096. u_win_create(960, 640, "Browser", &wi) != 0 &&
  7097. u_win_create(780, 540, "Browser", &wi) != 0) {
  7098. u_puts("browser: no graphics window\n");
  7099. u_exit(1);
  7100. }
  7101. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  7102. url_in.placeholder = "http://...";
  7103. br_doc_init(&doc);
  7104. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  7105. ui.theme.accent);
  7106. br_set_viewport(wi.width);
  7107. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  7108. s_copy(cwd, "/", sizeof(cwd));
  7109. heap_clear();
  7110. origin_cache_load();
  7111. css_cache_init();
  7112. script_cache_init();
  7113. page_scroll.offset = 0;
  7114. page_scroll.content_h = 0;
  7115. if (arg && arg[0]) {
  7116. navigate(arg, 1);
  7117. } else {
  7118. load_home(1);
  7119. /* Start ready to type: keep the home page, but leave the address
  7120. * bar empty instead of showing "about:home". */
  7121. ngui_input_set(&url_in, "");
  7122. ngui_set_focus(&ui, ID_URL);
  7123. }
  7124. for (;;) {
  7125. unsigned int action = 0;
  7126. unsigned int now;
  7127. click_url[0] = '\0';
  7128. if (pending_action) {
  7129. action |= pending_action & ACT_WAIT_NAV;
  7130. if (pending_url[0])
  7131. s_copy(click_url, pending_url, sizeof(click_url));
  7132. pending_action = 0;
  7133. pending_url[0] = '\0';
  7134. cancel_fetch = 0;
  7135. } else if (preload_active) {
  7136. if (preload_wait)
  7137. preload_wait = 0;
  7138. else
  7139. preload_step();
  7140. } else if (preload_pending &&
  7141. page_scroll.offset != preload_scroll) {
  7142. preload_scroll = page_scroll.offset;
  7143. preload_pending = 0;
  7144. preload_node = 0;
  7145. preload_active = 1;
  7146. }
  7147. js_browser_tick();
  7148. if (pending_action)
  7149. continue;
  7150. now = u_ticks_ms();
  7151. if (status_until && (int)(now - status_until) >= 0) {
  7152. status_text[0] = '\0';
  7153. status_until = 0;
  7154. status_error = 0;
  7155. ngui_invalidate(&ui);
  7156. }
  7157. if (!ngui_begin(&ui)) {
  7158. /* A queued navigation (e.g. Enter in the URL bar during
  7159. * a slow fetch) must be handled even when this frame
  7160. * needs no redraw. */
  7161. if (!action) {
  7162. u_sleep_ms(10);
  7163. continue;
  7164. }
  7165. } else {
  7166. draw(&action);
  7167. handle_keys(&action);
  7168. handle_page_click(&action);
  7169. ngui_end(&ui);
  7170. }
  7171. if (action & ACT_NAV) {
  7172. if (click_url[0]) {
  7173. navigate(click_url, 1);
  7174. click_url[0] = '\0';
  7175. } else {
  7176. navigate(url_in.text, 1);
  7177. }
  7178. }
  7179. if (action & ACT_BACK) {
  7180. if (hist_pos > 0) {
  7181. hist_pos--;
  7182. navigate(history[hist_pos], 0);
  7183. }
  7184. }
  7185. if (action & ACT_FORWARD) {
  7186. if (hist_pos + 1 < hist_len) {
  7187. hist_pos++;
  7188. navigate(history[hist_pos], 0);
  7189. }
  7190. }
  7191. if (action & ACT_RELOAD) {
  7192. if (s_eq(page_url, "about:home"))
  7193. load_home(0);
  7194. else
  7195. navigate(page_url, 0);
  7196. }
  7197. if (action & ACT_HOME)
  7198. load_home(1);
  7199. if (action & ACT_CLOSE)
  7200. quit = 1;
  7201. if (quit)
  7202. break;
  7203. if (pending_action)
  7204. continue;
  7205. u_sleep_ms(10);
  7206. }
  7207. fetch_helper_stop();
  7208. u_win_close();
  7209. u_exit(0);
  7210. }