browser.c 243 KB

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