browser.c 174 KB

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