browser.c 200 KB

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