browser.c 182 KB

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