browser.c 220 KB

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