sokol_app.h 468 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224
  1. #if defined(SOKOL_IMPL) && !defined(SOKOL_APP_IMPL)
  2. #define SOKOL_APP_IMPL
  3. #endif
  4. #ifndef SOKOL_APP_INCLUDED
  5. /*
  6. sokol_app.h -- cross-platform application wrapper
  7. Project URL: https://github.com/floooh/sokol
  8. Do this:
  9. #define SOKOL_IMPL or
  10. #define SOKOL_APP_IMPL
  11. before you include this file in *one* C or C++ file to create the
  12. implementation.
  13. In the same place define one of the following to select the 3D-API
  14. which should be initialized by sokol_app.h (this must also match
  15. the backend selected for sokol_gfx.h if both are used in the same
  16. project):
  17. #define SOKOL_GLCORE
  18. #define SOKOL_GLES3
  19. #define SOKOL_D3D11
  20. #define SOKOL_METAL
  21. #define SOKOL_WGPU
  22. #define SOKOL_NOAPI
  23. Optionally provide the following defines with your own implementations:
  24. SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
  25. SOKOL_UNREACHABLE() - a guard macro for unreachable code (default: assert(false))
  26. SOKOL_WIN32_FORCE_MAIN - define this on Win32 to use a main() entry point instead of WinMain
  27. SOKOL_NO_ENTRY - define this if sokol_app.h shouldn't "hijack" the main() function
  28. SOKOL_APP_API_DECL - public function declaration prefix (default: extern)
  29. SOKOL_API_DECL - same as SOKOL_APP_API_DECL
  30. SOKOL_API_IMPL - public function implementation prefix (default: -)
  31. Optionally define the following to force debug checks and validations
  32. even in release mode:
  33. SOKOL_DEBUG - by default this is defined if _DEBUG is defined
  34. If sokol_app.h is compiled as a DLL, define the following before
  35. including the declaration or implementation:
  36. SOKOL_DLL
  37. On Windows, SOKOL_DLL will define SOKOL_APP_API_DECL as __declspec(dllexport)
  38. or __declspec(dllimport) as needed.
  39. On Linux, SOKOL_GLCORE can use either GLX or EGL.
  40. GLX is default, set SOKOL_FORCE_EGL to override.
  41. For example code, see https://github.com/floooh/sokol-samples/tree/master/sapp
  42. Portions of the Windows and Linux GL initialization, event-, icon- etc... code
  43. have been taken from GLFW (http://www.glfw.org/).
  44. iOS onscreen keyboard support 'inspired' by libgdx.
  45. Link with the following system libraries:
  46. - on macOS with Metal: Cocoa, QuartzCore, Metal, MetalKit
  47. - on macOS with GL: Cocoa, QuartzCore, OpenGL
  48. - on iOS with Metal: Foundation, UIKit, Metal, MetalKit
  49. - on iOS with GL: Foundation, UIKit, OpenGLES, GLKit
  50. - on Linux with EGL: X11, Xi, Xcursor, EGL, GL (or GLESv2), dl, pthread, m(?)
  51. - on Linux with GLX: X11, Xi, Xcursor, GL, dl, pthread, m(?)
  52. - on Android: GLESv3, EGL, log, android
  53. - on Windows with the MSVC or Clang toolchains: no action needed, libs are defined in-source via pragma-comment-lib
  54. - on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' so that _WIN32 is defined
  55. - link with the following libs: -lkernel32 -luser32 -lshell32
  56. - additionally with the GL backend: -lgdi32
  57. - additionally with the D3D11 backend: -ld3d11 -ldxgi
  58. On Linux, you also need to use the -pthread compiler and linker option, otherwise weird
  59. things will happen, see here for details: https://github.com/floooh/sokol/issues/376
  60. On macOS and iOS, the implementation must be compiled as Objective-C.
  61. FEATURE OVERVIEW
  62. ================
  63. sokol_app.h provides a minimalistic cross-platform API which
  64. implements the 'application-wrapper' parts of a 3D application:
  65. - a common application entry function
  66. - creates a window and 3D-API context/device with a 'default framebuffer'
  67. - makes the rendered frame visible
  68. - provides keyboard-, mouse- and low-level touch-events
  69. - platforms: MacOS, iOS, HTML5, Win32, Linux/RaspberryPi, Android
  70. - 3D-APIs: Metal, D3D11, GL4.1, GL4.3, GLES3, WebGL, WebGL2, NOAPI
  71. FEATURE/PLATFORM MATRIX
  72. =======================
  73. | Windows | macOS | Linux | iOS | Android | HTML5
  74. --------------------+---------+-------+-------+-------+---------+--------
  75. gl 4.x | YES | YES | YES | --- | --- | ---
  76. gles3/webgl2 | --- | --- | YES(2)| YES | YES | YES
  77. metal | --- | YES | --- | YES | --- | ---
  78. d3d11 | YES | --- | --- | --- | --- | ---
  79. noapi | YES | TODO | TODO | --- | TODO | ---
  80. KEY_DOWN | YES | YES | YES | SOME | TODO | YES
  81. KEY_UP | YES | YES | YES | SOME | TODO | YES
  82. CHAR | YES | YES | YES | YES | TODO | YES
  83. MOUSE_DOWN | YES | YES | YES | --- | --- | YES
  84. MOUSE_UP | YES | YES | YES | --- | --- | YES
  85. MOUSE_SCROLL | YES | YES | YES | --- | --- | YES
  86. MOUSE_MOVE | YES | YES | YES | --- | --- | YES
  87. MOUSE_ENTER | YES | YES | YES | --- | --- | YES
  88. MOUSE_LEAVE | YES | YES | YES | --- | --- | YES
  89. TOUCHES_BEGAN | --- | --- | --- | YES | YES | YES
  90. TOUCHES_MOVED | --- | --- | --- | YES | YES | YES
  91. TOUCHES_ENDED | --- | --- | --- | YES | YES | YES
  92. TOUCHES_CANCELLED | --- | --- | --- | YES | YES | YES
  93. RESIZED | YES | YES | YES | YES | YES | YES
  94. ICONIFIED | YES | YES | YES | --- | --- | ---
  95. RESTORED | YES | YES | YES | --- | --- | ---
  96. FOCUSED | YES | YES | YES | --- | --- | YES
  97. UNFOCUSED | YES | YES | YES | --- | --- | YES
  98. SUSPENDED | --- | --- | --- | YES | YES | TODO
  99. RESUMED | --- | --- | --- | YES | YES | TODO
  100. QUIT_REQUESTED | YES | YES | YES | --- | --- | YES
  101. IME | TODO | TODO? | TODO | ??? | TODO | ???
  102. key repeat flag | YES | YES | YES | --- | --- | YES
  103. windowed | YES | YES | YES | --- | --- | YES
  104. fullscreen | YES | YES | YES | YES | YES | ---
  105. mouse hide | YES | YES | YES | --- | --- | YES
  106. mouse lock | YES | YES | YES | --- | --- | YES
  107. set cursor type | YES | YES | YES | --- | --- | YES
  108. screen keyboard | --- | --- | --- | YES | TODO | YES
  109. swap interval | YES | YES | YES | YES | TODO | YES
  110. high-dpi | YES | YES | TODO | YES | YES | YES
  111. clipboard | YES | YES | YES | --- | --- | YES
  112. MSAA | YES | YES | YES | YES | YES | YES
  113. drag'n'drop | YES | YES | YES | --- | --- | YES
  114. window icon | YES | YES(1)| YES | --- | --- | YES
  115. (1) macOS has no regular window icons, instead the dock icon is changed
  116. (2) supported with EGL only (not GLX)
  117. STEP BY STEP
  118. ============
  119. --- Add a sokol_main() function to your code which returns a sapp_desc structure
  120. with initialization parameters and callback function pointers. This
  121. function is called very early, usually at the start of the
  122. platform's entry function (e.g. main or WinMain). You should do as
  123. little as possible here, since the rest of your code might be called
  124. from another thread (this depends on the platform):
  125. sapp_desc sokol_main(int argc, char* argv[]) {
  126. return (sapp_desc) {
  127. .width = 640,
  128. .height = 480,
  129. .init_cb = my_init_func,
  130. .frame_cb = my_frame_func,
  131. .cleanup_cb = my_cleanup_func,
  132. .event_cb = my_event_func,
  133. ...
  134. };
  135. }
  136. To get any logging output in case of errors you need to provide a log
  137. callback. The easiest way is via sokol_log.h:
  138. #include "sokol_log.h"
  139. sapp_desc sokol_main(int argc, char* argv[]) {
  140. return (sapp_desc) {
  141. ...
  142. .logger.func = slog_func,
  143. };
  144. }
  145. There are many more setup parameters, but these are the most important.
  146. For a complete list search for the sapp_desc structure declaration
  147. below.
  148. DO NOT call any sokol-app function from inside sokol_main(), since
  149. sokol-app will not be initialized at this point.
  150. The .width and .height parameters are the preferred size of the 3D
  151. rendering canvas. The actual size may differ from this depending on
  152. platform and other circumstances. Also the canvas size may change at
  153. any time (for instance when the user resizes the application window,
  154. or rotates the mobile device). You can just keep .width and .height
  155. zero-initialized to open a default-sized window (what "default-size"
  156. exactly means is platform-specific, but usually it's a size that covers
  157. most of, but not all, of the display).
  158. All provided function callbacks will be called from the same thread,
  159. but this may be different from the thread where sokol_main() was called.
  160. .init_cb (void (*)(void))
  161. This function is called once after the application window,
  162. 3D rendering context and swap chain have been created. The
  163. function takes no arguments and has no return value.
  164. .frame_cb (void (*)(void))
  165. This is the per-frame callback, which is usually called 60
  166. times per second. This is where your application would update
  167. most of its state and perform all rendering.
  168. .cleanup_cb (void (*)(void))
  169. The cleanup callback is called once right before the application
  170. quits.
  171. .event_cb (void (*)(const sapp_event* event))
  172. The event callback is mainly for input handling, but is also
  173. used to communicate other types of events to the application. Keep the
  174. event_cb struct member zero-initialized if your application doesn't require
  175. event handling.
  176. As you can see, those 'standard callbacks' don't have a user_data
  177. argument, so any data that needs to be preserved between callbacks
  178. must live in global variables. If keeping state in global variables
  179. is not an option, there's an alternative set of callbacks with
  180. an additional user_data pointer argument:
  181. .user_data (void*)
  182. The user-data argument for the callbacks below
  183. .init_userdata_cb (void (*)(void* user_data))
  184. .frame_userdata_cb (void (*)(void* user_data))
  185. .cleanup_userdata_cb (void (*)(void* user_data))
  186. .event_userdata_cb (void(*)(const sapp_event* event, void* user_data))
  187. The function sapp_userdata() can be used to query the user_data
  188. pointer provided in the sapp_desc struct.
  189. You can also call sapp_query_desc() to get a copy of the
  190. original sapp_desc structure.
  191. NOTE that there's also an alternative compile mode where sokol_app.h
  192. doesn't "hijack" the main() function. Search below for SOKOL_NO_ENTRY.
  193. --- Implement the initialization callback function (init_cb), this is called
  194. once after the rendering surface, 3D API and swap chain have been
  195. initialized by sokol_app. All sokol-app functions can be called
  196. from inside the initialization callback, the most useful functions
  197. at this point are:
  198. int sapp_width(void)
  199. int sapp_height(void)
  200. Returns the current width and height of the default framebuffer in pixels,
  201. this may change from one frame to the next, and it may be different
  202. from the initial size provided in the sapp_desc struct.
  203. float sapp_widthf(void)
  204. float sapp_heightf(void)
  205. These are alternatives to sapp_width() and sapp_height() which return
  206. the default framebuffer size as float values instead of integer. This
  207. may help to prevent casting back and forth between int and float
  208. in more strongly typed languages than C and C++.
  209. double sapp_frame_duration(void)
  210. Returns the frame duration in seconds averaged over a number of
  211. frames to smooth out any jittering spikes.
  212. int sapp_color_format(void)
  213. int sapp_depth_format(void)
  214. The color and depth-stencil pixelformats of the default framebuffer,
  215. as integer values which are compatible with sokol-gfx's
  216. sg_pixel_format enum (so that they can be plugged directly in places
  217. where sg_pixel_format is expected). Possible values are:
  218. 23 == SG_PIXELFORMAT_RGBA8
  219. 28 == SG_PIXELFORMAT_BGRA8
  220. 42 == SG_PIXELFORMAT_DEPTH
  221. 43 == SG_PIXELFORMAT_DEPTH_STENCIL
  222. int sapp_sample_count(void)
  223. Return the MSAA sample count of the default framebuffer.
  224. const void* sapp_metal_get_device(void)
  225. const void* sapp_metal_get_current_drawable(void)
  226. const void* sapp_metal_get_depth_stencil_texture(void)
  227. const void* sapp_metal_get_msaa_color_texture(void)
  228. If the Metal backend has been selected, these functions return pointers
  229. to various Metal API objects required for rendering, otherwise
  230. they return a null pointer. These void pointers are actually
  231. Objective-C ids converted with a (ARC) __bridge cast so that
  232. the ids can be tunneled through C code. Also note that the returned
  233. pointers may change from one frame to the next, only the Metal device
  234. object is guaranteed to stay the same.
  235. const void* sapp_macos_get_window(void)
  236. On macOS, get the NSWindow object pointer, otherwise a null pointer.
  237. Before being used as Objective-C object, the void* must be converted
  238. back with a (ARC) __bridge cast.
  239. const void* sapp_ios_get_window(void)
  240. On iOS, get the UIWindow object pointer, otherwise a null pointer.
  241. Before being used as Objective-C object, the void* must be converted
  242. back with a (ARC) __bridge cast.
  243. const void* sapp_d3d11_get_device(void)
  244. const void* sapp_d3d11_get_device_context(void)
  245. const void* sapp_d3d11_get_render_view(void)
  246. const void* sapp_d3d11_get_resolve_view(void);
  247. const void* sapp_d3d11_get_depth_stencil_view(void)
  248. Similar to the sapp_metal_* functions, the sapp_d3d11_* functions
  249. return pointers to D3D11 API objects required for rendering,
  250. only if the D3D11 backend has been selected. Otherwise they
  251. return a null pointer. Note that the returned pointers to the
  252. render-target-view and depth-stencil-view may change from one
  253. frame to the next!
  254. const void* sapp_win32_get_hwnd(void)
  255. On Windows, get the window's HWND, otherwise a null pointer. The
  256. HWND has been cast to a void pointer in order to be tunneled
  257. through code which doesn't include Windows.h.
  258. const void* sapp_wgpu_get_device(void)
  259. const void* sapp_wgpu_get_render_view(void)
  260. const void* sapp_wgpu_get_resolve_view(void)
  261. const void* sapp_wgpu_get_depth_stencil_view(void)
  262. These are the WebGPU-specific functions to get the WebGPU
  263. objects and values required for rendering. If sokol_app.h
  264. is not compiled with SOKOL_WGPU, these functions return null.
  265. uint32_t sapp_gl_get_framebuffer(void)
  266. This returns the 'default framebuffer' of the GL context.
  267. Typically this will be zero.
  268. int sapp_gl_get_major_version(void)
  269. int sapp_gl_get_minor_version(void)
  270. Returns the major and minor version of the GL context
  271. (only for SOKOL_GLCORE, all other backends return zero here, including SOKOL_GLES3)
  272. const void* sapp_android_get_native_activity(void);
  273. On Android, get the native activity ANativeActivity pointer, otherwise
  274. a null pointer.
  275. --- Implement the frame-callback function, this function will be called
  276. on the same thread as the init callback, but might be on a different
  277. thread than the sokol_main() function. Note that the size of
  278. the rendering framebuffer might have changed since the frame callback
  279. was called last. Call the functions sapp_width() and sapp_height()
  280. each frame to get the current size.
  281. --- Optionally implement the event-callback to handle input events.
  282. sokol-app provides the following type of input events:
  283. - a 'virtual key' was pressed down or released
  284. - a single text character was entered (provided as UTF-32 encoded
  285. UNICODE code point)
  286. - a mouse button was pressed down or released (left, right, middle)
  287. - mouse-wheel or 2D scrolling events
  288. - the mouse was moved
  289. - the mouse has entered or left the application window boundaries
  290. - low-level, portable multi-touch events (began, moved, ended, cancelled)
  291. - the application window was resized, iconified or restored
  292. - the application was suspended or restored (on mobile platforms)
  293. - the user or application code has asked to quit the application
  294. - a string was pasted to the system clipboard
  295. - one or more files have been dropped onto the application window
  296. To explicitly 'consume' an event and prevent that the event is
  297. forwarded for further handling to the operating system, call
  298. sapp_consume_event() from inside the event handler (NOTE that
  299. this behaviour is currently only implemented for some HTML5
  300. events, support for other platforms and event types will
  301. be added as needed, please open a GitHub ticket and/or provide
  302. a PR if needed).
  303. NOTE: Do *not* call any 3D API rendering functions in the event
  304. callback function, since the 3D API context may not be active when the
  305. event callback is called (it may work on some platforms and 3D APIs,
  306. but not others, and the exact behaviour may change between
  307. sokol-app versions).
  308. --- Implement the cleanup-callback function, this is called once
  309. after the user quits the application (see the section
  310. "APPLICATION QUIT" for detailed information on quitting
  311. behaviour, and how to intercept a pending quit - for instance to show a
  312. "Really Quit?" dialog box). Note that the cleanup-callback isn't
  313. guaranteed to be called on the web and mobile platforms.
  314. MOUSE CURSOR TYPE AND VISIBILITY
  315. ================================
  316. You can show and hide the mouse cursor with
  317. void sapp_show_mouse(bool show)
  318. And to get the current shown status:
  319. bool sapp_mouse_shown(void)
  320. NOTE that hiding the mouse cursor is different and independent from
  321. the MOUSE/POINTER LOCK feature which will also hide the mouse pointer when
  322. active (MOUSE LOCK is described below).
  323. To change the mouse cursor to one of several predefined types, call
  324. the function:
  325. void sapp_set_mouse_cursor(sapp_mouse_cursor cursor)
  326. Setting the default mouse cursor SAPP_MOUSECURSOR_DEFAULT will restore
  327. the standard look.
  328. To get the currently active mouse cursor type, call:
  329. sapp_mouse_cursor sapp_get_mouse_cursor(void)
  330. MOUSE LOCK (AKA POINTER LOCK, AKA MOUSE CAPTURE)
  331. ================================================
  332. In normal mouse mode, no mouse movement events are reported when the
  333. mouse leaves the windows client area or hits the screen border (whether
  334. it's one or the other depends on the platform), and the mouse move events
  335. (SAPP_EVENTTYPE_MOUSE_MOVE) contain absolute mouse positions in
  336. framebuffer pixels in the sapp_event items mouse_x and mouse_y, and
  337. relative movement in framebuffer pixels in the sapp_event items mouse_dx
  338. and mouse_dy.
  339. To get continuous mouse movement (also when the mouse leaves the window
  340. client area or hits the screen border), activate mouse-lock mode
  341. by calling:
  342. sapp_lock_mouse(true)
  343. When mouse lock is activated, the mouse pointer is hidden, the
  344. reported absolute mouse position (sapp_event.mouse_x/y) appears
  345. frozen, and the relative mouse movement in sapp_event.mouse_dx/dy
  346. no longer has a direct relation to framebuffer pixels but instead
  347. uses "raw mouse input" (what "raw mouse input" exactly means also
  348. differs by platform).
  349. To deactivate mouse lock and return to normal mouse mode, call
  350. sapp_lock_mouse(false)
  351. And finally, to check if mouse lock is currently active, call
  352. if (sapp_mouse_locked()) { ... }
  353. On native platforms, the sapp_lock_mouse() and sapp_mouse_locked()
  354. functions work as expected (mouse lock is activated or deactivated
  355. immediately when sapp_lock_mouse() is called, and sapp_mouse_locked()
  356. also immediately returns the new state after sapp_lock_mouse()
  357. is called.
  358. On the web platform, sapp_lock_mouse() and sapp_mouse_locked() behave
  359. differently, as dictated by the limitations of the HTML5 Pointer Lock API:
  360. - sapp_lock_mouse(true) can be called at any time, but it will
  361. only take effect in a 'short-lived input event handler of a specific
  362. type', meaning when one of the following events happens:
  363. - SAPP_EVENTTYPE_MOUSE_DOWN
  364. - SAPP_EVENTTYPE_MOUSE_UP
  365. - SAPP_EVENTTYPE_MOUSE_SCROLL
  366. - SAPP_EVENTTYPE_KEY_UP
  367. - SAPP_EVENTTYPE_KEY_DOWN
  368. - The mouse lock/unlock action on the web platform is asynchronous,
  369. this means that sapp_mouse_locked() won't immediately return
  370. the new status after calling sapp_lock_mouse(), instead the
  371. reported status will only change when the pointer lock has actually
  372. been activated or deactivated in the browser.
  373. - On the web, mouse lock can be deactivated by the user at any time
  374. by pressing the Esc key. When this happens, sokol_app.h behaves
  375. the same as if sapp_lock_mouse(false) is called.
  376. For things like camera manipulation it's most straightforward to lock
  377. and unlock the mouse right from the sokol_app.h event handler, for
  378. instance the following code enters and leaves mouse lock when the
  379. left mouse button is pressed and released, and then uses the relative
  380. movement information to manipulate a camera (taken from the
  381. cgltf-sapp.c sample in the sokol-samples repository
  382. at https://github.com/floooh/sokol-samples):
  383. static void input(const sapp_event* ev) {
  384. switch (ev->type) {
  385. case SAPP_EVENTTYPE_MOUSE_DOWN:
  386. if (ev->mouse_button == SAPP_MOUSEBUTTON_LEFT) {
  387. sapp_lock_mouse(true);
  388. }
  389. break;
  390. case SAPP_EVENTTYPE_MOUSE_UP:
  391. if (ev->mouse_button == SAPP_MOUSEBUTTON_LEFT) {
  392. sapp_lock_mouse(false);
  393. }
  394. break;
  395. case SAPP_EVENTTYPE_MOUSE_MOVE:
  396. if (sapp_mouse_locked()) {
  397. cam_orbit(&state.camera, ev->mouse_dx * 0.25f, ev->mouse_dy * 0.25f);
  398. }
  399. break;
  400. default:
  401. break;
  402. }
  403. }
  404. CLIPBOARD SUPPORT
  405. =================
  406. Applications can send and receive UTF-8 encoded text data from and to the
  407. system clipboard. By default, clipboard support is disabled and
  408. must be enabled at startup via the following sapp_desc struct
  409. members:
  410. sapp_desc.enable_clipboard - set to true to enable clipboard support
  411. sapp_desc.clipboard_size - size of the internal clipboard buffer in bytes
  412. Enabling the clipboard will dynamically allocate a clipboard buffer
  413. for UTF-8 encoded text data of the requested size in bytes, the default
  414. size is 8 KBytes. Strings that don't fit into the clipboard buffer
  415. (including the terminating zero) will be silently clipped, so it's
  416. important that you provide a big enough clipboard size for your
  417. use case.
  418. To send data to the clipboard, call sapp_set_clipboard_string() with
  419. a pointer to an UTF-8 encoded, null-terminated C-string.
  420. NOTE that on the HTML5 platform, sapp_set_clipboard_string() must be
  421. called from inside a 'short-lived event handler', and there are a few
  422. other HTML5-specific caveats to workaround. You'll basically have to
  423. tinker until it works in all browsers :/ (maybe the situation will
  424. improve when all browsers agree on and implement the new
  425. HTML5 navigator.clipboard API).
  426. To get data from the clipboard, check for the SAPP_EVENTTYPE_CLIPBOARD_PASTED
  427. event in your event handler function, and then call sapp_get_clipboard_string()
  428. to obtain the pasted UTF-8 encoded text.
  429. NOTE that behaviour of sapp_get_clipboard_string() is slightly different
  430. depending on platform:
  431. - on the HTML5 platform, the internal clipboard buffer will only be updated
  432. right before the SAPP_EVENTTYPE_CLIPBOARD_PASTED event is sent,
  433. and sapp_get_clipboard_string() will simply return the current content
  434. of the clipboard buffer
  435. - on 'native' platforms, the call to sapp_get_clipboard_string() will
  436. update the internal clipboard buffer with the most recent data
  437. from the system clipboard
  438. Portable code should check for the SAPP_EVENTTYPE_CLIPBOARD_PASTED event,
  439. and then call sapp_get_clipboard_string() right in the event handler.
  440. The SAPP_EVENTTYPE_CLIPBOARD_PASTED event will be generated by sokol-app
  441. as follows:
  442. - on macOS: when the Cmd+V key is pressed down
  443. - on HTML5: when the browser sends a 'paste' event to the global 'window' object
  444. - on all other platforms: when the Ctrl+V key is pressed down
  445. DRAG AND DROP SUPPORT
  446. =====================
  447. PLEASE NOTE: the drag'n'drop feature works differently on WASM/HTML5
  448. and on the native desktop platforms (Win32, Linux and macOS) because
  449. of security-related restrictions in the HTML5 drag'n'drop API. The
  450. WASM/HTML5 specifics are described at the end of this documentation
  451. section:
  452. Like clipboard support, drag'n'drop support must be explicitly enabled
  453. at startup in the sapp_desc struct.
  454. sapp_desc sokol_main(void) {
  455. return (sapp_desc) {
  456. .enable_dragndrop = true, // default is false
  457. ...
  458. };
  459. }
  460. You can also adjust the maximum number of files that are accepted
  461. in a drop operation, and the maximum path length in bytes if needed:
  462. sapp_desc sokol_main(void) {
  463. return (sapp_desc) {
  464. .enable_dragndrop = true, // default is false
  465. .max_dropped_files = 8, // default is 1
  466. .max_dropped_file_path_length = 8192, // in bytes, default is 2048
  467. ...
  468. };
  469. }
  470. When drag'n'drop is enabled, the event callback will be invoked with an
  471. event of type SAPP_EVENTTYPE_FILES_DROPPED whenever the user drops files on
  472. the application window.
  473. After the SAPP_EVENTTYPE_FILES_DROPPED is received, you can query the
  474. number of dropped files, and their absolute paths by calling separate
  475. functions:
  476. void on_event(const sapp_event* ev) {
  477. if (ev->type == SAPP_EVENTTYPE_FILES_DROPPED) {
  478. // the mouse position where the drop happened
  479. float x = ev->mouse_x;
  480. float y = ev->mouse_y;
  481. // get the number of files and their paths like this:
  482. const int num_dropped_files = sapp_get_num_dropped_files();
  483. for (int i = 0; i < num_dropped_files; i++) {
  484. const char* path = sapp_get_dropped_file_path(i);
  485. ...
  486. }
  487. }
  488. }
  489. The returned file paths are UTF-8 encoded strings.
  490. You can call sapp_get_num_dropped_files() and sapp_get_dropped_file_path()
  491. anywhere, also outside the event handler callback, but be aware that the
  492. file path strings will be overwritten with the next drop operation.
  493. In any case, sapp_get_dropped_file_path() will never return a null pointer,
  494. instead an empty string "" will be returned if the drag'n'drop feature
  495. hasn't been enabled, the last drop-operation failed, or the file path index
  496. is out of range.
  497. Drag'n'drop caveats:
  498. - if more files are dropped in a single drop-action
  499. than sapp_desc.max_dropped_files, the additional
  500. files will be silently ignored
  501. - if any of the file paths is longer than
  502. sapp_desc.max_dropped_file_path_length (in number of bytes, after UTF-8
  503. encoding) the entire drop operation will be silently ignored (this
  504. needs some sort of error feedback in the future)
  505. - no mouse positions are reported while the drag is in
  506. process, this may change in the future
  507. Drag'n'drop on HTML5/WASM:
  508. The HTML5 drag'n'drop API doesn't return file paths, but instead
  509. black-box 'file objects' which must be used to load the content
  510. of dropped files. This is the reason why sokol_app.h adds two
  511. HTML5-specific functions to the drag'n'drop API:
  512. uint32_t sapp_html5_get_dropped_file_size(int index)
  513. Returns the size in bytes of a dropped file.
  514. void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request)
  515. Asynchronously loads the content of a dropped file into a
  516. provided memory buffer (which must be big enough to hold
  517. the file content)
  518. To start loading the first dropped file after an SAPP_EVENTTYPE_FILES_DROPPED
  519. event is received:
  520. sapp_html5_fetch_dropped_file(&(sapp_html5_fetch_request){
  521. .dropped_file_index = 0,
  522. .callback = fetch_cb
  523. .buffer = {
  524. .ptr = buf,
  525. .size = sizeof(buf)
  526. },
  527. .user_data = ...
  528. });
  529. Make sure that the memory pointed to by 'buf' stays valid until the
  530. callback function is called!
  531. As result of the asynchronous loading operation (no matter if succeeded or
  532. failed) the 'fetch_cb' function will be called:
  533. void fetch_cb(const sapp_html5_fetch_response* response) {
  534. // IMPORTANT: check if the loading operation actually succeeded:
  535. if (response->succeeded) {
  536. // the size of the loaded file:
  537. const size_t num_bytes = response->data.size;
  538. // and the pointer to the data (same as 'buf' in the fetch-call):
  539. const void* ptr = response->data.ptr;
  540. }
  541. else {
  542. // on error check the error code:
  543. switch (response->error_code) {
  544. case SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL:
  545. ...
  546. break;
  547. case SAPP_HTML5_FETCH_ERROR_OTHER:
  548. ...
  549. break;
  550. }
  551. }
  552. }
  553. Check the droptest-sapp example for a real-world example which works
  554. both on native platforms and the web:
  555. https://github.com/floooh/sokol-samples/blob/master/sapp/droptest-sapp.c
  556. HIGH-DPI RENDERING
  557. ==================
  558. You can set the sapp_desc.high_dpi flag during initialization to request
  559. a full-resolution framebuffer on HighDPI displays. The default behaviour
  560. is sapp_desc.high_dpi=false, this means that the application will
  561. render to a lower-resolution framebuffer on HighDPI displays and the
  562. rendered content will be upscaled by the window system composer.
  563. In a HighDPI scenario, you still request the same window size during
  564. sokol_main(), but the framebuffer sizes returned by sapp_width()
  565. and sapp_height() will be scaled up according to the DPI scaling
  566. ratio.
  567. Note that on some platforms the DPI scaling factor may change at any
  568. time (for instance when a window is moved from a high-dpi display
  569. to a low-dpi display).
  570. To query the current DPI scaling factor, call the function:
  571. float sapp_dpi_scale(void);
  572. For instance on a Retina Mac, returning the following sapp_desc
  573. struct from sokol_main():
  574. sapp_desc sokol_main(void) {
  575. return (sapp_desc) {
  576. .width = 640,
  577. .height = 480,
  578. .high_dpi = true,
  579. ...
  580. };
  581. }
  582. ...the functions the functions sapp_width(), sapp_height()
  583. and sapp_dpi_scale() will return the following values:
  584. sapp_width: 1280
  585. sapp_height: 960
  586. sapp_dpi_scale: 2.0
  587. If the high_dpi flag is false, or you're not running on a Retina display,
  588. the values would be:
  589. sapp_width: 640
  590. sapp_height: 480
  591. sapp_dpi_scale: 1.0
  592. If the window is moved from the Retina display to a low-dpi external display,
  593. the values would change as follows:
  594. sapp_width: 1280 => 640
  595. sapp_height: 960 => 480
  596. sapp_dpi_scale: 2.0 => 1.0
  597. Currently there is no event associated with a DPI change, but an
  598. SAPP_EVENTTYPE_RESIZED will be sent as a side effect of the
  599. framebuffer size changing.
  600. Per-monitor DPI is currently supported on macOS and Windows.
  601. APPLICATION QUIT
  602. ================
  603. Without special quit handling, a sokol_app.h application will quit
  604. 'gracefully' when the user clicks the window close-button unless a
  605. platform's application model prevents this (e.g. on web or mobile).
  606. 'Graceful exit' means that the application-provided cleanup callback will
  607. be called before the application quits.
  608. On native desktop platforms sokol_app.h provides more control over the
  609. application-quit-process. It's possible to initiate a 'programmatic quit'
  610. from the application code, and a quit initiated by the application user can
  611. be intercepted (for instance to show a custom dialog box).
  612. This 'programmatic quit protocol' is implemented through 3 functions
  613. and 1 event:
  614. - sapp_quit(): This function simply quits the application without
  615. giving the user a chance to intervene. Usually this might
  616. be called when the user clicks the 'Ok' button in a 'Really Quit?'
  617. dialog box
  618. - sapp_request_quit(): Calling sapp_request_quit() will send the
  619. event SAPP_EVENTTYPE_QUIT_REQUESTED to the applications event handler
  620. callback, giving the user code a chance to intervene and cancel the
  621. pending quit process (for instance to show a 'Really Quit?' dialog
  622. box). If the event handler callback does nothing, the application
  623. will be quit as usual. To prevent this, call the function
  624. sapp_cancel_quit() from inside the event handler.
  625. - sapp_cancel_quit(): Cancels a pending quit request, either initiated
  626. by the user clicking the window close button, or programmatically
  627. by calling sapp_request_quit(). The only place where calling this
  628. function makes sense is from inside the event handler callback when
  629. the SAPP_EVENTTYPE_QUIT_REQUESTED event has been received.
  630. - SAPP_EVENTTYPE_QUIT_REQUESTED: this event is sent when the user
  631. clicks the window's close button or application code calls the
  632. sapp_request_quit() function. The event handler callback code can handle
  633. this event by calling sapp_cancel_quit() to cancel the quit.
  634. If the event is ignored, the application will quit as usual.
  635. On the web platform, the quit behaviour differs from native platforms,
  636. because of web-specific restrictions:
  637. A `programmatic quit` initiated by calling sapp_quit() or
  638. sapp_request_quit() will work as described above: the cleanup callback is
  639. called, platform-specific cleanup is performed (on the web
  640. this means that JS event handlers are unregistered), and then
  641. the request-animation-loop will be exited. However that's all. The
  642. web page itself will continue to exist (e.g. it's not possible to
  643. programmatically close the browser tab).
  644. On the web it's also not possible to run custom code when the user
  645. closes a browser tab, so it's not possible to prevent this with a
  646. fancy custom dialog box.
  647. Instead the standard "Leave Site?" dialog box can be activated (or
  648. deactivated) with the following function:
  649. sapp_html5_ask_leave_site(bool ask);
  650. The initial state of the associated internal flag can be provided
  651. at startup via sapp_desc.html5_ask_leave_site.
  652. This feature should only be used sparingly in critical situations - for
  653. instance when the user would loose data - since popping up modal dialog
  654. boxes is considered quite rude in the web world. Note that there's no way
  655. to customize the content of this dialog box or run any code as a result
  656. of the user's decision. Also note that the user must have interacted with
  657. the site before the dialog box will appear. These are all security measures
  658. to prevent fishing.
  659. The Dear ImGui HighDPI sample contains example code of how to
  660. implement a 'Really Quit?' dialog box with Dear ImGui (native desktop
  661. platforms only), and for showing the hardwired "Leave Site?" dialog box
  662. when running on the web platform:
  663. https://floooh.github.io/sokol-html5/wasm/imgui-highdpi-sapp.html
  664. FULLSCREEN
  665. ==========
  666. If the sapp_desc.fullscreen flag is true, sokol-app will try to create
  667. a fullscreen window on platforms with a 'proper' window system
  668. (mobile devices will always use fullscreen). The implementation details
  669. depend on the target platform, in general sokol-app will use a
  670. 'soft approach' which doesn't interfere too much with the platform's
  671. window system (for instance borderless fullscreen window instead of
  672. a 'real' fullscreen mode). Such details might change over time
  673. as sokol-app is adapted for different needs.
  674. The most important effect of fullscreen mode to keep in mind is that
  675. the requested canvas width and height will be ignored for the initial
  676. window size, calling sapp_width() and sapp_height() will instead return
  677. the resolution of the fullscreen canvas (however the provided size
  678. might still be used for the non-fullscreen window, in case the user can
  679. switch back from fullscreen- to windowed-mode).
  680. To toggle fullscreen mode programmatically, call sapp_toggle_fullscreen().
  681. To check if the application window is currently in fullscreen mode,
  682. call sapp_is_fullscreen().
  683. WINDOW ICON SUPPORT
  684. ===================
  685. Some sokol_app.h backends allow to change the window icon programmatically:
  686. - on Win32: the small icon in the window's title bar, and the
  687. bigger icon in the task bar
  688. - on Linux: highly dependent on the used window manager, but usually
  689. the window's title bar icon and/or the task bar icon
  690. - on HTML5: the favicon shown in the page's browser tab
  691. - on macOS: the application icon shown in the dock, but only
  692. for currently running applications
  693. NOTE that it is not possible to set the actual application icon which is
  694. displayed by the operating system on the desktop or 'home screen'. Those
  695. icons must be provided 'traditionally' through operating-system-specific
  696. resources which are associated with the application (sokol_app.h might
  697. later support setting the window icon from platform specific resource data
  698. though).
  699. There are two ways to set the window icon:
  700. - at application start in the sokol_main() function by initializing
  701. the sapp_desc.icon nested struct
  702. - or later by calling the function sapp_set_icon()
  703. As a convenient shortcut, sokol_app.h comes with a builtin default-icon
  704. (a rainbow-colored 'S', which at least looks a bit better than the Windows
  705. default icon for applications), which can be activated like this:
  706. At startup in sokol_main():
  707. sapp_desc sokol_main(...) {
  708. return (sapp_desc){
  709. ...
  710. icon.sokol_default = true
  711. };
  712. }
  713. Or later by calling:
  714. sapp_set_icon(&(sapp_icon_desc){ .sokol_default = true });
  715. NOTE that a completely zero-initialized sapp_icon_desc struct will not
  716. update the window icon in any way. This is an 'escape hatch' so that you
  717. can handle the window icon update yourself (or if you do this already,
  718. sokol_app.h won't get in your way, in this case just leave the
  719. sapp_desc.icon struct zero-initialized).
  720. Providing your own icon images works exactly like in GLFW (down to the
  721. data format):
  722. You provide one or more 'candidate images' in different sizes, and the
  723. sokol_app.h platform backends pick the best match for the specific backend
  724. and icon type.
  725. For each candidate image, you need to provide:
  726. - the width in pixels
  727. - the height in pixels
  728. - and the actual pixel data in RGBA8 pixel format (e.g. 0xFFCC8844
  729. on a little-endian CPU means: alpha=0xFF, blue=0xCC, green=0x88, red=0x44)
  730. For instance, if you have 3 candidate images (small, medium, big) of
  731. sizes 16x16, 32x32 and 64x64 the corresponding sapp_icon_desc struct is setup
  732. like this:
  733. // the actual pixel data (RGBA8, origin top-left)
  734. const uint32_t small[16][16] = { ... };
  735. const uint32_t medium[32][32] = { ... };
  736. const uint32_t big[64][64] = { ... };
  737. const sapp_icon_desc icon_desc = {
  738. .images = {
  739. { .width = 16, .height = 16, .pixels = SAPP_RANGE(small) },
  740. { .width = 32, .height = 32, .pixels = SAPP_RANGE(medium) },
  741. // ...or without the SAPP_RANGE helper macro:
  742. { .width = 64, .height = 64, .pixels = { .ptr=big, .size=sizeof(big) } }
  743. }
  744. };
  745. An sapp_icon_desc struct initialized like this can then either be applied
  746. at application start in sokol_main:
  747. sapp_desc sokol_main(...) {
  748. return (sapp_desc){
  749. ...
  750. icon = icon_desc
  751. };
  752. }
  753. ...or later by calling sapp_set_icon():
  754. sapp_set_icon(&icon_desc);
  755. Some window icon caveats:
  756. - once the window icon has been updated, there's no way to go back to
  757. the platform's default icon, this is because some platforms (Linux
  758. and HTML5) don't switch the icon visual back to the default even if
  759. the custom icon is deleted or removed
  760. - on HTML5, if the sokol_app.h icon doesn't show up in the browser
  761. tab, check that there's no traditional favicon 'link' element
  762. is defined in the page's index.html, sokol_app.h will only
  763. append a new favicon link element, but not delete any manually
  764. defined favicon in the page
  765. For an example and test of the window icon feature, check out the
  766. 'icon-sapp' sample on the sokol-samples git repository.
  767. ONSCREEN KEYBOARD
  768. =================
  769. On some platforms which don't provide a physical keyboard, sokol-app
  770. can display the platform's integrated onscreen keyboard for text
  771. input. To request that the onscreen keyboard is shown, call
  772. sapp_show_keyboard(true);
  773. Likewise, to hide the keyboard call:
  774. sapp_show_keyboard(false);
  775. Note that onscreen keyboard functionality is no longer supported
  776. on the browser platform (the previous hacks and workarounds to make browser
  777. keyboards work for on web applications that don't use HTML UIs
  778. never really worked across browsers).
  779. INPUT EVENT BUBBLING ON THE WEB PLATFORM
  780. ========================================
  781. By default, input event bubbling on the web platform is configured in
  782. a way that makes the most sense for 'full-canvas' apps that cover the
  783. entire browser client window area:
  784. - mouse, touch and wheel events do not bubble up, this prevents various
  785. ugly side events, like:
  786. - HTML text overlays being selected on double- or triple-click into
  787. the canvas
  788. - 'scroll bumping' even when the canvas covers the entire client area
  789. - key_up/down events for 'character keys' *do* bubble up (otherwise
  790. the browser will not generate UNICODE character events)
  791. - all other key events *do not* bubble up by default (this prevents side effects
  792. like F1 opening help, or F7 starting 'caret browsing')
  793. - character events do not bubble up (although I haven't noticed any side effects
  794. otherwise)
  795. Event bubbling can be enabled for input event categories during initialization
  796. in the sapp_desc struct:
  797. sapp_desc sokol_main(int argc, char* argv[]) {
  798. return (sapp_desc){
  799. //...
  800. .html5_bubble_mouse_events = true,
  801. .html5_bubble_touch_events = true,
  802. .html5_bubble_wheel_events = true,
  803. .html5_bubble_key_events = true,
  804. .html5_bubble_char_events = true,
  805. };
  806. }
  807. This basically opens the floodgates and lets *all* input events bubble up to the browser.
  808. To prevent individual events from bubbling, call sapp_consume_event() from within
  809. the sokol_app.h event callback when that specific event is reported.
  810. OPTIONAL: DON'T HIJACK main() (#define SOKOL_NO_ENTRY)
  811. ======================================================
  812. NOTE: SOKOL_NO_ENTRY and sapp_run() is currently not supported on Android.
  813. In its default configuration, sokol_app.h "hijacks" the platform's
  814. standard main() function. This was done because different platforms
  815. have different entry point conventions which are not compatible with
  816. C's main() (for instance WinMain on Windows has completely different
  817. arguments). However, this "main hijacking" posed a problem for
  818. usage scenarios like integrating sokol_app.h with other languages than
  819. C or C++, so an alternative SOKOL_NO_ENTRY mode has been added
  820. in which the user code provides the platform's main function:
  821. - define SOKOL_NO_ENTRY before including the sokol_app.h implementation
  822. - do *not* provide a sokol_main() function
  823. - instead provide the standard main() function of the platform
  824. - from the main function, call the function ```sapp_run()``` which
  825. takes a pointer to an ```sapp_desc``` structure.
  826. - from here on```sapp_run()``` takes over control and calls the provided
  827. init-, frame-, event- and cleanup-callbacks just like in the default model.
  828. sapp_run() behaves differently across platforms:
  829. - on some platforms, sapp_run() will return when the application quits
  830. - on other platforms, sapp_run() will never return, even when the
  831. application quits (the operating system is free to simply terminate
  832. the application at any time)
  833. - on Emscripten specifically, sapp_run() will return immediately while
  834. the frame callback keeps being called
  835. This different behaviour of sapp_run() essentially means that there shouldn't
  836. be any code *after* sapp_run(), because that may either never be called, or in
  837. case of Emscripten will be called at an unexpected time (at application start).
  838. An application also should not depend on the cleanup-callback being called
  839. when cross-platform compatibility is required.
  840. Since sapp_run() returns immediately on Emscripten you shouldn't activate
  841. the 'EXIT_RUNTIME' linker option (this is disabled by default when compiling
  842. for the browser target), since the C/C++ exit runtime would be called immediately at
  843. application start, causing any global objects to be destroyed and global
  844. variables to be zeroed.
  845. WINDOWS CONSOLE OUTPUT
  846. ======================
  847. On Windows, regular windowed applications don't show any stdout/stderr text
  848. output, which can be a bit of a hassle for printf() debugging or generally
  849. logging text to the console. Also, console output by default uses a local
  850. codepage setting and thus international UTF-8 encoded text is printed
  851. as garbage.
  852. To help with these issues, sokol_app.h can be configured at startup
  853. via the following Windows-specific sapp_desc flags:
  854. sapp_desc.win32_console_utf8 (default: false)
  855. When set to true, the output console codepage will be switched
  856. to UTF-8 (and restored to the original codepage on exit)
  857. sapp_desc.win32_console_attach (default: false)
  858. When set to true, stdout and stderr will be attached to the
  859. console of the parent process (if the parent process actually
  860. has a console). This means that if the application was started
  861. in a command line window, stdout and stderr output will be printed
  862. to the terminal, just like a regular command line program. But if
  863. the application is started via double-click, it will behave like
  864. a regular UI application, and stdout/stderr will not be visible.
  865. sapp_desc.win32_console_create (default: false)
  866. When set to true, a new console window will be created and
  867. stdout/stderr will be redirected to that console window. It
  868. doesn't matter if the application is started from the command
  869. line or via double-click.
  870. MEMORY ALLOCATION OVERRIDE
  871. ==========================
  872. You can override the memory allocation functions at initialization time
  873. like this:
  874. void* my_alloc(size_t size, void* user_data) {
  875. return malloc(size);
  876. }
  877. void my_free(void* ptr, void* user_data) {
  878. free(ptr);
  879. }
  880. sapp_desc sokol_main(int argc, char* argv[]) {
  881. return (sapp_desc){
  882. // ...
  883. .allocator = {
  884. .alloc_fn = my_alloc,
  885. .free_fn = my_free,
  886. .user_data = ...,
  887. }
  888. };
  889. }
  890. If no overrides are provided, malloc and free will be used.
  891. This only affects memory allocation calls done by sokol_app.h
  892. itself though, not any allocations in OS libraries.
  893. ERROR REPORTING AND LOGGING
  894. ===========================
  895. To get any logging information at all you need to provide a logging callback in the setup call
  896. the easiest way is to use sokol_log.h:
  897. #include "sokol_log.h"
  898. sapp_desc sokol_main(int argc, char* argv[]) {
  899. return (sapp_desc) {
  900. ...
  901. .logger.func = slog_func,
  902. };
  903. }
  904. To override logging with your own callback, first write a logging function like this:
  905. void my_log(const char* tag, // e.g. 'sapp'
  906. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  907. uint32_t log_item_id, // SAPP_LOGITEM_*
  908. const char* message_or_null, // a message string, may be nullptr in release mode
  909. uint32_t line_nr, // line number in sokol_app.h
  910. const char* filename_or_null, // source filename, may be nullptr in release mode
  911. void* user_data)
  912. {
  913. ...
  914. }
  915. ...and then setup sokol-app like this:
  916. sapp_desc sokol_main(int argc, char* argv[]) {
  917. return (sapp_desc) {
  918. ...
  919. .logger = {
  920. .func = my_log,
  921. .user_data = my_user_data,
  922. }
  923. };
  924. }
  925. The provided logging function must be reentrant (e.g. be callable from
  926. different threads).
  927. If you don't want to provide your own custom logger it is highly recommended to use
  928. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  929. errors.
  930. TEMP NOTE DUMP
  931. ==============
  932. - sapp_desc needs a bool whether to initialize depth-stencil surface
  933. - the Android implementation calls cleanup_cb() and destroys the egl context in onDestroy
  934. at the latest but should do it earlier, in onStop, as an app is "killable" after onStop
  935. on Android Honeycomb and later (it can't be done at the moment as the app may be started
  936. again after onStop and the sokol lifecycle does not yet handle context teardown/bringup)
  937. LICENSE
  938. =======
  939. zlib/libpng license
  940. Copyright (c) 2018 Andre Weissflog
  941. This software is provided 'as-is', without any express or implied warranty.
  942. In no event will the authors be held liable for any damages arising from the
  943. use of this software.
  944. Permission is granted to anyone to use this software for any purpose,
  945. including commercial applications, and to alter it and redistribute it
  946. freely, subject to the following restrictions:
  947. 1. The origin of this software must not be misrepresented; you must not
  948. claim that you wrote the original software. If you use this software in a
  949. product, an acknowledgment in the product documentation would be
  950. appreciated but is not required.
  951. 2. Altered source versions must be plainly marked as such, and must not
  952. be misrepresented as being the original software.
  953. 3. This notice may not be removed or altered from any source
  954. distribution.
  955. */
  956. #define SOKOL_APP_INCLUDED (1)
  957. #include <stddef.h> // size_t
  958. #include <stdint.h>
  959. #include <stdbool.h>
  960. #if defined(SOKOL_API_DECL) && !defined(SOKOL_APP_API_DECL)
  961. #define SOKOL_APP_API_DECL SOKOL_API_DECL
  962. #endif
  963. #ifndef SOKOL_APP_API_DECL
  964. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_APP_IMPL)
  965. #define SOKOL_APP_API_DECL __declspec(dllexport)
  966. #elif defined(_WIN32) && defined(SOKOL_DLL)
  967. #define SOKOL_APP_API_DECL __declspec(dllimport)
  968. #else
  969. #define SOKOL_APP_API_DECL extern
  970. #endif
  971. #endif
  972. #ifdef __cplusplus
  973. extern "C" {
  974. #endif
  975. /* misc constants */
  976. enum {
  977. SAPP_MAX_TOUCHPOINTS = 8,
  978. SAPP_MAX_MOUSEBUTTONS = 3,
  979. SAPP_MAX_KEYCODES = 512,
  980. SAPP_MAX_ICONIMAGES = 8,
  981. };
  982. /*
  983. sapp_event_type
  984. The type of event that's passed to the event handler callback
  985. in the sapp_event.type field. These are not just "traditional"
  986. input events, but also notify the application about state changes
  987. or other user-invoked actions.
  988. */
  989. typedef enum sapp_event_type {
  990. SAPP_EVENTTYPE_INVALID,
  991. SAPP_EVENTTYPE_KEY_DOWN,
  992. SAPP_EVENTTYPE_KEY_UP,
  993. SAPP_EVENTTYPE_CHAR,
  994. SAPP_EVENTTYPE_MOUSE_DOWN,
  995. SAPP_EVENTTYPE_MOUSE_UP,
  996. SAPP_EVENTTYPE_MOUSE_SCROLL,
  997. SAPP_EVENTTYPE_MOUSE_MOVE,
  998. SAPP_EVENTTYPE_MOUSE_ENTER,
  999. SAPP_EVENTTYPE_MOUSE_LEAVE,
  1000. SAPP_EVENTTYPE_TOUCHES_BEGAN,
  1001. SAPP_EVENTTYPE_TOUCHES_MOVED,
  1002. SAPP_EVENTTYPE_TOUCHES_ENDED,
  1003. SAPP_EVENTTYPE_TOUCHES_CANCELLED,
  1004. SAPP_EVENTTYPE_RESIZED,
  1005. SAPP_EVENTTYPE_ICONIFIED,
  1006. SAPP_EVENTTYPE_RESTORED,
  1007. SAPP_EVENTTYPE_FOCUSED,
  1008. SAPP_EVENTTYPE_UNFOCUSED,
  1009. SAPP_EVENTTYPE_SUSPENDED,
  1010. SAPP_EVENTTYPE_RESUMED,
  1011. SAPP_EVENTTYPE_QUIT_REQUESTED,
  1012. SAPP_EVENTTYPE_CLIPBOARD_PASTED,
  1013. SAPP_EVENTTYPE_FILES_DROPPED,
  1014. _SAPP_EVENTTYPE_NUM,
  1015. _SAPP_EVENTTYPE_FORCE_U32 = 0x7FFFFFFF
  1016. } sapp_event_type;
  1017. /*
  1018. sapp_keycode
  1019. The 'virtual keycode' of a KEY_DOWN or KEY_UP event in the
  1020. struct field sapp_event.key_code.
  1021. Note that the keycode values are identical with GLFW.
  1022. */
  1023. typedef enum sapp_keycode {
  1024. SAPP_KEYCODE_INVALID = 0,
  1025. SAPP_KEYCODE_SPACE = 32,
  1026. SAPP_KEYCODE_APOSTROPHE = 39, /* ' */
  1027. SAPP_KEYCODE_COMMA = 44, /* , */
  1028. SAPP_KEYCODE_MINUS = 45, /* - */
  1029. SAPP_KEYCODE_PERIOD = 46, /* . */
  1030. SAPP_KEYCODE_SLASH = 47, /* / */
  1031. SAPP_KEYCODE_0 = 48,
  1032. SAPP_KEYCODE_1 = 49,
  1033. SAPP_KEYCODE_2 = 50,
  1034. SAPP_KEYCODE_3 = 51,
  1035. SAPP_KEYCODE_4 = 52,
  1036. SAPP_KEYCODE_5 = 53,
  1037. SAPP_KEYCODE_6 = 54,
  1038. SAPP_KEYCODE_7 = 55,
  1039. SAPP_KEYCODE_8 = 56,
  1040. SAPP_KEYCODE_9 = 57,
  1041. SAPP_KEYCODE_SEMICOLON = 59, /* ; */
  1042. SAPP_KEYCODE_EQUAL = 61, /* = */
  1043. SAPP_KEYCODE_A = 65,
  1044. SAPP_KEYCODE_B = 66,
  1045. SAPP_KEYCODE_C = 67,
  1046. SAPP_KEYCODE_D = 68,
  1047. SAPP_KEYCODE_E = 69,
  1048. SAPP_KEYCODE_F = 70,
  1049. SAPP_KEYCODE_G = 71,
  1050. SAPP_KEYCODE_H = 72,
  1051. SAPP_KEYCODE_I = 73,
  1052. SAPP_KEYCODE_J = 74,
  1053. SAPP_KEYCODE_K = 75,
  1054. SAPP_KEYCODE_L = 76,
  1055. SAPP_KEYCODE_M = 77,
  1056. SAPP_KEYCODE_N = 78,
  1057. SAPP_KEYCODE_O = 79,
  1058. SAPP_KEYCODE_P = 80,
  1059. SAPP_KEYCODE_Q = 81,
  1060. SAPP_KEYCODE_R = 82,
  1061. SAPP_KEYCODE_S = 83,
  1062. SAPP_KEYCODE_T = 84,
  1063. SAPP_KEYCODE_U = 85,
  1064. SAPP_KEYCODE_V = 86,
  1065. SAPP_KEYCODE_W = 87,
  1066. SAPP_KEYCODE_X = 88,
  1067. SAPP_KEYCODE_Y = 89,
  1068. SAPP_KEYCODE_Z = 90,
  1069. SAPP_KEYCODE_LEFT_BRACKET = 91, /* [ */
  1070. SAPP_KEYCODE_BACKSLASH = 92, /* \ */
  1071. SAPP_KEYCODE_RIGHT_BRACKET = 93, /* ] */
  1072. SAPP_KEYCODE_GRAVE_ACCENT = 96, /* ` */
  1073. SAPP_KEYCODE_WORLD_1 = 161, /* non-US #1 */
  1074. SAPP_KEYCODE_WORLD_2 = 162, /* non-US #2 */
  1075. SAPP_KEYCODE_ESCAPE = 256,
  1076. SAPP_KEYCODE_ENTER = 257,
  1077. SAPP_KEYCODE_TAB = 258,
  1078. SAPP_KEYCODE_BACKSPACE = 259,
  1079. SAPP_KEYCODE_INSERT = 260,
  1080. SAPP_KEYCODE_DELETE = 261,
  1081. SAPP_KEYCODE_RIGHT = 262,
  1082. SAPP_KEYCODE_LEFT = 263,
  1083. SAPP_KEYCODE_DOWN = 264,
  1084. SAPP_KEYCODE_UP = 265,
  1085. SAPP_KEYCODE_PAGE_UP = 266,
  1086. SAPP_KEYCODE_PAGE_DOWN = 267,
  1087. SAPP_KEYCODE_HOME = 268,
  1088. SAPP_KEYCODE_END = 269,
  1089. SAPP_KEYCODE_CAPS_LOCK = 280,
  1090. SAPP_KEYCODE_SCROLL_LOCK = 281,
  1091. SAPP_KEYCODE_NUM_LOCK = 282,
  1092. SAPP_KEYCODE_PRINT_SCREEN = 283,
  1093. SAPP_KEYCODE_PAUSE = 284,
  1094. SAPP_KEYCODE_F1 = 290,
  1095. SAPP_KEYCODE_F2 = 291,
  1096. SAPP_KEYCODE_F3 = 292,
  1097. SAPP_KEYCODE_F4 = 293,
  1098. SAPP_KEYCODE_F5 = 294,
  1099. SAPP_KEYCODE_F6 = 295,
  1100. SAPP_KEYCODE_F7 = 296,
  1101. SAPP_KEYCODE_F8 = 297,
  1102. SAPP_KEYCODE_F9 = 298,
  1103. SAPP_KEYCODE_F10 = 299,
  1104. SAPP_KEYCODE_F11 = 300,
  1105. SAPP_KEYCODE_F12 = 301,
  1106. SAPP_KEYCODE_F13 = 302,
  1107. SAPP_KEYCODE_F14 = 303,
  1108. SAPP_KEYCODE_F15 = 304,
  1109. SAPP_KEYCODE_F16 = 305,
  1110. SAPP_KEYCODE_F17 = 306,
  1111. SAPP_KEYCODE_F18 = 307,
  1112. SAPP_KEYCODE_F19 = 308,
  1113. SAPP_KEYCODE_F20 = 309,
  1114. SAPP_KEYCODE_F21 = 310,
  1115. SAPP_KEYCODE_F22 = 311,
  1116. SAPP_KEYCODE_F23 = 312,
  1117. SAPP_KEYCODE_F24 = 313,
  1118. SAPP_KEYCODE_F25 = 314,
  1119. SAPP_KEYCODE_KP_0 = 320,
  1120. SAPP_KEYCODE_KP_1 = 321,
  1121. SAPP_KEYCODE_KP_2 = 322,
  1122. SAPP_KEYCODE_KP_3 = 323,
  1123. SAPP_KEYCODE_KP_4 = 324,
  1124. SAPP_KEYCODE_KP_5 = 325,
  1125. SAPP_KEYCODE_KP_6 = 326,
  1126. SAPP_KEYCODE_KP_7 = 327,
  1127. SAPP_KEYCODE_KP_8 = 328,
  1128. SAPP_KEYCODE_KP_9 = 329,
  1129. SAPP_KEYCODE_KP_DECIMAL = 330,
  1130. SAPP_KEYCODE_KP_DIVIDE = 331,
  1131. SAPP_KEYCODE_KP_MULTIPLY = 332,
  1132. SAPP_KEYCODE_KP_SUBTRACT = 333,
  1133. SAPP_KEYCODE_KP_ADD = 334,
  1134. SAPP_KEYCODE_KP_ENTER = 335,
  1135. SAPP_KEYCODE_KP_EQUAL = 336,
  1136. SAPP_KEYCODE_LEFT_SHIFT = 340,
  1137. SAPP_KEYCODE_LEFT_CONTROL = 341,
  1138. SAPP_KEYCODE_LEFT_ALT = 342,
  1139. SAPP_KEYCODE_LEFT_SUPER = 343,
  1140. SAPP_KEYCODE_RIGHT_SHIFT = 344,
  1141. SAPP_KEYCODE_RIGHT_CONTROL = 345,
  1142. SAPP_KEYCODE_RIGHT_ALT = 346,
  1143. SAPP_KEYCODE_RIGHT_SUPER = 347,
  1144. SAPP_KEYCODE_MENU = 348,
  1145. } sapp_keycode;
  1146. /*
  1147. Android specific 'tool type' enum for touch events. This lets the
  1148. application check what type of input device was used for
  1149. touch events.
  1150. NOTE: the values must remain in sync with the corresponding
  1151. Android SDK type, so don't change those.
  1152. See https://developer.android.com/reference/android/view/MotionEvent#TOOL_TYPE_UNKNOWN
  1153. */
  1154. typedef enum sapp_android_tooltype {
  1155. SAPP_ANDROIDTOOLTYPE_UNKNOWN = 0, // TOOL_TYPE_UNKNOWN
  1156. SAPP_ANDROIDTOOLTYPE_FINGER = 1, // TOOL_TYPE_FINGER
  1157. SAPP_ANDROIDTOOLTYPE_STYLUS = 2, // TOOL_TYPE_STYLUS
  1158. SAPP_ANDROIDTOOLTYPE_MOUSE = 3, // TOOL_TYPE_MOUSE
  1159. } sapp_android_tooltype;
  1160. /*
  1161. sapp_touchpoint
  1162. Describes a single touchpoint in a multitouch event (TOUCHES_BEGAN,
  1163. TOUCHES_MOVED, TOUCHES_ENDED).
  1164. Touch points are stored in the nested array sapp_event.touches[],
  1165. and the number of touches is stored in sapp_event.num_touches.
  1166. */
  1167. typedef struct sapp_touchpoint {
  1168. uintptr_t identifier;
  1169. float pos_x;
  1170. float pos_y;
  1171. sapp_android_tooltype android_tooltype; // only valid on Android
  1172. bool changed;
  1173. } sapp_touchpoint;
  1174. /*
  1175. sapp_mousebutton
  1176. The currently pressed mouse button in the events MOUSE_DOWN
  1177. and MOUSE_UP, stored in the struct field sapp_event.mouse_button.
  1178. */
  1179. typedef enum sapp_mousebutton {
  1180. SAPP_MOUSEBUTTON_LEFT = 0x0,
  1181. SAPP_MOUSEBUTTON_RIGHT = 0x1,
  1182. SAPP_MOUSEBUTTON_MIDDLE = 0x2,
  1183. SAPP_MOUSEBUTTON_INVALID = 0x100,
  1184. } sapp_mousebutton;
  1185. /*
  1186. These are currently pressed modifier keys (and mouse buttons) which are
  1187. passed in the event struct field sapp_event.modifiers.
  1188. */
  1189. enum {
  1190. SAPP_MODIFIER_SHIFT = 0x1, // left or right shift key
  1191. SAPP_MODIFIER_CTRL = 0x2, // left or right control key
  1192. SAPP_MODIFIER_ALT = 0x4, // left or right alt key
  1193. SAPP_MODIFIER_SUPER = 0x8, // left or right 'super' key
  1194. SAPP_MODIFIER_LMB = 0x100, // left mouse button
  1195. SAPP_MODIFIER_RMB = 0x200, // right mouse button
  1196. SAPP_MODIFIER_MMB = 0x400, // middle mouse button
  1197. };
  1198. /*
  1199. sapp_event
  1200. This is an all-in-one event struct passed to the event handler
  1201. user callback function. Note that it depends on the event
  1202. type what struct fields actually contain useful values, so you
  1203. should first check the event type before reading other struct
  1204. fields.
  1205. */
  1206. typedef struct sapp_event {
  1207. uint64_t frame_count; // current frame counter, always valid, useful for checking if two events were issued in the same frame
  1208. sapp_event_type type; // the event type, always valid
  1209. sapp_keycode key_code; // the virtual key code, only valid in KEY_UP, KEY_DOWN
  1210. uint32_t char_code; // the UTF-32 character code, only valid in CHAR events
  1211. bool key_repeat; // true if this is a key-repeat event, valid in KEY_UP, KEY_DOWN and CHAR
  1212. uint32_t modifiers; // current modifier keys, valid in all key-, char- and mouse-events
  1213. sapp_mousebutton mouse_button; // mouse button that was pressed or released, valid in MOUSE_DOWN, MOUSE_UP
  1214. float mouse_x; // current horizontal mouse position in pixels, always valid except during mouse lock
  1215. float mouse_y; // current vertical mouse position in pixels, always valid except during mouse lock
  1216. float mouse_dx; // relative horizontal mouse movement since last frame, always valid
  1217. float mouse_dy; // relative vertical mouse movement since last frame, always valid
  1218. float scroll_x; // horizontal mouse wheel scroll distance, valid in MOUSE_SCROLL events
  1219. float scroll_y; // vertical mouse wheel scroll distance, valid in MOUSE_SCROLL events
  1220. int num_touches; // number of valid items in the touches[] array
  1221. sapp_touchpoint touches[SAPP_MAX_TOUCHPOINTS]; // current touch points, valid in TOUCHES_BEGIN, TOUCHES_MOVED, TOUCHES_ENDED
  1222. int window_width; // current window- and framebuffer sizes in pixels, always valid
  1223. int window_height;
  1224. int framebuffer_width; // = window_width * dpi_scale
  1225. int framebuffer_height; // = window_height * dpi_scale
  1226. } sapp_event;
  1227. /*
  1228. sg_range
  1229. A general pointer/size-pair struct and constructor macros for passing binary blobs
  1230. into sokol_app.h.
  1231. */
  1232. typedef struct sapp_range {
  1233. const void* ptr;
  1234. size_t size;
  1235. } sapp_range;
  1236. // disabling this for every includer isn't great, but the warnings are also quite pointless
  1237. #if defined(_MSC_VER)
  1238. #pragma warning(disable:4221) /* /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y' */
  1239. #pragma warning(disable:4204) /* VS2015: nonstandard extension used: non-constant aggregate initializer */
  1240. #endif
  1241. #if defined(__cplusplus)
  1242. #define SAPP_RANGE(x) sapp_range{ &x, sizeof(x) }
  1243. #else
  1244. #define SAPP_RANGE(x) (sapp_range){ &x, sizeof(x) }
  1245. #endif
  1246. /*
  1247. sapp_image_desc
  1248. This is used to describe image data to sokol_app.h (at first, window
  1249. icons, later maybe cursor images).
  1250. Note that the actual image pixel format depends on the use case:
  1251. - window icon pixels are RGBA8
  1252. */
  1253. typedef struct sapp_image_desc {
  1254. int width;
  1255. int height;
  1256. sapp_range pixels;
  1257. } sapp_image_desc;
  1258. /*
  1259. sapp_icon_desc
  1260. An icon description structure for use in sapp_desc.icon and
  1261. sapp_set_icon().
  1262. When setting a custom image, the application can provide a number of
  1263. candidates differing in size, and sokol_app.h will pick the image(s)
  1264. closest to the size expected by the platform's window system.
  1265. To set sokol-app's default icon, set .sokol_default to true.
  1266. Otherwise provide candidate images of different sizes in the
  1267. images[] array.
  1268. If both the sokol_default flag is set to true, any image candidates
  1269. will be ignored and the sokol_app.h default icon will be set.
  1270. */
  1271. typedef struct sapp_icon_desc {
  1272. bool sokol_default;
  1273. sapp_image_desc images[SAPP_MAX_ICONIMAGES];
  1274. } sapp_icon_desc;
  1275. /*
  1276. sapp_allocator
  1277. Used in sapp_desc to provide custom memory-alloc and -free functions
  1278. to sokol_app.h. If memory management should be overridden, both the
  1279. alloc_fn and free_fn function must be provided (e.g. it's not valid to
  1280. override one function but not the other).
  1281. */
  1282. typedef struct sapp_allocator {
  1283. void* (*alloc_fn)(size_t size, void* user_data);
  1284. void (*free_fn)(void* ptr, void* user_data);
  1285. void* user_data;
  1286. } sapp_allocator;
  1287. /*
  1288. sapp_log_item
  1289. Log items are defined via X-Macros and expanded to an enum
  1290. 'sapp_log_item', and in debug mode to corresponding
  1291. human readable error messages.
  1292. */
  1293. #define _SAPP_LOG_ITEMS \
  1294. _SAPP_LOGITEM_XMACRO(OK, "Ok") \
  1295. _SAPP_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  1296. _SAPP_LOGITEM_XMACRO(MACOS_INVALID_NSOPENGL_PROFILE, "macos: invalid NSOpenGLProfile (valid choices are 1.0 and 4.1)") \
  1297. _SAPP_LOGITEM_XMACRO(WIN32_LOAD_OPENGL32_DLL_FAILED, "failed loading opengl32.dll") \
  1298. _SAPP_LOGITEM_XMACRO(WIN32_CREATE_HELPER_WINDOW_FAILED, "failed to create helper window") \
  1299. _SAPP_LOGITEM_XMACRO(WIN32_HELPER_WINDOW_GETDC_FAILED, "failed to get helper window DC") \
  1300. _SAPP_LOGITEM_XMACRO(WIN32_DUMMY_CONTEXT_SET_PIXELFORMAT_FAILED, "failed to set pixel format for dummy GL context") \
  1301. _SAPP_LOGITEM_XMACRO(WIN32_CREATE_DUMMY_CONTEXT_FAILED, "failed to create dummy GL context") \
  1302. _SAPP_LOGITEM_XMACRO(WIN32_DUMMY_CONTEXT_MAKE_CURRENT_FAILED, "failed to make dummy GL context current") \
  1303. _SAPP_LOGITEM_XMACRO(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED, "failed to get WGL pixel format attribute") \
  1304. _SAPP_LOGITEM_XMACRO(WIN32_WGL_FIND_PIXELFORMAT_FAILED, "failed to find matching WGL pixel format") \
  1305. _SAPP_LOGITEM_XMACRO(WIN32_WGL_DESCRIBE_PIXELFORMAT_FAILED, "failed to get pixel format descriptor") \
  1306. _SAPP_LOGITEM_XMACRO(WIN32_WGL_SET_PIXELFORMAT_FAILED, "failed to set selected pixel format") \
  1307. _SAPP_LOGITEM_XMACRO(WIN32_WGL_ARB_CREATE_CONTEXT_REQUIRED, "ARB_create_context required") \
  1308. _SAPP_LOGITEM_XMACRO(WIN32_WGL_ARB_CREATE_CONTEXT_PROFILE_REQUIRED, "ARB_create_context_profile required") \
  1309. _SAPP_LOGITEM_XMACRO(WIN32_WGL_OPENGL_VERSION_NOT_SUPPORTED, "requested OpenGL version not supported by GL driver (ERROR_INVALID_VERSION_ARB)") \
  1310. _SAPP_LOGITEM_XMACRO(WIN32_WGL_OPENGL_PROFILE_NOT_SUPPORTED, "requested OpenGL profile not support by GL driver (ERROR_INVALID_PROFILE_ARB)") \
  1311. _SAPP_LOGITEM_XMACRO(WIN32_WGL_INCOMPATIBLE_DEVICE_CONTEXT, "CreateContextAttribsARB failed with ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB") \
  1312. _SAPP_LOGITEM_XMACRO(WIN32_WGL_CREATE_CONTEXT_ATTRIBS_FAILED_OTHER, "CreateContextAttribsARB failed for other reason") \
  1313. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_CREATE_DEVICE_AND_SWAPCHAIN_WITH_DEBUG_FAILED, "D3D11CreateDeviceAndSwapChain() with D3D11_CREATE_DEVICE_DEBUG failed, retrying without debug flag.") \
  1314. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_GET_IDXGIFACTORY_FAILED, "could not obtain IDXGIFactory object") \
  1315. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_GET_IDXGIADAPTER_FAILED, "could not obtain IDXGIAdapter object") \
  1316. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_QUERY_INTERFACE_IDXGIDEVICE1_FAILED, "could not obtain IDXGIDevice1 interface") \
  1317. _SAPP_LOGITEM_XMACRO(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_LOCK, "RegisterRawInputDevices() failed (on mouse lock)") \
  1318. _SAPP_LOGITEM_XMACRO(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_UNLOCK, "RegisterRawInputDevices() failed (on mouse unlock)") \
  1319. _SAPP_LOGITEM_XMACRO(WIN32_GET_RAW_INPUT_DATA_FAILED, "GetRawInputData() failed") \
  1320. _SAPP_LOGITEM_XMACRO(LINUX_GLX_LOAD_LIBGL_FAILED, "failed to load libGL") \
  1321. _SAPP_LOGITEM_XMACRO(LINUX_GLX_LOAD_ENTRY_POINTS_FAILED, "failed to load GLX entry points") \
  1322. _SAPP_LOGITEM_XMACRO(LINUX_GLX_EXTENSION_NOT_FOUND, "GLX extension not found") \
  1323. _SAPP_LOGITEM_XMACRO(LINUX_GLX_QUERY_VERSION_FAILED, "failed to query GLX version") \
  1324. _SAPP_LOGITEM_XMACRO(LINUX_GLX_VERSION_TOO_LOW, "GLX version too low (need at least 1.3)") \
  1325. _SAPP_LOGITEM_XMACRO(LINUX_GLX_NO_GLXFBCONFIGS, "glXGetFBConfigs() returned no configs") \
  1326. _SAPP_LOGITEM_XMACRO(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG, "failed to find a suitable GLXFBConfig") \
  1327. _SAPP_LOGITEM_XMACRO(LINUX_GLX_GET_VISUAL_FROM_FBCONFIG_FAILED, "glXGetVisualFromFBConfig failed") \
  1328. _SAPP_LOGITEM_XMACRO(LINUX_GLX_REQUIRED_EXTENSIONS_MISSING, "GLX extensions ARB_create_context and ARB_create_context_profile missing") \
  1329. _SAPP_LOGITEM_XMACRO(LINUX_GLX_CREATE_CONTEXT_FAILED, "Failed to create GL context via glXCreateContextAttribsARB") \
  1330. _SAPP_LOGITEM_XMACRO(LINUX_GLX_CREATE_WINDOW_FAILED, "glXCreateWindow() failed") \
  1331. _SAPP_LOGITEM_XMACRO(LINUX_X11_CREATE_WINDOW_FAILED, "XCreateWindow() failed") \
  1332. _SAPP_LOGITEM_XMACRO(LINUX_EGL_BIND_OPENGL_API_FAILED, "eglBindAPI(EGL_OPENGL_API) failed") \
  1333. _SAPP_LOGITEM_XMACRO(LINUX_EGL_BIND_OPENGL_ES_API_FAILED, "eglBindAPI(EGL_OPENGL_ES_API) failed") \
  1334. _SAPP_LOGITEM_XMACRO(LINUX_EGL_GET_DISPLAY_FAILED, "eglGetDisplay() failed") \
  1335. _SAPP_LOGITEM_XMACRO(LINUX_EGL_INITIALIZE_FAILED, "eglInitialize() failed") \
  1336. _SAPP_LOGITEM_XMACRO(LINUX_EGL_NO_CONFIGS, "eglChooseConfig() returned no configs") \
  1337. _SAPP_LOGITEM_XMACRO(LINUX_EGL_NO_NATIVE_VISUAL, "eglGetConfigAttrib() for EGL_NATIVE_VISUAL_ID failed") \
  1338. _SAPP_LOGITEM_XMACRO(LINUX_EGL_GET_VISUAL_INFO_FAILED, "XGetVisualInfo() failed") \
  1339. _SAPP_LOGITEM_XMACRO(LINUX_EGL_CREATE_WINDOW_SURFACE_FAILED, "eglCreateWindowSurface() failed") \
  1340. _SAPP_LOGITEM_XMACRO(LINUX_EGL_CREATE_CONTEXT_FAILED, "eglCreateContext() failed") \
  1341. _SAPP_LOGITEM_XMACRO(LINUX_EGL_MAKE_CURRENT_FAILED, "eglMakeCurrent() failed") \
  1342. _SAPP_LOGITEM_XMACRO(LINUX_X11_OPEN_DISPLAY_FAILED, "XOpenDisplay() failed") \
  1343. _SAPP_LOGITEM_XMACRO(LINUX_X11_QUERY_SYSTEM_DPI_FAILED, "failed to query system dpi value, assuming default 96.0") \
  1344. _SAPP_LOGITEM_XMACRO(LINUX_X11_DROPPED_FILE_URI_WRONG_SCHEME, "dropped file URL doesn't start with 'file://'") \
  1345. _SAPP_LOGITEM_XMACRO(LINUX_X11_FAILED_TO_BECOME_OWNER_OF_CLIPBOARD, "X11: Failed to become owner of clipboard selection") \
  1346. _SAPP_LOGITEM_XMACRO(ANDROID_UNSUPPORTED_INPUT_EVENT_INPUT_CB, "unsupported input event encountered in _sapp_android_input_cb()") \
  1347. _SAPP_LOGITEM_XMACRO(ANDROID_UNSUPPORTED_INPUT_EVENT_MAIN_CB, "unsupported input event encountered in _sapp_android_main_cb()") \
  1348. _SAPP_LOGITEM_XMACRO(ANDROID_READ_MSG_FAILED, "failed to read message in _sapp_android_main_cb()") \
  1349. _SAPP_LOGITEM_XMACRO(ANDROID_WRITE_MSG_FAILED, "failed to write message in _sapp_android_msg") \
  1350. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_CREATE, "MSG_CREATE") \
  1351. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_RESUME, "MSG_RESUME") \
  1352. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_PAUSE, "MSG_PAUSE") \
  1353. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_FOCUS, "MSG_FOCUS") \
  1354. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_NO_FOCUS, "MSG_NO_FOCUS") \
  1355. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_SET_NATIVE_WINDOW, "MSG_SET_NATIVE_WINDOW") \
  1356. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_SET_INPUT_QUEUE, "MSG_SET_INPUT_QUEUE") \
  1357. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_DESTROY, "MSG_DESTROY") \
  1358. _SAPP_LOGITEM_XMACRO(ANDROID_UNKNOWN_MSG, "unknown msg type received") \
  1359. _SAPP_LOGITEM_XMACRO(ANDROID_LOOP_THREAD_STARTED, "loop thread started") \
  1360. _SAPP_LOGITEM_XMACRO(ANDROID_LOOP_THREAD_DONE, "loop thread done") \
  1361. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSTART, "NativeActivity onStart()") \
  1362. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONRESUME, "NativeActivity onResume") \
  1363. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSAVEINSTANCESTATE, "NativeActivity onSaveInstanceState") \
  1364. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONWINDOWFOCUSCHANGED, "NativeActivity onWindowFocusChanged") \
  1365. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONPAUSE, "NativeActivity onPause") \
  1366. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSTOP, "NativeActivity onStop()") \
  1367. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWCREATED, "NativeActivity onNativeWindowCreated") \
  1368. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWDESTROYED, "NativeActivity onNativeWindowDestroyed") \
  1369. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUECREATED, "NativeActivity onInputQueueCreated") \
  1370. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUEDESTROYED, "NativeActivity onInputQueueDestroyed") \
  1371. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONCONFIGURATIONCHANGED, "NativeActivity onConfigurationChanged") \
  1372. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONLOWMEMORY, "NativeActivity onLowMemory") \
  1373. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONDESTROY, "NativeActivity onDestroy") \
  1374. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_DONE, "NativeActivity done") \
  1375. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONCREATE, "NativeActivity onCreate") \
  1376. _SAPP_LOGITEM_XMACRO(ANDROID_CREATE_THREAD_PIPE_FAILED, "failed to create thread pipe") \
  1377. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_CREATE_SUCCESS, "NativeActivity successfully created") \
  1378. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_SURFACE_FAILED, "wgpu: failed to create surface for swapchain") \
  1379. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_SWAPCHAIN_FAILED, "wgpu: failed to create swapchain object") \
  1380. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_TEXTURE_FAILED, "wgpu: failed to create depth-stencil texture for swapchain") \
  1381. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_VIEW_FAILED, "wgpu: failed to create view object for swapchain depth-stencil texture") \
  1382. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_MSAA_TEXTURE_FAILED, "wgpu: failed to create msaa texture for swapchain") \
  1383. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_MSAA_VIEW_FAILED, "wgpu: failed to create view object for swapchain msaa texture") \
  1384. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_DEVICE_STATUS_ERROR, "wgpu: requesting device failed with status 'error'") \
  1385. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_DEVICE_STATUS_UNKNOWN, "wgpu: requesting device failed with status 'unknown'") \
  1386. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_UNAVAILABLE, "wgpu: requesting adapter failed with 'unavailable'") \
  1387. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_ERROR, "wgpu: requesting adapter failed with status 'error'") \
  1388. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_UNKNOWN, "wgpu: requesting adapter failed with status 'unknown'") \
  1389. _SAPP_LOGITEM_XMACRO(WGPU_CREATE_INSTANCE_FAILED, "wgpu: failed to create instance") \
  1390. _SAPP_LOGITEM_XMACRO(IMAGE_DATA_SIZE_MISMATCH, "image data size mismatch (must be width*height*4 bytes)") \
  1391. _SAPP_LOGITEM_XMACRO(DROPPED_FILE_PATH_TOO_LONG, "dropped file path too long (sapp_desc.max_dropped_filed_path_length)") \
  1392. _SAPP_LOGITEM_XMACRO(CLIPBOARD_STRING_TOO_BIG, "clipboard string didn't fit into clipboard buffer") \
  1393. #define _SAPP_LOGITEM_XMACRO(item,msg) SAPP_LOGITEM_##item,
  1394. typedef enum sapp_log_item {
  1395. _SAPP_LOG_ITEMS
  1396. } sapp_log_item;
  1397. #undef _SAPP_LOGITEM_XMACRO
  1398. /*
  1399. sapp_logger
  1400. Used in sapp_desc to provide a logging function. Please be aware that
  1401. without logging function, sokol-app will be completely silent, e.g. it will
  1402. not report errors or warnings. For maximum error verbosity, compile in
  1403. debug mode (e.g. NDEBUG *not* defined) and install a logger (for instance
  1404. the standard logging function from sokol_log.h).
  1405. */
  1406. typedef struct sapp_logger {
  1407. void (*func)(
  1408. const char* tag, // always "sapp"
  1409. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  1410. uint32_t log_item_id, // SAPP_LOGITEM_*
  1411. const char* message_or_null, // a message string, may be nullptr in release mode
  1412. uint32_t line_nr, // line number in sokol_app.h
  1413. const char* filename_or_null, // source filename, may be nullptr in release mode
  1414. void* user_data);
  1415. void* user_data;
  1416. } sapp_logger;
  1417. typedef struct sapp_desc {
  1418. void (*init_cb)(void); // these are the user-provided callbacks without user data
  1419. void (*frame_cb)(void);
  1420. void (*cleanup_cb)(void);
  1421. void (*event_cb)(const sapp_event*);
  1422. void* user_data; // these are the user-provided callbacks with user data
  1423. void (*init_userdata_cb)(void*);
  1424. void (*frame_userdata_cb)(void*);
  1425. void (*cleanup_userdata_cb)(void*);
  1426. void (*event_userdata_cb)(const sapp_event*, void*);
  1427. int width; // the preferred width of the window / canvas
  1428. int height; // the preferred height of the window / canvas
  1429. int sample_count; // MSAA sample count
  1430. int swap_interval; // the preferred swap interval (ignored on some platforms)
  1431. bool high_dpi; // whether the rendering canvas is full-resolution on HighDPI displays
  1432. bool fullscreen; // whether the window should be created in fullscreen mode
  1433. bool alpha; // whether the framebuffer should have an alpha channel (ignored on some platforms)
  1434. const char* window_title; // the window title as UTF-8 encoded string
  1435. bool enable_clipboard; // enable clipboard access, default is false
  1436. int clipboard_size; // max size of clipboard content in bytes
  1437. bool enable_dragndrop; // enable file dropping (drag'n'drop), default is false
  1438. int max_dropped_files; // max number of dropped files to process (default: 1)
  1439. int max_dropped_file_path_length; // max length in bytes of a dropped UTF-8 file path (default: 2048)
  1440. sapp_icon_desc icon; // the initial window icon to set
  1441. sapp_allocator allocator; // optional memory allocation overrides (default: malloc/free)
  1442. sapp_logger logger; // logging callback override (default: NO LOGGING!)
  1443. // backend-specific options
  1444. int gl_major_version; // override GL major and minor version (the default GL version is 4.1 on macOS, 4.3 elsewhere)
  1445. int gl_minor_version;
  1446. bool win32_console_utf8; // if true, set the output console codepage to UTF-8
  1447. bool win32_console_create; // if true, attach stdout/stderr to a new console window
  1448. bool win32_console_attach; // if true, attach stdout/stderr to parent process
  1449. const char* html5_canvas_name; // the name (id) of the HTML5 canvas element, default is "canvas"
  1450. bool html5_canvas_resize; // if true, the HTML5 canvas size is set to sapp_desc.width/height, otherwise canvas size is tracked
  1451. bool html5_preserve_drawing_buffer; // HTML5 only: whether to preserve default framebuffer content between frames
  1452. bool html5_premultiplied_alpha; // HTML5 only: whether the rendered pixels use premultiplied alpha convention
  1453. bool html5_ask_leave_site; // initial state of the internal html5_ask_leave_site flag (see sapp_html5_ask_leave_site())
  1454. bool html5_bubble_mouse_events; // if true, mouse events will bubble up to the web page
  1455. bool html5_bubble_touch_events; // same for touch events
  1456. bool html5_bubble_wheel_events; // same for wheel events
  1457. bool html5_bubble_key_events; // if true, bubble up *all* key events to browser, not just key events that represent characters
  1458. bool html5_bubble_char_events; // if true, bubble up character events to browser
  1459. bool html5_use_emsc_set_main_loop; // if true, use emscripten_set_main_loop() instead of emscripten_request_animation_frame_loop()
  1460. bool html5_emsc_set_main_loop_simulate_infinite_loop; // this will be passed as the simulate_infinite_loop arg to emscripten_set_main_loop()
  1461. bool ios_keyboard_resizes_canvas; // if true, showing the iOS keyboard shrinks the canvas
  1462. } sapp_desc;
  1463. /* HTML5 specific: request and response structs for
  1464. asynchronously loading dropped-file content.
  1465. */
  1466. typedef enum sapp_html5_fetch_error {
  1467. SAPP_HTML5_FETCH_ERROR_NO_ERROR,
  1468. SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL,
  1469. SAPP_HTML5_FETCH_ERROR_OTHER,
  1470. } sapp_html5_fetch_error;
  1471. typedef struct sapp_html5_fetch_response {
  1472. bool succeeded; // true if the loading operation has succeeded
  1473. sapp_html5_fetch_error error_code;
  1474. int file_index; // index of the dropped file (0..sapp_get_num_dropped_filed()-1)
  1475. sapp_range data; // pointer and size of the fetched data (data.ptr == buffer.ptr, data.size <= buffer.size)
  1476. sapp_range buffer; // the user-provided buffer ptr/size pair (buffer.ptr == data.ptr, buffer.size >= data.size)
  1477. void* user_data; // user-provided user data pointer
  1478. } sapp_html5_fetch_response;
  1479. typedef struct sapp_html5_fetch_request {
  1480. int dropped_file_index; // 0..sapp_get_num_dropped_files()-1
  1481. void (*callback)(const sapp_html5_fetch_response*); // response callback function pointer (required)
  1482. sapp_range buffer; // ptr/size of a memory buffer to load the data into
  1483. void* user_data; // optional userdata pointer
  1484. } sapp_html5_fetch_request;
  1485. /*
  1486. sapp_mouse_cursor
  1487. Predefined cursor image definitions, set with sapp_set_mouse_cursor(sapp_mouse_cursor cursor)
  1488. */
  1489. typedef enum sapp_mouse_cursor {
  1490. SAPP_MOUSECURSOR_DEFAULT = 0, // equivalent with system default cursor
  1491. SAPP_MOUSECURSOR_ARROW,
  1492. SAPP_MOUSECURSOR_IBEAM,
  1493. SAPP_MOUSECURSOR_CROSSHAIR,
  1494. SAPP_MOUSECURSOR_POINTING_HAND,
  1495. SAPP_MOUSECURSOR_RESIZE_EW,
  1496. SAPP_MOUSECURSOR_RESIZE_NS,
  1497. SAPP_MOUSECURSOR_RESIZE_NWSE,
  1498. SAPP_MOUSECURSOR_RESIZE_NESW,
  1499. SAPP_MOUSECURSOR_RESIZE_ALL,
  1500. SAPP_MOUSECURSOR_NOT_ALLOWED,
  1501. _SAPP_MOUSECURSOR_NUM,
  1502. } sapp_mouse_cursor;
  1503. /* user-provided functions */
  1504. extern sapp_desc sokol_main(int argc, char* argv[]);
  1505. /* returns true after sokol-app has been initialized */
  1506. SOKOL_APP_API_DECL bool sapp_isvalid(void);
  1507. /* returns the current framebuffer width in pixels */
  1508. SOKOL_APP_API_DECL int sapp_width(void);
  1509. /* same as sapp_width(), but returns float */
  1510. SOKOL_APP_API_DECL float sapp_widthf(void);
  1511. /* returns the current framebuffer height in pixels */
  1512. SOKOL_APP_API_DECL int sapp_height(void);
  1513. /* same as sapp_height(), but returns float */
  1514. SOKOL_APP_API_DECL float sapp_heightf(void);
  1515. /* get default framebuffer color pixel format */
  1516. SOKOL_APP_API_DECL int sapp_color_format(void);
  1517. /* get default framebuffer depth pixel format */
  1518. SOKOL_APP_API_DECL int sapp_depth_format(void);
  1519. /* get default framebuffer sample count */
  1520. SOKOL_APP_API_DECL int sapp_sample_count(void);
  1521. /* returns true when high_dpi was requested and actually running in a high-dpi scenario */
  1522. SOKOL_APP_API_DECL bool sapp_high_dpi(void);
  1523. /* returns the dpi scaling factor (window pixels to framebuffer pixels) */
  1524. SOKOL_APP_API_DECL float sapp_dpi_scale(void);
  1525. /* show or hide the mobile device onscreen keyboard */
  1526. SOKOL_APP_API_DECL void sapp_show_keyboard(bool show);
  1527. /* return true if the mobile device onscreen keyboard is currently shown */
  1528. SOKOL_APP_API_DECL bool sapp_keyboard_shown(void);
  1529. /* query fullscreen mode */
  1530. SOKOL_APP_API_DECL bool sapp_is_fullscreen(void);
  1531. /* toggle fullscreen mode */
  1532. SOKOL_APP_API_DECL void sapp_toggle_fullscreen(void);
  1533. /* show or hide the mouse cursor */
  1534. SOKOL_APP_API_DECL void sapp_show_mouse(bool show);
  1535. /* show or hide the mouse cursor */
  1536. SOKOL_APP_API_DECL bool sapp_mouse_shown(void);
  1537. /* enable/disable mouse-pointer-lock mode */
  1538. SOKOL_APP_API_DECL void sapp_lock_mouse(bool lock);
  1539. /* return true if in mouse-pointer-lock mode (this may toggle a few frames later) */
  1540. SOKOL_APP_API_DECL bool sapp_mouse_locked(void);
  1541. /* set mouse cursor type */
  1542. SOKOL_APP_API_DECL void sapp_set_mouse_cursor(sapp_mouse_cursor cursor);
  1543. /* get current mouse cursor type */
  1544. SOKOL_APP_API_DECL sapp_mouse_cursor sapp_get_mouse_cursor(void);
  1545. /* return the userdata pointer optionally provided in sapp_desc */
  1546. SOKOL_APP_API_DECL void* sapp_userdata(void);
  1547. /* return a copy of the sapp_desc structure */
  1548. SOKOL_APP_API_DECL sapp_desc sapp_query_desc(void);
  1549. /* initiate a "soft quit" (sends SAPP_EVENTTYPE_QUIT_REQUESTED) */
  1550. SOKOL_APP_API_DECL void sapp_request_quit(void);
  1551. /* cancel a pending quit (when SAPP_EVENTTYPE_QUIT_REQUESTED has been received) */
  1552. SOKOL_APP_API_DECL void sapp_cancel_quit(void);
  1553. /* initiate a "hard quit" (quit application without sending SAPP_EVENTTYPE_QUIT_REQUESTED) */
  1554. SOKOL_APP_API_DECL void sapp_quit(void);
  1555. /* call from inside event callback to consume the current event (don't forward to platform) */
  1556. SOKOL_APP_API_DECL void sapp_consume_event(void);
  1557. /* get the current frame counter (for comparison with sapp_event.frame_count) */
  1558. SOKOL_APP_API_DECL uint64_t sapp_frame_count(void);
  1559. /* get an averaged/smoothed frame duration in seconds */
  1560. SOKOL_APP_API_DECL double sapp_frame_duration(void);
  1561. /* write string into clipboard */
  1562. SOKOL_APP_API_DECL void sapp_set_clipboard_string(const char* str);
  1563. /* read string from clipboard (usually during SAPP_EVENTTYPE_CLIPBOARD_PASTED) */
  1564. SOKOL_APP_API_DECL const char* sapp_get_clipboard_string(void);
  1565. /* set the window title (only on desktop platforms) */
  1566. SOKOL_APP_API_DECL void sapp_set_window_title(const char* str);
  1567. /* set the window icon (only on Windows and Linux) */
  1568. SOKOL_APP_API_DECL void sapp_set_icon(const sapp_icon_desc* icon_desc);
  1569. /* gets the total number of dropped files (after an SAPP_EVENTTYPE_FILES_DROPPED event) */
  1570. SOKOL_APP_API_DECL int sapp_get_num_dropped_files(void);
  1571. /* gets the dropped file paths */
  1572. SOKOL_APP_API_DECL const char* sapp_get_dropped_file_path(int index);
  1573. /* special run-function for SOKOL_NO_ENTRY (in standard mode this is an empty stub) */
  1574. SOKOL_APP_API_DECL void sapp_run(const sapp_desc* desc);
  1575. /* EGL: get EGLDisplay object */
  1576. SOKOL_APP_API_DECL const void* sapp_egl_get_display(void);
  1577. /* EGL: get EGLContext object */
  1578. SOKOL_APP_API_DECL const void* sapp_egl_get_context(void);
  1579. /* HTML5: enable or disable the hardwired "Leave Site?" dialog box */
  1580. SOKOL_APP_API_DECL void sapp_html5_ask_leave_site(bool ask);
  1581. /* HTML5: get byte size of a dropped file */
  1582. SOKOL_APP_API_DECL uint32_t sapp_html5_get_dropped_file_size(int index);
  1583. /* HTML5: asynchronously load the content of a dropped file */
  1584. SOKOL_APP_API_DECL void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request);
  1585. /* Metal: get bridged pointer to Metal device object */
  1586. SOKOL_APP_API_DECL const void* sapp_metal_get_device(void);
  1587. /* Metal: get bridged pointer to MTKView's current drawable of type CAMetalDrawable */
  1588. SOKOL_APP_API_DECL const void* sapp_metal_get_current_drawable(void);
  1589. /* Metal: get bridged pointer to MTKView's depth-stencil texture of type MTLTexture */
  1590. SOKOL_APP_API_DECL const void* sapp_metal_get_depth_stencil_texture(void);
  1591. /* Metal: get bridged pointer to MTKView's msaa-color-texture of type MTLTexture (may be null) */
  1592. SOKOL_APP_API_DECL const void* sapp_metal_get_msaa_color_texture(void);
  1593. /* macOS: get bridged pointer to macOS NSWindow */
  1594. SOKOL_APP_API_DECL const void* sapp_macos_get_window(void);
  1595. /* iOS: get bridged pointer to iOS UIWindow */
  1596. SOKOL_APP_API_DECL const void* sapp_ios_get_window(void);
  1597. /* D3D11: get pointer to ID3D11Device object */
  1598. SOKOL_APP_API_DECL const void* sapp_d3d11_get_device(void);
  1599. /* D3D11: get pointer to ID3D11DeviceContext object */
  1600. SOKOL_APP_API_DECL const void* sapp_d3d11_get_device_context(void);
  1601. /* D3D11: get pointer to IDXGISwapChain object */
  1602. SOKOL_APP_API_DECL const void* sapp_d3d11_get_swap_chain(void);
  1603. /* D3D11: get pointer to ID3D11RenderTargetView object for rendering */
  1604. SOKOL_APP_API_DECL const void* sapp_d3d11_get_render_view(void);
  1605. /* D3D11: get pointer ID3D11RenderTargetView object for msaa-resolve (may return null) */
  1606. SOKOL_APP_API_DECL const void* sapp_d3d11_get_resolve_view(void);
  1607. /* D3D11: get pointer ID3D11DepthStencilView */
  1608. SOKOL_APP_API_DECL const void* sapp_d3d11_get_depth_stencil_view(void);
  1609. /* Win32: get the HWND window handle */
  1610. SOKOL_APP_API_DECL const void* sapp_win32_get_hwnd(void);
  1611. /* WebGPU: get WGPUDevice handle */
  1612. SOKOL_APP_API_DECL const void* sapp_wgpu_get_device(void);
  1613. /* WebGPU: get swapchain's WGPUTextureView handle for rendering */
  1614. SOKOL_APP_API_DECL const void* sapp_wgpu_get_render_view(void);
  1615. /* WebGPU: get swapchain's MSAA-resolve WGPUTextureView (may return null) */
  1616. SOKOL_APP_API_DECL const void* sapp_wgpu_get_resolve_view(void);
  1617. /* WebGPU: get swapchain's WGPUTextureView for the depth-stencil surface */
  1618. SOKOL_APP_API_DECL const void* sapp_wgpu_get_depth_stencil_view(void);
  1619. /* GL: get framebuffer object */
  1620. SOKOL_APP_API_DECL uint32_t sapp_gl_get_framebuffer(void);
  1621. /* GL: get major version (only valid for desktop GL) */
  1622. SOKOL_APP_API_DECL int sapp_gl_get_major_version(void);
  1623. /* GL: get minor version (only valid for desktop GL) */
  1624. SOKOL_APP_API_DECL int sapp_gl_get_minor_version(void);
  1625. /* Android: get native activity handle */
  1626. SOKOL_APP_API_DECL const void* sapp_android_get_native_activity(void);
  1627. #ifdef __cplusplus
  1628. } /* extern "C" */
  1629. /* reference-based equivalents for C++ */
  1630. inline void sapp_run(const sapp_desc& desc) { return sapp_run(&desc); }
  1631. #endif
  1632. // this WinRT specific hack is required when wWinMain is in a static library
  1633. #if defined(_MSC_VER) && defined(UNICODE)
  1634. #include <winapifamily.h>
  1635. #if defined(WINAPI_FAMILY_PARTITION) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  1636. #pragma comment(linker, "/include:wWinMain")
  1637. #endif
  1638. #endif
  1639. #endif // SOKOL_APP_INCLUDED
  1640. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  1641. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  1642. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  1643. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1644. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  1645. //
  1646. // >>implementation
  1647. #ifdef SOKOL_APP_IMPL
  1648. #define SOKOL_APP_IMPL_INCLUDED (1)
  1649. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  1650. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sapp_desc.allocator to override memory allocation functions"
  1651. #endif
  1652. #include <stdlib.h> // malloc, free
  1653. #include <string.h> // memset, strncmp
  1654. #include <stddef.h> // size_t
  1655. #include <math.h> // roundf
  1656. // helper macros
  1657. #define _sapp_def(val, def) (((val) == 0) ? (def) : (val))
  1658. #define _sapp_absf(a) (((a)<0.0f)?-(a):(a))
  1659. #define _SAPP_MAX_TITLE_LENGTH (128)
  1660. #define _SAPP_FALLBACK_DEFAULT_WINDOW_WIDTH (640)
  1661. #define _SAPP_FALLBACK_DEFAULT_WINDOW_HEIGHT (480)
  1662. // NOTE: the pixel format values *must* be compatible with sg_pixel_format
  1663. #define _SAPP_PIXELFORMAT_RGBA8 (23)
  1664. #define _SAPP_PIXELFORMAT_BGRA8 (28)
  1665. #define _SAPP_PIXELFORMAT_DEPTH (43)
  1666. #define _SAPP_PIXELFORMAT_DEPTH_STENCIL (44)
  1667. // check if the config defines are alright
  1668. #if defined(__APPLE__)
  1669. // see https://clang.llvm.org/docs/LanguageExtensions.html#automatic-reference-counting
  1670. #if !defined(__cplusplus)
  1671. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  1672. #error "sokol_app.h requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  1673. #endif
  1674. #endif
  1675. #define _SAPP_APPLE (1)
  1676. #include <TargetConditionals.h>
  1677. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  1678. /* MacOS */
  1679. #define _SAPP_MACOS (1)
  1680. #if !defined(SOKOL_METAL) && !defined(SOKOL_GLCORE)
  1681. #error("sokol_app.h: unknown 3D API selected for MacOS, must be SOKOL_METAL or SOKOL_GLCORE")
  1682. #endif
  1683. #else
  1684. /* iOS or iOS Simulator */
  1685. #define _SAPP_IOS (1)
  1686. #if !defined(SOKOL_METAL) && !defined(SOKOL_GLES3)
  1687. #error("sokol_app.h: unknown 3D API selected for iOS, must be SOKOL_METAL or SOKOL_GLES3")
  1688. #endif
  1689. #endif
  1690. #elif defined(__EMSCRIPTEN__)
  1691. /* emscripten (asm.js or wasm) */
  1692. #define _SAPP_EMSCRIPTEN (1)
  1693. #if !defined(SOKOL_GLES3) && !defined(SOKOL_WGPU)
  1694. #error("sokol_app.h: unknown 3D API selected for emscripten, must be SOKOL_GLES3 or SOKOL_WGPU")
  1695. #endif
  1696. #elif defined(_WIN32)
  1697. /* Windows (D3D11 or GL) */
  1698. #define _SAPP_WIN32 (1)
  1699. #if !defined(SOKOL_D3D11) && !defined(SOKOL_GLCORE) && !defined(SOKOL_NOAPI)
  1700. #error("sokol_app.h: unknown 3D API selected for Win32, must be SOKOL_D3D11, SOKOL_GLCORE or SOKOL_NOAPI")
  1701. #endif
  1702. #elif defined(__ANDROID__)
  1703. /* Android */
  1704. #define _SAPP_ANDROID (1)
  1705. #if !defined(SOKOL_GLES3)
  1706. #error("sokol_app.h: unknown 3D API selected for Android, must be SOKOL_GLES3")
  1707. #endif
  1708. #if defined(SOKOL_NO_ENTRY)
  1709. #error("sokol_app.h: SOKOL_NO_ENTRY is not supported on Android")
  1710. #endif
  1711. #elif defined(__linux__) || defined(__unix__)
  1712. /* Linux */
  1713. #define _SAPP_LINUX (1)
  1714. #if defined(SOKOL_GLCORE)
  1715. #if !defined(SOKOL_FORCE_EGL)
  1716. #define _SAPP_GLX (1)
  1717. #endif
  1718. #define GL_GLEXT_PROTOTYPES
  1719. #include <GL/gl.h>
  1720. #elif defined(SOKOL_GLES3)
  1721. #include <GLES3/gl3.h>
  1722. #include <GLES3/gl3ext.h>
  1723. #else
  1724. #error("sokol_app.h: unknown 3D API selected for Linux, must be SOKOL_GLCORE, SOKOL_GLES3")
  1725. #endif
  1726. #else
  1727. #error "sokol_app.h: Unknown platform"
  1728. #endif
  1729. #if defined(SOKOL_GLCORE) || defined(SOKOL_GLES3)
  1730. #define _SAPP_ANY_GL (1)
  1731. #endif
  1732. #ifndef SOKOL_API_IMPL
  1733. #define SOKOL_API_IMPL
  1734. #endif
  1735. #ifndef SOKOL_DEBUG
  1736. #ifndef NDEBUG
  1737. #define SOKOL_DEBUG
  1738. #endif
  1739. #endif
  1740. #ifndef SOKOL_ASSERT
  1741. #include <assert.h>
  1742. #define SOKOL_ASSERT(c) assert(c)
  1743. #endif
  1744. #ifndef SOKOL_UNREACHABLE
  1745. #define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
  1746. #endif
  1747. #ifndef _SOKOL_PRIVATE
  1748. #if defined(__GNUC__) || defined(__clang__)
  1749. #define _SOKOL_PRIVATE __attribute__((unused)) static
  1750. #else
  1751. #define _SOKOL_PRIVATE static
  1752. #endif
  1753. #endif
  1754. #ifndef _SOKOL_UNUSED
  1755. #define _SOKOL_UNUSED(x) (void)(x)
  1756. #endif
  1757. #if defined(_SAPP_APPLE)
  1758. #if defined(SOKOL_METAL)
  1759. #import <Metal/Metal.h>
  1760. #import <MetalKit/MetalKit.h>
  1761. #endif
  1762. #if defined(_SAPP_MACOS)
  1763. #if defined(_SAPP_ANY_GL)
  1764. #ifndef GL_SILENCE_DEPRECATION
  1765. #define GL_SILENCE_DEPRECATION
  1766. #endif
  1767. #include <Cocoa/Cocoa.h>
  1768. #include <OpenGL/gl3.h>
  1769. #endif
  1770. #elif defined(_SAPP_IOS)
  1771. #import <UIKit/UIKit.h>
  1772. #if defined(_SAPP_ANY_GL)
  1773. #import <GLKit/GLKit.h>
  1774. #include <OpenGLES/ES3/gl.h>
  1775. #endif
  1776. #endif
  1777. #include <AvailabilityMacros.h>
  1778. #include <mach/mach_time.h>
  1779. #elif defined(_SAPP_EMSCRIPTEN)
  1780. #if defined(SOKOL_WGPU)
  1781. #include <webgpu/webgpu.h>
  1782. #endif
  1783. #if defined(SOKOL_GLES3)
  1784. #include <GLES3/gl3.h>
  1785. #endif
  1786. #include <emscripten/emscripten.h>
  1787. #include <emscripten/html5.h>
  1788. #elif defined(_SAPP_WIN32)
  1789. #ifdef _MSC_VER
  1790. #pragma warning(push)
  1791. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  1792. #pragma warning(disable:4204) /* nonstandard extension used: non-constant aggregate initializer */
  1793. #pragma warning(disable:4054) /* 'type cast': from function pointer */
  1794. #pragma warning(disable:4055) /* 'type cast': from data pointer */
  1795. #pragma warning(disable:4505) /* unreferenced local function has been removed */
  1796. #pragma warning(disable:4115) /* /W4: 'ID3D11ModuleInstance': named type definition in parentheses (in d3d11.h) */
  1797. #endif
  1798. #ifndef WIN32_LEAN_AND_MEAN
  1799. #define WIN32_LEAN_AND_MEAN
  1800. #endif
  1801. #ifndef NOMINMAX
  1802. #define NOMINMAX
  1803. #endif
  1804. #include <windows.h>
  1805. #include <windowsx.h>
  1806. #include <shellapi.h>
  1807. #if !defined(SOKOL_NO_ENTRY) // if SOKOL_NO_ENTRY is defined, it's the applications' responsibility to use the right subsystem
  1808. #if defined(SOKOL_WIN32_FORCE_MAIN)
  1809. #pragma comment (linker, "/subsystem:console")
  1810. #else
  1811. #pragma comment (linker, "/subsystem:windows")
  1812. #endif
  1813. #endif
  1814. #include <stdio.h> /* freopen_s() */
  1815. #include <wchar.h> /* wcslen() */
  1816. #pragma comment (lib, "kernel32")
  1817. #pragma comment (lib, "user32")
  1818. #pragma comment (lib, "shell32") /* CommandLineToArgvW, DragQueryFileW, DragFinished */
  1819. #pragma comment (lib, "gdi32")
  1820. #if defined(SOKOL_D3D11)
  1821. #pragma comment (lib, "dxgi")
  1822. #pragma comment (lib, "d3d11")
  1823. #endif
  1824. #if defined(SOKOL_D3D11)
  1825. #ifndef D3D11_NO_HELPERS
  1826. #define D3D11_NO_HELPERS
  1827. #endif
  1828. #include <d3d11.h>
  1829. #include <dxgi.h>
  1830. // DXGI_SWAP_EFFECT_FLIP_DISCARD is only defined in newer Windows SDKs, so don't depend on it
  1831. #define _SAPP_DXGI_SWAP_EFFECT_FLIP_DISCARD (4)
  1832. #endif
  1833. #ifndef WM_MOUSEHWHEEL /* see https://github.com/floooh/sokol/issues/138 */
  1834. #define WM_MOUSEHWHEEL (0x020E)
  1835. #endif
  1836. #ifndef WM_DPICHANGED
  1837. #define WM_DPICHANGED (0x02E0)
  1838. #endif
  1839. #elif defined(_SAPP_ANDROID)
  1840. #include <pthread.h>
  1841. #include <unistd.h>
  1842. #include <time.h>
  1843. #include <android/native_activity.h>
  1844. #include <android/looper.h>
  1845. #include <EGL/egl.h>
  1846. #include <GLES3/gl3.h>
  1847. #elif defined(_SAPP_LINUX)
  1848. #define GL_GLEXT_PROTOTYPES
  1849. #include <X11/Xlib.h>
  1850. #include <X11/Xutil.h>
  1851. #include <X11/XKBlib.h>
  1852. #include <X11/keysym.h>
  1853. #include <X11/Xresource.h>
  1854. #include <X11/Xatom.h>
  1855. #include <X11/extensions/XInput2.h>
  1856. #include <X11/Xcursor/Xcursor.h>
  1857. #include <X11/cursorfont.h> /* XC_* font cursors */
  1858. #include <X11/Xmd.h> /* CARD32 */
  1859. #if !defined(_SAPP_GLX)
  1860. #include <EGL/egl.h>
  1861. #endif
  1862. #include <dlfcn.h> /* dlopen, dlsym, dlclose */
  1863. #include <limits.h> /* LONG_MAX */
  1864. #include <pthread.h> /* only used a linker-guard, search for _sapp_linux_run() and see first comment */
  1865. #include <time.h>
  1866. #include <poll.h>
  1867. #endif
  1868. #if defined(_SAPP_APPLE)
  1869. // this is ARC compatible
  1870. #if defined(__cplusplus)
  1871. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { item = type(); }
  1872. #else
  1873. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { item = (type) { 0 }; }
  1874. #endif
  1875. #else
  1876. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { _sapp_clear(&item, sizeof(item)); }
  1877. #endif
  1878. // ███████ ██████ █████ ███ ███ ███████ ████████ ██ ███ ███ ██ ███ ██ ██████
  1879. // ██ ██ ██ ██ ██ ████ ████ ██ ██ ██ ████ ████ ██ ████ ██ ██
  1880. // █████ ██████ ███████ ██ ████ ██ █████ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ███
  1881. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1882. // ██ ██ ██ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ████ ██████
  1883. //
  1884. // >>frame timing
  1885. #define _SAPP_RING_NUM_SLOTS (256)
  1886. typedef struct {
  1887. int head;
  1888. int tail;
  1889. double buf[_SAPP_RING_NUM_SLOTS];
  1890. } _sapp_ring_t;
  1891. _SOKOL_PRIVATE int _sapp_ring_idx(int i) {
  1892. return i % _SAPP_RING_NUM_SLOTS;
  1893. }
  1894. _SOKOL_PRIVATE void _sapp_ring_init(_sapp_ring_t* ring) {
  1895. ring->head = 0;
  1896. ring->tail = 0;
  1897. }
  1898. _SOKOL_PRIVATE bool _sapp_ring_full(_sapp_ring_t* ring) {
  1899. return _sapp_ring_idx(ring->head + 1) == ring->tail;
  1900. }
  1901. _SOKOL_PRIVATE bool _sapp_ring_empty(_sapp_ring_t* ring) {
  1902. return ring->head == ring->tail;
  1903. }
  1904. _SOKOL_PRIVATE int _sapp_ring_count(_sapp_ring_t* ring) {
  1905. int count;
  1906. if (ring->head >= ring->tail) {
  1907. count = ring->head - ring->tail;
  1908. }
  1909. else {
  1910. count = (ring->head + _SAPP_RING_NUM_SLOTS) - ring->tail;
  1911. }
  1912. SOKOL_ASSERT((count >= 0) && (count < _SAPP_RING_NUM_SLOTS));
  1913. return count;
  1914. }
  1915. _SOKOL_PRIVATE void _sapp_ring_enqueue(_sapp_ring_t* ring, double val) {
  1916. SOKOL_ASSERT(!_sapp_ring_full(ring));
  1917. ring->buf[ring->head] = val;
  1918. ring->head = _sapp_ring_idx(ring->head + 1);
  1919. }
  1920. _SOKOL_PRIVATE double _sapp_ring_dequeue(_sapp_ring_t* ring) {
  1921. SOKOL_ASSERT(!_sapp_ring_empty(ring));
  1922. double val = ring->buf[ring->tail];
  1923. ring->tail = _sapp_ring_idx(ring->tail + 1);
  1924. return val;
  1925. }
  1926. /*
  1927. NOTE:
  1928. Q: Why not use CAMetalDrawable.presentedTime on macOS and iOS?
  1929. A: The value appears to be highly unstable during the first few
  1930. seconds, sometimes several frames are dropped in sequence, or
  1931. switch between 120 and 60 Hz for a few frames. Simply measuring
  1932. and averaging the frame time yielded a more stable frame duration.
  1933. Maybe switching to CVDisplayLink would yield better results.
  1934. Until then just measure the time.
  1935. */
  1936. typedef struct {
  1937. #if defined(_SAPP_APPLE)
  1938. struct {
  1939. mach_timebase_info_data_t timebase;
  1940. uint64_t start;
  1941. } mach;
  1942. #elif defined(_SAPP_EMSCRIPTEN)
  1943. // empty
  1944. #elif defined(_SAPP_WIN32)
  1945. struct {
  1946. LARGE_INTEGER freq;
  1947. LARGE_INTEGER start;
  1948. } win;
  1949. #else // Linux, Android, ...
  1950. #ifdef CLOCK_MONOTONIC
  1951. #define _SAPP_CLOCK_MONOTONIC CLOCK_MONOTONIC
  1952. #else
  1953. // on some embedded platforms, CLOCK_MONOTONIC isn't defined
  1954. #define _SAPP_CLOCK_MONOTONIC (1)
  1955. #endif
  1956. struct {
  1957. uint64_t start;
  1958. } posix;
  1959. #endif
  1960. } _sapp_timestamp_t;
  1961. _SOKOL_PRIVATE int64_t _sapp_int64_muldiv(int64_t value, int64_t numer, int64_t denom) {
  1962. int64_t q = value / denom;
  1963. int64_t r = value % denom;
  1964. return q * numer + r * numer / denom;
  1965. }
  1966. _SOKOL_PRIVATE void _sapp_timestamp_init(_sapp_timestamp_t* ts) {
  1967. #if defined(_SAPP_APPLE)
  1968. mach_timebase_info(&ts->mach.timebase);
  1969. ts->mach.start = mach_absolute_time();
  1970. #elif defined(_SAPP_EMSCRIPTEN)
  1971. (void)ts;
  1972. #elif defined(_SAPP_WIN32)
  1973. QueryPerformanceFrequency(&ts->win.freq);
  1974. QueryPerformanceCounter(&ts->win.start);
  1975. #else
  1976. struct timespec tspec;
  1977. clock_gettime(_SAPP_CLOCK_MONOTONIC, &tspec);
  1978. ts->posix.start = (uint64_t)tspec.tv_sec*1000000000 + (uint64_t)tspec.tv_nsec;
  1979. #endif
  1980. }
  1981. _SOKOL_PRIVATE double _sapp_timestamp_now(_sapp_timestamp_t* ts) {
  1982. #if defined(_SAPP_APPLE)
  1983. const uint64_t traw = mach_absolute_time() - ts->mach.start;
  1984. const uint64_t now = (uint64_t) _sapp_int64_muldiv((int64_t)traw, (int64_t)ts->mach.timebase.numer, (int64_t)ts->mach.timebase.denom);
  1985. return (double)now / 1000000000.0;
  1986. #elif defined(_SAPP_EMSCRIPTEN)
  1987. (void)ts;
  1988. SOKOL_ASSERT(false);
  1989. return 0.0;
  1990. #elif defined(_SAPP_WIN32)
  1991. LARGE_INTEGER qpc;
  1992. QueryPerformanceCounter(&qpc);
  1993. const uint64_t now = (uint64_t)_sapp_int64_muldiv(qpc.QuadPart - ts->win.start.QuadPart, 1000000000, ts->win.freq.QuadPart);
  1994. return (double)now / 1000000000.0;
  1995. #else
  1996. struct timespec tspec;
  1997. clock_gettime(_SAPP_CLOCK_MONOTONIC, &tspec);
  1998. const uint64_t now = ((uint64_t)tspec.tv_sec*1000000000 + (uint64_t)tspec.tv_nsec) - ts->posix.start;
  1999. return (double)now / 1000000000.0;
  2000. #endif
  2001. }
  2002. typedef struct {
  2003. double last;
  2004. double accum;
  2005. double avg;
  2006. int spike_count;
  2007. int num;
  2008. _sapp_timestamp_t timestamp;
  2009. _sapp_ring_t ring;
  2010. } _sapp_timing_t;
  2011. _SOKOL_PRIVATE void _sapp_timing_reset(_sapp_timing_t* t) {
  2012. t->last = 0.0;
  2013. t->accum = 0.0;
  2014. t->spike_count = 0;
  2015. t->num = 0;
  2016. _sapp_ring_init(&t->ring);
  2017. }
  2018. _SOKOL_PRIVATE void _sapp_timing_init(_sapp_timing_t* t) {
  2019. t->avg = 1.0 / 60.0; // dummy value until first actual value is available
  2020. _sapp_timing_reset(t);
  2021. _sapp_timestamp_init(&t->timestamp);
  2022. }
  2023. _SOKOL_PRIVATE void _sapp_timing_put(_sapp_timing_t* t, double dur) {
  2024. // arbitrary upper limit to ignore outliers (e.g. during window resizing, or debugging)
  2025. double min_dur = 0.0;
  2026. double max_dur = 0.1;
  2027. // if we have enough samples for a useful average, use a much tighter 'valid window'
  2028. if (_sapp_ring_full(&t->ring)) {
  2029. min_dur = t->avg * 0.8;
  2030. max_dur = t->avg * 1.2;
  2031. }
  2032. if ((dur < min_dur) || (dur > max_dur)) {
  2033. t->spike_count++;
  2034. // if there have been many spikes in a row, the display refresh rate
  2035. // might have changed, so a timing reset is needed
  2036. if (t->spike_count > 20) {
  2037. _sapp_timing_reset(t);
  2038. }
  2039. return;
  2040. }
  2041. if (_sapp_ring_full(&t->ring)) {
  2042. double old_val = _sapp_ring_dequeue(&t->ring);
  2043. t->accum -= old_val;
  2044. t->num -= 1;
  2045. }
  2046. _sapp_ring_enqueue(&t->ring, dur);
  2047. t->accum += dur;
  2048. t->num += 1;
  2049. SOKOL_ASSERT(t->num > 0);
  2050. t->avg = t->accum / t->num;
  2051. t->spike_count = 0;
  2052. }
  2053. _SOKOL_PRIVATE void _sapp_timing_discontinuity(_sapp_timing_t* t) {
  2054. t->last = 0.0;
  2055. }
  2056. _SOKOL_PRIVATE void _sapp_timing_measure(_sapp_timing_t* t) {
  2057. const double now = _sapp_timestamp_now(&t->timestamp);
  2058. if (t->last > 0.0) {
  2059. double dur = now - t->last;
  2060. _sapp_timing_put(t, dur);
  2061. }
  2062. t->last = now;
  2063. }
  2064. _SOKOL_PRIVATE void _sapp_timing_external(_sapp_timing_t* t, double now) {
  2065. if (t->last > 0.0) {
  2066. double dur = now - t->last;
  2067. _sapp_timing_put(t, dur);
  2068. }
  2069. t->last = now;
  2070. }
  2071. _SOKOL_PRIVATE double _sapp_timing_get_avg(_sapp_timing_t* t) {
  2072. return t->avg;
  2073. }
  2074. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  2075. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2076. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  2077. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2078. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  2079. //
  2080. // >> structs
  2081. #if defined(_SAPP_MACOS)
  2082. @interface _sapp_macos_app_delegate : NSObject<NSApplicationDelegate>
  2083. @end
  2084. @interface _sapp_macos_window : NSWindow
  2085. @end
  2086. @interface _sapp_macos_window_delegate : NSObject<NSWindowDelegate>
  2087. @end
  2088. #if defined(SOKOL_METAL)
  2089. @interface _sapp_macos_view : MTKView
  2090. @end
  2091. #elif defined(SOKOL_GLCORE)
  2092. @interface _sapp_macos_view : NSOpenGLView
  2093. - (void)timerFired:(id)sender;
  2094. @end
  2095. #endif // SOKOL_GLCORE
  2096. typedef struct {
  2097. uint32_t flags_changed_store;
  2098. uint8_t mouse_buttons;
  2099. NSWindow* window;
  2100. NSTrackingArea* tracking_area;
  2101. id keyup_monitor;
  2102. _sapp_macos_app_delegate* app_dlg;
  2103. _sapp_macos_window_delegate* win_dlg;
  2104. _sapp_macos_view* view;
  2105. NSCursor* cursors[_SAPP_MOUSECURSOR_NUM];
  2106. #if defined(SOKOL_METAL)
  2107. id<MTLDevice> mtl_device;
  2108. #endif
  2109. } _sapp_macos_t;
  2110. #endif // _SAPP_MACOS
  2111. #if defined(_SAPP_IOS)
  2112. @interface _sapp_app_delegate : NSObject<UIApplicationDelegate>
  2113. @end
  2114. @interface _sapp_textfield_dlg : NSObject<UITextFieldDelegate>
  2115. - (void)keyboardWasShown:(NSNotification*)notif;
  2116. - (void)keyboardWillBeHidden:(NSNotification*)notif;
  2117. - (void)keyboardDidChangeFrame:(NSNotification*)notif;
  2118. @end
  2119. #if defined(SOKOL_METAL)
  2120. @interface _sapp_ios_view : MTKView;
  2121. @end
  2122. #else
  2123. @interface _sapp_ios_view : GLKView
  2124. @end
  2125. #endif
  2126. typedef struct {
  2127. UIWindow* window;
  2128. _sapp_ios_view* view;
  2129. UITextField* textfield;
  2130. _sapp_textfield_dlg* textfield_dlg;
  2131. #if defined(SOKOL_METAL)
  2132. UIViewController* view_ctrl;
  2133. id<MTLDevice> mtl_device;
  2134. #else
  2135. GLKViewController* view_ctrl;
  2136. EAGLContext* eagl_ctx;
  2137. #endif
  2138. bool suspended;
  2139. } _sapp_ios_t;
  2140. #endif // _SAPP_IOS
  2141. #if defined(_SAPP_EMSCRIPTEN)
  2142. #if defined(SOKOL_WGPU)
  2143. typedef struct {
  2144. WGPUInstance instance;
  2145. WGPUAdapter adapter;
  2146. WGPUDevice device;
  2147. WGPUTextureFormat render_format;
  2148. WGPUSurface surface;
  2149. WGPUSwapChain swapchain;
  2150. WGPUTexture msaa_tex;
  2151. WGPUTextureView msaa_view;
  2152. WGPUTexture depth_stencil_tex;
  2153. WGPUTextureView depth_stencil_view;
  2154. WGPUTextureView swapchain_view;
  2155. bool async_init_done;
  2156. } _sapp_wgpu_t;
  2157. #endif
  2158. typedef struct {
  2159. bool mouse_lock_requested;
  2160. uint16_t mouse_buttons;
  2161. } _sapp_emsc_t;
  2162. #endif // _SAPP_EMSCRIPTEN
  2163. #if defined(SOKOL_D3D11) && defined(_SAPP_WIN32)
  2164. typedef struct {
  2165. ID3D11Device* device;
  2166. ID3D11DeviceContext* device_context;
  2167. ID3D11Texture2D* rt;
  2168. ID3D11RenderTargetView* rtv;
  2169. ID3D11Texture2D* msaa_rt;
  2170. ID3D11RenderTargetView* msaa_rtv;
  2171. ID3D11Texture2D* ds;
  2172. ID3D11DepthStencilView* dsv;
  2173. DXGI_SWAP_CHAIN_DESC swap_chain_desc;
  2174. IDXGISwapChain* swap_chain;
  2175. IDXGIDevice1* dxgi_device;
  2176. bool use_dxgi_frame_stats;
  2177. UINT sync_refresh_count;
  2178. } _sapp_d3d11_t;
  2179. #endif
  2180. #if defined(_SAPP_WIN32)
  2181. #ifndef DPI_ENUMS_DECLARED
  2182. typedef enum PROCESS_DPI_AWARENESS
  2183. {
  2184. PROCESS_DPI_UNAWARE = 0,
  2185. PROCESS_SYSTEM_DPI_AWARE = 1,
  2186. PROCESS_PER_MONITOR_DPI_AWARE = 2
  2187. } PROCESS_DPI_AWARENESS;
  2188. typedef enum MONITOR_DPI_TYPE {
  2189. MDT_EFFECTIVE_DPI = 0,
  2190. MDT_ANGULAR_DPI = 1,
  2191. MDT_RAW_DPI = 2,
  2192. MDT_DEFAULT = MDT_EFFECTIVE_DPI
  2193. } MONITOR_DPI_TYPE;
  2194. #endif // DPI_ENUMS_DECLARED
  2195. typedef struct {
  2196. bool aware;
  2197. float content_scale;
  2198. float window_scale;
  2199. float mouse_scale;
  2200. } _sapp_win32_dpi_t;
  2201. typedef struct {
  2202. HWND hwnd;
  2203. HMONITOR hmonitor;
  2204. HDC dc;
  2205. HICON big_icon;
  2206. HICON small_icon;
  2207. HCURSOR cursors[_SAPP_MOUSECURSOR_NUM];
  2208. UINT orig_codepage;
  2209. LONG mouse_locked_x, mouse_locked_y;
  2210. RECT stored_window_rect; // used to restore window pos/size when toggling fullscreen => windowed
  2211. bool is_win10_or_greater;
  2212. bool in_create_window;
  2213. bool iconified;
  2214. bool mouse_tracked;
  2215. uint8_t mouse_capture_mask;
  2216. _sapp_win32_dpi_t dpi;
  2217. bool raw_input_mousepos_valid;
  2218. LONG raw_input_mousepos_x;
  2219. LONG raw_input_mousepos_y;
  2220. uint8_t raw_input_data[256];
  2221. } _sapp_win32_t;
  2222. #if defined(SOKOL_GLCORE)
  2223. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  2224. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  2225. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  2226. #define WGL_PIXEL_TYPE_ARB 0x2013
  2227. #define WGL_TYPE_RGBA_ARB 0x202b
  2228. #define WGL_ACCELERATION_ARB 0x2003
  2229. #define WGL_NO_ACCELERATION_ARB 0x2025
  2230. #define WGL_RED_BITS_ARB 0x2015
  2231. #define WGL_GREEN_BITS_ARB 0x2017
  2232. #define WGL_BLUE_BITS_ARB 0x2019
  2233. #define WGL_ALPHA_BITS_ARB 0x201b
  2234. #define WGL_DEPTH_BITS_ARB 0x2022
  2235. #define WGL_STENCIL_BITS_ARB 0x2023
  2236. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  2237. #define WGL_SAMPLES_ARB 0x2042
  2238. #define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
  2239. #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  2240. #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
  2241. #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  2242. #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
  2243. #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
  2244. #define WGL_CONTEXT_FLAGS_ARB 0x2094
  2245. #define ERROR_INVALID_VERSION_ARB 0x2095
  2246. #define ERROR_INVALID_PROFILE_ARB 0x2096
  2247. #define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
  2248. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int);
  2249. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC)(HDC,int,int,UINT,const int*,int*);
  2250. typedef const char* (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void);
  2251. typedef const char* (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC)(HDC);
  2252. typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC,HGLRC,const int*);
  2253. typedef HGLRC (WINAPI * PFN_wglCreateContext)(HDC);
  2254. typedef BOOL (WINAPI * PFN_wglDeleteContext)(HGLRC);
  2255. typedef PROC (WINAPI * PFN_wglGetProcAddress)(LPCSTR);
  2256. typedef HDC (WINAPI * PFN_wglGetCurrentDC)(void);
  2257. typedef BOOL (WINAPI * PFN_wglMakeCurrent)(HDC,HGLRC);
  2258. typedef struct {
  2259. HINSTANCE opengl32;
  2260. HGLRC gl_ctx;
  2261. PFN_wglCreateContext CreateContext;
  2262. PFN_wglDeleteContext DeleteContext;
  2263. PFN_wglGetProcAddress GetProcAddress;
  2264. PFN_wglGetCurrentDC GetCurrentDC;
  2265. PFN_wglMakeCurrent MakeCurrent;
  2266. PFNWGLSWAPINTERVALEXTPROC SwapIntervalEXT;
  2267. PFNWGLGETPIXELFORMATATTRIBIVARBPROC GetPixelFormatAttribivARB;
  2268. PFNWGLGETEXTENSIONSSTRINGEXTPROC GetExtensionsStringEXT;
  2269. PFNWGLGETEXTENSIONSSTRINGARBPROC GetExtensionsStringARB;
  2270. PFNWGLCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
  2271. // special case glGetIntegerv
  2272. void (WINAPI *GetIntegerv)(uint32_t pname, int32_t* data);
  2273. bool ext_swap_control;
  2274. bool arb_multisample;
  2275. bool arb_pixel_format;
  2276. bool arb_create_context;
  2277. bool arb_create_context_profile;
  2278. HWND msg_hwnd;
  2279. HDC msg_dc;
  2280. } _sapp_wgl_t;
  2281. #endif // SOKOL_GLCORE
  2282. #endif // _SAPP_WIN32
  2283. #if defined(_SAPP_ANDROID)
  2284. typedef enum {
  2285. _SOKOL_ANDROID_MSG_CREATE,
  2286. _SOKOL_ANDROID_MSG_RESUME,
  2287. _SOKOL_ANDROID_MSG_PAUSE,
  2288. _SOKOL_ANDROID_MSG_FOCUS,
  2289. _SOKOL_ANDROID_MSG_NO_FOCUS,
  2290. _SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW,
  2291. _SOKOL_ANDROID_MSG_SET_INPUT_QUEUE,
  2292. _SOKOL_ANDROID_MSG_DESTROY,
  2293. } _sapp_android_msg_t;
  2294. typedef struct {
  2295. pthread_t thread;
  2296. pthread_mutex_t mutex;
  2297. pthread_cond_t cond;
  2298. int read_from_main_fd;
  2299. int write_from_main_fd;
  2300. } _sapp_android_pt_t;
  2301. typedef struct {
  2302. ANativeWindow* window;
  2303. AInputQueue* input;
  2304. } _sapp_android_resources_t;
  2305. typedef struct {
  2306. ANativeActivity* activity;
  2307. _sapp_android_pt_t pt;
  2308. _sapp_android_resources_t pending;
  2309. _sapp_android_resources_t current;
  2310. ALooper* looper;
  2311. bool is_thread_started;
  2312. bool is_thread_stopping;
  2313. bool is_thread_stopped;
  2314. bool has_created;
  2315. bool has_resumed;
  2316. bool has_focus;
  2317. EGLConfig config;
  2318. EGLDisplay display;
  2319. EGLContext context;
  2320. EGLSurface surface;
  2321. } _sapp_android_t;
  2322. #endif // _SAPP_ANDROID
  2323. #if defined(_SAPP_LINUX)
  2324. #define _SAPP_X11_XDND_VERSION (5)
  2325. #define _SAPP_X11_MAX_X11_KEYCODES (256)
  2326. #define GLX_VENDOR 1
  2327. #define GLX_RGBA_BIT 0x00000001
  2328. #define GLX_WINDOW_BIT 0x00000001
  2329. #define GLX_DRAWABLE_TYPE 0x8010
  2330. #define GLX_RENDER_TYPE 0x8011
  2331. #define GLX_DOUBLEBUFFER 5
  2332. #define GLX_RED_SIZE 8
  2333. #define GLX_GREEN_SIZE 9
  2334. #define GLX_BLUE_SIZE 10
  2335. #define GLX_ALPHA_SIZE 11
  2336. #define GLX_DEPTH_SIZE 12
  2337. #define GLX_STENCIL_SIZE 13
  2338. #define GLX_SAMPLES 0x186a1
  2339. #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  2340. #define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
  2341. #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  2342. #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
  2343. #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
  2344. #define GLX_CONTEXT_FLAGS_ARB 0x2094
  2345. typedef XID GLXWindow;
  2346. typedef XID GLXDrawable;
  2347. typedef struct __GLXFBConfig* GLXFBConfig;
  2348. typedef struct __GLXcontext* GLXContext;
  2349. typedef void (*__GLXextproc)(void);
  2350. typedef int (*PFNGLXGETFBCONFIGATTRIBPROC)(Display*,GLXFBConfig,int,int*);
  2351. typedef const char* (*PFNGLXGETCLIENTSTRINGPROC)(Display*,int);
  2352. typedef Bool (*PFNGLXQUERYEXTENSIONPROC)(Display*,int*,int*);
  2353. typedef Bool (*PFNGLXQUERYVERSIONPROC)(Display*,int*,int*);
  2354. typedef void (*PFNGLXDESTROYCONTEXTPROC)(Display*,GLXContext);
  2355. typedef Bool (*PFNGLXMAKECURRENTPROC)(Display*,GLXDrawable,GLXContext);
  2356. typedef void (*PFNGLXSWAPBUFFERSPROC)(Display*,GLXDrawable);
  2357. typedef const char* (*PFNGLXQUERYEXTENSIONSSTRINGPROC)(Display*,int);
  2358. typedef GLXFBConfig* (*PFNGLXGETFBCONFIGSPROC)(Display*,int,int*);
  2359. typedef __GLXextproc (* PFNGLXGETPROCADDRESSPROC)(const char *procName);
  2360. typedef void (*PFNGLXSWAPINTERVALEXTPROC)(Display*,GLXDrawable,int);
  2361. typedef XVisualInfo* (*PFNGLXGETVISUALFROMFBCONFIGPROC)(Display*,GLXFBConfig);
  2362. typedef GLXWindow (*PFNGLXCREATEWINDOWPROC)(Display*,GLXFBConfig,Window,const int*);
  2363. typedef void (*PFNGLXDESTROYWINDOWPROC)(Display*,GLXWindow);
  2364. typedef int (*PFNGLXSWAPINTERVALMESAPROC)(int);
  2365. typedef GLXContext (*PFNGLXCREATECONTEXTATTRIBSARBPROC)(Display*,GLXFBConfig,GLXContext,Bool,const int*);
  2366. typedef struct {
  2367. bool available;
  2368. int major_opcode;
  2369. int event_base;
  2370. int error_base;
  2371. int major;
  2372. int minor;
  2373. } _sapp_xi_t;
  2374. typedef struct {
  2375. int version;
  2376. Window source;
  2377. Atom format;
  2378. Atom XdndAware;
  2379. Atom XdndEnter;
  2380. Atom XdndPosition;
  2381. Atom XdndStatus;
  2382. Atom XdndActionCopy;
  2383. Atom XdndDrop;
  2384. Atom XdndFinished;
  2385. Atom XdndSelection;
  2386. Atom XdndTypeList;
  2387. Atom text_uri_list;
  2388. } _sapp_xdnd_t;
  2389. typedef struct {
  2390. uint8_t mouse_buttons;
  2391. Display* display;
  2392. int screen;
  2393. Window root;
  2394. Colormap colormap;
  2395. Window window;
  2396. Cursor hidden_cursor;
  2397. Cursor cursors[_SAPP_MOUSECURSOR_NUM];
  2398. int window_state;
  2399. float dpi;
  2400. unsigned char error_code;
  2401. Atom UTF8_STRING;
  2402. Atom CLIPBOARD;
  2403. Atom TARGETS;
  2404. Atom WM_PROTOCOLS;
  2405. Atom WM_DELETE_WINDOW;
  2406. Atom WM_STATE;
  2407. Atom NET_WM_NAME;
  2408. Atom NET_WM_ICON_NAME;
  2409. Atom NET_WM_ICON;
  2410. Atom NET_WM_STATE;
  2411. Atom NET_WM_STATE_FULLSCREEN;
  2412. _sapp_xi_t xi;
  2413. _sapp_xdnd_t xdnd;
  2414. // XLib manual says keycodes are in the range [8, 255] inclusive.
  2415. // https://tronche.com/gui/x/xlib/input/keyboard-encoding.html
  2416. bool key_repeat[_SAPP_X11_MAX_X11_KEYCODES];
  2417. } _sapp_x11_t;
  2418. #if defined(_SAPP_GLX)
  2419. typedef struct {
  2420. void* libgl;
  2421. int major;
  2422. int minor;
  2423. int event_base;
  2424. int error_base;
  2425. GLXContext ctx;
  2426. GLXWindow window;
  2427. // GLX 1.3 functions
  2428. PFNGLXGETFBCONFIGSPROC GetFBConfigs;
  2429. PFNGLXGETFBCONFIGATTRIBPROC GetFBConfigAttrib;
  2430. PFNGLXGETCLIENTSTRINGPROC GetClientString;
  2431. PFNGLXQUERYEXTENSIONPROC QueryExtension;
  2432. PFNGLXQUERYVERSIONPROC QueryVersion;
  2433. PFNGLXDESTROYCONTEXTPROC DestroyContext;
  2434. PFNGLXMAKECURRENTPROC MakeCurrent;
  2435. PFNGLXSWAPBUFFERSPROC SwapBuffers;
  2436. PFNGLXQUERYEXTENSIONSSTRINGPROC QueryExtensionsString;
  2437. PFNGLXGETVISUALFROMFBCONFIGPROC GetVisualFromFBConfig;
  2438. PFNGLXCREATEWINDOWPROC CreateWindow;
  2439. PFNGLXDESTROYWINDOWPROC DestroyWindow;
  2440. // GLX 1.4 and extension functions
  2441. PFNGLXGETPROCADDRESSPROC GetProcAddress;
  2442. PFNGLXGETPROCADDRESSPROC GetProcAddressARB;
  2443. PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT;
  2444. PFNGLXSWAPINTERVALMESAPROC SwapIntervalMESA;
  2445. PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
  2446. // special case glGetIntegerv
  2447. void (*GetIntegerv)(uint32_t pname, int32_t* data);
  2448. // extension availability
  2449. bool EXT_swap_control;
  2450. bool MESA_swap_control;
  2451. bool ARB_multisample;
  2452. bool ARB_create_context;
  2453. bool ARB_create_context_profile;
  2454. } _sapp_glx_t;
  2455. #else
  2456. typedef struct {
  2457. EGLDisplay display;
  2458. EGLContext context;
  2459. EGLSurface surface;
  2460. } _sapp_egl_t;
  2461. #endif // _SAPP_GLX
  2462. #endif // _SAPP_LINUX
  2463. #if defined(_SAPP_ANY_GL)
  2464. typedef struct {
  2465. uint32_t framebuffer;
  2466. } _sapp_gl_t;
  2467. #endif
  2468. typedef struct {
  2469. bool enabled;
  2470. int buf_size;
  2471. char* buffer;
  2472. } _sapp_clipboard_t;
  2473. typedef struct {
  2474. bool enabled;
  2475. int max_files;
  2476. int max_path_length;
  2477. int num_files;
  2478. int buf_size;
  2479. char* buffer;
  2480. } _sapp_drop_t;
  2481. typedef struct {
  2482. float x, y;
  2483. float dx, dy;
  2484. bool shown;
  2485. bool locked;
  2486. bool pos_valid;
  2487. sapp_mouse_cursor current_cursor;
  2488. } _sapp_mouse_t;
  2489. typedef struct {
  2490. sapp_desc desc;
  2491. bool valid;
  2492. bool fullscreen;
  2493. bool first_frame;
  2494. bool init_called;
  2495. bool cleanup_called;
  2496. bool quit_requested;
  2497. bool quit_ordered;
  2498. bool event_consumed;
  2499. bool html5_ask_leave_site;
  2500. bool onscreen_keyboard_shown;
  2501. int window_width;
  2502. int window_height;
  2503. int framebuffer_width;
  2504. int framebuffer_height;
  2505. int sample_count;
  2506. int swap_interval;
  2507. float dpi_scale;
  2508. uint64_t frame_count;
  2509. _sapp_timing_t timing;
  2510. sapp_event event;
  2511. _sapp_mouse_t mouse;
  2512. _sapp_clipboard_t clipboard;
  2513. _sapp_drop_t drop;
  2514. sapp_icon_desc default_icon_desc;
  2515. uint32_t* default_icon_pixels;
  2516. #if defined(_SAPP_MACOS)
  2517. _sapp_macos_t macos;
  2518. #elif defined(_SAPP_IOS)
  2519. _sapp_ios_t ios;
  2520. #elif defined(_SAPP_EMSCRIPTEN)
  2521. _sapp_emsc_t emsc;
  2522. #if defined(SOKOL_WGPU)
  2523. _sapp_wgpu_t wgpu;
  2524. #endif
  2525. #elif defined(_SAPP_WIN32)
  2526. _sapp_win32_t win32;
  2527. #if defined(SOKOL_D3D11)
  2528. _sapp_d3d11_t d3d11;
  2529. #elif defined(SOKOL_GLCORE)
  2530. _sapp_wgl_t wgl;
  2531. #endif
  2532. #elif defined(_SAPP_ANDROID)
  2533. _sapp_android_t android;
  2534. #elif defined(_SAPP_LINUX)
  2535. _sapp_x11_t x11;
  2536. #if defined(_SAPP_GLX)
  2537. _sapp_glx_t glx;
  2538. #else
  2539. _sapp_egl_t egl;
  2540. #endif
  2541. #endif
  2542. #if defined(_SAPP_ANY_GL)
  2543. _sapp_gl_t gl;
  2544. #endif
  2545. char html5_canvas_selector[_SAPP_MAX_TITLE_LENGTH];
  2546. char window_title[_SAPP_MAX_TITLE_LENGTH]; // UTF-8
  2547. wchar_t window_title_wide[_SAPP_MAX_TITLE_LENGTH]; // UTF-32 or UCS-2 */
  2548. sapp_keycode keycodes[SAPP_MAX_KEYCODES];
  2549. } _sapp_t;
  2550. static _sapp_t _sapp;
  2551. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  2552. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  2553. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  2554. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2555. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  2556. //
  2557. // >>logging
  2558. #if defined(SOKOL_DEBUG)
  2559. #define _SAPP_LOGITEM_XMACRO(item,msg) #item ": " msg,
  2560. static const char* _sapp_log_messages[] = {
  2561. _SAPP_LOG_ITEMS
  2562. };
  2563. #undef _SAPP_LOGITEM_XMACRO
  2564. #endif // SOKOL_DEBUG
  2565. #define _SAPP_PANIC(code) _sapp_log(SAPP_LOGITEM_ ##code, 0, 0, __LINE__)
  2566. #define _SAPP_ERROR(code) _sapp_log(SAPP_LOGITEM_ ##code, 1, 0, __LINE__)
  2567. #define _SAPP_WARN(code) _sapp_log(SAPP_LOGITEM_ ##code, 2, 0, __LINE__)
  2568. #define _SAPP_INFO(code) _sapp_log(SAPP_LOGITEM_ ##code, 3, 0, __LINE__)
  2569. static void _sapp_log(sapp_log_item log_item, uint32_t log_level, const char* msg, uint32_t line_nr) {
  2570. if (_sapp.desc.logger.func) {
  2571. const char* filename = 0;
  2572. #if defined(SOKOL_DEBUG)
  2573. filename = __FILE__;
  2574. if (0 == msg) {
  2575. msg = _sapp_log_messages[log_item];
  2576. }
  2577. #endif
  2578. _sapp.desc.logger.func("sapp", log_level, log_item, msg, line_nr, filename, _sapp.desc.logger.user_data);
  2579. }
  2580. else {
  2581. // for log level PANIC it would be 'undefined behaviour' to continue
  2582. if (log_level == 0) {
  2583. abort();
  2584. }
  2585. }
  2586. }
  2587. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  2588. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  2589. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  2590. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2591. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  2592. //
  2593. // >>memory
  2594. _SOKOL_PRIVATE void _sapp_clear(void* ptr, size_t size) {
  2595. SOKOL_ASSERT(ptr && (size > 0));
  2596. memset(ptr, 0, size);
  2597. }
  2598. _SOKOL_PRIVATE void* _sapp_malloc(size_t size) {
  2599. SOKOL_ASSERT(size > 0);
  2600. void* ptr;
  2601. if (_sapp.desc.allocator.alloc_fn) {
  2602. ptr = _sapp.desc.allocator.alloc_fn(size, _sapp.desc.allocator.user_data);
  2603. } else {
  2604. ptr = malloc(size);
  2605. }
  2606. if (0 == ptr) {
  2607. _SAPP_PANIC(MALLOC_FAILED);
  2608. }
  2609. return ptr;
  2610. }
  2611. _SOKOL_PRIVATE void* _sapp_malloc_clear(size_t size) {
  2612. void* ptr = _sapp_malloc(size);
  2613. _sapp_clear(ptr, size);
  2614. return ptr;
  2615. }
  2616. _SOKOL_PRIVATE void _sapp_free(void* ptr) {
  2617. if (_sapp.desc.allocator.free_fn) {
  2618. _sapp.desc.allocator.free_fn(ptr, _sapp.desc.allocator.user_data);
  2619. }
  2620. else {
  2621. free(ptr);
  2622. }
  2623. }
  2624. // ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  2625. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2626. // ███████ █████ ██ ██████ █████ ██████ ███████
  2627. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2628. // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  2629. //
  2630. // >>helpers
  2631. _SOKOL_PRIVATE void _sapp_call_init(void) {
  2632. if (_sapp.desc.init_cb) {
  2633. _sapp.desc.init_cb();
  2634. }
  2635. else if (_sapp.desc.init_userdata_cb) {
  2636. _sapp.desc.init_userdata_cb(_sapp.desc.user_data);
  2637. }
  2638. _sapp.init_called = true;
  2639. }
  2640. _SOKOL_PRIVATE void _sapp_call_frame(void) {
  2641. if (_sapp.init_called && !_sapp.cleanup_called) {
  2642. if (_sapp.desc.frame_cb) {
  2643. _sapp.desc.frame_cb();
  2644. }
  2645. else if (_sapp.desc.frame_userdata_cb) {
  2646. _sapp.desc.frame_userdata_cb(_sapp.desc.user_data);
  2647. }
  2648. }
  2649. }
  2650. _SOKOL_PRIVATE void _sapp_call_cleanup(void) {
  2651. if (!_sapp.cleanup_called) {
  2652. if (_sapp.desc.cleanup_cb) {
  2653. _sapp.desc.cleanup_cb();
  2654. }
  2655. else if (_sapp.desc.cleanup_userdata_cb) {
  2656. _sapp.desc.cleanup_userdata_cb(_sapp.desc.user_data);
  2657. }
  2658. _sapp.cleanup_called = true;
  2659. }
  2660. }
  2661. _SOKOL_PRIVATE bool _sapp_call_event(const sapp_event* e) {
  2662. if (!_sapp.cleanup_called) {
  2663. if (_sapp.desc.event_cb) {
  2664. _sapp.desc.event_cb(e);
  2665. }
  2666. else if (_sapp.desc.event_userdata_cb) {
  2667. _sapp.desc.event_userdata_cb(e, _sapp.desc.user_data);
  2668. }
  2669. }
  2670. if (_sapp.event_consumed) {
  2671. _sapp.event_consumed = false;
  2672. return true;
  2673. }
  2674. else {
  2675. return false;
  2676. }
  2677. }
  2678. _SOKOL_PRIVATE char* _sapp_dropped_file_path_ptr(int index) {
  2679. SOKOL_ASSERT(_sapp.drop.buffer);
  2680. SOKOL_ASSERT((index >= 0) && (index <= _sapp.drop.max_files));
  2681. int offset = index * _sapp.drop.max_path_length;
  2682. SOKOL_ASSERT(offset < _sapp.drop.buf_size);
  2683. return &_sapp.drop.buffer[offset];
  2684. }
  2685. /* Copy a string into a fixed size buffer with guaranteed zero-
  2686. termination.
  2687. Return false if the string didn't fit into the buffer and had to be clamped.
  2688. FIXME: Currently UTF-8 strings might become invalid if the string
  2689. is clamped, because the last zero-byte might be written into
  2690. the middle of a multi-byte sequence.
  2691. */
  2692. _SOKOL_PRIVATE bool _sapp_strcpy(const char* src, char* dst, int max_len) {
  2693. SOKOL_ASSERT(src && dst && (max_len > 0));
  2694. char* const end = &(dst[max_len-1]);
  2695. char c = 0;
  2696. for (int i = 0; i < max_len; i++) {
  2697. c = *src;
  2698. if (c != 0) {
  2699. src++;
  2700. }
  2701. *dst++ = c;
  2702. }
  2703. /* truncated? */
  2704. if (c != 0) {
  2705. *end = 0;
  2706. return false;
  2707. }
  2708. else {
  2709. return true;
  2710. }
  2711. }
  2712. _SOKOL_PRIVATE sapp_desc _sapp_desc_defaults(const sapp_desc* desc) {
  2713. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  2714. sapp_desc res = *desc;
  2715. res.sample_count = _sapp_def(res.sample_count, 1);
  2716. res.swap_interval = _sapp_def(res.swap_interval, 1);
  2717. // NOTE: can't patch the default for gl_major_version and gl_minor_version
  2718. // independently, because a desired version 4.0 would be patched to 4.2
  2719. // (or expressed differently: zero is a valid value for gl_minor_version
  2720. // and can't be used to indicate 'default')
  2721. if (0 == res.gl_major_version) {
  2722. #if defined(_SAPP_APPLE)
  2723. res.gl_major_version = 4;
  2724. res.gl_minor_version = 1;
  2725. #else
  2726. res.gl_major_version = 4;
  2727. res.gl_minor_version = 3;
  2728. #endif
  2729. }
  2730. res.html5_canvas_name = _sapp_def(res.html5_canvas_name, "canvas");
  2731. res.clipboard_size = _sapp_def(res.clipboard_size, 8192);
  2732. res.max_dropped_files = _sapp_def(res.max_dropped_files, 1);
  2733. res.max_dropped_file_path_length = _sapp_def(res.max_dropped_file_path_length, 2048);
  2734. res.window_title = _sapp_def(res.window_title, "sokol_app");
  2735. return res;
  2736. }
  2737. _SOKOL_PRIVATE void _sapp_init_state(const sapp_desc* desc) {
  2738. SOKOL_ASSERT(desc);
  2739. SOKOL_ASSERT(desc->width >= 0);
  2740. SOKOL_ASSERT(desc->height >= 0);
  2741. SOKOL_ASSERT(desc->sample_count >= 0);
  2742. SOKOL_ASSERT(desc->swap_interval >= 0);
  2743. SOKOL_ASSERT(desc->clipboard_size >= 0);
  2744. SOKOL_ASSERT(desc->max_dropped_files >= 0);
  2745. SOKOL_ASSERT(desc->max_dropped_file_path_length >= 0);
  2746. _SAPP_CLEAR_ARC_STRUCT(_sapp_t, _sapp);
  2747. _sapp.desc = _sapp_desc_defaults(desc);
  2748. _sapp.first_frame = true;
  2749. // NOTE: _sapp.desc.width/height may be 0! Platform backends need to deal with this
  2750. _sapp.window_width = _sapp.desc.width;
  2751. _sapp.window_height = _sapp.desc.height;
  2752. _sapp.framebuffer_width = _sapp.window_width;
  2753. _sapp.framebuffer_height = _sapp.window_height;
  2754. _sapp.sample_count = _sapp.desc.sample_count;
  2755. _sapp.swap_interval = _sapp.desc.swap_interval;
  2756. _sapp.html5_canvas_selector[0] = '#';
  2757. _sapp_strcpy(_sapp.desc.html5_canvas_name, &_sapp.html5_canvas_selector[1], sizeof(_sapp.html5_canvas_selector) - 1);
  2758. _sapp.desc.html5_canvas_name = &_sapp.html5_canvas_selector[1];
  2759. _sapp.html5_ask_leave_site = _sapp.desc.html5_ask_leave_site;
  2760. _sapp.clipboard.enabled = _sapp.desc.enable_clipboard;
  2761. if (_sapp.clipboard.enabled) {
  2762. _sapp.clipboard.buf_size = _sapp.desc.clipboard_size;
  2763. _sapp.clipboard.buffer = (char*) _sapp_malloc_clear((size_t)_sapp.clipboard.buf_size);
  2764. }
  2765. _sapp.drop.enabled = _sapp.desc.enable_dragndrop;
  2766. if (_sapp.drop.enabled) {
  2767. _sapp.drop.max_files = _sapp.desc.max_dropped_files;
  2768. _sapp.drop.max_path_length = _sapp.desc.max_dropped_file_path_length;
  2769. _sapp.drop.buf_size = _sapp.drop.max_files * _sapp.drop.max_path_length;
  2770. _sapp.drop.buffer = (char*) _sapp_malloc_clear((size_t)_sapp.drop.buf_size);
  2771. }
  2772. _sapp_strcpy(_sapp.desc.window_title, _sapp.window_title, sizeof(_sapp.window_title));
  2773. _sapp.desc.window_title = _sapp.window_title;
  2774. _sapp.dpi_scale = 1.0f;
  2775. _sapp.fullscreen = _sapp.desc.fullscreen;
  2776. _sapp.mouse.shown = true;
  2777. _sapp_timing_init(&_sapp.timing);
  2778. }
  2779. _SOKOL_PRIVATE void _sapp_discard_state(void) {
  2780. if (_sapp.clipboard.enabled) {
  2781. SOKOL_ASSERT(_sapp.clipboard.buffer);
  2782. _sapp_free((void*)_sapp.clipboard.buffer);
  2783. }
  2784. if (_sapp.drop.enabled) {
  2785. SOKOL_ASSERT(_sapp.drop.buffer);
  2786. _sapp_free((void*)_sapp.drop.buffer);
  2787. }
  2788. if (_sapp.default_icon_pixels) {
  2789. _sapp_free((void*)_sapp.default_icon_pixels);
  2790. }
  2791. _SAPP_CLEAR_ARC_STRUCT(_sapp_t, _sapp);
  2792. }
  2793. _SOKOL_PRIVATE void _sapp_init_event(sapp_event_type type) {
  2794. _sapp_clear(&_sapp.event, sizeof(_sapp.event));
  2795. _sapp.event.type = type;
  2796. _sapp.event.frame_count = _sapp.frame_count;
  2797. _sapp.event.mouse_button = SAPP_MOUSEBUTTON_INVALID;
  2798. _sapp.event.window_width = _sapp.window_width;
  2799. _sapp.event.window_height = _sapp.window_height;
  2800. _sapp.event.framebuffer_width = _sapp.framebuffer_width;
  2801. _sapp.event.framebuffer_height = _sapp.framebuffer_height;
  2802. _sapp.event.mouse_x = _sapp.mouse.x;
  2803. _sapp.event.mouse_y = _sapp.mouse.y;
  2804. _sapp.event.mouse_dx = _sapp.mouse.dx;
  2805. _sapp.event.mouse_dy = _sapp.mouse.dy;
  2806. }
  2807. _SOKOL_PRIVATE bool _sapp_events_enabled(void) {
  2808. /* only send events when an event callback is set, and the init function was called */
  2809. return (_sapp.desc.event_cb || _sapp.desc.event_userdata_cb) && _sapp.init_called;
  2810. }
  2811. _SOKOL_PRIVATE sapp_keycode _sapp_translate_key(int scan_code) {
  2812. if ((scan_code >= 0) && (scan_code < SAPP_MAX_KEYCODES)) {
  2813. return _sapp.keycodes[scan_code];
  2814. }
  2815. else {
  2816. return SAPP_KEYCODE_INVALID;
  2817. }
  2818. }
  2819. _SOKOL_PRIVATE void _sapp_clear_drop_buffer(void) {
  2820. if (_sapp.drop.enabled) {
  2821. SOKOL_ASSERT(_sapp.drop.buffer);
  2822. _sapp_clear(_sapp.drop.buffer, (size_t)_sapp.drop.buf_size);
  2823. }
  2824. }
  2825. _SOKOL_PRIVATE void _sapp_frame(void) {
  2826. if (_sapp.first_frame) {
  2827. _sapp.first_frame = false;
  2828. _sapp_call_init();
  2829. }
  2830. _sapp_call_frame();
  2831. _sapp.frame_count++;
  2832. }
  2833. _SOKOL_PRIVATE bool _sapp_image_validate(const sapp_image_desc* desc) {
  2834. SOKOL_ASSERT(desc->width > 0);
  2835. SOKOL_ASSERT(desc->height > 0);
  2836. SOKOL_ASSERT(desc->pixels.ptr != 0);
  2837. SOKOL_ASSERT(desc->pixels.size > 0);
  2838. const size_t wh_size = (size_t)(desc->width * desc->height) * sizeof(uint32_t);
  2839. if (wh_size != desc->pixels.size) {
  2840. _SAPP_ERROR(IMAGE_DATA_SIZE_MISMATCH);
  2841. return false;
  2842. }
  2843. return true;
  2844. }
  2845. _SOKOL_PRIVATE int _sapp_image_bestmatch(const sapp_image_desc image_descs[], int num_images, int width, int height) {
  2846. int least_diff = 0x7FFFFFFF;
  2847. int least_index = 0;
  2848. for (int i = 0; i < num_images; i++) {
  2849. int diff = (image_descs[i].width * image_descs[i].height) - (width * height);
  2850. if (diff < 0) {
  2851. diff = -diff;
  2852. }
  2853. if (diff < least_diff) {
  2854. least_diff = diff;
  2855. least_index = i;
  2856. }
  2857. }
  2858. return least_index;
  2859. }
  2860. _SOKOL_PRIVATE int _sapp_icon_num_images(const sapp_icon_desc* desc) {
  2861. int index = 0;
  2862. for (; index < SAPP_MAX_ICONIMAGES; index++) {
  2863. if (0 == desc->images[index].pixels.ptr) {
  2864. break;
  2865. }
  2866. }
  2867. return index;
  2868. }
  2869. _SOKOL_PRIVATE bool _sapp_validate_icon_desc(const sapp_icon_desc* desc, int num_images) {
  2870. SOKOL_ASSERT(num_images <= SAPP_MAX_ICONIMAGES);
  2871. for (int i = 0; i < num_images; i++) {
  2872. const sapp_image_desc* img_desc = &desc->images[i];
  2873. if (!_sapp_image_validate(img_desc)) {
  2874. return false;
  2875. }
  2876. }
  2877. return true;
  2878. }
  2879. _SOKOL_PRIVATE void _sapp_setup_default_icon(void) {
  2880. SOKOL_ASSERT(0 == _sapp.default_icon_pixels);
  2881. const int num_icons = 3;
  2882. const int icon_sizes[3] = { 16, 32, 64 }; // must be multiple of 8!
  2883. // allocate a pixel buffer for all icon pixels
  2884. int all_num_pixels = 0;
  2885. for (int i = 0; i < num_icons; i++) {
  2886. all_num_pixels += icon_sizes[i] * icon_sizes[i];
  2887. }
  2888. _sapp.default_icon_pixels = (uint32_t*) _sapp_malloc_clear((size_t)all_num_pixels * sizeof(uint32_t));
  2889. // initialize default_icon_desc struct
  2890. uint32_t* dst = _sapp.default_icon_pixels;
  2891. const uint32_t* dst_end = dst + all_num_pixels;
  2892. (void)dst_end; // silence unused warning in release mode
  2893. for (int i = 0; i < num_icons; i++) {
  2894. const int dim = (int) icon_sizes[i];
  2895. const int num_pixels = dim * dim;
  2896. sapp_image_desc* img_desc = &_sapp.default_icon_desc.images[i];
  2897. img_desc->width = dim;
  2898. img_desc->height = dim;
  2899. img_desc->pixels.ptr = dst;
  2900. img_desc->pixels.size = (size_t)num_pixels * sizeof(uint32_t);
  2901. dst += num_pixels;
  2902. }
  2903. SOKOL_ASSERT(dst == dst_end);
  2904. // Amstrad CPC font 'S'
  2905. const uint8_t tile[8] = {
  2906. 0x3C,
  2907. 0x66,
  2908. 0x60,
  2909. 0x3C,
  2910. 0x06,
  2911. 0x66,
  2912. 0x3C,
  2913. 0x00,
  2914. };
  2915. // rainbow colors
  2916. const uint32_t colors[8] = {
  2917. 0xFF4370FF,
  2918. 0xFF26A7FF,
  2919. 0xFF58EEFF,
  2920. 0xFF57E1D4,
  2921. 0xFF65CC9C,
  2922. 0xFF6ABB66,
  2923. 0xFFF5A542,
  2924. 0xFFC2577E,
  2925. };
  2926. dst = _sapp.default_icon_pixels;
  2927. const uint32_t blank = 0x00FFFFFF;
  2928. const uint32_t shadow = 0xFF000000;
  2929. for (int i = 0; i < num_icons; i++) {
  2930. const int dim = icon_sizes[i];
  2931. SOKOL_ASSERT((dim % 8) == 0);
  2932. const int scale = dim / 8;
  2933. for (int ty = 0, y = 0; ty < 8; ty++) {
  2934. const uint32_t color = colors[ty];
  2935. for (int sy = 0; sy < scale; sy++, y++) {
  2936. uint8_t bits = tile[ty];
  2937. for (int tx = 0, x = 0; tx < 8; tx++, bits<<=1) {
  2938. uint32_t pixel = (0 == (bits & 0x80)) ? blank : color;
  2939. for (int sx = 0; sx < scale; sx++, x++) {
  2940. SOKOL_ASSERT(dst < dst_end);
  2941. *dst++ = pixel;
  2942. }
  2943. }
  2944. }
  2945. }
  2946. }
  2947. SOKOL_ASSERT(dst == dst_end);
  2948. // right shadow
  2949. dst = _sapp.default_icon_pixels;
  2950. for (int i = 0; i < num_icons; i++) {
  2951. const int dim = icon_sizes[i];
  2952. for (int y = 0; y < dim; y++) {
  2953. uint32_t prev_color = blank;
  2954. for (int x = 0; x < dim; x++) {
  2955. const int dst_index = y * dim + x;
  2956. const uint32_t cur_color = dst[dst_index];
  2957. if ((cur_color == blank) && (prev_color != blank)) {
  2958. dst[dst_index] = shadow;
  2959. }
  2960. prev_color = cur_color;
  2961. }
  2962. }
  2963. dst += dim * dim;
  2964. }
  2965. SOKOL_ASSERT(dst == dst_end);
  2966. // bottom shadow
  2967. dst = _sapp.default_icon_pixels;
  2968. for (int i = 0; i < num_icons; i++) {
  2969. const int dim = icon_sizes[i];
  2970. for (int x = 0; x < dim; x++) {
  2971. uint32_t prev_color = blank;
  2972. for (int y = 0; y < dim; y++) {
  2973. const int dst_index = y * dim + x;
  2974. const uint32_t cur_color = dst[dst_index];
  2975. if ((cur_color == blank) && (prev_color != blank)) {
  2976. dst[dst_index] = shadow;
  2977. }
  2978. prev_color = cur_color;
  2979. }
  2980. }
  2981. dst += dim * dim;
  2982. }
  2983. SOKOL_ASSERT(dst == dst_end);
  2984. }
  2985. // █████ ██████ ██████ ██ ███████
  2986. // ██ ██ ██ ██ ██ ██ ██ ██
  2987. // ███████ ██████ ██████ ██ █████
  2988. // ██ ██ ██ ██ ██ ██
  2989. // ██ ██ ██ ██ ███████ ███████
  2990. //
  2991. // >>apple
  2992. #if defined(_SAPP_APPLE)
  2993. #if __has_feature(objc_arc)
  2994. #define _SAPP_OBJC_RELEASE(obj) { obj = nil; }
  2995. #else
  2996. #define _SAPP_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  2997. #endif
  2998. // ███ ███ █████ ██████ ██████ ███████
  2999. // ████ ████ ██ ██ ██ ██ ██ ██
  3000. // ██ ████ ██ ███████ ██ ██ ██ ███████
  3001. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  3002. // ██ ██ ██ ██ ██████ ██████ ███████
  3003. //
  3004. // >>macos
  3005. #if defined(_SAPP_MACOS)
  3006. _SOKOL_PRIVATE void _sapp_macos_init_keytable(void) {
  3007. _sapp.keycodes[0x1D] = SAPP_KEYCODE_0;
  3008. _sapp.keycodes[0x12] = SAPP_KEYCODE_1;
  3009. _sapp.keycodes[0x13] = SAPP_KEYCODE_2;
  3010. _sapp.keycodes[0x14] = SAPP_KEYCODE_3;
  3011. _sapp.keycodes[0x15] = SAPP_KEYCODE_4;
  3012. _sapp.keycodes[0x17] = SAPP_KEYCODE_5;
  3013. _sapp.keycodes[0x16] = SAPP_KEYCODE_6;
  3014. _sapp.keycodes[0x1A] = SAPP_KEYCODE_7;
  3015. _sapp.keycodes[0x1C] = SAPP_KEYCODE_8;
  3016. _sapp.keycodes[0x19] = SAPP_KEYCODE_9;
  3017. _sapp.keycodes[0x00] = SAPP_KEYCODE_A;
  3018. _sapp.keycodes[0x0B] = SAPP_KEYCODE_B;
  3019. _sapp.keycodes[0x08] = SAPP_KEYCODE_C;
  3020. _sapp.keycodes[0x02] = SAPP_KEYCODE_D;
  3021. _sapp.keycodes[0x0E] = SAPP_KEYCODE_E;
  3022. _sapp.keycodes[0x03] = SAPP_KEYCODE_F;
  3023. _sapp.keycodes[0x05] = SAPP_KEYCODE_G;
  3024. _sapp.keycodes[0x04] = SAPP_KEYCODE_H;
  3025. _sapp.keycodes[0x22] = SAPP_KEYCODE_I;
  3026. _sapp.keycodes[0x26] = SAPP_KEYCODE_J;
  3027. _sapp.keycodes[0x28] = SAPP_KEYCODE_K;
  3028. _sapp.keycodes[0x25] = SAPP_KEYCODE_L;
  3029. _sapp.keycodes[0x2E] = SAPP_KEYCODE_M;
  3030. _sapp.keycodes[0x2D] = SAPP_KEYCODE_N;
  3031. _sapp.keycodes[0x1F] = SAPP_KEYCODE_O;
  3032. _sapp.keycodes[0x23] = SAPP_KEYCODE_P;
  3033. _sapp.keycodes[0x0C] = SAPP_KEYCODE_Q;
  3034. _sapp.keycodes[0x0F] = SAPP_KEYCODE_R;
  3035. _sapp.keycodes[0x01] = SAPP_KEYCODE_S;
  3036. _sapp.keycodes[0x11] = SAPP_KEYCODE_T;
  3037. _sapp.keycodes[0x20] = SAPP_KEYCODE_U;
  3038. _sapp.keycodes[0x09] = SAPP_KEYCODE_V;
  3039. _sapp.keycodes[0x0D] = SAPP_KEYCODE_W;
  3040. _sapp.keycodes[0x07] = SAPP_KEYCODE_X;
  3041. _sapp.keycodes[0x10] = SAPP_KEYCODE_Y;
  3042. _sapp.keycodes[0x06] = SAPP_KEYCODE_Z;
  3043. _sapp.keycodes[0x27] = SAPP_KEYCODE_APOSTROPHE;
  3044. _sapp.keycodes[0x2A] = SAPP_KEYCODE_BACKSLASH;
  3045. _sapp.keycodes[0x2B] = SAPP_KEYCODE_COMMA;
  3046. _sapp.keycodes[0x18] = SAPP_KEYCODE_EQUAL;
  3047. _sapp.keycodes[0x32] = SAPP_KEYCODE_GRAVE_ACCENT;
  3048. _sapp.keycodes[0x21] = SAPP_KEYCODE_LEFT_BRACKET;
  3049. _sapp.keycodes[0x1B] = SAPP_KEYCODE_MINUS;
  3050. _sapp.keycodes[0x2F] = SAPP_KEYCODE_PERIOD;
  3051. _sapp.keycodes[0x1E] = SAPP_KEYCODE_RIGHT_BRACKET;
  3052. _sapp.keycodes[0x29] = SAPP_KEYCODE_SEMICOLON;
  3053. _sapp.keycodes[0x2C] = SAPP_KEYCODE_SLASH;
  3054. _sapp.keycodes[0x0A] = SAPP_KEYCODE_WORLD_1;
  3055. _sapp.keycodes[0x33] = SAPP_KEYCODE_BACKSPACE;
  3056. _sapp.keycodes[0x39] = SAPP_KEYCODE_CAPS_LOCK;
  3057. _sapp.keycodes[0x75] = SAPP_KEYCODE_DELETE;
  3058. _sapp.keycodes[0x7D] = SAPP_KEYCODE_DOWN;
  3059. _sapp.keycodes[0x77] = SAPP_KEYCODE_END;
  3060. _sapp.keycodes[0x24] = SAPP_KEYCODE_ENTER;
  3061. _sapp.keycodes[0x35] = SAPP_KEYCODE_ESCAPE;
  3062. _sapp.keycodes[0x7A] = SAPP_KEYCODE_F1;
  3063. _sapp.keycodes[0x78] = SAPP_KEYCODE_F2;
  3064. _sapp.keycodes[0x63] = SAPP_KEYCODE_F3;
  3065. _sapp.keycodes[0x76] = SAPP_KEYCODE_F4;
  3066. _sapp.keycodes[0x60] = SAPP_KEYCODE_F5;
  3067. _sapp.keycodes[0x61] = SAPP_KEYCODE_F6;
  3068. _sapp.keycodes[0x62] = SAPP_KEYCODE_F7;
  3069. _sapp.keycodes[0x64] = SAPP_KEYCODE_F8;
  3070. _sapp.keycodes[0x65] = SAPP_KEYCODE_F9;
  3071. _sapp.keycodes[0x6D] = SAPP_KEYCODE_F10;
  3072. _sapp.keycodes[0x67] = SAPP_KEYCODE_F11;
  3073. _sapp.keycodes[0x6F] = SAPP_KEYCODE_F12;
  3074. _sapp.keycodes[0x69] = SAPP_KEYCODE_F13;
  3075. _sapp.keycodes[0x6B] = SAPP_KEYCODE_F14;
  3076. _sapp.keycodes[0x71] = SAPP_KEYCODE_F15;
  3077. _sapp.keycodes[0x6A] = SAPP_KEYCODE_F16;
  3078. _sapp.keycodes[0x40] = SAPP_KEYCODE_F17;
  3079. _sapp.keycodes[0x4F] = SAPP_KEYCODE_F18;
  3080. _sapp.keycodes[0x50] = SAPP_KEYCODE_F19;
  3081. _sapp.keycodes[0x5A] = SAPP_KEYCODE_F20;
  3082. _sapp.keycodes[0x73] = SAPP_KEYCODE_HOME;
  3083. _sapp.keycodes[0x72] = SAPP_KEYCODE_INSERT;
  3084. _sapp.keycodes[0x7B] = SAPP_KEYCODE_LEFT;
  3085. _sapp.keycodes[0x3A] = SAPP_KEYCODE_LEFT_ALT;
  3086. _sapp.keycodes[0x3B] = SAPP_KEYCODE_LEFT_CONTROL;
  3087. _sapp.keycodes[0x38] = SAPP_KEYCODE_LEFT_SHIFT;
  3088. _sapp.keycodes[0x37] = SAPP_KEYCODE_LEFT_SUPER;
  3089. _sapp.keycodes[0x6E] = SAPP_KEYCODE_MENU;
  3090. _sapp.keycodes[0x47] = SAPP_KEYCODE_NUM_LOCK;
  3091. _sapp.keycodes[0x79] = SAPP_KEYCODE_PAGE_DOWN;
  3092. _sapp.keycodes[0x74] = SAPP_KEYCODE_PAGE_UP;
  3093. _sapp.keycodes[0x7C] = SAPP_KEYCODE_RIGHT;
  3094. _sapp.keycodes[0x3D] = SAPP_KEYCODE_RIGHT_ALT;
  3095. _sapp.keycodes[0x3E] = SAPP_KEYCODE_RIGHT_CONTROL;
  3096. _sapp.keycodes[0x3C] = SAPP_KEYCODE_RIGHT_SHIFT;
  3097. _sapp.keycodes[0x36] = SAPP_KEYCODE_RIGHT_SUPER;
  3098. _sapp.keycodes[0x31] = SAPP_KEYCODE_SPACE;
  3099. _sapp.keycodes[0x30] = SAPP_KEYCODE_TAB;
  3100. _sapp.keycodes[0x7E] = SAPP_KEYCODE_UP;
  3101. _sapp.keycodes[0x52] = SAPP_KEYCODE_KP_0;
  3102. _sapp.keycodes[0x53] = SAPP_KEYCODE_KP_1;
  3103. _sapp.keycodes[0x54] = SAPP_KEYCODE_KP_2;
  3104. _sapp.keycodes[0x55] = SAPP_KEYCODE_KP_3;
  3105. _sapp.keycodes[0x56] = SAPP_KEYCODE_KP_4;
  3106. _sapp.keycodes[0x57] = SAPP_KEYCODE_KP_5;
  3107. _sapp.keycodes[0x58] = SAPP_KEYCODE_KP_6;
  3108. _sapp.keycodes[0x59] = SAPP_KEYCODE_KP_7;
  3109. _sapp.keycodes[0x5B] = SAPP_KEYCODE_KP_8;
  3110. _sapp.keycodes[0x5C] = SAPP_KEYCODE_KP_9;
  3111. _sapp.keycodes[0x45] = SAPP_KEYCODE_KP_ADD;
  3112. _sapp.keycodes[0x41] = SAPP_KEYCODE_KP_DECIMAL;
  3113. _sapp.keycodes[0x4B] = SAPP_KEYCODE_KP_DIVIDE;
  3114. _sapp.keycodes[0x4C] = SAPP_KEYCODE_KP_ENTER;
  3115. _sapp.keycodes[0x51] = SAPP_KEYCODE_KP_EQUAL;
  3116. _sapp.keycodes[0x43] = SAPP_KEYCODE_KP_MULTIPLY;
  3117. _sapp.keycodes[0x4E] = SAPP_KEYCODE_KP_SUBTRACT;
  3118. }
  3119. _SOKOL_PRIVATE void _sapp_macos_discard_state(void) {
  3120. // NOTE: it's safe to call [release] on a nil object
  3121. if (_sapp.macos.keyup_monitor != nil) {
  3122. [NSEvent removeMonitor:_sapp.macos.keyup_monitor];
  3123. // NOTE: removeMonitor also releases the object
  3124. _sapp.macos.keyup_monitor = nil;
  3125. }
  3126. _SAPP_OBJC_RELEASE(_sapp.macos.tracking_area);
  3127. _SAPP_OBJC_RELEASE(_sapp.macos.app_dlg);
  3128. _SAPP_OBJC_RELEASE(_sapp.macos.win_dlg);
  3129. _SAPP_OBJC_RELEASE(_sapp.macos.view);
  3130. #if defined(SOKOL_METAL)
  3131. _SAPP_OBJC_RELEASE(_sapp.macos.mtl_device);
  3132. #endif
  3133. _SAPP_OBJC_RELEASE(_sapp.macos.window);
  3134. }
  3135. // undocumented methods for creating cursors (see GLFW 3.4 and imgui_impl_osx.mm)
  3136. @interface NSCursor()
  3137. + (id)_windowResizeNorthWestSouthEastCursor;
  3138. + (id)_windowResizeNorthEastSouthWestCursor;
  3139. + (id)_windowResizeNorthSouthCursor;
  3140. + (id)_windowResizeEastWestCursor;
  3141. @end
  3142. _SOKOL_PRIVATE void _sapp_macos_init_cursors(void) {
  3143. _sapp.macos.cursors[SAPP_MOUSECURSOR_DEFAULT] = nil; // not a bug
  3144. _sapp.macos.cursors[SAPP_MOUSECURSOR_ARROW] = [NSCursor arrowCursor];
  3145. _sapp.macos.cursors[SAPP_MOUSECURSOR_IBEAM] = [NSCursor IBeamCursor];
  3146. _sapp.macos.cursors[SAPP_MOUSECURSOR_CROSSHAIR] = [NSCursor crosshairCursor];
  3147. _sapp.macos.cursors[SAPP_MOUSECURSOR_POINTING_HAND] = [NSCursor pointingHandCursor];
  3148. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_EW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
  3149. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
  3150. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
  3151. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
  3152. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_ALL] = [NSCursor closedHandCursor];
  3153. _sapp.macos.cursors[SAPP_MOUSECURSOR_NOT_ALLOWED] = [NSCursor operationNotAllowedCursor];
  3154. }
  3155. _SOKOL_PRIVATE void _sapp_macos_run(const sapp_desc* desc) {
  3156. _sapp_init_state(desc);
  3157. _sapp_macos_init_keytable();
  3158. [NSApplication sharedApplication];
  3159. // set the application dock icon as early as possible, otherwise
  3160. // the dummy icon will be visible for a short time
  3161. sapp_set_icon(&_sapp.desc.icon);
  3162. _sapp.macos.app_dlg = [[_sapp_macos_app_delegate alloc] init];
  3163. NSApp.delegate = _sapp.macos.app_dlg;
  3164. // workaround for "no key-up sent while Cmd is pressed" taken from GLFW:
  3165. NSEvent* (^keyup_monitor)(NSEvent*) = ^NSEvent* (NSEvent* event) {
  3166. if ([event modifierFlags] & NSEventModifierFlagCommand) {
  3167. [[NSApp keyWindow] sendEvent:event];
  3168. }
  3169. return event;
  3170. };
  3171. _sapp.macos.keyup_monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyUp handler:keyup_monitor];
  3172. [NSApp run];
  3173. // NOTE: [NSApp run] never returns, instead cleanup code
  3174. // must be put into applicationWillTerminate
  3175. }
  3176. /* MacOS entry function */
  3177. #if !defined(SOKOL_NO_ENTRY)
  3178. int main(int argc, char* argv[]) {
  3179. sapp_desc desc = sokol_main(argc, argv);
  3180. _sapp_macos_run(&desc);
  3181. return 0;
  3182. }
  3183. #endif /* SOKOL_NO_ENTRY */
  3184. _SOKOL_PRIVATE uint32_t _sapp_macos_mods(NSEvent* ev) {
  3185. const NSEventModifierFlags f = (ev == nil) ? NSEvent.modifierFlags : ev.modifierFlags;
  3186. const NSUInteger b = NSEvent.pressedMouseButtons;
  3187. uint32_t m = 0;
  3188. if (f & NSEventModifierFlagShift) {
  3189. m |= SAPP_MODIFIER_SHIFT;
  3190. }
  3191. if (f & NSEventModifierFlagControl) {
  3192. m |= SAPP_MODIFIER_CTRL;
  3193. }
  3194. if (f & NSEventModifierFlagOption) {
  3195. m |= SAPP_MODIFIER_ALT;
  3196. }
  3197. if (f & NSEventModifierFlagCommand) {
  3198. m |= SAPP_MODIFIER_SUPER;
  3199. }
  3200. if (0 != (b & (1<<0))) {
  3201. m |= SAPP_MODIFIER_LMB;
  3202. }
  3203. if (0 != (b & (1<<1))) {
  3204. m |= SAPP_MODIFIER_RMB;
  3205. }
  3206. if (0 != (b & (1<<2))) {
  3207. m |= SAPP_MODIFIER_MMB;
  3208. }
  3209. return m;
  3210. }
  3211. _SOKOL_PRIVATE void _sapp_macos_mouse_event(sapp_event_type type, sapp_mousebutton btn, uint32_t mod) {
  3212. if (_sapp_events_enabled()) {
  3213. _sapp_init_event(type);
  3214. _sapp.event.mouse_button = btn;
  3215. _sapp.event.modifiers = mod;
  3216. _sapp_call_event(&_sapp.event);
  3217. }
  3218. }
  3219. _SOKOL_PRIVATE void _sapp_macos_key_event(sapp_event_type type, sapp_keycode key, bool repeat, uint32_t mod) {
  3220. if (_sapp_events_enabled()) {
  3221. _sapp_init_event(type);
  3222. _sapp.event.key_code = key;
  3223. _sapp.event.key_repeat = repeat;
  3224. _sapp.event.modifiers = mod;
  3225. _sapp_call_event(&_sapp.event);
  3226. }
  3227. }
  3228. _SOKOL_PRIVATE void _sapp_macos_app_event(sapp_event_type type) {
  3229. if (_sapp_events_enabled()) {
  3230. _sapp_init_event(type);
  3231. _sapp_call_event(&_sapp.event);
  3232. }
  3233. }
  3234. /* NOTE: unlike the iOS version of this function, the macOS version
  3235. can dynamically update the DPI scaling factor when a window is moved
  3236. between HighDPI / LowDPI screens.
  3237. */
  3238. _SOKOL_PRIVATE void _sapp_macos_update_dimensions(void) {
  3239. if (_sapp.desc.high_dpi) {
  3240. _sapp.dpi_scale = [_sapp.macos.window screen].backingScaleFactor;
  3241. }
  3242. else {
  3243. _sapp.dpi_scale = 1.0f;
  3244. }
  3245. _sapp.macos.view.layer.contentsScale = _sapp.dpi_scale; // NOTE: needed because we set layerContentsPlacement to a non-scaling value in windowWillStartLiveResize.
  3246. const NSRect bounds = [_sapp.macos.view bounds];
  3247. _sapp.window_width = (int)roundf(bounds.size.width);
  3248. _sapp.window_height = (int)roundf(bounds.size.height);
  3249. #if defined(SOKOL_METAL)
  3250. _sapp.framebuffer_width = (int)roundf(bounds.size.width * _sapp.dpi_scale);
  3251. _sapp.framebuffer_height = (int)roundf(bounds.size.height * _sapp.dpi_scale);
  3252. const CGSize fb_size = _sapp.macos.view.drawableSize;
  3253. const int cur_fb_width = (int)roundf(fb_size.width);
  3254. const int cur_fb_height = (int)roundf(fb_size.height);
  3255. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  3256. (_sapp.framebuffer_height != cur_fb_height);
  3257. #elif defined(SOKOL_GLCORE)
  3258. const int cur_fb_width = (int)roundf(bounds.size.width * _sapp.dpi_scale);
  3259. const int cur_fb_height = (int)roundf(bounds.size.height * _sapp.dpi_scale);
  3260. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  3261. (_sapp.framebuffer_height != cur_fb_height);
  3262. _sapp.framebuffer_width = cur_fb_width;
  3263. _sapp.framebuffer_height = cur_fb_height;
  3264. #endif
  3265. if (_sapp.framebuffer_width == 0) {
  3266. _sapp.framebuffer_width = 1;
  3267. }
  3268. if (_sapp.framebuffer_height == 0) {
  3269. _sapp.framebuffer_height = 1;
  3270. }
  3271. if (_sapp.window_width == 0) {
  3272. _sapp.window_width = 1;
  3273. }
  3274. if (_sapp.window_height == 0) {
  3275. _sapp.window_height = 1;
  3276. }
  3277. if (dim_changed) {
  3278. #if defined(SOKOL_METAL)
  3279. CGSize drawable_size = { (CGFloat) _sapp.framebuffer_width, (CGFloat) _sapp.framebuffer_height };
  3280. _sapp.macos.view.drawableSize = drawable_size;
  3281. #else
  3282. // nothing to do for GL?
  3283. #endif
  3284. if (!_sapp.first_frame) {
  3285. _sapp_macos_app_event(SAPP_EVENTTYPE_RESIZED);
  3286. }
  3287. }
  3288. }
  3289. _SOKOL_PRIVATE void _sapp_macos_toggle_fullscreen(void) {
  3290. /* NOTE: the _sapp.fullscreen flag is also notified by the
  3291. windowDidEnterFullscreen / windowDidExitFullscreen
  3292. event handlers
  3293. */
  3294. _sapp.fullscreen = !_sapp.fullscreen;
  3295. [_sapp.macos.window toggleFullScreen:nil];
  3296. }
  3297. _SOKOL_PRIVATE void _sapp_macos_set_clipboard_string(const char* str) {
  3298. @autoreleasepool {
  3299. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  3300. [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
  3301. [pasteboard setString:@(str) forType:NSPasteboardTypeString];
  3302. }
  3303. }
  3304. _SOKOL_PRIVATE const char* _sapp_macos_get_clipboard_string(void) {
  3305. SOKOL_ASSERT(_sapp.clipboard.buffer);
  3306. @autoreleasepool {
  3307. _sapp.clipboard.buffer[0] = 0;
  3308. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  3309. if (![[pasteboard types] containsObject:NSPasteboardTypeString]) {
  3310. return _sapp.clipboard.buffer;
  3311. }
  3312. NSString* str = [pasteboard stringForType:NSPasteboardTypeString];
  3313. if (!str) {
  3314. return _sapp.clipboard.buffer;
  3315. }
  3316. _sapp_strcpy([str UTF8String], _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  3317. }
  3318. return _sapp.clipboard.buffer;
  3319. }
  3320. _SOKOL_PRIVATE void _sapp_macos_update_window_title(void) {
  3321. [_sapp.macos.window setTitle: [NSString stringWithUTF8String:_sapp.window_title]];
  3322. }
  3323. _SOKOL_PRIVATE void _sapp_macos_mouse_update_from_nspoint(NSPoint mouse_pos, bool clear_dxdy) {
  3324. if (!_sapp.mouse.locked) {
  3325. float new_x = mouse_pos.x * _sapp.dpi_scale;
  3326. float new_y = _sapp.framebuffer_height - (mouse_pos.y * _sapp.dpi_scale) - 1;
  3327. if (clear_dxdy) {
  3328. _sapp.mouse.dx = 0.0f;
  3329. _sapp.mouse.dy = 0.0f;
  3330. }
  3331. else if (_sapp.mouse.pos_valid) {
  3332. // don't update dx/dy in the very first update
  3333. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  3334. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  3335. }
  3336. _sapp.mouse.x = new_x;
  3337. _sapp.mouse.y = new_y;
  3338. _sapp.mouse.pos_valid = true;
  3339. }
  3340. }
  3341. _SOKOL_PRIVATE void _sapp_macos_mouse_update_from_nsevent(NSEvent* event, bool clear_dxdy) {
  3342. _sapp_macos_mouse_update_from_nspoint(event.locationInWindow, clear_dxdy);
  3343. }
  3344. _SOKOL_PRIVATE void _sapp_macos_show_mouse(bool visible) {
  3345. /* NOTE: this function is only called when the mouse visibility actually changes */
  3346. if (visible) {
  3347. CGDisplayShowCursor(kCGDirectMainDisplay);
  3348. }
  3349. else {
  3350. CGDisplayHideCursor(kCGDirectMainDisplay);
  3351. }
  3352. }
  3353. _SOKOL_PRIVATE void _sapp_macos_lock_mouse(bool lock) {
  3354. if (lock == _sapp.mouse.locked) {
  3355. return;
  3356. }
  3357. _sapp.mouse.dx = 0.0f;
  3358. _sapp.mouse.dy = 0.0f;
  3359. _sapp.mouse.locked = lock;
  3360. /*
  3361. NOTE that this code doesn't warp the mouse cursor to the window
  3362. center as everybody else does it. This lead to a spike in the
  3363. *second* mouse-moved event after the warp happened. The
  3364. mouse centering doesn't seem to be required (mouse-moved events
  3365. are reported correctly even when the cursor is at an edge of the screen).
  3366. NOTE also that the hide/show of the mouse cursor should properly
  3367. stack with calls to sapp_show_mouse()
  3368. */
  3369. if (_sapp.mouse.locked) {
  3370. CGAssociateMouseAndMouseCursorPosition(NO);
  3371. [NSCursor hide];
  3372. }
  3373. else {
  3374. [NSCursor unhide];
  3375. CGAssociateMouseAndMouseCursorPosition(YES);
  3376. }
  3377. }
  3378. _SOKOL_PRIVATE void _sapp_macos_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  3379. // show/hide cursor only if visibility status has changed (required because show/hide stacks)
  3380. if (shown != _sapp.mouse.shown) {
  3381. if (shown) {
  3382. [NSCursor unhide];
  3383. }
  3384. else {
  3385. [NSCursor hide];
  3386. }
  3387. }
  3388. // update cursor type
  3389. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  3390. if (_sapp.macos.cursors[cursor]) {
  3391. [_sapp.macos.cursors[cursor] set];
  3392. }
  3393. else {
  3394. [[NSCursor arrowCursor] set];
  3395. }
  3396. }
  3397. _SOKOL_PRIVATE void _sapp_macos_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  3398. NSDockTile* dock_tile = NSApp.dockTile;
  3399. const int wanted_width = (int) dock_tile.size.width;
  3400. const int wanted_height = (int) dock_tile.size.height;
  3401. const int img_index = _sapp_image_bestmatch(icon_desc->images, num_images, wanted_width, wanted_height);
  3402. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  3403. CGColorSpaceRef cg_color_space = CGColorSpaceCreateDeviceRGB();
  3404. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)img_desc->pixels.ptr, (CFIndex)img_desc->pixels.size);
  3405. CGDataProviderRef cg_data_provider = CGDataProviderCreateWithCFData(cf_data);
  3406. CGImageRef cg_img = CGImageCreate(
  3407. (size_t)img_desc->width, // width
  3408. (size_t)img_desc->height, // height
  3409. 8, // bitsPerComponent
  3410. 32, // bitsPerPixel
  3411. (size_t)img_desc->width * 4,// bytesPerRow
  3412. cg_color_space, // space
  3413. kCGImageAlphaLast | kCGImageByteOrderDefault, // bitmapInfo
  3414. cg_data_provider, // provider
  3415. NULL, // decode
  3416. false, // shouldInterpolate
  3417. kCGRenderingIntentDefault);
  3418. CFRelease(cf_data);
  3419. CGDataProviderRelease(cg_data_provider);
  3420. CGColorSpaceRelease(cg_color_space);
  3421. NSImage* ns_image = [[NSImage alloc] initWithCGImage:cg_img size:dock_tile.size];
  3422. dock_tile.contentView = [NSImageView imageViewWithImage:ns_image];
  3423. [dock_tile display];
  3424. _SAPP_OBJC_RELEASE(ns_image);
  3425. CGImageRelease(cg_img);
  3426. }
  3427. _SOKOL_PRIVATE void _sapp_macos_frame(void) {
  3428. _sapp_frame();
  3429. if (_sapp.quit_requested || _sapp.quit_ordered) {
  3430. [_sapp.macos.window performClose:nil];
  3431. }
  3432. }
  3433. @implementation _sapp_macos_app_delegate
  3434. - (void)applicationDidFinishLaunching:(NSNotification*)aNotification {
  3435. _SOKOL_UNUSED(aNotification);
  3436. _sapp_macos_init_cursors();
  3437. if ((_sapp.window_width == 0) || (_sapp.window_height == 0)) {
  3438. // use 4/5 of screen size as default size
  3439. NSRect screen_rect = NSScreen.mainScreen.frame;
  3440. if (_sapp.window_width == 0) {
  3441. _sapp.window_width = (int)roundf((screen_rect.size.width * 4.0f) / 5.0f);
  3442. }
  3443. if (_sapp.window_height == 0) {
  3444. _sapp.window_height = (int)roundf((screen_rect.size.height * 4.0f) / 5.0f);
  3445. }
  3446. }
  3447. const NSUInteger style =
  3448. NSWindowStyleMaskTitled |
  3449. NSWindowStyleMaskClosable |
  3450. NSWindowStyleMaskMiniaturizable |
  3451. NSWindowStyleMaskResizable;
  3452. NSRect window_rect = NSMakeRect(0, 0, _sapp.window_width, _sapp.window_height);
  3453. _sapp.macos.window = [[_sapp_macos_window alloc]
  3454. initWithContentRect:window_rect
  3455. styleMask:style
  3456. backing:NSBackingStoreBuffered
  3457. defer:NO];
  3458. _sapp.macos.window.releasedWhenClosed = NO; // this is necessary for proper cleanup in applicationWillTerminate
  3459. _sapp.macos.window.title = [NSString stringWithUTF8String:_sapp.window_title];
  3460. _sapp.macos.window.acceptsMouseMovedEvents = YES;
  3461. _sapp.macos.window.restorable = YES;
  3462. _sapp.macos.win_dlg = [[_sapp_macos_window_delegate alloc] init];
  3463. _sapp.macos.window.delegate = _sapp.macos.win_dlg;
  3464. #if defined(SOKOL_METAL)
  3465. NSInteger max_fps = 60;
  3466. #if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 120000)
  3467. if (@available(macOS 12.0, *)) {
  3468. max_fps = [NSScreen.mainScreen maximumFramesPerSecond];
  3469. }
  3470. #endif
  3471. _sapp.macos.mtl_device = MTLCreateSystemDefaultDevice();
  3472. _sapp.macos.view = [[_sapp_macos_view alloc] init];
  3473. [_sapp.macos.view updateTrackingAreas];
  3474. _sapp.macos.view.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  3475. _sapp.macos.view.device = _sapp.macos.mtl_device;
  3476. _sapp.macos.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
  3477. _sapp.macos.view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  3478. _sapp.macos.view.sampleCount = (NSUInteger) _sapp.sample_count;
  3479. _sapp.macos.view.autoResizeDrawable = false;
  3480. _sapp.macos.window.contentView = _sapp.macos.view;
  3481. [_sapp.macos.window makeFirstResponder:_sapp.macos.view];
  3482. _sapp.macos.view.layer.magnificationFilter = kCAFilterNearest;
  3483. #elif defined(SOKOL_GLCORE)
  3484. NSOpenGLPixelFormatAttribute attrs[32];
  3485. int i = 0;
  3486. attrs[i++] = NSOpenGLPFAAccelerated;
  3487. attrs[i++] = NSOpenGLPFADoubleBuffer;
  3488. attrs[i++] = NSOpenGLPFAOpenGLProfile;
  3489. const int glVersion = _sapp.desc.gl_major_version * 10 + _sapp.desc.gl_minor_version;
  3490. switch(glVersion) {
  3491. case 10: attrs[i++] = NSOpenGLProfileVersionLegacy; break;
  3492. case 32: attrs[i++] = NSOpenGLProfileVersion3_2Core; break;
  3493. case 41: attrs[i++] = NSOpenGLProfileVersion4_1Core; break;
  3494. default:
  3495. _SAPP_PANIC(MACOS_INVALID_NSOPENGL_PROFILE);
  3496. }
  3497. attrs[i++] = NSOpenGLPFAColorSize; attrs[i++] = 24;
  3498. attrs[i++] = NSOpenGLPFAAlphaSize; attrs[i++] = 8;
  3499. attrs[i++] = NSOpenGLPFADepthSize; attrs[i++] = 24;
  3500. attrs[i++] = NSOpenGLPFAStencilSize; attrs[i++] = 8;
  3501. if (_sapp.sample_count > 1) {
  3502. attrs[i++] = NSOpenGLPFAMultisample;
  3503. attrs[i++] = NSOpenGLPFASampleBuffers; attrs[i++] = 1;
  3504. attrs[i++] = NSOpenGLPFASamples; attrs[i++] = (NSOpenGLPixelFormatAttribute)_sapp.sample_count;
  3505. }
  3506. else {
  3507. attrs[i++] = NSOpenGLPFASampleBuffers; attrs[i++] = 0;
  3508. }
  3509. attrs[i++] = 0;
  3510. NSOpenGLPixelFormat* glpixelformat_obj = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  3511. SOKOL_ASSERT(glpixelformat_obj != nil);
  3512. _sapp.macos.view = [[_sapp_macos_view alloc]
  3513. initWithFrame:window_rect
  3514. pixelFormat:glpixelformat_obj];
  3515. _SAPP_OBJC_RELEASE(glpixelformat_obj);
  3516. [_sapp.macos.view updateTrackingAreas];
  3517. if (_sapp.desc.high_dpi) {
  3518. [_sapp.macos.view setWantsBestResolutionOpenGLSurface:YES];
  3519. }
  3520. else {
  3521. [_sapp.macos.view setWantsBestResolutionOpenGLSurface:NO];
  3522. }
  3523. _sapp.macos.window.contentView = _sapp.macos.view;
  3524. [_sapp.macos.window makeFirstResponder:_sapp.macos.view];
  3525. NSTimer* timer_obj = [NSTimer timerWithTimeInterval:0.001
  3526. target:_sapp.macos.view
  3527. selector:@selector(timerFired:)
  3528. userInfo:nil
  3529. repeats:YES];
  3530. [[NSRunLoop currentRunLoop] addTimer:timer_obj forMode:NSDefaultRunLoopMode];
  3531. timer_obj = nil;
  3532. #endif
  3533. [_sapp.macos.window center];
  3534. _sapp.valid = true;
  3535. if (_sapp.fullscreen) {
  3536. /* ^^^ on GL, this already toggles a rendered frame, so set the valid flag before */
  3537. [_sapp.macos.window toggleFullScreen:self];
  3538. }
  3539. NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
  3540. [NSApp activateIgnoringOtherApps:YES];
  3541. [_sapp.macos.window makeKeyAndOrderFront:nil];
  3542. _sapp_macos_update_dimensions();
  3543. [NSEvent setMouseCoalescingEnabled:NO];
  3544. // workaround for window not being focused during a long init callback
  3545. // for details see: https://github.com/floooh/sokol/pull/982
  3546. // also see: https://gitlab.gnome.org/GNOME/gtk/-/issues/2342
  3547. NSEvent *focusevent = [NSEvent otherEventWithType:NSEventTypeAppKitDefined
  3548. location:NSZeroPoint
  3549. modifierFlags:0x40
  3550. timestamp:0
  3551. windowNumber:0
  3552. context:nil
  3553. subtype:NSEventSubtypeApplicationActivated
  3554. data1:0
  3555. data2:0];
  3556. [NSApp postEvent:focusevent atStart:YES];
  3557. }
  3558. - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender {
  3559. _SOKOL_UNUSED(sender);
  3560. return YES;
  3561. }
  3562. - (void)applicationWillTerminate:(NSNotification*)notification {
  3563. _SOKOL_UNUSED(notification);
  3564. _sapp_call_cleanup();
  3565. _sapp_macos_discard_state();
  3566. _sapp_discard_state();
  3567. }
  3568. @end
  3569. @implementation _sapp_macos_window_delegate
  3570. - (BOOL)windowShouldClose:(id)sender {
  3571. _SOKOL_UNUSED(sender);
  3572. /* only give user-code a chance to intervene when sapp_quit() wasn't already called */
  3573. if (!_sapp.quit_ordered) {
  3574. /* if window should be closed and event handling is enabled, give user code
  3575. a chance to intervene via sapp_cancel_quit()
  3576. */
  3577. _sapp.quit_requested = true;
  3578. _sapp_macos_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  3579. /* user code hasn't intervened, quit the app */
  3580. if (_sapp.quit_requested) {
  3581. _sapp.quit_ordered = true;
  3582. }
  3583. }
  3584. if (_sapp.quit_ordered) {
  3585. return YES;
  3586. }
  3587. else {
  3588. return NO;
  3589. }
  3590. }
  3591. #if defined(SOKOL_METAL)
  3592. - (void)windowWillStartLiveResize:(NSNotification *)notification {
  3593. // Work around the MTKView resizing glitch by "anchoring" the layer to the window corner opposite
  3594. // to the currently manipulated corner (or edge). This prevents the content stretching back and
  3595. // forth during resizing. This is a workaround for this issue: https://github.com/floooh/sokol/issues/700
  3596. // Can be removed if/when migrating to CAMetalLayer: https://github.com/floooh/sokol/issues/727
  3597. bool resizing_from_left = _sapp.mouse.x < _sapp.window_width/2;
  3598. bool resizing_from_top = _sapp.mouse.y < _sapp.window_height/2;
  3599. NSViewLayerContentsPlacement placement;
  3600. if (resizing_from_left) {
  3601. placement = resizing_from_top ? NSViewLayerContentsPlacementBottomRight : NSViewLayerContentsPlacementTopRight;
  3602. } else {
  3603. placement = resizing_from_top ? NSViewLayerContentsPlacementBottomLeft : NSViewLayerContentsPlacementTopLeft;
  3604. }
  3605. _sapp.macos.view.layerContentsPlacement = placement;
  3606. }
  3607. #endif
  3608. - (void)windowDidResize:(NSNotification*)notification {
  3609. _SOKOL_UNUSED(notification);
  3610. _sapp_macos_update_dimensions();
  3611. }
  3612. - (void)windowDidChangeScreen:(NSNotification*)notification {
  3613. _SOKOL_UNUSED(notification);
  3614. _sapp_timing_reset(&_sapp.timing);
  3615. _sapp_macos_update_dimensions();
  3616. }
  3617. - (void)windowDidMiniaturize:(NSNotification*)notification {
  3618. _SOKOL_UNUSED(notification);
  3619. _sapp_macos_app_event(SAPP_EVENTTYPE_ICONIFIED);
  3620. }
  3621. - (void)windowDidDeminiaturize:(NSNotification*)notification {
  3622. _SOKOL_UNUSED(notification);
  3623. _sapp_macos_app_event(SAPP_EVENTTYPE_RESTORED);
  3624. }
  3625. - (void)windowDidBecomeKey:(NSNotification*)notification {
  3626. _SOKOL_UNUSED(notification);
  3627. _sapp_macos_app_event(SAPP_EVENTTYPE_FOCUSED);
  3628. }
  3629. - (void)windowDidResignKey:(NSNotification*)notification {
  3630. _SOKOL_UNUSED(notification);
  3631. _sapp_macos_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  3632. }
  3633. - (void)windowDidEnterFullScreen:(NSNotification*)notification {
  3634. _SOKOL_UNUSED(notification);
  3635. _sapp.fullscreen = true;
  3636. }
  3637. - (void)windowDidExitFullScreen:(NSNotification*)notification {
  3638. _SOKOL_UNUSED(notification);
  3639. _sapp.fullscreen = false;
  3640. }
  3641. @end
  3642. @implementation _sapp_macos_window
  3643. - (instancetype)initWithContentRect:(NSRect)contentRect
  3644. styleMask:(NSWindowStyleMask)style
  3645. backing:(NSBackingStoreType)backingStoreType
  3646. defer:(BOOL)flag {
  3647. if (self = [super initWithContentRect:contentRect styleMask:style backing:backingStoreType defer:flag]) {
  3648. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  3649. [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
  3650. #endif
  3651. }
  3652. return self;
  3653. }
  3654. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  3655. return NSDragOperationCopy;
  3656. }
  3657. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  3658. return NSDragOperationCopy;
  3659. }
  3660. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  3661. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  3662. NSPasteboard *pboard = [sender draggingPasteboard];
  3663. if ([pboard.types containsObject:NSPasteboardTypeFileURL]) {
  3664. _sapp_clear_drop_buffer();
  3665. _sapp.drop.num_files = ((int)pboard.pasteboardItems.count > _sapp.drop.max_files) ? _sapp.drop.max_files : (int)pboard.pasteboardItems.count;
  3666. bool drop_failed = false;
  3667. for (int i = 0; i < _sapp.drop.num_files; i++) {
  3668. NSURL *fileUrl = [NSURL fileURLWithPath:[pboard.pasteboardItems[(NSUInteger)i] stringForType:NSPasteboardTypeFileURL]];
  3669. if (!_sapp_strcpy(fileUrl.standardizedURL.path.UTF8String, _sapp_dropped_file_path_ptr(i), _sapp.drop.max_path_length)) {
  3670. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  3671. drop_failed = true;
  3672. break;
  3673. }
  3674. }
  3675. if (!drop_failed) {
  3676. if (_sapp_events_enabled()) {
  3677. _sapp_macos_mouse_update_from_nspoint(sender.draggingLocation, true);
  3678. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  3679. _sapp.event.modifiers = _sapp_macos_mods(nil);
  3680. _sapp_call_event(&_sapp.event);
  3681. }
  3682. }
  3683. else {
  3684. _sapp_clear_drop_buffer();
  3685. _sapp.drop.num_files = 0;
  3686. }
  3687. return YES;
  3688. }
  3689. #endif
  3690. return NO;
  3691. }
  3692. @end
  3693. @implementation _sapp_macos_view
  3694. #if defined(SOKOL_GLCORE)
  3695. - (void)timerFired:(id)sender {
  3696. _SOKOL_UNUSED(sender);
  3697. [self setNeedsDisplay:YES];
  3698. }
  3699. - (void)prepareOpenGL {
  3700. [super prepareOpenGL];
  3701. GLint swapInt = 1;
  3702. NSOpenGLContext* ctx = [_sapp.macos.view openGLContext];
  3703. [ctx setValues:&swapInt forParameter:NSOpenGLContextParameterSwapInterval];
  3704. [ctx makeCurrentContext];
  3705. }
  3706. #endif
  3707. _SOKOL_PRIVATE void _sapp_macos_poll_input_events(void) {
  3708. /*
  3709. NOTE: late event polling temporarily out-commented to check if this
  3710. causes infrequent and almost impossible to reproduce problems with the
  3711. window close events, see:
  3712. https://github.com/floooh/sokol/pull/483#issuecomment-805148815
  3713. const NSEventMask mask = NSEventMaskLeftMouseDown |
  3714. NSEventMaskLeftMouseUp|
  3715. NSEventMaskRightMouseDown |
  3716. NSEventMaskRightMouseUp |
  3717. NSEventMaskMouseMoved |
  3718. NSEventMaskLeftMouseDragged |
  3719. NSEventMaskRightMouseDragged |
  3720. NSEventMaskMouseEntered |
  3721. NSEventMaskMouseExited |
  3722. NSEventMaskKeyDown |
  3723. NSEventMaskKeyUp |
  3724. NSEventMaskCursorUpdate |
  3725. NSEventMaskScrollWheel |
  3726. NSEventMaskTabletPoint |
  3727. NSEventMaskTabletProximity |
  3728. NSEventMaskOtherMouseDown |
  3729. NSEventMaskOtherMouseUp |
  3730. NSEventMaskOtherMouseDragged |
  3731. NSEventMaskPressure |
  3732. NSEventMaskDirectTouch;
  3733. @autoreleasepool {
  3734. for (;;) {
  3735. // NOTE: using NSDefaultRunLoopMode here causes stuttering in the GL backend,
  3736. // see: https://github.com/floooh/sokol/issues/486
  3737. NSEvent* event = [NSApp nextEventMatchingMask:mask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES];
  3738. if (event == nil) {
  3739. break;
  3740. }
  3741. [NSApp sendEvent:event];
  3742. }
  3743. }
  3744. */
  3745. }
  3746. - (void)drawRect:(NSRect)rect {
  3747. _SOKOL_UNUSED(rect);
  3748. #if defined(_SAPP_ANY_GL)
  3749. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  3750. #endif
  3751. _sapp_timing_measure(&_sapp.timing);
  3752. /* Catch any last-moment input events */
  3753. _sapp_macos_poll_input_events();
  3754. @autoreleasepool {
  3755. _sapp_macos_frame();
  3756. }
  3757. #if defined(_SAPP_ANY_GL)
  3758. [[_sapp.macos.view openGLContext] flushBuffer];
  3759. #endif
  3760. }
  3761. - (BOOL)isOpaque {
  3762. return YES;
  3763. }
  3764. - (BOOL)canBecomeKeyView {
  3765. return YES;
  3766. }
  3767. - (BOOL)acceptsFirstResponder {
  3768. return YES;
  3769. }
  3770. - (void)updateTrackingAreas {
  3771. if (_sapp.macos.tracking_area != nil) {
  3772. [self removeTrackingArea:_sapp.macos.tracking_area];
  3773. _SAPP_OBJC_RELEASE(_sapp.macos.tracking_area);
  3774. }
  3775. const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
  3776. NSTrackingActiveInKeyWindow |
  3777. NSTrackingEnabledDuringMouseDrag |
  3778. NSTrackingCursorUpdate |
  3779. NSTrackingInVisibleRect |
  3780. NSTrackingAssumeInside;
  3781. _sapp.macos.tracking_area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
  3782. [self addTrackingArea:_sapp.macos.tracking_area];
  3783. [super updateTrackingAreas];
  3784. }
  3785. // helper function to make GL context active
  3786. static void _sapp_gl_make_current(void) {
  3787. #if defined(SOKOL_GLCORE)
  3788. [[_sapp.macos.view openGLContext] makeCurrentContext];
  3789. #endif
  3790. }
  3791. - (void)mouseEntered:(NSEvent*)event {
  3792. _sapp_gl_make_current();
  3793. _sapp_macos_mouse_update_from_nsevent(event, true);
  3794. /* don't send mouse enter/leave while dragging (so that it behaves the same as
  3795. on Windows while SetCapture is active
  3796. */
  3797. if (0 == _sapp.macos.mouse_buttons) {
  3798. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3799. }
  3800. }
  3801. - (void)mouseExited:(NSEvent*)event {
  3802. _sapp_gl_make_current();
  3803. _sapp_macos_mouse_update_from_nsevent(event, true);
  3804. if (0 == _sapp.macos.mouse_buttons) {
  3805. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3806. }
  3807. }
  3808. - (void)mouseDown:(NSEvent*)event {
  3809. _sapp_gl_make_current();
  3810. _sapp_macos_mouse_update_from_nsevent(event, false);
  3811. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_LEFT, _sapp_macos_mods(event));
  3812. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_LEFT);
  3813. }
  3814. - (void)mouseUp:(NSEvent*)event {
  3815. _sapp_gl_make_current();
  3816. _sapp_macos_mouse_update_from_nsevent(event, false);
  3817. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_LEFT, _sapp_macos_mods(event));
  3818. _sapp.macos.mouse_buttons &= ~(1<<SAPP_MOUSEBUTTON_LEFT);
  3819. }
  3820. - (void)rightMouseDown:(NSEvent*)event {
  3821. _sapp_gl_make_current();
  3822. _sapp_macos_mouse_update_from_nsevent(event, false);
  3823. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_RIGHT, _sapp_macos_mods(event));
  3824. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_RIGHT);
  3825. }
  3826. - (void)rightMouseUp:(NSEvent*)event {
  3827. _sapp_gl_make_current();
  3828. _sapp_macos_mouse_update_from_nsevent(event, false);
  3829. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_RIGHT, _sapp_macos_mods(event));
  3830. _sapp.macos.mouse_buttons &= ~(1<<SAPP_MOUSEBUTTON_RIGHT);
  3831. }
  3832. - (void)otherMouseDown:(NSEvent*)event {
  3833. _sapp_gl_make_current();
  3834. _sapp_macos_mouse_update_from_nsevent(event, false);
  3835. if (2 == event.buttonNumber) {
  3836. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_MIDDLE, _sapp_macos_mods(event));
  3837. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_MIDDLE);
  3838. }
  3839. }
  3840. - (void)otherMouseUp:(NSEvent*)event {
  3841. _sapp_gl_make_current();
  3842. _sapp_macos_mouse_update_from_nsevent(event, false);
  3843. if (2 == event.buttonNumber) {
  3844. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_MIDDLE, _sapp_macos_mods(event));
  3845. _sapp.macos.mouse_buttons &= (1<<SAPP_MOUSEBUTTON_MIDDLE);
  3846. }
  3847. }
  3848. - (void)otherMouseDragged:(NSEvent*)event {
  3849. _sapp_gl_make_current();
  3850. _sapp_macos_mouse_update_from_nsevent(event, false);
  3851. if (2 == event.buttonNumber) {
  3852. if (_sapp.mouse.locked) {
  3853. _sapp.mouse.dx = [event deltaX];
  3854. _sapp.mouse.dy = [event deltaY];
  3855. }
  3856. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3857. }
  3858. }
  3859. - (void)mouseMoved:(NSEvent*)event {
  3860. _sapp_gl_make_current();
  3861. _sapp_macos_mouse_update_from_nsevent(event, false);
  3862. if (_sapp.mouse.locked) {
  3863. _sapp.mouse.dx = [event deltaX];
  3864. _sapp.mouse.dy = [event deltaY];
  3865. }
  3866. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID , _sapp_macos_mods(event));
  3867. }
  3868. - (void)mouseDragged:(NSEvent*)event {
  3869. _sapp_gl_make_current();
  3870. _sapp_macos_mouse_update_from_nsevent(event, false);
  3871. if (_sapp.mouse.locked) {
  3872. _sapp.mouse.dx = [event deltaX];
  3873. _sapp.mouse.dy = [event deltaY];
  3874. }
  3875. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID , _sapp_macos_mods(event));
  3876. }
  3877. - (void)rightMouseDragged:(NSEvent*)event {
  3878. _sapp_gl_make_current();
  3879. _sapp_macos_mouse_update_from_nsevent(event, false);
  3880. if (_sapp.mouse.locked) {
  3881. _sapp.mouse.dx = [event deltaX];
  3882. _sapp.mouse.dy = [event deltaY];
  3883. }
  3884. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3885. }
  3886. - (void)scrollWheel:(NSEvent*)event {
  3887. _sapp_gl_make_current();
  3888. _sapp_macos_mouse_update_from_nsevent(event, true);
  3889. if (_sapp_events_enabled()) {
  3890. float dx = (float) event.scrollingDeltaX;
  3891. float dy = (float) event.scrollingDeltaY;
  3892. if (event.hasPreciseScrollingDeltas) {
  3893. dx *= 0.1;
  3894. dy *= 0.1;
  3895. }
  3896. if ((_sapp_absf(dx) > 0.0f) || (_sapp_absf(dy) > 0.0f)) {
  3897. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  3898. _sapp.event.modifiers = _sapp_macos_mods(event);
  3899. _sapp.event.scroll_x = dx;
  3900. _sapp.event.scroll_y = dy;
  3901. _sapp_call_event(&_sapp.event);
  3902. }
  3903. }
  3904. }
  3905. - (void)keyDown:(NSEvent*)event {
  3906. if (_sapp_events_enabled()) {
  3907. _sapp_gl_make_current();
  3908. const uint32_t mods = _sapp_macos_mods(event);
  3909. const sapp_keycode key_code = _sapp_translate_key(event.keyCode);
  3910. _sapp_macos_key_event(SAPP_EVENTTYPE_KEY_DOWN, key_code, event.isARepeat, mods);
  3911. const NSString* chars = event.characters;
  3912. const NSUInteger len = chars.length;
  3913. if (len > 0) {
  3914. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  3915. _sapp.event.modifiers = mods;
  3916. for (NSUInteger i = 0; i < len; i++) {
  3917. const unichar codepoint = [chars characterAtIndex:i];
  3918. if ((codepoint & 0xFF00) == 0xF700) {
  3919. continue;
  3920. }
  3921. _sapp.event.char_code = codepoint;
  3922. _sapp.event.key_repeat = event.isARepeat;
  3923. _sapp_call_event(&_sapp.event);
  3924. }
  3925. }
  3926. /* if this is a Cmd+V (paste), also send a CLIPBOARD_PASTE event */
  3927. if (_sapp.clipboard.enabled && (mods == SAPP_MODIFIER_SUPER) && (key_code == SAPP_KEYCODE_V)) {
  3928. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  3929. _sapp_call_event(&_sapp.event);
  3930. }
  3931. }
  3932. }
  3933. - (void)keyUp:(NSEvent*)event {
  3934. _sapp_gl_make_current();
  3935. _sapp_macos_key_event(SAPP_EVENTTYPE_KEY_UP,
  3936. _sapp_translate_key(event.keyCode),
  3937. event.isARepeat,
  3938. _sapp_macos_mods(event));
  3939. }
  3940. - (void)flagsChanged:(NSEvent*)event {
  3941. const uint32_t old_f = _sapp.macos.flags_changed_store;
  3942. const uint32_t new_f = (uint32_t)event.modifierFlags;
  3943. _sapp.macos.flags_changed_store = new_f;
  3944. sapp_keycode key_code = SAPP_KEYCODE_INVALID;
  3945. bool down = false;
  3946. if ((new_f ^ old_f) & NSEventModifierFlagShift) {
  3947. key_code = SAPP_KEYCODE_LEFT_SHIFT;
  3948. down = 0 != (new_f & NSEventModifierFlagShift);
  3949. }
  3950. if ((new_f ^ old_f) & NSEventModifierFlagControl) {
  3951. key_code = SAPP_KEYCODE_LEFT_CONTROL;
  3952. down = 0 != (new_f & NSEventModifierFlagControl);
  3953. }
  3954. if ((new_f ^ old_f) & NSEventModifierFlagOption) {
  3955. key_code = SAPP_KEYCODE_LEFT_ALT;
  3956. down = 0 != (new_f & NSEventModifierFlagOption);
  3957. }
  3958. if ((new_f ^ old_f) & NSEventModifierFlagCommand) {
  3959. key_code = SAPP_KEYCODE_LEFT_SUPER;
  3960. down = 0 != (new_f & NSEventModifierFlagCommand);
  3961. }
  3962. if (key_code != SAPP_KEYCODE_INVALID) {
  3963. _sapp_macos_key_event(down ? SAPP_EVENTTYPE_KEY_DOWN : SAPP_EVENTTYPE_KEY_UP,
  3964. key_code,
  3965. false,
  3966. _sapp_macos_mods(event));
  3967. }
  3968. }
  3969. @end
  3970. #endif // macOS
  3971. // ██ ██████ ███████
  3972. // ██ ██ ██ ██
  3973. // ██ ██ ██ ███████
  3974. // ██ ██ ██ ██
  3975. // ██ ██████ ███████
  3976. //
  3977. // >>ios
  3978. #if defined(_SAPP_IOS)
  3979. _SOKOL_PRIVATE void _sapp_ios_discard_state(void) {
  3980. // NOTE: it's safe to call [release] on a nil object
  3981. _SAPP_OBJC_RELEASE(_sapp.ios.textfield_dlg);
  3982. _SAPP_OBJC_RELEASE(_sapp.ios.textfield);
  3983. #if defined(SOKOL_METAL)
  3984. _SAPP_OBJC_RELEASE(_sapp.ios.view_ctrl);
  3985. _SAPP_OBJC_RELEASE(_sapp.ios.mtl_device);
  3986. #else
  3987. _SAPP_OBJC_RELEASE(_sapp.ios.view_ctrl);
  3988. _SAPP_OBJC_RELEASE(_sapp.ios.eagl_ctx);
  3989. #endif
  3990. _SAPP_OBJC_RELEASE(_sapp.ios.view);
  3991. _SAPP_OBJC_RELEASE(_sapp.ios.window);
  3992. }
  3993. _SOKOL_PRIVATE void _sapp_ios_run(const sapp_desc* desc) {
  3994. _sapp_init_state(desc);
  3995. static int argc = 1;
  3996. static char* argv[] = { (char*)"sokol_app" };
  3997. UIApplicationMain(argc, argv, nil, NSStringFromClass([_sapp_app_delegate class]));
  3998. }
  3999. /* iOS entry function */
  4000. #if !defined(SOKOL_NO_ENTRY)
  4001. int main(int argc, char* argv[]) {
  4002. sapp_desc desc = sokol_main(argc, argv);
  4003. _sapp_ios_run(&desc);
  4004. return 0;
  4005. }
  4006. #endif /* SOKOL_NO_ENTRY */
  4007. _SOKOL_PRIVATE void _sapp_ios_app_event(sapp_event_type type) {
  4008. if (_sapp_events_enabled()) {
  4009. _sapp_init_event(type);
  4010. _sapp_call_event(&_sapp.event);
  4011. }
  4012. }
  4013. _SOKOL_PRIVATE void _sapp_ios_touch_event(sapp_event_type type, NSSet<UITouch *>* touches, UIEvent* event) {
  4014. if (_sapp_events_enabled()) {
  4015. _sapp_init_event(type);
  4016. NSEnumerator* enumerator = event.allTouches.objectEnumerator;
  4017. UITouch* ios_touch;
  4018. while ((ios_touch = [enumerator nextObject])) {
  4019. if ((_sapp.event.num_touches + 1) < SAPP_MAX_TOUCHPOINTS) {
  4020. CGPoint ios_pos = [ios_touch locationInView:_sapp.ios.view];
  4021. sapp_touchpoint* cur_point = &_sapp.event.touches[_sapp.event.num_touches++];
  4022. cur_point->identifier = (uintptr_t) ios_touch;
  4023. cur_point->pos_x = ios_pos.x * _sapp.dpi_scale;
  4024. cur_point->pos_y = ios_pos.y * _sapp.dpi_scale;
  4025. cur_point->changed = [touches containsObject:ios_touch];
  4026. }
  4027. }
  4028. if (_sapp.event.num_touches > 0) {
  4029. _sapp_call_event(&_sapp.event);
  4030. }
  4031. }
  4032. }
  4033. _SOKOL_PRIVATE void _sapp_ios_update_dimensions(void) {
  4034. CGRect screen_rect = UIScreen.mainScreen.bounds;
  4035. _sapp.framebuffer_width = (int)roundf(screen_rect.size.width * _sapp.dpi_scale);
  4036. _sapp.framebuffer_height = (int)roundf(screen_rect.size.height * _sapp.dpi_scale);
  4037. _sapp.window_width = (int)roundf(screen_rect.size.width);
  4038. _sapp.window_height = (int)roundf(screen_rect.size.height);
  4039. int cur_fb_width, cur_fb_height;
  4040. #if defined(SOKOL_METAL)
  4041. const CGSize fb_size = _sapp.ios.view.drawableSize;
  4042. cur_fb_width = (int)roundf(fb_size.width);
  4043. cur_fb_height = (int)roundf(fb_size.height);
  4044. #else
  4045. cur_fb_width = (int)roundf(_sapp.ios.view.drawableWidth);
  4046. cur_fb_height = (int)roundf(_sapp.ios.view.drawableHeight);
  4047. #endif
  4048. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  4049. (_sapp.framebuffer_height != cur_fb_height);
  4050. if (dim_changed) {
  4051. #if defined(SOKOL_METAL)
  4052. const CGSize drawable_size = { (CGFloat) _sapp.framebuffer_width, (CGFloat) _sapp.framebuffer_height };
  4053. _sapp.ios.view.drawableSize = drawable_size;
  4054. #else
  4055. // nothing to do here, GLKView correctly respects the view's contentScaleFactor
  4056. #endif
  4057. if (!_sapp.first_frame) {
  4058. _sapp_ios_app_event(SAPP_EVENTTYPE_RESIZED);
  4059. }
  4060. }
  4061. }
  4062. _SOKOL_PRIVATE void _sapp_ios_frame(void) {
  4063. _sapp_ios_update_dimensions();
  4064. _sapp_frame();
  4065. }
  4066. _SOKOL_PRIVATE void _sapp_ios_show_keyboard(bool shown) {
  4067. /* if not happened yet, create an invisible text field */
  4068. if (nil == _sapp.ios.textfield) {
  4069. _sapp.ios.textfield_dlg = [[_sapp_textfield_dlg alloc] init];
  4070. _sapp.ios.textfield = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];
  4071. _sapp.ios.textfield.keyboardType = UIKeyboardTypeDefault;
  4072. _sapp.ios.textfield.returnKeyType = UIReturnKeyDefault;
  4073. _sapp.ios.textfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
  4074. _sapp.ios.textfield.autocorrectionType = UITextAutocorrectionTypeNo;
  4075. _sapp.ios.textfield.spellCheckingType = UITextSpellCheckingTypeNo;
  4076. _sapp.ios.textfield.hidden = YES;
  4077. _sapp.ios.textfield.text = @"x";
  4078. _sapp.ios.textfield.delegate = _sapp.ios.textfield_dlg;
  4079. [_sapp.ios.view_ctrl.view addSubview:_sapp.ios.textfield];
  4080. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4081. selector:@selector(keyboardWasShown:)
  4082. name:UIKeyboardDidShowNotification object:nil];
  4083. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4084. selector:@selector(keyboardWillBeHidden:)
  4085. name:UIKeyboardWillHideNotification object:nil];
  4086. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4087. selector:@selector(keyboardDidChangeFrame:)
  4088. name:UIKeyboardDidChangeFrameNotification object:nil];
  4089. }
  4090. if (shown) {
  4091. /* setting the text field as first responder brings up the onscreen keyboard */
  4092. [_sapp.ios.textfield becomeFirstResponder];
  4093. }
  4094. else {
  4095. [_sapp.ios.textfield resignFirstResponder];
  4096. }
  4097. }
  4098. @implementation _sapp_app_delegate
  4099. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  4100. CGRect screen_rect = UIScreen.mainScreen.bounds;
  4101. _sapp.ios.window = [[UIWindow alloc] initWithFrame:screen_rect];
  4102. _sapp.window_width = (int)roundf(screen_rect.size.width);
  4103. _sapp.window_height = (int)roundf(screen_rect.size.height);
  4104. if (_sapp.desc.high_dpi) {
  4105. _sapp.dpi_scale = (float) UIScreen.mainScreen.nativeScale;
  4106. }
  4107. else {
  4108. _sapp.dpi_scale = 1.0f;
  4109. }
  4110. _sapp.framebuffer_width = (int)roundf(_sapp.window_width * _sapp.dpi_scale);
  4111. _sapp.framebuffer_height = (int)roundf(_sapp.window_height * _sapp.dpi_scale);
  4112. NSInteger max_fps = UIScreen.mainScreen.maximumFramesPerSecond;
  4113. #if defined(SOKOL_METAL)
  4114. _sapp.ios.mtl_device = MTLCreateSystemDefaultDevice();
  4115. _sapp.ios.view = [[_sapp_ios_view alloc] init];
  4116. _sapp.ios.view.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  4117. _sapp.ios.view.device = _sapp.ios.mtl_device;
  4118. _sapp.ios.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
  4119. _sapp.ios.view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  4120. _sapp.ios.view.sampleCount = (NSUInteger)_sapp.sample_count;
  4121. /* NOTE: iOS MTKView seems to ignore thew view's contentScaleFactor
  4122. and automatically renders at Retina resolution. We'll disable
  4123. autoResize and instead do the resizing in _sapp_ios_update_dimensions()
  4124. */
  4125. _sapp.ios.view.autoResizeDrawable = false;
  4126. _sapp.ios.view.userInteractionEnabled = YES;
  4127. _sapp.ios.view.multipleTouchEnabled = YES;
  4128. _sapp.ios.view_ctrl = [[UIViewController alloc] init];
  4129. _sapp.ios.view_ctrl.modalPresentationStyle = UIModalPresentationFullScreen;
  4130. _sapp.ios.view_ctrl.view = _sapp.ios.view;
  4131. _sapp.ios.window.rootViewController = _sapp.ios.view_ctrl;
  4132. #else
  4133. _sapp.ios.eagl_ctx = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
  4134. _sapp.ios.view = [[_sapp_ios_view alloc] initWithFrame:screen_rect];
  4135. _sapp.ios.view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
  4136. _sapp.ios.view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
  4137. _sapp.ios.view.drawableStencilFormat = GLKViewDrawableStencilFormatNone;
  4138. GLKViewDrawableMultisample msaa = _sapp.sample_count > 1 ? GLKViewDrawableMultisample4X : GLKViewDrawableMultisampleNone;
  4139. _sapp.ios.view.drawableMultisample = msaa;
  4140. _sapp.ios.view.context = _sapp.ios.eagl_ctx;
  4141. _sapp.ios.view.enableSetNeedsDisplay = NO;
  4142. _sapp.ios.view.userInteractionEnabled = YES;
  4143. _sapp.ios.view.multipleTouchEnabled = YES;
  4144. // on GLKView, contentScaleFactor appears to work just fine!
  4145. if (_sapp.desc.high_dpi) {
  4146. _sapp.ios.view.contentScaleFactor = _sapp.dpi_scale;
  4147. }
  4148. else {
  4149. _sapp.ios.view.contentScaleFactor = 1.0;
  4150. }
  4151. _sapp.ios.view_ctrl = [[GLKViewController alloc] init];
  4152. _sapp.ios.view_ctrl.view = _sapp.ios.view;
  4153. _sapp.ios.view_ctrl.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  4154. _sapp.ios.window.rootViewController = _sapp.ios.view_ctrl;
  4155. #endif
  4156. [_sapp.ios.window makeKeyAndVisible];
  4157. _sapp.valid = true;
  4158. return YES;
  4159. }
  4160. - (void)applicationWillResignActive:(UIApplication *)application {
  4161. if (!_sapp.ios.suspended) {
  4162. _sapp.ios.suspended = true;
  4163. _sapp_ios_app_event(SAPP_EVENTTYPE_SUSPENDED);
  4164. }
  4165. }
  4166. - (void)applicationDidBecomeActive:(UIApplication *)application {
  4167. if (_sapp.ios.suspended) {
  4168. _sapp.ios.suspended = false;
  4169. _sapp_ios_app_event(SAPP_EVENTTYPE_RESUMED);
  4170. }
  4171. }
  4172. /* NOTE: this method will rarely ever be called, iOS application
  4173. which are terminated by the user are usually killed via signal 9
  4174. by the operating system.
  4175. */
  4176. - (void)applicationWillTerminate:(UIApplication *)application {
  4177. _SOKOL_UNUSED(application);
  4178. _sapp_call_cleanup();
  4179. _sapp_ios_discard_state();
  4180. _sapp_discard_state();
  4181. }
  4182. @end
  4183. @implementation _sapp_textfield_dlg
  4184. - (void)keyboardWasShown:(NSNotification*)notif {
  4185. _sapp.onscreen_keyboard_shown = true;
  4186. /* query the keyboard's size, and modify the content view's size */
  4187. if (_sapp.desc.ios_keyboard_resizes_canvas) {
  4188. NSDictionary* info = notif.userInfo;
  4189. CGFloat kbd_h = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
  4190. CGRect view_frame = UIScreen.mainScreen.bounds;
  4191. view_frame.size.height -= kbd_h;
  4192. _sapp.ios.view.frame = view_frame;
  4193. }
  4194. }
  4195. - (void)keyboardWillBeHidden:(NSNotification*)notif {
  4196. _sapp.onscreen_keyboard_shown = false;
  4197. if (_sapp.desc.ios_keyboard_resizes_canvas) {
  4198. _sapp.ios.view.frame = UIScreen.mainScreen.bounds;
  4199. }
  4200. }
  4201. - (void)keyboardDidChangeFrame:(NSNotification*)notif {
  4202. /* this is for the case when the screen rotation changes while the keyboard is open */
  4203. if (_sapp.onscreen_keyboard_shown && _sapp.desc.ios_keyboard_resizes_canvas) {
  4204. NSDictionary* info = notif.userInfo;
  4205. CGFloat kbd_h = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
  4206. CGRect view_frame = UIScreen.mainScreen.bounds;
  4207. view_frame.size.height -= kbd_h;
  4208. _sapp.ios.view.frame = view_frame;
  4209. }
  4210. }
  4211. - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
  4212. if (_sapp_events_enabled()) {
  4213. const NSUInteger len = string.length;
  4214. if (len > 0) {
  4215. for (NSUInteger i = 0; i < len; i++) {
  4216. unichar c = [string characterAtIndex:i];
  4217. if (c >= 32) {
  4218. /* ignore surrogates for now */
  4219. if ((c < 0xD800) || (c > 0xDFFF)) {
  4220. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  4221. _sapp.event.char_code = c;
  4222. _sapp_call_event(&_sapp.event);
  4223. }
  4224. }
  4225. if (c <= 32) {
  4226. sapp_keycode k = SAPP_KEYCODE_INVALID;
  4227. switch (c) {
  4228. case 10: k = SAPP_KEYCODE_ENTER; break;
  4229. case 32: k = SAPP_KEYCODE_SPACE; break;
  4230. default: break;
  4231. }
  4232. if (k != SAPP_KEYCODE_INVALID) {
  4233. _sapp_init_event(SAPP_EVENTTYPE_KEY_DOWN);
  4234. _sapp.event.key_code = k;
  4235. _sapp_call_event(&_sapp.event);
  4236. _sapp_init_event(SAPP_EVENTTYPE_KEY_UP);
  4237. _sapp.event.key_code = k;
  4238. _sapp_call_event(&_sapp.event);
  4239. }
  4240. }
  4241. }
  4242. }
  4243. else {
  4244. /* this was a backspace */
  4245. _sapp_init_event(SAPP_EVENTTYPE_KEY_DOWN);
  4246. _sapp.event.key_code = SAPP_KEYCODE_BACKSPACE;
  4247. _sapp_call_event(&_sapp.event);
  4248. _sapp_init_event(SAPP_EVENTTYPE_KEY_UP);
  4249. _sapp.event.key_code = SAPP_KEYCODE_BACKSPACE;
  4250. _sapp_call_event(&_sapp.event);
  4251. }
  4252. }
  4253. return NO;
  4254. }
  4255. @end
  4256. @implementation _sapp_ios_view
  4257. - (void)drawRect:(CGRect)rect {
  4258. _SOKOL_UNUSED(rect);
  4259. #if defined(_SAPP_ANY_GL)
  4260. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  4261. #endif
  4262. _sapp_timing_measure(&_sapp.timing);
  4263. @autoreleasepool {
  4264. _sapp_ios_frame();
  4265. }
  4266. }
  4267. - (BOOL)isOpaque {
  4268. return YES;
  4269. }
  4270. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4271. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_BEGAN, touches, event);
  4272. }
  4273. - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4274. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_MOVED, touches, event);
  4275. }
  4276. - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4277. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_ENDED, touches, event);
  4278. }
  4279. - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4280. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_CANCELLED, touches, event);
  4281. }
  4282. @end
  4283. #endif /* TARGET_OS_IPHONE */
  4284. #endif /* _SAPP_APPLE */
  4285. // ███████ ███ ███ ███████ ██████ ██████ ██ ██████ ████████ ███████ ███ ██
  4286. // ██ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  4287. // █████ ██ ████ ██ ███████ ██ ██████ ██ ██████ ██ █████ ██ ██ ██
  4288. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  4289. // ███████ ██ ██ ███████ ██████ ██ ██ ██ ██ ██ ███████ ██ ████
  4290. //
  4291. // >>emscripten
  4292. #if defined(_SAPP_EMSCRIPTEN)
  4293. #if defined(EM_JS_DEPS)
  4294. EM_JS_DEPS(sokol_app, "$withStackSave,$stringToUTF8OnStack");
  4295. #endif
  4296. #ifdef __cplusplus
  4297. extern "C" {
  4298. #endif
  4299. typedef void (*_sapp_html5_fetch_callback) (const sapp_html5_fetch_response*);
  4300. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_onpaste(const char* str) {
  4301. if (_sapp.clipboard.enabled) {
  4302. _sapp_strcpy(str, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  4303. if (_sapp_events_enabled()) {
  4304. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  4305. _sapp_call_event(&_sapp.event);
  4306. }
  4307. }
  4308. }
  4309. /* https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload */
  4310. EMSCRIPTEN_KEEPALIVE int _sapp_html5_get_ask_leave_site(void) {
  4311. return _sapp.html5_ask_leave_site ? 1 : 0;
  4312. }
  4313. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_begin_drop(int num) {
  4314. if (!_sapp.drop.enabled) {
  4315. return;
  4316. }
  4317. if (num < 0) {
  4318. num = 0;
  4319. }
  4320. if (num > _sapp.drop.max_files) {
  4321. num = _sapp.drop.max_files;
  4322. }
  4323. _sapp.drop.num_files = num;
  4324. _sapp_clear_drop_buffer();
  4325. }
  4326. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_drop(int i, const char* name) {
  4327. /* NOTE: name is only the filename part, not a path */
  4328. if (!_sapp.drop.enabled) {
  4329. return;
  4330. }
  4331. if (0 == name) {
  4332. return;
  4333. }
  4334. SOKOL_ASSERT(_sapp.drop.num_files <= _sapp.drop.max_files);
  4335. if ((i < 0) || (i >= _sapp.drop.num_files)) {
  4336. return;
  4337. }
  4338. if (!_sapp_strcpy(name, _sapp_dropped_file_path_ptr(i), _sapp.drop.max_path_length)) {
  4339. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  4340. _sapp.drop.num_files = 0;
  4341. }
  4342. }
  4343. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_end_drop(int x, int y, int mods) {
  4344. if (!_sapp.drop.enabled) {
  4345. return;
  4346. }
  4347. if (0 == _sapp.drop.num_files) {
  4348. /* there was an error copying the filenames */
  4349. _sapp_clear_drop_buffer();
  4350. return;
  4351. }
  4352. if (_sapp_events_enabled()) {
  4353. _sapp.mouse.x = (float)x * _sapp.dpi_scale;
  4354. _sapp.mouse.y = (float)y * _sapp.dpi_scale;
  4355. _sapp.mouse.dx = 0.0f;
  4356. _sapp.mouse.dy = 0.0f;
  4357. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  4358. // see sapp_js_add_dragndrop_listeners for mods constants
  4359. if (mods & 1) { _sapp.event.modifiers |= SAPP_MODIFIER_SHIFT; }
  4360. if (mods & 2) { _sapp.event.modifiers |= SAPP_MODIFIER_CTRL; }
  4361. if (mods & 4) { _sapp.event.modifiers |= SAPP_MODIFIER_ALT; }
  4362. if (mods & 8) { _sapp.event.modifiers |= SAPP_MODIFIER_SUPER; }
  4363. _sapp_call_event(&_sapp.event);
  4364. }
  4365. }
  4366. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_invoke_fetch_cb(int index, int success, int error_code, _sapp_html5_fetch_callback callback, uint32_t fetched_size, void* buf_ptr, uint32_t buf_size, void* user_data) {
  4367. sapp_html5_fetch_response response;
  4368. _sapp_clear(&response, sizeof(response));
  4369. response.succeeded = (0 != success);
  4370. response.error_code = (sapp_html5_fetch_error) error_code;
  4371. response.file_index = index;
  4372. response.data.ptr = buf_ptr;
  4373. response.data.size = fetched_size;
  4374. response.buffer.ptr = buf_ptr;
  4375. response.buffer.size = buf_size;
  4376. response.user_data = user_data;
  4377. callback(&response);
  4378. }
  4379. #ifdef __cplusplus
  4380. } /* extern "C" */
  4381. #endif
  4382. EM_JS(void, sapp_js_add_beforeunload_listener, (void), {
  4383. Module.sokol_beforeunload = (event) => {
  4384. if (__sapp_html5_get_ask_leave_site() != 0) {
  4385. event.preventDefault();
  4386. event.returnValue = ' ';
  4387. }
  4388. };
  4389. window.addEventListener('beforeunload', Module.sokol_beforeunload);
  4390. });
  4391. EM_JS(void, sapp_js_remove_beforeunload_listener, (void), {
  4392. window.removeEventListener('beforeunload', Module.sokol_beforeunload);
  4393. });
  4394. EM_JS(void, sapp_js_add_clipboard_listener, (void), {
  4395. Module.sokol_paste = (event) => {
  4396. const pasted_str = event.clipboardData.getData('text');
  4397. withStackSave(() => {
  4398. const cstr = stringToUTF8OnStack(pasted_str);
  4399. __sapp_emsc_onpaste(cstr);
  4400. });
  4401. };
  4402. window.addEventListener('paste', Module.sokol_paste);
  4403. });
  4404. EM_JS(void, sapp_js_remove_clipboard_listener, (void), {
  4405. window.removeEventListener('paste', Module.sokol_paste);
  4406. });
  4407. EM_JS(void, sapp_js_write_clipboard, (const char* c_str), {
  4408. const str = UTF8ToString(c_str);
  4409. const ta = document.createElement('textarea');
  4410. ta.setAttribute('autocomplete', 'off');
  4411. ta.setAttribute('autocorrect', 'off');
  4412. ta.setAttribute('autocapitalize', 'off');
  4413. ta.setAttribute('spellcheck', 'false');
  4414. ta.style.left = -100 + 'px';
  4415. ta.style.top = -100 + 'px';
  4416. ta.style.height = 1;
  4417. ta.style.width = 1;
  4418. ta.value = str;
  4419. document.body.appendChild(ta);
  4420. ta.select();
  4421. document.execCommand('copy');
  4422. document.body.removeChild(ta);
  4423. });
  4424. _SOKOL_PRIVATE void _sapp_emsc_set_clipboard_string(const char* str) {
  4425. sapp_js_write_clipboard(str);
  4426. }
  4427. EM_JS(void, sapp_js_add_dragndrop_listeners, (const char* canvas_name_cstr), {
  4428. Module.sokol_drop_files = [];
  4429. const canvas_name = UTF8ToString(canvas_name_cstr);
  4430. const canvas = document.getElementById(canvas_name);
  4431. Module.sokol_dragenter = (event) => {
  4432. event.stopPropagation();
  4433. event.preventDefault();
  4434. };
  4435. Module.sokol_dragleave = (event) => {
  4436. event.stopPropagation();
  4437. event.preventDefault();
  4438. };
  4439. Module.sokol_dragover = (event) => {
  4440. event.stopPropagation();
  4441. event.preventDefault();
  4442. };
  4443. Module.sokol_drop = (event) => {
  4444. event.stopPropagation();
  4445. event.preventDefault();
  4446. const files = event.dataTransfer.files;
  4447. Module.sokol_dropped_files = files;
  4448. __sapp_emsc_begin_drop(files.length);
  4449. for (let i = 0; i < files.length; i++) {
  4450. withStackSave(() => {
  4451. const cstr = stringToUTF8OnStack(files[i].name);
  4452. __sapp_emsc_drop(i, cstr);
  4453. });
  4454. }
  4455. let mods = 0;
  4456. if (event.shiftKey) { mods |= 1; }
  4457. if (event.ctrlKey) { mods |= 2; }
  4458. if (event.altKey) { mods |= 4; }
  4459. if (event.metaKey) { mods |= 8; }
  4460. // FIXME? see computation of targetX/targetY in emscripten via getClientBoundingRect
  4461. __sapp_emsc_end_drop(event.clientX, event.clientY, mods);
  4462. };
  4463. canvas.addEventListener('dragenter', Module.sokol_dragenter, false);
  4464. canvas.addEventListener('dragleave', Module.sokol_dragleave, false);
  4465. canvas.addEventListener('dragover', Module.sokol_dragover, false);
  4466. canvas.addEventListener('drop', Module.sokol_drop, false);
  4467. });
  4468. EM_JS(uint32_t, sapp_js_dropped_file_size, (int index), {
  4469. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4470. const files = Module.sokol_dropped_files;
  4471. if ((index < 0) || (index >= files.length)) {
  4472. return 0;
  4473. }
  4474. else {
  4475. return files[index].size;
  4476. }
  4477. });
  4478. EM_JS(void, sapp_js_fetch_dropped_file, (int index, _sapp_html5_fetch_callback callback, void* buf_ptr, uint32_t buf_size, void* user_data), {
  4479. const reader = new FileReader();
  4480. reader.onload = (loadEvent) => {
  4481. const content = loadEvent.target.result;
  4482. if (content.byteLength > buf_size) {
  4483. // SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL
  4484. __sapp_emsc_invoke_fetch_cb(index, 0, 1, callback, 0, buf_ptr, buf_size, user_data);
  4485. }
  4486. else {
  4487. HEAPU8.set(new Uint8Array(content), buf_ptr);
  4488. __sapp_emsc_invoke_fetch_cb(index, 1, 0, callback, content.byteLength, buf_ptr, buf_size, user_data);
  4489. }
  4490. };
  4491. reader.onerror = () => {
  4492. // SAPP_HTML5_FETCH_ERROR_OTHER
  4493. __sapp_emsc_invoke_fetch_cb(index, 0, 2, callback, 0, buf_ptr, buf_size, user_data);
  4494. };
  4495. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4496. const files = Module.sokol_dropped_files;
  4497. reader.readAsArrayBuffer(files[index]);
  4498. });
  4499. EM_JS(void, sapp_js_remove_dragndrop_listeners, (const char* canvas_name_cstr), {
  4500. const canvas_name = UTF8ToString(canvas_name_cstr);
  4501. const canvas = document.getElementById(canvas_name);
  4502. canvas.removeEventListener('dragenter', Module.sokol_dragenter);
  4503. canvas.removeEventListener('dragleave', Module.sokol_dragleave);
  4504. canvas.removeEventListener('dragover', Module.sokol_dragover);
  4505. canvas.removeEventListener('drop', Module.sokol_drop);
  4506. });
  4507. EM_JS(void, sapp_js_init, (const char* c_str_target), {
  4508. // lookup and store canvas object by name
  4509. const target_str = UTF8ToString(c_str_target);
  4510. Module.sapp_emsc_target = document.getElementById(target_str);
  4511. if (!Module.sapp_emsc_target) {
  4512. console.log("sokol_app.h: invalid target:" + target_str);
  4513. }
  4514. if (!Module.sapp_emsc_target.requestPointerLock) {
  4515. console.log("sokol_app.h: target doesn't support requestPointerLock:" + target_str);
  4516. }
  4517. });
  4518. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_pointerlockchange_cb(int emsc_type, const EmscriptenPointerlockChangeEvent* emsc_event, void* user_data) {
  4519. _SOKOL_UNUSED(emsc_type);
  4520. _SOKOL_UNUSED(user_data);
  4521. _sapp.mouse.locked = emsc_event->isActive;
  4522. return EM_TRUE;
  4523. }
  4524. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_pointerlockerror_cb(int emsc_type, const void* reserved, void* user_data) {
  4525. _SOKOL_UNUSED(emsc_type);
  4526. _SOKOL_UNUSED(reserved);
  4527. _SOKOL_UNUSED(user_data);
  4528. _sapp.mouse.locked = false;
  4529. _sapp.emsc.mouse_lock_requested = false;
  4530. return true;
  4531. }
  4532. EM_JS(void, sapp_js_request_pointerlock, (void), {
  4533. if (Module.sapp_emsc_target) {
  4534. if (Module.sapp_emsc_target.requestPointerLock) {
  4535. Module.sapp_emsc_target.requestPointerLock();
  4536. }
  4537. }
  4538. });
  4539. EM_JS(void, sapp_js_exit_pointerlock, (void), {
  4540. if (document.exitPointerLock) {
  4541. document.exitPointerLock();
  4542. }
  4543. });
  4544. _SOKOL_PRIVATE void _sapp_emsc_lock_mouse(bool lock) {
  4545. if (lock) {
  4546. /* request mouse-lock during event handler invocation (see _sapp_emsc_update_mouse_lock_state) */
  4547. _sapp.emsc.mouse_lock_requested = true;
  4548. }
  4549. else {
  4550. /* NOTE: the _sapp.mouse_locked state will be set in the pointerlockchange callback */
  4551. _sapp.emsc.mouse_lock_requested = false;
  4552. sapp_js_exit_pointerlock();
  4553. }
  4554. }
  4555. /* called from inside event handlers to check if mouse lock had been requested,
  4556. and if yes, actually enter mouse lock.
  4557. */
  4558. _SOKOL_PRIVATE void _sapp_emsc_update_mouse_lock_state(void) {
  4559. if (_sapp.emsc.mouse_lock_requested) {
  4560. _sapp.emsc.mouse_lock_requested = false;
  4561. sapp_js_request_pointerlock();
  4562. }
  4563. }
  4564. // set mouse cursor type
  4565. EM_JS(void, sapp_js_set_cursor, (int cursor_type, int shown), {
  4566. if (Module.sapp_emsc_target) {
  4567. let cursor;
  4568. if (shown === 0) {
  4569. cursor = "none";
  4570. }
  4571. else switch (cursor_type) {
  4572. case 0: cursor = "auto"; break; // SAPP_MOUSECURSOR_DEFAULT
  4573. case 1: cursor = "default"; break; // SAPP_MOUSECURSOR_ARROW
  4574. case 2: cursor = "text"; break; // SAPP_MOUSECURSOR_IBEAM
  4575. case 3: cursor = "crosshair"; break; // SAPP_MOUSECURSOR_CROSSHAIR
  4576. case 4: cursor = "pointer"; break; // SAPP_MOUSECURSOR_POINTING_HAND
  4577. case 5: cursor = "ew-resize"; break; // SAPP_MOUSECURSOR_RESIZE_EW
  4578. case 6: cursor = "ns-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NS
  4579. case 7: cursor = "nwse-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NWSE
  4580. case 8: cursor = "nesw-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NESW
  4581. case 9: cursor = "all-scroll"; break; // SAPP_MOUSECURSOR_RESIZE_ALL
  4582. case 10: cursor = "not-allowed"; break; // SAPP_MOUSECURSOR_NOT_ALLOWED
  4583. default: cursor = "auto"; break;
  4584. }
  4585. Module.sapp_emsc_target.style.cursor = cursor;
  4586. }
  4587. });
  4588. _SOKOL_PRIVATE void _sapp_emsc_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  4589. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  4590. sapp_js_set_cursor((int)cursor, shown ? 1 : 0);
  4591. }
  4592. /* JS helper functions to update browser tab favicon */
  4593. EM_JS(void, sapp_js_clear_favicon, (void), {
  4594. const link = document.getElementById('sokol-app-favicon');
  4595. if (link) {
  4596. document.head.removeChild(link);
  4597. }
  4598. });
  4599. EM_JS(void, sapp_js_set_favicon, (int w, int h, const uint8_t* pixels), {
  4600. const canvas = document.createElement('canvas');
  4601. canvas.width = w;
  4602. canvas.height = h;
  4603. const ctx = canvas.getContext('2d');
  4604. const img_data = ctx.createImageData(w, h);
  4605. img_data.data.set(HEAPU8.subarray(pixels, pixels + w*h*4));
  4606. ctx.putImageData(img_data, 0, 0);
  4607. const new_link = document.createElement('link');
  4608. new_link.id = 'sokol-app-favicon';
  4609. new_link.rel = 'shortcut icon';
  4610. new_link.href = canvas.toDataURL();
  4611. document.head.appendChild(new_link);
  4612. });
  4613. _SOKOL_PRIVATE void _sapp_emsc_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  4614. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  4615. sapp_js_clear_favicon();
  4616. // find the best matching image candidate for 16x16 pixels
  4617. int img_index = _sapp_image_bestmatch(icon_desc->images, num_images, 16, 16);
  4618. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  4619. sapp_js_set_favicon(img_desc->width, img_desc->height, (const uint8_t*) img_desc->pixels.ptr);
  4620. }
  4621. _SOKOL_PRIVATE uint32_t _sapp_emsc_mouse_button_mods(uint16_t buttons) {
  4622. uint32_t m = 0;
  4623. if (0 != (buttons & (1<<0))) { m |= SAPP_MODIFIER_LMB; }
  4624. if (0 != (buttons & (1<<1))) { m |= SAPP_MODIFIER_RMB; } // not a bug
  4625. if (0 != (buttons & (1<<2))) { m |= SAPP_MODIFIER_MMB; } // not a bug
  4626. return m;
  4627. }
  4628. _SOKOL_PRIVATE uint32_t _sapp_emsc_mouse_event_mods(const EmscriptenMouseEvent* ev) {
  4629. uint32_t m = 0;
  4630. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  4631. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  4632. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  4633. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  4634. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  4635. return m;
  4636. }
  4637. _SOKOL_PRIVATE uint32_t _sapp_emsc_key_event_mods(const EmscriptenKeyboardEvent* ev) {
  4638. uint32_t m = 0;
  4639. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  4640. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  4641. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  4642. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  4643. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  4644. return m;
  4645. }
  4646. _SOKOL_PRIVATE uint32_t _sapp_emsc_touch_event_mods(const EmscriptenTouchEvent* ev) {
  4647. uint32_t m = 0;
  4648. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  4649. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  4650. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  4651. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  4652. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  4653. return m;
  4654. }
  4655. #if defined(SOKOL_WGPU)
  4656. _SOKOL_PRIVATE void _sapp_emsc_wgpu_size_changed(void);
  4657. #endif
  4658. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_size_changed(int event_type, const EmscriptenUiEvent* ui_event, void* user_data) {
  4659. _SOKOL_UNUSED(event_type);
  4660. _SOKOL_UNUSED(user_data);
  4661. double w, h;
  4662. emscripten_get_element_css_size(_sapp.html5_canvas_selector, &w, &h);
  4663. /* The above method might report zero when toggling HTML5 fullscreen,
  4664. in that case use the window's inner width reported by the
  4665. emscripten event. This works ok when toggling *into* fullscreen
  4666. but doesn't properly restore the previous canvas size when switching
  4667. back from fullscreen.
  4668. In general, due to the HTML5's fullscreen API's flaky nature it is
  4669. recommended to use 'soft fullscreen' (stretching the WebGL canvas
  4670. over the browser windows client rect) with a CSS definition like this:
  4671. position: absolute;
  4672. top: 0px;
  4673. left: 0px;
  4674. margin: 0px;
  4675. border: 0;
  4676. width: 100%;
  4677. height: 100%;
  4678. overflow: hidden;
  4679. display: block;
  4680. */
  4681. if (w < 1.0) {
  4682. w = ui_event->windowInnerWidth;
  4683. }
  4684. else {
  4685. _sapp.window_width = (int)roundf(w);
  4686. }
  4687. if (h < 1.0) {
  4688. h = ui_event->windowInnerHeight;
  4689. }
  4690. else {
  4691. _sapp.window_height = (int)roundf(h);
  4692. }
  4693. if (_sapp.desc.high_dpi) {
  4694. _sapp.dpi_scale = emscripten_get_device_pixel_ratio();
  4695. }
  4696. _sapp.framebuffer_width = (int)roundf(w * _sapp.dpi_scale);
  4697. _sapp.framebuffer_height = (int)roundf(h * _sapp.dpi_scale);
  4698. SOKOL_ASSERT((_sapp.framebuffer_width > 0) && (_sapp.framebuffer_height > 0));
  4699. emscripten_set_canvas_element_size(_sapp.html5_canvas_selector, _sapp.framebuffer_width, _sapp.framebuffer_height);
  4700. #if defined(SOKOL_WGPU)
  4701. // on WebGPU: recreate size-dependent rendering surfaces
  4702. _sapp_emsc_wgpu_size_changed();
  4703. #endif
  4704. if (_sapp_events_enabled()) {
  4705. _sapp_init_event(SAPP_EVENTTYPE_RESIZED);
  4706. _sapp_call_event(&_sapp.event);
  4707. }
  4708. return true;
  4709. }
  4710. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_mouse_cb(int emsc_type, const EmscriptenMouseEvent* emsc_event, void* user_data) {
  4711. _SOKOL_UNUSED(user_data);
  4712. bool consume_event = !_sapp.desc.html5_bubble_mouse_events;
  4713. _sapp.emsc.mouse_buttons = emsc_event->buttons;
  4714. if (_sapp.mouse.locked) {
  4715. _sapp.mouse.dx = (float) emsc_event->movementX;
  4716. _sapp.mouse.dy = (float) emsc_event->movementY;
  4717. } else {
  4718. float new_x = emsc_event->targetX * _sapp.dpi_scale;
  4719. float new_y = emsc_event->targetY * _sapp.dpi_scale;
  4720. if (_sapp.mouse.pos_valid) {
  4721. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  4722. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  4723. }
  4724. _sapp.mouse.x = new_x;
  4725. _sapp.mouse.y = new_y;
  4726. _sapp.mouse.pos_valid = true;
  4727. }
  4728. if (_sapp_events_enabled() && (emsc_event->button >= 0) && (emsc_event->button < SAPP_MAX_MOUSEBUTTONS)) {
  4729. sapp_event_type type;
  4730. bool is_button_event = false;
  4731. bool clear_dxdy = false;
  4732. switch (emsc_type) {
  4733. case EMSCRIPTEN_EVENT_MOUSEDOWN:
  4734. type = SAPP_EVENTTYPE_MOUSE_DOWN;
  4735. is_button_event = true;
  4736. break;
  4737. case EMSCRIPTEN_EVENT_MOUSEUP:
  4738. type = SAPP_EVENTTYPE_MOUSE_UP;
  4739. is_button_event = true;
  4740. break;
  4741. case EMSCRIPTEN_EVENT_MOUSEMOVE:
  4742. type = SAPP_EVENTTYPE_MOUSE_MOVE;
  4743. break;
  4744. case EMSCRIPTEN_EVENT_MOUSEENTER:
  4745. type = SAPP_EVENTTYPE_MOUSE_ENTER;
  4746. clear_dxdy = true;
  4747. break;
  4748. case EMSCRIPTEN_EVENT_MOUSELEAVE:
  4749. type = SAPP_EVENTTYPE_MOUSE_LEAVE;
  4750. clear_dxdy = true;
  4751. break;
  4752. default:
  4753. type = SAPP_EVENTTYPE_INVALID;
  4754. break;
  4755. }
  4756. if (clear_dxdy) {
  4757. _sapp.mouse.dx = 0.0f;
  4758. _sapp.mouse.dy = 0.0f;
  4759. }
  4760. if (type != SAPP_EVENTTYPE_INVALID) {
  4761. _sapp_init_event(type);
  4762. _sapp.event.modifiers = _sapp_emsc_mouse_event_mods(emsc_event);
  4763. if (is_button_event) {
  4764. switch (emsc_event->button) {
  4765. case 0: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_LEFT; break;
  4766. case 1: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_MIDDLE; break;
  4767. case 2: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_RIGHT; break;
  4768. default: _sapp.event.mouse_button = (sapp_mousebutton)emsc_event->button; break;
  4769. }
  4770. } else {
  4771. _sapp.event.mouse_button = SAPP_MOUSEBUTTON_INVALID;
  4772. }
  4773. consume_event |= _sapp_call_event(&_sapp.event);
  4774. }
  4775. // mouse lock can only be activated in mouse button events (not in move, enter or leave)
  4776. if (is_button_event) {
  4777. _sapp_emsc_update_mouse_lock_state();
  4778. }
  4779. }
  4780. return consume_event;
  4781. }
  4782. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_wheel_cb(int emsc_type, const EmscriptenWheelEvent* emsc_event, void* user_data) {
  4783. _SOKOL_UNUSED(emsc_type);
  4784. _SOKOL_UNUSED(user_data);
  4785. bool consume_event = !_sapp.desc.html5_bubble_wheel_events;
  4786. _sapp.emsc.mouse_buttons = emsc_event->mouse.buttons;
  4787. if (_sapp_events_enabled()) {
  4788. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  4789. _sapp.event.modifiers = _sapp_emsc_mouse_event_mods(&emsc_event->mouse);
  4790. /* see https://github.com/floooh/sokol/issues/339 */
  4791. float scale;
  4792. switch (emsc_event->deltaMode) {
  4793. case DOM_DELTA_PIXEL: scale = -0.04f; break;
  4794. case DOM_DELTA_LINE: scale = -1.33f; break;
  4795. case DOM_DELTA_PAGE: scale = -10.0f; break; // FIXME: this is a guess
  4796. default: scale = -0.1f; break; // shouldn't happen
  4797. }
  4798. _sapp.event.scroll_x = scale * (float)emsc_event->deltaX;
  4799. _sapp.event.scroll_y = scale * (float)emsc_event->deltaY;
  4800. consume_event |= _sapp_call_event(&_sapp.event);
  4801. }
  4802. _sapp_emsc_update_mouse_lock_state();
  4803. return consume_event;
  4804. }
  4805. static struct {
  4806. const char* str;
  4807. sapp_keycode code;
  4808. } _sapp_emsc_keymap[] = {
  4809. { "Backspace", SAPP_KEYCODE_BACKSPACE },
  4810. { "Tab", SAPP_KEYCODE_TAB },
  4811. { "Enter", SAPP_KEYCODE_ENTER },
  4812. { "ShiftLeft", SAPP_KEYCODE_LEFT_SHIFT },
  4813. { "ShiftRight", SAPP_KEYCODE_RIGHT_SHIFT },
  4814. { "ControlLeft", SAPP_KEYCODE_LEFT_CONTROL },
  4815. { "ControlRight", SAPP_KEYCODE_RIGHT_CONTROL },
  4816. { "AltLeft", SAPP_KEYCODE_LEFT_ALT },
  4817. { "AltRight", SAPP_KEYCODE_RIGHT_ALT },
  4818. { "Pause", SAPP_KEYCODE_PAUSE },
  4819. { "CapsLock", SAPP_KEYCODE_CAPS_LOCK },
  4820. { "Escape", SAPP_KEYCODE_ESCAPE },
  4821. { "Space", SAPP_KEYCODE_SPACE },
  4822. { "PageUp", SAPP_KEYCODE_PAGE_UP },
  4823. { "PageDown", SAPP_KEYCODE_PAGE_DOWN },
  4824. { "End", SAPP_KEYCODE_END },
  4825. { "Home", SAPP_KEYCODE_HOME },
  4826. { "ArrowLeft", SAPP_KEYCODE_LEFT },
  4827. { "ArrowUp", SAPP_KEYCODE_UP },
  4828. { "ArrowRight", SAPP_KEYCODE_RIGHT },
  4829. { "ArrowDown", SAPP_KEYCODE_DOWN },
  4830. { "PrintScreen", SAPP_KEYCODE_PRINT_SCREEN },
  4831. { "Insert", SAPP_KEYCODE_INSERT },
  4832. { "Delete", SAPP_KEYCODE_DELETE },
  4833. { "Digit0", SAPP_KEYCODE_0 },
  4834. { "Digit1", SAPP_KEYCODE_1 },
  4835. { "Digit2", SAPP_KEYCODE_2 },
  4836. { "Digit3", SAPP_KEYCODE_3 },
  4837. { "Digit4", SAPP_KEYCODE_4 },
  4838. { "Digit5", SAPP_KEYCODE_5 },
  4839. { "Digit6", SAPP_KEYCODE_6 },
  4840. { "Digit7", SAPP_KEYCODE_7 },
  4841. { "Digit8", SAPP_KEYCODE_8 },
  4842. { "Digit9", SAPP_KEYCODE_9 },
  4843. { "KeyA", SAPP_KEYCODE_A },
  4844. { "KeyB", SAPP_KEYCODE_B },
  4845. { "KeyC", SAPP_KEYCODE_C },
  4846. { "KeyD", SAPP_KEYCODE_D },
  4847. { "KeyE", SAPP_KEYCODE_E },
  4848. { "KeyF", SAPP_KEYCODE_F },
  4849. { "KeyG", SAPP_KEYCODE_G },
  4850. { "KeyH", SAPP_KEYCODE_H },
  4851. { "KeyI", SAPP_KEYCODE_I },
  4852. { "KeyJ", SAPP_KEYCODE_J },
  4853. { "KeyK", SAPP_KEYCODE_K },
  4854. { "KeyL", SAPP_KEYCODE_L },
  4855. { "KeyM", SAPP_KEYCODE_M },
  4856. { "KeyN", SAPP_KEYCODE_N },
  4857. { "KeyO", SAPP_KEYCODE_O },
  4858. { "KeyP", SAPP_KEYCODE_P },
  4859. { "KeyQ", SAPP_KEYCODE_Q },
  4860. { "KeyR", SAPP_KEYCODE_R },
  4861. { "KeyS", SAPP_KEYCODE_S },
  4862. { "KeyT", SAPP_KEYCODE_T },
  4863. { "KeyU", SAPP_KEYCODE_U },
  4864. { "KeyV", SAPP_KEYCODE_V },
  4865. { "KeyW", SAPP_KEYCODE_W },
  4866. { "KeyX", SAPP_KEYCODE_X },
  4867. { "KeyY", SAPP_KEYCODE_Y },
  4868. { "KeyZ", SAPP_KEYCODE_Z },
  4869. { "MetaLeft", SAPP_KEYCODE_LEFT_SUPER },
  4870. { "MetaRight", SAPP_KEYCODE_RIGHT_SUPER },
  4871. { "Numpad0", SAPP_KEYCODE_KP_0 },
  4872. { "Numpad1", SAPP_KEYCODE_KP_1 },
  4873. { "Numpad2", SAPP_KEYCODE_KP_2 },
  4874. { "Numpad3", SAPP_KEYCODE_KP_3 },
  4875. { "Numpad4", SAPP_KEYCODE_KP_4 },
  4876. { "Numpad5", SAPP_KEYCODE_KP_5 },
  4877. { "Numpad6", SAPP_KEYCODE_KP_6 },
  4878. { "Numpad7", SAPP_KEYCODE_KP_7 },
  4879. { "Numpad8", SAPP_KEYCODE_KP_8 },
  4880. { "Numpad9", SAPP_KEYCODE_KP_9 },
  4881. { "NumpadMultiply", SAPP_KEYCODE_KP_MULTIPLY },
  4882. { "NumpadAdd", SAPP_KEYCODE_KP_ADD },
  4883. { "NumpadSubtract", SAPP_KEYCODE_KP_SUBTRACT },
  4884. { "NumpadDecimal", SAPP_KEYCODE_KP_DECIMAL },
  4885. { "NumpadDivide", SAPP_KEYCODE_KP_DIVIDE },
  4886. { "F1", SAPP_KEYCODE_F1 },
  4887. { "F2", SAPP_KEYCODE_F2 },
  4888. { "F3", SAPP_KEYCODE_F3 },
  4889. { "F4", SAPP_KEYCODE_F4 },
  4890. { "F5", SAPP_KEYCODE_F5 },
  4891. { "F6", SAPP_KEYCODE_F6 },
  4892. { "F7", SAPP_KEYCODE_F7 },
  4893. { "F8", SAPP_KEYCODE_F8 },
  4894. { "F9", SAPP_KEYCODE_F9 },
  4895. { "F10", SAPP_KEYCODE_F10 },
  4896. { "F11", SAPP_KEYCODE_F11 },
  4897. { "F12", SAPP_KEYCODE_F12 },
  4898. { "NumLock", SAPP_KEYCODE_NUM_LOCK },
  4899. { "ScrollLock", SAPP_KEYCODE_SCROLL_LOCK },
  4900. { "Semicolon", SAPP_KEYCODE_SEMICOLON },
  4901. { "Equal", SAPP_KEYCODE_EQUAL },
  4902. { "Comma", SAPP_KEYCODE_COMMA },
  4903. { "Minus", SAPP_KEYCODE_MINUS },
  4904. { "Period", SAPP_KEYCODE_PERIOD },
  4905. { "Slash", SAPP_KEYCODE_SLASH },
  4906. { "Backquote", SAPP_KEYCODE_GRAVE_ACCENT },
  4907. { "BracketLeft", SAPP_KEYCODE_LEFT_BRACKET },
  4908. { "Backslash", SAPP_KEYCODE_BACKSLASH },
  4909. { "BracketRight", SAPP_KEYCODE_RIGHT_BRACKET },
  4910. { "Quote", SAPP_KEYCODE_GRAVE_ACCENT }, // FIXME: ???
  4911. { 0, SAPP_KEYCODE_INVALID },
  4912. };
  4913. _SOKOL_PRIVATE sapp_keycode _sapp_emsc_translate_key(const char* str) {
  4914. int i = 0;
  4915. const char* keystr;
  4916. while (( keystr = _sapp_emsc_keymap[i].str )) {
  4917. if (0 == strcmp(str, keystr)) {
  4918. return _sapp_emsc_keymap[i].code;
  4919. }
  4920. i += 1;
  4921. }
  4922. return SAPP_KEYCODE_INVALID;
  4923. }
  4924. // returns true if the key code is a 'character key', this is used to decide
  4925. // if a key event needs to bubble up to create a char event
  4926. _SOKOL_PRIVATE bool _sapp_emsc_is_char_key(sapp_keycode key_code) {
  4927. return key_code < SAPP_KEYCODE_WORLD_1;
  4928. }
  4929. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_key_cb(int emsc_type, const EmscriptenKeyboardEvent* emsc_event, void* user_data) {
  4930. _SOKOL_UNUSED(user_data);
  4931. bool consume_event = false;
  4932. if (_sapp_events_enabled()) {
  4933. sapp_event_type type;
  4934. switch (emsc_type) {
  4935. case EMSCRIPTEN_EVENT_KEYDOWN:
  4936. type = SAPP_EVENTTYPE_KEY_DOWN;
  4937. break;
  4938. case EMSCRIPTEN_EVENT_KEYUP:
  4939. type = SAPP_EVENTTYPE_KEY_UP;
  4940. break;
  4941. case EMSCRIPTEN_EVENT_KEYPRESS:
  4942. type = SAPP_EVENTTYPE_CHAR;
  4943. break;
  4944. default:
  4945. type = SAPP_EVENTTYPE_INVALID;
  4946. break;
  4947. }
  4948. if (type != SAPP_EVENTTYPE_INVALID) {
  4949. bool send_keyup_followup = false;
  4950. _sapp_init_event(type);
  4951. _sapp.event.key_repeat = emsc_event->repeat;
  4952. _sapp.event.modifiers = _sapp_emsc_key_event_mods(emsc_event);
  4953. if (type == SAPP_EVENTTYPE_CHAR) {
  4954. // NOTE: charCode doesn't appear to be supported on Android Chrome
  4955. _sapp.event.char_code = emsc_event->charCode;
  4956. consume_event |= !_sapp.desc.html5_bubble_char_events;
  4957. } else {
  4958. if (0 != emsc_event->code[0]) {
  4959. // This code path is for desktop browsers which send untranslated 'physical' key code strings
  4960. // (which is what we actually want for key events)
  4961. _sapp.event.key_code = _sapp_emsc_translate_key(emsc_event->code);
  4962. } else {
  4963. // This code path is for mobile browsers which only send localized key code
  4964. // strings. Note that the translation will only work for a small subset
  4965. // of localization-agnostic keys (like Enter, arrow keys, etc...), but
  4966. // regular alpha-numeric keys will all result in an SAPP_KEYCODE_INVALID)
  4967. _sapp.event.key_code = _sapp_emsc_translate_key(emsc_event->key);
  4968. }
  4969. // Special hack for macOS: if the Super key is pressed, macOS doesn't
  4970. // send keyUp events. As a workaround, to prevent keys from
  4971. // "sticking", we'll send a keyup event following a keydown
  4972. // when the SUPER key is pressed
  4973. if ((type == SAPP_EVENTTYPE_KEY_DOWN) &&
  4974. (_sapp.event.key_code != SAPP_KEYCODE_LEFT_SUPER) &&
  4975. (_sapp.event.key_code != SAPP_KEYCODE_RIGHT_SUPER) &&
  4976. (_sapp.event.modifiers & SAPP_MODIFIER_SUPER))
  4977. {
  4978. send_keyup_followup = true;
  4979. }
  4980. // 'character key events' will always need to bubble up, otherwise the browser
  4981. // wouldn't be able to generate character events.
  4982. if (!_sapp_emsc_is_char_key(_sapp.event.key_code)) {
  4983. consume_event |= !_sapp.desc.html5_bubble_key_events;
  4984. }
  4985. }
  4986. consume_event |= _sapp_call_event(&_sapp.event);
  4987. if (send_keyup_followup) {
  4988. _sapp.event.type = SAPP_EVENTTYPE_KEY_UP;
  4989. consume_event |= _sapp_call_event(&_sapp.event);
  4990. }
  4991. }
  4992. }
  4993. _sapp_emsc_update_mouse_lock_state();
  4994. return consume_event;
  4995. }
  4996. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_touch_cb(int emsc_type, const EmscriptenTouchEvent* emsc_event, void* user_data) {
  4997. _SOKOL_UNUSED(user_data);
  4998. bool consume_event = !_sapp.desc.html5_bubble_touch_events;
  4999. if (_sapp_events_enabled()) {
  5000. sapp_event_type type;
  5001. switch (emsc_type) {
  5002. case EMSCRIPTEN_EVENT_TOUCHSTART:
  5003. type = SAPP_EVENTTYPE_TOUCHES_BEGAN;
  5004. break;
  5005. case EMSCRIPTEN_EVENT_TOUCHMOVE:
  5006. type = SAPP_EVENTTYPE_TOUCHES_MOVED;
  5007. break;
  5008. case EMSCRIPTEN_EVENT_TOUCHEND:
  5009. type = SAPP_EVENTTYPE_TOUCHES_ENDED;
  5010. break;
  5011. case EMSCRIPTEN_EVENT_TOUCHCANCEL:
  5012. type = SAPP_EVENTTYPE_TOUCHES_CANCELLED;
  5013. break;
  5014. default:
  5015. type = SAPP_EVENTTYPE_INVALID;
  5016. break;
  5017. }
  5018. if (type != SAPP_EVENTTYPE_INVALID) {
  5019. _sapp_init_event(type);
  5020. _sapp.event.modifiers = _sapp_emsc_touch_event_mods(emsc_event);
  5021. _sapp.event.num_touches = emsc_event->numTouches;
  5022. if (_sapp.event.num_touches > SAPP_MAX_TOUCHPOINTS) {
  5023. _sapp.event.num_touches = SAPP_MAX_TOUCHPOINTS;
  5024. }
  5025. for (int i = 0; i < _sapp.event.num_touches; i++) {
  5026. const EmscriptenTouchPoint* src = &emsc_event->touches[i];
  5027. sapp_touchpoint* dst = &_sapp.event.touches[i];
  5028. dst->identifier = (uintptr_t)src->identifier;
  5029. dst->pos_x = src->targetX * _sapp.dpi_scale;
  5030. dst->pos_y = src->targetY * _sapp.dpi_scale;
  5031. dst->changed = src->isChanged;
  5032. }
  5033. consume_event |= _sapp_call_event(&_sapp.event);
  5034. }
  5035. }
  5036. return consume_event;
  5037. }
  5038. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_focus_cb(int emsc_type, const EmscriptenFocusEvent* emsc_event, void* user_data) {
  5039. _SOKOL_UNUSED(emsc_type);
  5040. _SOKOL_UNUSED(emsc_event);
  5041. _SOKOL_UNUSED(user_data);
  5042. if (_sapp_events_enabled()) {
  5043. _sapp_init_event(SAPP_EVENTTYPE_FOCUSED);
  5044. _sapp_call_event(&_sapp.event);
  5045. }
  5046. return true;
  5047. }
  5048. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_blur_cb(int emsc_type, const EmscriptenFocusEvent* emsc_event, void* user_data) {
  5049. _SOKOL_UNUSED(emsc_type);
  5050. _SOKOL_UNUSED(emsc_event);
  5051. _SOKOL_UNUSED(user_data);
  5052. if (_sapp_events_enabled()) {
  5053. _sapp_init_event(SAPP_EVENTTYPE_UNFOCUSED);
  5054. _sapp_call_event(&_sapp.event);
  5055. }
  5056. return true;
  5057. }
  5058. #if defined(SOKOL_GLES3)
  5059. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_webgl_context_cb(int emsc_type, const void* reserved, void* user_data) {
  5060. _SOKOL_UNUSED(reserved);
  5061. _SOKOL_UNUSED(user_data);
  5062. sapp_event_type type;
  5063. switch (emsc_type) {
  5064. case EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: type = SAPP_EVENTTYPE_SUSPENDED; break;
  5065. case EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: type = SAPP_EVENTTYPE_RESUMED; break;
  5066. default: type = SAPP_EVENTTYPE_INVALID; break;
  5067. }
  5068. if (_sapp_events_enabled() && (SAPP_EVENTTYPE_INVALID != type)) {
  5069. _sapp_init_event(type);
  5070. _sapp_call_event(&_sapp.event);
  5071. }
  5072. return true;
  5073. }
  5074. _SOKOL_PRIVATE void _sapp_emsc_webgl_init(void) {
  5075. EmscriptenWebGLContextAttributes attrs;
  5076. emscripten_webgl_init_context_attributes(&attrs);
  5077. attrs.alpha = _sapp.desc.alpha;
  5078. attrs.depth = true;
  5079. attrs.stencil = true;
  5080. attrs.antialias = _sapp.sample_count > 1;
  5081. attrs.premultipliedAlpha = _sapp.desc.html5_premultiplied_alpha;
  5082. attrs.preserveDrawingBuffer = _sapp.desc.html5_preserve_drawing_buffer;
  5083. attrs.enableExtensionsByDefault = true;
  5084. attrs.majorVersion = 2;
  5085. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(_sapp.html5_canvas_selector, &attrs);
  5086. // FIXME: error message?
  5087. emscripten_webgl_make_context_current(ctx);
  5088. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  5089. // FIXME: remove PVRTC support here and in sokol-gfx at some point
  5090. // some WebGL extension are not enabled automatically by emscripten
  5091. emscripten_webgl_enable_extension(ctx, "WEBKIT_WEBGL_compressed_texture_pvrtc");
  5092. }
  5093. #endif
  5094. #if defined(SOKOL_WGPU)
  5095. _SOKOL_PRIVATE void _sapp_emsc_wgpu_create_swapchain(void) {
  5096. SOKOL_ASSERT(_sapp.wgpu.instance);
  5097. SOKOL_ASSERT(_sapp.wgpu.device);
  5098. SOKOL_ASSERT(0 == _sapp.wgpu.surface);
  5099. SOKOL_ASSERT(0 == _sapp.wgpu.swapchain);
  5100. SOKOL_ASSERT(0 == _sapp.wgpu.msaa_tex);
  5101. SOKOL_ASSERT(0 == _sapp.wgpu.msaa_view);
  5102. SOKOL_ASSERT(0 == _sapp.wgpu.depth_stencil_tex);
  5103. SOKOL_ASSERT(0 == _sapp.wgpu.depth_stencil_view);
  5104. SOKOL_ASSERT(0 == _sapp.wgpu.swapchain_view);
  5105. WGPUSurfaceDescriptorFromCanvasHTMLSelector canvas_desc;
  5106. _sapp_clear(&canvas_desc, sizeof(canvas_desc));
  5107. canvas_desc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector;
  5108. canvas_desc.selector = _sapp.html5_canvas_selector;
  5109. WGPUSurfaceDescriptor surf_desc;
  5110. _sapp_clear(&surf_desc, sizeof(surf_desc));
  5111. surf_desc.nextInChain = &canvas_desc.chain;
  5112. _sapp.wgpu.surface = wgpuInstanceCreateSurface(_sapp.wgpu.instance, &surf_desc);
  5113. if (0 == _sapp.wgpu.surface) {
  5114. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_SURFACE_FAILED);
  5115. }
  5116. _sapp.wgpu.render_format = wgpuSurfaceGetPreferredFormat(_sapp.wgpu.surface, _sapp.wgpu.adapter);
  5117. WGPUSwapChainDescriptor sc_desc;
  5118. _sapp_clear(&sc_desc, sizeof(sc_desc));
  5119. sc_desc.usage = WGPUTextureUsage_RenderAttachment;
  5120. sc_desc.format = _sapp.wgpu.render_format;
  5121. sc_desc.width = (uint32_t)_sapp.framebuffer_width;
  5122. sc_desc.height = (uint32_t)_sapp.framebuffer_height;
  5123. sc_desc.presentMode = WGPUPresentMode_Fifo;
  5124. _sapp.wgpu.swapchain = wgpuDeviceCreateSwapChain(_sapp.wgpu.device, _sapp.wgpu.surface, &sc_desc);
  5125. if (0 == _sapp.wgpu.swapchain) {
  5126. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_SWAPCHAIN_FAILED);
  5127. }
  5128. WGPUTextureDescriptor ds_desc;
  5129. _sapp_clear(&ds_desc, sizeof(ds_desc));
  5130. ds_desc.usage = WGPUTextureUsage_RenderAttachment;
  5131. ds_desc.dimension = WGPUTextureDimension_2D;
  5132. ds_desc.size.width = (uint32_t)_sapp.framebuffer_width;
  5133. ds_desc.size.height = (uint32_t)_sapp.framebuffer_height;
  5134. ds_desc.size.depthOrArrayLayers = 1;
  5135. ds_desc.format = WGPUTextureFormat_Depth32FloatStencil8;
  5136. ds_desc.mipLevelCount = 1;
  5137. ds_desc.sampleCount = (uint32_t)_sapp.sample_count;
  5138. _sapp.wgpu.depth_stencil_tex = wgpuDeviceCreateTexture(_sapp.wgpu.device, &ds_desc);
  5139. if (0 == _sapp.wgpu.depth_stencil_tex) {
  5140. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_TEXTURE_FAILED);
  5141. }
  5142. _sapp.wgpu.depth_stencil_view = wgpuTextureCreateView(_sapp.wgpu.depth_stencil_tex, 0);
  5143. if (0 == _sapp.wgpu.depth_stencil_view) {
  5144. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_VIEW_FAILED);
  5145. }
  5146. if (_sapp.sample_count > 1) {
  5147. WGPUTextureDescriptor msaa_desc;
  5148. _sapp_clear(&msaa_desc, sizeof(msaa_desc));
  5149. msaa_desc.usage = WGPUTextureUsage_RenderAttachment;
  5150. msaa_desc.dimension = WGPUTextureDimension_2D;
  5151. msaa_desc.size.width = (uint32_t)_sapp.framebuffer_width;
  5152. msaa_desc.size.height = (uint32_t)_sapp.framebuffer_height;
  5153. msaa_desc.size.depthOrArrayLayers = 1;
  5154. msaa_desc.format = _sapp.wgpu.render_format;
  5155. msaa_desc.mipLevelCount = 1;
  5156. msaa_desc.sampleCount = (uint32_t)_sapp.sample_count;
  5157. _sapp.wgpu.msaa_tex = wgpuDeviceCreateTexture(_sapp.wgpu.device, &msaa_desc);
  5158. if (0 == _sapp.wgpu.msaa_tex) {
  5159. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_MSAA_TEXTURE_FAILED);
  5160. }
  5161. _sapp.wgpu.msaa_view = wgpuTextureCreateView(_sapp.wgpu.msaa_tex, 0);
  5162. if (0 == _sapp.wgpu.msaa_view) {
  5163. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_MSAA_VIEW_FAILED);
  5164. }
  5165. }
  5166. }
  5167. _SOKOL_PRIVATE void _sapp_emsc_wgpu_discard_swapchain(void) {
  5168. if (_sapp.wgpu.msaa_view) {
  5169. wgpuTextureViewRelease(_sapp.wgpu.msaa_view);
  5170. _sapp.wgpu.msaa_view = 0;
  5171. }
  5172. if (_sapp.wgpu.msaa_tex) {
  5173. wgpuTextureRelease(_sapp.wgpu.msaa_tex);
  5174. _sapp.wgpu.msaa_tex = 0;
  5175. }
  5176. if (_sapp.wgpu.depth_stencil_view) {
  5177. wgpuTextureViewRelease(_sapp.wgpu.depth_stencil_view);
  5178. _sapp.wgpu.depth_stencil_view = 0;
  5179. }
  5180. if (_sapp.wgpu.depth_stencil_tex) {
  5181. wgpuTextureRelease(_sapp.wgpu.depth_stencil_tex);
  5182. _sapp.wgpu.depth_stencil_tex = 0;
  5183. }
  5184. if (_sapp.wgpu.swapchain) {
  5185. wgpuSwapChainRelease(_sapp.wgpu.swapchain);
  5186. _sapp.wgpu.swapchain = 0;
  5187. }
  5188. if (_sapp.wgpu.surface) {
  5189. wgpuSurfaceRelease(_sapp.wgpu.surface);
  5190. _sapp.wgpu.surface = 0;
  5191. }
  5192. }
  5193. _SOKOL_PRIVATE void _sapp_emsc_wgpu_size_changed(void) {
  5194. _sapp_emsc_wgpu_discard_swapchain();
  5195. _sapp_emsc_wgpu_create_swapchain();
  5196. }
  5197. _SOKOL_PRIVATE void _sapp_emsc_wgpu_request_device_cb(WGPURequestDeviceStatus status, WGPUDevice device, const char* msg, void* userdata) {
  5198. _SOKOL_UNUSED(msg);
  5199. _SOKOL_UNUSED(userdata);
  5200. SOKOL_ASSERT(!_sapp.wgpu.async_init_done);
  5201. if (status != WGPURequestDeviceStatus_Success) {
  5202. if (status == WGPURequestDeviceStatus_Error) {
  5203. _SAPP_PANIC(WGPU_REQUEST_DEVICE_STATUS_ERROR);
  5204. } else {
  5205. _SAPP_PANIC(WGPU_REQUEST_DEVICE_STATUS_UNKNOWN);
  5206. }
  5207. }
  5208. SOKOL_ASSERT(device);
  5209. _sapp.wgpu.device = device;
  5210. _sapp_emsc_wgpu_create_swapchain();
  5211. _sapp.wgpu.async_init_done = true;
  5212. }
  5213. _SOKOL_PRIVATE void _sapp_emsc_wgpu_request_adapter_cb(WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* msg, void* userdata) {
  5214. _SOKOL_UNUSED(msg);
  5215. _SOKOL_UNUSED(userdata);
  5216. if (status != WGPURequestAdapterStatus_Success) {
  5217. switch (status) {
  5218. case WGPURequestAdapterStatus_Unavailable: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_UNAVAILABLE); break;
  5219. case WGPURequestAdapterStatus_Error: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_ERROR); break;
  5220. default: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_UNKNOWN); break;
  5221. }
  5222. }
  5223. SOKOL_ASSERT(adapter);
  5224. _sapp.wgpu.adapter = adapter;
  5225. size_t cur_feature_index = 1;
  5226. #define _SAPP_WGPU_MAX_REQUESTED_FEATURES (8)
  5227. WGPUFeatureName requiredFeatures[_SAPP_WGPU_MAX_REQUESTED_FEATURES] = {
  5228. WGPUFeatureName_Depth32FloatStencil8,
  5229. };
  5230. // check for optional features we're interested in
  5231. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionBC)) {
  5232. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5233. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionBC;
  5234. }
  5235. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionETC2)) {
  5236. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5237. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionETC2;
  5238. }
  5239. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionASTC)) {
  5240. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5241. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionASTC;
  5242. }
  5243. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_Float32Filterable)) {
  5244. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5245. requiredFeatures[cur_feature_index++] = WGPUFeatureName_Float32Filterable;
  5246. }
  5247. #undef _SAPP_WGPU_MAX_REQUESTED_FEATURES
  5248. WGPUDeviceDescriptor dev_desc;
  5249. _sapp_clear(&dev_desc, sizeof(dev_desc));
  5250. dev_desc.requiredFeatureCount = cur_feature_index;
  5251. dev_desc.requiredFeatures = requiredFeatures,
  5252. wgpuAdapterRequestDevice(adapter, &dev_desc, _sapp_emsc_wgpu_request_device_cb, 0);
  5253. }
  5254. _SOKOL_PRIVATE void _sapp_emsc_wgpu_init(void) {
  5255. SOKOL_ASSERT(0 == _sapp.wgpu.instance);
  5256. SOKOL_ASSERT(!_sapp.wgpu.async_init_done);
  5257. _sapp.wgpu.instance = wgpuCreateInstance(0);
  5258. if (0 == _sapp.wgpu.instance) {
  5259. _SAPP_PANIC(WGPU_CREATE_INSTANCE_FAILED);
  5260. }
  5261. // FIXME: power preference?
  5262. wgpuInstanceRequestAdapter(_sapp.wgpu.instance, 0, _sapp_emsc_wgpu_request_adapter_cb, 0);
  5263. }
  5264. _SOKOL_PRIVATE void _sapp_emsc_wgpu_frame(void) {
  5265. if (_sapp.wgpu.async_init_done) {
  5266. _sapp.wgpu.swapchain_view = wgpuSwapChainGetCurrentTextureView(_sapp.wgpu.swapchain);
  5267. _sapp_frame();
  5268. wgpuTextureViewRelease(_sapp.wgpu.swapchain_view);
  5269. _sapp.wgpu.swapchain_view = 0;
  5270. }
  5271. }
  5272. #endif // SOKOL_WGPU
  5273. _SOKOL_PRIVATE void _sapp_emsc_register_eventhandlers(void) {
  5274. // NOTE: HTML canvas doesn't receive input focus, this is why key event handlers are added
  5275. // to the window object (this could be worked around by adding a "tab index" to the
  5276. // canvas)
  5277. emscripten_set_mousedown_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5278. emscripten_set_mouseup_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5279. emscripten_set_mousemove_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5280. emscripten_set_mouseenter_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5281. emscripten_set_mouseleave_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5282. emscripten_set_wheel_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_wheel_cb);
  5283. emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5284. emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5285. emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5286. emscripten_set_touchstart_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5287. emscripten_set_touchmove_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5288. emscripten_set_touchend_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5289. emscripten_set_touchcancel_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5290. emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, _sapp_emsc_pointerlockchange_cb);
  5291. emscripten_set_pointerlockerror_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, _sapp_emsc_pointerlockerror_cb);
  5292. emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_focus_cb);
  5293. emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_blur_cb);
  5294. sapp_js_add_beforeunload_listener();
  5295. if (_sapp.clipboard.enabled) {
  5296. sapp_js_add_clipboard_listener();
  5297. }
  5298. if (_sapp.drop.enabled) {
  5299. sapp_js_add_dragndrop_listeners(&_sapp.html5_canvas_selector[1]);
  5300. }
  5301. #if defined(SOKOL_GLES3)
  5302. emscripten_set_webglcontextlost_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_webgl_context_cb);
  5303. emscripten_set_webglcontextrestored_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_webgl_context_cb);
  5304. #endif
  5305. }
  5306. _SOKOL_PRIVATE void _sapp_emsc_unregister_eventhandlers(void) {
  5307. emscripten_set_mousedown_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5308. emscripten_set_mouseup_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5309. emscripten_set_mousemove_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5310. emscripten_set_mouseenter_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5311. emscripten_set_mouseleave_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5312. emscripten_set_wheel_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5313. emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5314. emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5315. emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5316. emscripten_set_touchstart_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5317. emscripten_set_touchmove_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5318. emscripten_set_touchend_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5319. emscripten_set_touchcancel_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5320. emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, 0);
  5321. emscripten_set_pointerlockerror_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, 0);
  5322. emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5323. emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5324. if (!_sapp.desc.html5_canvas_resize) {
  5325. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5326. }
  5327. sapp_js_remove_beforeunload_listener();
  5328. if (_sapp.clipboard.enabled) {
  5329. sapp_js_remove_clipboard_listener();
  5330. }
  5331. if (_sapp.drop.enabled) {
  5332. sapp_js_remove_dragndrop_listeners(&_sapp.html5_canvas_selector[1]);
  5333. }
  5334. #if defined(SOKOL_GLES3)
  5335. emscripten_set_webglcontextlost_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5336. emscripten_set_webglcontextrestored_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5337. #endif
  5338. }
  5339. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_frame_animation_loop(double time, void* userData) {
  5340. _SOKOL_UNUSED(userData);
  5341. _sapp_timing_external(&_sapp.timing, time / 1000.0);
  5342. #if defined(SOKOL_WGPU)
  5343. _sapp_emsc_wgpu_frame();
  5344. #else
  5345. _sapp_frame();
  5346. #endif
  5347. // quit-handling
  5348. if (_sapp.quit_requested) {
  5349. _sapp_init_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  5350. _sapp_call_event(&_sapp.event);
  5351. if (_sapp.quit_requested) {
  5352. _sapp.quit_ordered = true;
  5353. }
  5354. }
  5355. if (_sapp.quit_ordered) {
  5356. _sapp_emsc_unregister_eventhandlers();
  5357. _sapp_call_cleanup();
  5358. _sapp_discard_state();
  5359. return EM_FALSE;
  5360. }
  5361. return EM_TRUE;
  5362. }
  5363. _SOKOL_PRIVATE void _sapp_emsc_frame_main_loop(void) {
  5364. const double time = emscripten_performance_now();
  5365. if (!_sapp_emsc_frame_animation_loop(time, 0)) {
  5366. emscripten_cancel_main_loop();
  5367. }
  5368. }
  5369. _SOKOL_PRIVATE void _sapp_emsc_run(const sapp_desc* desc) {
  5370. _sapp_init_state(desc);
  5371. sapp_js_init(&_sapp.html5_canvas_selector[1]);
  5372. double w, h;
  5373. if (_sapp.desc.html5_canvas_resize) {
  5374. w = (double) _sapp_def(_sapp.desc.width, _SAPP_FALLBACK_DEFAULT_WINDOW_WIDTH);
  5375. h = (double) _sapp_def(_sapp.desc.height, _SAPP_FALLBACK_DEFAULT_WINDOW_HEIGHT);
  5376. }
  5377. else {
  5378. emscripten_get_element_css_size(_sapp.html5_canvas_selector, &w, &h);
  5379. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, false, _sapp_emsc_size_changed);
  5380. }
  5381. if (_sapp.desc.high_dpi) {
  5382. _sapp.dpi_scale = emscripten_get_device_pixel_ratio();
  5383. }
  5384. _sapp.window_width = (int)roundf(w);
  5385. _sapp.window_height = (int)roundf(h);
  5386. _sapp.framebuffer_width = (int)roundf(w * _sapp.dpi_scale);
  5387. _sapp.framebuffer_height = (int)roundf(h * _sapp.dpi_scale);
  5388. emscripten_set_canvas_element_size(_sapp.html5_canvas_selector, _sapp.framebuffer_width, _sapp.framebuffer_height);
  5389. #if defined(SOKOL_GLES3)
  5390. _sapp_emsc_webgl_init();
  5391. #elif defined(SOKOL_WGPU)
  5392. _sapp_emsc_wgpu_init();
  5393. #endif
  5394. _sapp.valid = true;
  5395. _sapp_emsc_register_eventhandlers();
  5396. sapp_set_icon(&desc->icon);
  5397. // start the frame loop
  5398. if (_sapp.desc.html5_use_emsc_set_main_loop) {
  5399. emscripten_set_main_loop(_sapp_emsc_frame_main_loop, 0, _sapp.desc.html5_emsc_set_main_loop_simulate_infinite_loop);
  5400. } else {
  5401. emscripten_request_animation_frame_loop(_sapp_emsc_frame_animation_loop, 0);
  5402. }
  5403. // NOT A BUG: do not call _sapp_discard_state() here, instead this is
  5404. // called in _sapp_emsc_frame() when the application is ordered to quit
  5405. }
  5406. #if !defined(SOKOL_NO_ENTRY)
  5407. int main(int argc, char* argv[]) {
  5408. sapp_desc desc = sokol_main(argc, argv);
  5409. _sapp_emsc_run(&desc);
  5410. return 0;
  5411. }
  5412. #endif /* SOKOL_NO_ENTRY */
  5413. #endif /* _SAPP_EMSCRIPTEN */
  5414. // ██████ ██ ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  5415. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5416. // ██ ███ ██ ███████ █████ ██ ██████ █████ ██████ ███████
  5417. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5418. // ██████ ███████ ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  5419. //
  5420. // >>gl helpers
  5421. #if defined(SOKOL_GLCORE)
  5422. typedef struct {
  5423. int red_bits;
  5424. int green_bits;
  5425. int blue_bits;
  5426. int alpha_bits;
  5427. int depth_bits;
  5428. int stencil_bits;
  5429. int samples;
  5430. bool doublebuffer;
  5431. uintptr_t handle;
  5432. } _sapp_gl_fbconfig;
  5433. _SOKOL_PRIVATE void _sapp_gl_init_fbconfig(_sapp_gl_fbconfig* fbconfig) {
  5434. _sapp_clear(fbconfig, sizeof(_sapp_gl_fbconfig));
  5435. /* -1 means "don't care" */
  5436. fbconfig->red_bits = -1;
  5437. fbconfig->green_bits = -1;
  5438. fbconfig->blue_bits = -1;
  5439. fbconfig->alpha_bits = -1;
  5440. fbconfig->depth_bits = -1;
  5441. fbconfig->stencil_bits = -1;
  5442. fbconfig->samples = -1;
  5443. }
  5444. typedef struct {
  5445. int least_missing;
  5446. int least_color_diff;
  5447. int least_extra_diff;
  5448. bool best_match;
  5449. } _sapp_gl_fbselect;
  5450. _SOKOL_PRIVATE void _sapp_gl_init_fbselect(_sapp_gl_fbselect* fbselect) {
  5451. _sapp_clear(fbselect, sizeof(_sapp_gl_fbselect));
  5452. fbselect->least_missing = 1000000;
  5453. fbselect->least_color_diff = 10000000;
  5454. fbselect->least_extra_diff = 10000000;
  5455. fbselect->best_match = false;
  5456. }
  5457. // NOTE: this is used only in the WGL code path
  5458. _SOKOL_PRIVATE bool _sapp_gl_select_fbconfig(_sapp_gl_fbselect* fbselect, const _sapp_gl_fbconfig* desired, const _sapp_gl_fbconfig* current) {
  5459. int missing = 0;
  5460. if (desired->doublebuffer != current->doublebuffer) {
  5461. return false;
  5462. }
  5463. if ((desired->alpha_bits > 0) && (current->alpha_bits == 0)) {
  5464. missing++;
  5465. }
  5466. if ((desired->depth_bits > 0) && (current->depth_bits == 0)) {
  5467. missing++;
  5468. }
  5469. if ((desired->stencil_bits > 0) && (current->stencil_bits == 0)) {
  5470. missing++;
  5471. }
  5472. if ((desired->samples > 0) && (current->samples == 0)) {
  5473. /* Technically, several multisampling buffers could be
  5474. involved, but that's a lower level implementation detail and
  5475. not important to us here, so we count them as one
  5476. */
  5477. missing++;
  5478. }
  5479. /* These polynomials make many small channel size differences matter
  5480. less than one large channel size difference
  5481. Calculate color channel size difference value
  5482. */
  5483. int color_diff = 0;
  5484. if (desired->red_bits != -1) {
  5485. color_diff += (desired->red_bits - current->red_bits) * (desired->red_bits - current->red_bits);
  5486. }
  5487. if (desired->green_bits != -1) {
  5488. color_diff += (desired->green_bits - current->green_bits) * (desired->green_bits - current->green_bits);
  5489. }
  5490. if (desired->blue_bits != -1) {
  5491. color_diff += (desired->blue_bits - current->blue_bits) * (desired->blue_bits - current->blue_bits);
  5492. }
  5493. /* Calculate non-color channel size difference value */
  5494. int extra_diff = 0;
  5495. if (desired->alpha_bits != -1) {
  5496. extra_diff += (desired->alpha_bits - current->alpha_bits) * (desired->alpha_bits - current->alpha_bits);
  5497. }
  5498. if (desired->depth_bits != -1) {
  5499. extra_diff += (desired->depth_bits - current->depth_bits) * (desired->depth_bits - current->depth_bits);
  5500. }
  5501. if (desired->stencil_bits != -1) {
  5502. extra_diff += (desired->stencil_bits - current->stencil_bits) * (desired->stencil_bits - current->stencil_bits);
  5503. }
  5504. if (desired->samples != -1) {
  5505. extra_diff += (desired->samples - current->samples) * (desired->samples - current->samples);
  5506. }
  5507. /* Figure out if the current one is better than the best one found so far
  5508. Least number of missing buffers is the most important heuristic,
  5509. then color buffer size match and lastly size match for other buffers
  5510. */
  5511. bool new_closest = false;
  5512. if (missing < fbselect->least_missing) {
  5513. new_closest = true;
  5514. } else if (missing == fbselect->least_missing) {
  5515. if ((color_diff < fbselect->least_color_diff) ||
  5516. ((color_diff == fbselect->least_color_diff) && (extra_diff < fbselect->least_extra_diff)))
  5517. {
  5518. new_closest = true;
  5519. }
  5520. }
  5521. if (new_closest) {
  5522. fbselect->least_missing = missing;
  5523. fbselect->least_color_diff = color_diff;
  5524. fbselect->least_extra_diff = extra_diff;
  5525. fbselect->best_match = (missing | color_diff | extra_diff) == 0;
  5526. }
  5527. return new_closest;
  5528. }
  5529. // NOTE: this is used only in the GLX code path
  5530. _SOKOL_PRIVATE const _sapp_gl_fbconfig* _sapp_gl_choose_fbconfig(const _sapp_gl_fbconfig* desired, const _sapp_gl_fbconfig* alternatives, int count) {
  5531. int missing, least_missing = 1000000;
  5532. int color_diff, least_color_diff = 10000000;
  5533. int extra_diff, least_extra_diff = 10000000;
  5534. const _sapp_gl_fbconfig* current;
  5535. const _sapp_gl_fbconfig* closest = 0;
  5536. for (int i = 0; i < count; i++) {
  5537. current = alternatives + i;
  5538. if (desired->doublebuffer != current->doublebuffer) {
  5539. continue;
  5540. }
  5541. missing = 0;
  5542. if (desired->alpha_bits > 0 && current->alpha_bits == 0) {
  5543. missing++;
  5544. }
  5545. if (desired->depth_bits > 0 && current->depth_bits == 0) {
  5546. missing++;
  5547. }
  5548. if (desired->stencil_bits > 0 && current->stencil_bits == 0) {
  5549. missing++;
  5550. }
  5551. if (desired->samples > 0 && current->samples == 0) {
  5552. /* Technically, several multisampling buffers could be
  5553. involved, but that's a lower level implementation detail and
  5554. not important to us here, so we count them as one
  5555. */
  5556. missing++;
  5557. }
  5558. /* These polynomials make many small channel size differences matter
  5559. less than one large channel size difference
  5560. Calculate color channel size difference value
  5561. */
  5562. color_diff = 0;
  5563. if (desired->red_bits != -1) {
  5564. color_diff += (desired->red_bits - current->red_bits) * (desired->red_bits - current->red_bits);
  5565. }
  5566. if (desired->green_bits != -1) {
  5567. color_diff += (desired->green_bits - current->green_bits) * (desired->green_bits - current->green_bits);
  5568. }
  5569. if (desired->blue_bits != -1) {
  5570. color_diff += (desired->blue_bits - current->blue_bits) * (desired->blue_bits - current->blue_bits);
  5571. }
  5572. /* Calculate non-color channel size difference value */
  5573. extra_diff = 0;
  5574. if (desired->alpha_bits != -1) {
  5575. extra_diff += (desired->alpha_bits - current->alpha_bits) * (desired->alpha_bits - current->alpha_bits);
  5576. }
  5577. if (desired->depth_bits != -1) {
  5578. extra_diff += (desired->depth_bits - current->depth_bits) * (desired->depth_bits - current->depth_bits);
  5579. }
  5580. if (desired->stencil_bits != -1) {
  5581. extra_diff += (desired->stencil_bits - current->stencil_bits) * (desired->stencil_bits - current->stencil_bits);
  5582. }
  5583. if (desired->samples != -1) {
  5584. extra_diff += (desired->samples - current->samples) * (desired->samples - current->samples);
  5585. }
  5586. /* Figure out if the current one is better than the best one found so far
  5587. Least number of missing buffers is the most important heuristic,
  5588. then color buffer size match and lastly size match for other buffers
  5589. */
  5590. if (missing < least_missing) {
  5591. closest = current;
  5592. }
  5593. else if (missing == least_missing) {
  5594. if ((color_diff < least_color_diff) ||
  5595. (color_diff == least_color_diff && extra_diff < least_extra_diff))
  5596. {
  5597. closest = current;
  5598. }
  5599. }
  5600. if (current == closest) {
  5601. least_missing = missing;
  5602. least_color_diff = color_diff;
  5603. least_extra_diff = extra_diff;
  5604. }
  5605. }
  5606. return closest;
  5607. }
  5608. #endif
  5609. // ██ ██ ██ ███ ██ ██████ ██████ ██ ██ ███████
  5610. // ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██
  5611. // ██ █ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █ ██ ███████
  5612. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██ ██
  5613. // ███ ███ ██ ██ ████ ██████ ██████ ███ ███ ███████
  5614. //
  5615. // >>windows
  5616. #if defined(_SAPP_WIN32)
  5617. _SOKOL_PRIVATE bool _sapp_win32_utf8_to_wide(const char* src, wchar_t* dst, int dst_num_bytes) {
  5618. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  5619. _sapp_clear(dst, (size_t)dst_num_bytes);
  5620. const int dst_chars = dst_num_bytes / (int)sizeof(wchar_t);
  5621. const int dst_needed = MultiByteToWideChar(CP_UTF8, 0, src, -1, 0, 0);
  5622. if ((dst_needed > 0) && (dst_needed < dst_chars)) {
  5623. MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, dst_chars);
  5624. return true;
  5625. }
  5626. else {
  5627. /* input string doesn't fit into destination buffer */
  5628. return false;
  5629. }
  5630. }
  5631. _SOKOL_PRIVATE void _sapp_win32_app_event(sapp_event_type type) {
  5632. if (_sapp_events_enabled()) {
  5633. _sapp_init_event(type);
  5634. _sapp_call_event(&_sapp.event);
  5635. }
  5636. }
  5637. _SOKOL_PRIVATE void _sapp_win32_init_keytable(void) {
  5638. /* same as GLFW */
  5639. _sapp.keycodes[0x00B] = SAPP_KEYCODE_0;
  5640. _sapp.keycodes[0x002] = SAPP_KEYCODE_1;
  5641. _sapp.keycodes[0x003] = SAPP_KEYCODE_2;
  5642. _sapp.keycodes[0x004] = SAPP_KEYCODE_3;
  5643. _sapp.keycodes[0x005] = SAPP_KEYCODE_4;
  5644. _sapp.keycodes[0x006] = SAPP_KEYCODE_5;
  5645. _sapp.keycodes[0x007] = SAPP_KEYCODE_6;
  5646. _sapp.keycodes[0x008] = SAPP_KEYCODE_7;
  5647. _sapp.keycodes[0x009] = SAPP_KEYCODE_8;
  5648. _sapp.keycodes[0x00A] = SAPP_KEYCODE_9;
  5649. _sapp.keycodes[0x01E] = SAPP_KEYCODE_A;
  5650. _sapp.keycodes[0x030] = SAPP_KEYCODE_B;
  5651. _sapp.keycodes[0x02E] = SAPP_KEYCODE_C;
  5652. _sapp.keycodes[0x020] = SAPP_KEYCODE_D;
  5653. _sapp.keycodes[0x012] = SAPP_KEYCODE_E;
  5654. _sapp.keycodes[0x021] = SAPP_KEYCODE_F;
  5655. _sapp.keycodes[0x022] = SAPP_KEYCODE_G;
  5656. _sapp.keycodes[0x023] = SAPP_KEYCODE_H;
  5657. _sapp.keycodes[0x017] = SAPP_KEYCODE_I;
  5658. _sapp.keycodes[0x024] = SAPP_KEYCODE_J;
  5659. _sapp.keycodes[0x025] = SAPP_KEYCODE_K;
  5660. _sapp.keycodes[0x026] = SAPP_KEYCODE_L;
  5661. _sapp.keycodes[0x032] = SAPP_KEYCODE_M;
  5662. _sapp.keycodes[0x031] = SAPP_KEYCODE_N;
  5663. _sapp.keycodes[0x018] = SAPP_KEYCODE_O;
  5664. _sapp.keycodes[0x019] = SAPP_KEYCODE_P;
  5665. _sapp.keycodes[0x010] = SAPP_KEYCODE_Q;
  5666. _sapp.keycodes[0x013] = SAPP_KEYCODE_R;
  5667. _sapp.keycodes[0x01F] = SAPP_KEYCODE_S;
  5668. _sapp.keycodes[0x014] = SAPP_KEYCODE_T;
  5669. _sapp.keycodes[0x016] = SAPP_KEYCODE_U;
  5670. _sapp.keycodes[0x02F] = SAPP_KEYCODE_V;
  5671. _sapp.keycodes[0x011] = SAPP_KEYCODE_W;
  5672. _sapp.keycodes[0x02D] = SAPP_KEYCODE_X;
  5673. _sapp.keycodes[0x015] = SAPP_KEYCODE_Y;
  5674. _sapp.keycodes[0x02C] = SAPP_KEYCODE_Z;
  5675. _sapp.keycodes[0x028] = SAPP_KEYCODE_APOSTROPHE;
  5676. _sapp.keycodes[0x02B] = SAPP_KEYCODE_BACKSLASH;
  5677. _sapp.keycodes[0x033] = SAPP_KEYCODE_COMMA;
  5678. _sapp.keycodes[0x00D] = SAPP_KEYCODE_EQUAL;
  5679. _sapp.keycodes[0x029] = SAPP_KEYCODE_GRAVE_ACCENT;
  5680. _sapp.keycodes[0x01A] = SAPP_KEYCODE_LEFT_BRACKET;
  5681. _sapp.keycodes[0x00C] = SAPP_KEYCODE_MINUS;
  5682. _sapp.keycodes[0x034] = SAPP_KEYCODE_PERIOD;
  5683. _sapp.keycodes[0x01B] = SAPP_KEYCODE_RIGHT_BRACKET;
  5684. _sapp.keycodes[0x027] = SAPP_KEYCODE_SEMICOLON;
  5685. _sapp.keycodes[0x035] = SAPP_KEYCODE_SLASH;
  5686. _sapp.keycodes[0x056] = SAPP_KEYCODE_WORLD_2;
  5687. _sapp.keycodes[0x00E] = SAPP_KEYCODE_BACKSPACE;
  5688. _sapp.keycodes[0x153] = SAPP_KEYCODE_DELETE;
  5689. _sapp.keycodes[0x14F] = SAPP_KEYCODE_END;
  5690. _sapp.keycodes[0x01C] = SAPP_KEYCODE_ENTER;
  5691. _sapp.keycodes[0x001] = SAPP_KEYCODE_ESCAPE;
  5692. _sapp.keycodes[0x147] = SAPP_KEYCODE_HOME;
  5693. _sapp.keycodes[0x152] = SAPP_KEYCODE_INSERT;
  5694. _sapp.keycodes[0x15D] = SAPP_KEYCODE_MENU;
  5695. _sapp.keycodes[0x151] = SAPP_KEYCODE_PAGE_DOWN;
  5696. _sapp.keycodes[0x149] = SAPP_KEYCODE_PAGE_UP;
  5697. _sapp.keycodes[0x045] = SAPP_KEYCODE_PAUSE;
  5698. _sapp.keycodes[0x146] = SAPP_KEYCODE_PAUSE;
  5699. _sapp.keycodes[0x039] = SAPP_KEYCODE_SPACE;
  5700. _sapp.keycodes[0x00F] = SAPP_KEYCODE_TAB;
  5701. _sapp.keycodes[0x03A] = SAPP_KEYCODE_CAPS_LOCK;
  5702. _sapp.keycodes[0x145] = SAPP_KEYCODE_NUM_LOCK;
  5703. _sapp.keycodes[0x046] = SAPP_KEYCODE_SCROLL_LOCK;
  5704. _sapp.keycodes[0x03B] = SAPP_KEYCODE_F1;
  5705. _sapp.keycodes[0x03C] = SAPP_KEYCODE_F2;
  5706. _sapp.keycodes[0x03D] = SAPP_KEYCODE_F3;
  5707. _sapp.keycodes[0x03E] = SAPP_KEYCODE_F4;
  5708. _sapp.keycodes[0x03F] = SAPP_KEYCODE_F5;
  5709. _sapp.keycodes[0x040] = SAPP_KEYCODE_F6;
  5710. _sapp.keycodes[0x041] = SAPP_KEYCODE_F7;
  5711. _sapp.keycodes[0x042] = SAPP_KEYCODE_F8;
  5712. _sapp.keycodes[0x043] = SAPP_KEYCODE_F9;
  5713. _sapp.keycodes[0x044] = SAPP_KEYCODE_F10;
  5714. _sapp.keycodes[0x057] = SAPP_KEYCODE_F11;
  5715. _sapp.keycodes[0x058] = SAPP_KEYCODE_F12;
  5716. _sapp.keycodes[0x064] = SAPP_KEYCODE_F13;
  5717. _sapp.keycodes[0x065] = SAPP_KEYCODE_F14;
  5718. _sapp.keycodes[0x066] = SAPP_KEYCODE_F15;
  5719. _sapp.keycodes[0x067] = SAPP_KEYCODE_F16;
  5720. _sapp.keycodes[0x068] = SAPP_KEYCODE_F17;
  5721. _sapp.keycodes[0x069] = SAPP_KEYCODE_F18;
  5722. _sapp.keycodes[0x06A] = SAPP_KEYCODE_F19;
  5723. _sapp.keycodes[0x06B] = SAPP_KEYCODE_F20;
  5724. _sapp.keycodes[0x06C] = SAPP_KEYCODE_F21;
  5725. _sapp.keycodes[0x06D] = SAPP_KEYCODE_F22;
  5726. _sapp.keycodes[0x06E] = SAPP_KEYCODE_F23;
  5727. _sapp.keycodes[0x076] = SAPP_KEYCODE_F24;
  5728. _sapp.keycodes[0x038] = SAPP_KEYCODE_LEFT_ALT;
  5729. _sapp.keycodes[0x01D] = SAPP_KEYCODE_LEFT_CONTROL;
  5730. _sapp.keycodes[0x02A] = SAPP_KEYCODE_LEFT_SHIFT;
  5731. _sapp.keycodes[0x15B] = SAPP_KEYCODE_LEFT_SUPER;
  5732. _sapp.keycodes[0x137] = SAPP_KEYCODE_PRINT_SCREEN;
  5733. _sapp.keycodes[0x138] = SAPP_KEYCODE_RIGHT_ALT;
  5734. _sapp.keycodes[0x11D] = SAPP_KEYCODE_RIGHT_CONTROL;
  5735. _sapp.keycodes[0x036] = SAPP_KEYCODE_RIGHT_SHIFT;
  5736. _sapp.keycodes[0x136] = SAPP_KEYCODE_RIGHT_SHIFT;
  5737. _sapp.keycodes[0x15C] = SAPP_KEYCODE_RIGHT_SUPER;
  5738. _sapp.keycodes[0x150] = SAPP_KEYCODE_DOWN;
  5739. _sapp.keycodes[0x14B] = SAPP_KEYCODE_LEFT;
  5740. _sapp.keycodes[0x14D] = SAPP_KEYCODE_RIGHT;
  5741. _sapp.keycodes[0x148] = SAPP_KEYCODE_UP;
  5742. _sapp.keycodes[0x052] = SAPP_KEYCODE_KP_0;
  5743. _sapp.keycodes[0x04F] = SAPP_KEYCODE_KP_1;
  5744. _sapp.keycodes[0x050] = SAPP_KEYCODE_KP_2;
  5745. _sapp.keycodes[0x051] = SAPP_KEYCODE_KP_3;
  5746. _sapp.keycodes[0x04B] = SAPP_KEYCODE_KP_4;
  5747. _sapp.keycodes[0x04C] = SAPP_KEYCODE_KP_5;
  5748. _sapp.keycodes[0x04D] = SAPP_KEYCODE_KP_6;
  5749. _sapp.keycodes[0x047] = SAPP_KEYCODE_KP_7;
  5750. _sapp.keycodes[0x048] = SAPP_KEYCODE_KP_8;
  5751. _sapp.keycodes[0x049] = SAPP_KEYCODE_KP_9;
  5752. _sapp.keycodes[0x04E] = SAPP_KEYCODE_KP_ADD;
  5753. _sapp.keycodes[0x053] = SAPP_KEYCODE_KP_DECIMAL;
  5754. _sapp.keycodes[0x135] = SAPP_KEYCODE_KP_DIVIDE;
  5755. _sapp.keycodes[0x11C] = SAPP_KEYCODE_KP_ENTER;
  5756. _sapp.keycodes[0x037] = SAPP_KEYCODE_KP_MULTIPLY;
  5757. _sapp.keycodes[0x04A] = SAPP_KEYCODE_KP_SUBTRACT;
  5758. }
  5759. #endif // _SAPP_WIN32
  5760. #if defined(_SAPP_WIN32)
  5761. #if defined(SOKOL_D3D11)
  5762. #if defined(__cplusplus)
  5763. #define _sapp_d3d11_Release(self) (self)->Release()
  5764. #define _sapp_win32_refiid(iid) iid
  5765. #else
  5766. #define _sapp_d3d11_Release(self) (self)->lpVtbl->Release(self)
  5767. #define _sapp_win32_refiid(iid) &iid
  5768. #endif
  5769. #define _SAPP_SAFE_RELEASE(obj) if (obj) { _sapp_d3d11_Release(obj); obj=0; }
  5770. static const IID _sapp_IID_ID3D11Texture2D = { 0x6f15aaf2,0xd208,0x4e89, {0x9a,0xb4,0x48,0x95,0x35,0xd3,0x4f,0x9c} };
  5771. static const IID _sapp_IID_IDXGIDevice1 = { 0x77db970f,0x6276,0x48ba, {0xba,0x28,0x07,0x01,0x43,0xb4,0x39,0x2c} };
  5772. static const IID _sapp_IID_IDXGIFactory = { 0x7b7166ec,0x21c7,0x44ae, {0xb2,0x1a,0xc9,0xae,0x32,0x1a,0xe3,0x69} };
  5773. static inline HRESULT _sapp_dxgi_GetBuffer(IDXGISwapChain* self, UINT Buffer, REFIID riid, void** ppSurface) {
  5774. #if defined(__cplusplus)
  5775. return self->GetBuffer(Buffer, riid, ppSurface);
  5776. #else
  5777. return self->lpVtbl->GetBuffer(self, Buffer, riid, ppSurface);
  5778. #endif
  5779. }
  5780. static inline HRESULT _sapp_d3d11_QueryInterface(ID3D11Device* self, REFIID riid, void** ppvObject) {
  5781. #if defined(__cplusplus)
  5782. return self->QueryInterface(riid, ppvObject);
  5783. #else
  5784. return self->lpVtbl->QueryInterface(self, riid, ppvObject);
  5785. #endif
  5786. }
  5787. static inline HRESULT _sapp_d3d11_CreateRenderTargetView(ID3D11Device* self, ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView) {
  5788. #if defined(__cplusplus)
  5789. return self->CreateRenderTargetView(pResource, pDesc, ppRTView);
  5790. #else
  5791. return self->lpVtbl->CreateRenderTargetView(self, pResource, pDesc, ppRTView);
  5792. #endif
  5793. }
  5794. static inline HRESULT _sapp_d3d11_CreateTexture2D(ID3D11Device* self, const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D) {
  5795. #if defined(__cplusplus)
  5796. return self->CreateTexture2D(pDesc, pInitialData, ppTexture2D);
  5797. #else
  5798. return self->lpVtbl->CreateTexture2D(self, pDesc, pInitialData, ppTexture2D);
  5799. #endif
  5800. }
  5801. static inline HRESULT _sapp_d3d11_CreateDepthStencilView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView) {
  5802. #if defined(__cplusplus)
  5803. return self->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView);
  5804. #else
  5805. return self->lpVtbl->CreateDepthStencilView(self, pResource, pDesc, ppDepthStencilView);
  5806. #endif
  5807. }
  5808. static inline HRESULT _sapp_dxgi_ResizeBuffers(IDXGISwapChain* self, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags) {
  5809. #if defined(__cplusplus)
  5810. return self->ResizeBuffers(BufferCount, Width, Height, NewFormat, SwapChainFlags);
  5811. #else
  5812. return self->lpVtbl->ResizeBuffers(self, BufferCount, Width, Height, NewFormat, SwapChainFlags);
  5813. #endif
  5814. }
  5815. static inline HRESULT _sapp_dxgi_Present(IDXGISwapChain* self, UINT SyncInterval, UINT Flags) {
  5816. #if defined(__cplusplus)
  5817. return self->Present(SyncInterval, Flags);
  5818. #else
  5819. return self->lpVtbl->Present(self, SyncInterval, Flags);
  5820. #endif
  5821. }
  5822. static inline HRESULT _sapp_dxgi_GetFrameStatistics(IDXGISwapChain* self, DXGI_FRAME_STATISTICS* pStats) {
  5823. #if defined(__cplusplus)
  5824. return self->GetFrameStatistics(pStats);
  5825. #else
  5826. return self->lpVtbl->GetFrameStatistics(self, pStats);
  5827. #endif
  5828. }
  5829. static inline HRESULT _sapp_dxgi_SetMaximumFrameLatency(IDXGIDevice1* self, UINT MaxLatency) {
  5830. #if defined(__cplusplus)
  5831. return self->SetMaximumFrameLatency(MaxLatency);
  5832. #else
  5833. return self->lpVtbl->SetMaximumFrameLatency(self, MaxLatency);
  5834. #endif
  5835. }
  5836. static inline HRESULT _sapp_dxgi_GetAdapter(IDXGIDevice1* self, IDXGIAdapter** pAdapter) {
  5837. #if defined(__cplusplus)
  5838. return self->GetAdapter(pAdapter);
  5839. #else
  5840. return self->lpVtbl->GetAdapter(self, pAdapter);
  5841. #endif
  5842. }
  5843. static inline HRESULT _sapp_dxgi_GetParent(IDXGIObject* self, REFIID riid, void** ppParent) {
  5844. #if defined(__cplusplus)
  5845. return self->GetParent(riid, ppParent);
  5846. #else
  5847. return self->lpVtbl->GetParent(self, riid, ppParent);
  5848. #endif
  5849. }
  5850. static inline HRESULT _sapp_dxgi_MakeWindowAssociation(IDXGIFactory* self, HWND WindowHandle, UINT Flags) {
  5851. #if defined(__cplusplus)
  5852. return self->MakeWindowAssociation(WindowHandle, Flags);
  5853. #else
  5854. return self->lpVtbl->MakeWindowAssociation(self, WindowHandle, Flags);
  5855. #endif
  5856. }
  5857. _SOKOL_PRIVATE void _sapp_d3d11_create_device_and_swapchain(void) {
  5858. DXGI_SWAP_CHAIN_DESC* sc_desc = &_sapp.d3d11.swap_chain_desc;
  5859. sc_desc->BufferDesc.Width = (UINT)_sapp.framebuffer_width;
  5860. sc_desc->BufferDesc.Height = (UINT)_sapp.framebuffer_height;
  5861. sc_desc->BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  5862. sc_desc->BufferDesc.RefreshRate.Numerator = 60;
  5863. sc_desc->BufferDesc.RefreshRate.Denominator = 1;
  5864. sc_desc->OutputWindow = _sapp.win32.hwnd;
  5865. sc_desc->Windowed = true;
  5866. if (_sapp.win32.is_win10_or_greater) {
  5867. sc_desc->BufferCount = 2;
  5868. sc_desc->SwapEffect = (DXGI_SWAP_EFFECT) _SAPP_DXGI_SWAP_EFFECT_FLIP_DISCARD;
  5869. _sapp.d3d11.use_dxgi_frame_stats = true;
  5870. }
  5871. else {
  5872. sc_desc->BufferCount = 1;
  5873. sc_desc->SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  5874. _sapp.d3d11.use_dxgi_frame_stats = false;
  5875. }
  5876. sc_desc->SampleDesc.Count = 1;
  5877. sc_desc->SampleDesc.Quality = 0;
  5878. sc_desc->BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  5879. UINT create_flags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  5880. #if defined(SOKOL_DEBUG)
  5881. create_flags |= D3D11_CREATE_DEVICE_DEBUG;
  5882. #endif
  5883. D3D_FEATURE_LEVEL feature_level;
  5884. HRESULT hr = D3D11CreateDeviceAndSwapChain(
  5885. NULL, /* pAdapter (use default) */
  5886. D3D_DRIVER_TYPE_HARDWARE, /* DriverType */
  5887. NULL, /* Software */
  5888. create_flags, /* Flags */
  5889. NULL, /* pFeatureLevels */
  5890. 0, /* FeatureLevels */
  5891. D3D11_SDK_VERSION, /* SDKVersion */
  5892. sc_desc, /* pSwapChainDesc */
  5893. &_sapp.d3d11.swap_chain, /* ppSwapChain */
  5894. &_sapp.d3d11.device, /* ppDevice */
  5895. &feature_level, /* pFeatureLevel */
  5896. &_sapp.d3d11.device_context); /* ppImmediateContext */
  5897. _SOKOL_UNUSED(hr);
  5898. #if defined(SOKOL_DEBUG)
  5899. if (!SUCCEEDED(hr)) {
  5900. // if initialization with D3D11_CREATE_DEVICE_DEBUG fails, this could be because the
  5901. // 'D3D11 debug layer' stopped working, indicated by the error message:
  5902. // ===
  5903. // D3D11CreateDevice: Flags (0x2) were specified which require the D3D11 SDK Layers for Windows 10, but they are not present on the system.
  5904. // These flags must be removed, or the Windows 10 SDK must be installed.
  5905. // Flags include: D3D11_CREATE_DEVICE_DEBUG
  5906. // ===
  5907. //
  5908. // ...just retry with the DEBUG flag switched off
  5909. _SAPP_ERROR(WIN32_D3D11_CREATE_DEVICE_AND_SWAPCHAIN_WITH_DEBUG_FAILED);
  5910. create_flags &= ~D3D11_CREATE_DEVICE_DEBUG;
  5911. hr = D3D11CreateDeviceAndSwapChain(
  5912. NULL, /* pAdapter (use default) */
  5913. D3D_DRIVER_TYPE_HARDWARE, /* DriverType */
  5914. NULL, /* Software */
  5915. create_flags, /* Flags */
  5916. NULL, /* pFeatureLevels */
  5917. 0, /* FeatureLevels */
  5918. D3D11_SDK_VERSION, /* SDKVersion */
  5919. sc_desc, /* pSwapChainDesc */
  5920. &_sapp.d3d11.swap_chain, /* ppSwapChain */
  5921. &_sapp.d3d11.device, /* ppDevice */
  5922. &feature_level, /* pFeatureLevel */
  5923. &_sapp.d3d11.device_context); /* ppImmediateContext */
  5924. }
  5925. #endif
  5926. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.swap_chain && _sapp.d3d11.device && _sapp.d3d11.device_context);
  5927. // minimize frame latency, disable Alt-Enter
  5928. hr = _sapp_d3d11_QueryInterface(_sapp.d3d11.device, _sapp_win32_refiid(_sapp_IID_IDXGIDevice1), (void**)&_sapp.d3d11.dxgi_device);
  5929. if (SUCCEEDED(hr) && _sapp.d3d11.dxgi_device) {
  5930. _sapp_dxgi_SetMaximumFrameLatency(_sapp.d3d11.dxgi_device, 1);
  5931. IDXGIAdapter* dxgi_adapter = 0;
  5932. hr = _sapp_dxgi_GetAdapter(_sapp.d3d11.dxgi_device, &dxgi_adapter);
  5933. if (SUCCEEDED(hr) && dxgi_adapter) {
  5934. IDXGIFactory* dxgi_factory = 0;
  5935. hr = _sapp_dxgi_GetParent((IDXGIObject*)dxgi_adapter, _sapp_win32_refiid(_sapp_IID_IDXGIFactory), (void**)&dxgi_factory);
  5936. if (SUCCEEDED(hr)) {
  5937. _sapp_dxgi_MakeWindowAssociation(dxgi_factory, _sapp.win32.hwnd, DXGI_MWA_NO_ALT_ENTER|DXGI_MWA_NO_PRINT_SCREEN);
  5938. _SAPP_SAFE_RELEASE(dxgi_factory);
  5939. }
  5940. else {
  5941. _SAPP_ERROR(WIN32_D3D11_GET_IDXGIFACTORY_FAILED);
  5942. }
  5943. _SAPP_SAFE_RELEASE(dxgi_adapter);
  5944. }
  5945. else {
  5946. _SAPP_ERROR(WIN32_D3D11_GET_IDXGIADAPTER_FAILED);
  5947. }
  5948. }
  5949. else {
  5950. _SAPP_PANIC(WIN32_D3D11_QUERY_INTERFACE_IDXGIDEVICE1_FAILED);
  5951. }
  5952. }
  5953. _SOKOL_PRIVATE void _sapp_d3d11_destroy_device_and_swapchain(void) {
  5954. _SAPP_SAFE_RELEASE(_sapp.d3d11.swap_chain);
  5955. _SAPP_SAFE_RELEASE(_sapp.d3d11.dxgi_device);
  5956. _SAPP_SAFE_RELEASE(_sapp.d3d11.device_context);
  5957. _SAPP_SAFE_RELEASE(_sapp.d3d11.device);
  5958. }
  5959. _SOKOL_PRIVATE void _sapp_d3d11_create_default_render_target(void) {
  5960. SOKOL_ASSERT(0 == _sapp.d3d11.rt);
  5961. SOKOL_ASSERT(0 == _sapp.d3d11.rtv);
  5962. SOKOL_ASSERT(0 == _sapp.d3d11.msaa_rt);
  5963. SOKOL_ASSERT(0 == _sapp.d3d11.msaa_rtv);
  5964. SOKOL_ASSERT(0 == _sapp.d3d11.ds);
  5965. SOKOL_ASSERT(0 == _sapp.d3d11.dsv);
  5966. HRESULT hr;
  5967. /* view for the swapchain-created framebuffer */
  5968. hr = _sapp_dxgi_GetBuffer(_sapp.d3d11.swap_chain, 0, _sapp_win32_refiid(_sapp_IID_ID3D11Texture2D), (void**)&_sapp.d3d11.rt);
  5969. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.rt);
  5970. hr = _sapp_d3d11_CreateRenderTargetView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.rt, NULL, &_sapp.d3d11.rtv);
  5971. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.rtv);
  5972. /* common desc for MSAA and depth-stencil texture */
  5973. D3D11_TEXTURE2D_DESC tex_desc;
  5974. _sapp_clear(&tex_desc, sizeof(tex_desc));
  5975. tex_desc.Width = (UINT)_sapp.framebuffer_width;
  5976. tex_desc.Height = (UINT)_sapp.framebuffer_height;
  5977. tex_desc.MipLevels = 1;
  5978. tex_desc.ArraySize = 1;
  5979. tex_desc.Usage = D3D11_USAGE_DEFAULT;
  5980. tex_desc.BindFlags = D3D11_BIND_RENDER_TARGET;
  5981. tex_desc.SampleDesc.Count = (UINT) _sapp.sample_count;
  5982. tex_desc.SampleDesc.Quality = (UINT) (_sapp.sample_count > 1 ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0);
  5983. /* create MSAA texture and view if antialiasing requested */
  5984. if (_sapp.sample_count > 1) {
  5985. tex_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  5986. hr = _sapp_d3d11_CreateTexture2D(_sapp.d3d11.device, &tex_desc, NULL, &_sapp.d3d11.msaa_rt);
  5987. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.msaa_rt);
  5988. hr = _sapp_d3d11_CreateRenderTargetView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.msaa_rt, NULL, &_sapp.d3d11.msaa_rtv);
  5989. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.msaa_rtv);
  5990. }
  5991. /* texture and view for the depth-stencil-surface */
  5992. tex_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  5993. tex_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  5994. hr = _sapp_d3d11_CreateTexture2D(_sapp.d3d11.device, &tex_desc, NULL, &_sapp.d3d11.ds);
  5995. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.ds);
  5996. hr = _sapp_d3d11_CreateDepthStencilView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.ds, NULL, &_sapp.d3d11.dsv);
  5997. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.dsv);
  5998. }
  5999. _SOKOL_PRIVATE void _sapp_d3d11_destroy_default_render_target(void) {
  6000. _SAPP_SAFE_RELEASE(_sapp.d3d11.rt);
  6001. _SAPP_SAFE_RELEASE(_sapp.d3d11.rtv);
  6002. _SAPP_SAFE_RELEASE(_sapp.d3d11.msaa_rt);
  6003. _SAPP_SAFE_RELEASE(_sapp.d3d11.msaa_rtv);
  6004. _SAPP_SAFE_RELEASE(_sapp.d3d11.ds);
  6005. _SAPP_SAFE_RELEASE(_sapp.d3d11.dsv);
  6006. }
  6007. _SOKOL_PRIVATE void _sapp_d3d11_resize_default_render_target(void) {
  6008. if (_sapp.d3d11.swap_chain) {
  6009. _sapp_d3d11_destroy_default_render_target();
  6010. _sapp_dxgi_ResizeBuffers(_sapp.d3d11.swap_chain, _sapp.d3d11.swap_chain_desc.BufferCount, (UINT)_sapp.framebuffer_width, (UINT)_sapp.framebuffer_height, DXGI_FORMAT_B8G8R8A8_UNORM, 0);
  6011. _sapp_d3d11_create_default_render_target();
  6012. }
  6013. }
  6014. _SOKOL_PRIVATE void _sapp_d3d11_present(bool do_not_wait) {
  6015. UINT flags = 0;
  6016. if (_sapp.win32.is_win10_or_greater && do_not_wait) {
  6017. /* this hack/workaround somewhat improves window-movement and -sizing
  6018. responsiveness when rendering is controlled via WM_TIMER during window
  6019. move and resize on NVIDIA cards on Win10 with recent drivers.
  6020. */
  6021. flags = DXGI_PRESENT_DO_NOT_WAIT;
  6022. }
  6023. _sapp_dxgi_Present(_sapp.d3d11.swap_chain, (UINT)_sapp.swap_interval, flags);
  6024. }
  6025. #endif /* SOKOL_D3D11 */
  6026. #if defined(SOKOL_GLCORE)
  6027. _SOKOL_PRIVATE void _sapp_wgl_init(void) {
  6028. _sapp.wgl.opengl32 = LoadLibraryA("opengl32.dll");
  6029. if (!_sapp.wgl.opengl32) {
  6030. _SAPP_PANIC(WIN32_LOAD_OPENGL32_DLL_FAILED);
  6031. }
  6032. SOKOL_ASSERT(_sapp.wgl.opengl32);
  6033. _sapp.wgl.CreateContext = (PFN_wglCreateContext)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglCreateContext");
  6034. SOKOL_ASSERT(_sapp.wgl.CreateContext);
  6035. _sapp.wgl.DeleteContext = (PFN_wglDeleteContext)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglDeleteContext");
  6036. SOKOL_ASSERT(_sapp.wgl.DeleteContext);
  6037. _sapp.wgl.GetProcAddress = (PFN_wglGetProcAddress)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglGetProcAddress");
  6038. SOKOL_ASSERT(_sapp.wgl.GetProcAddress);
  6039. _sapp.wgl.GetCurrentDC = (PFN_wglGetCurrentDC)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglGetCurrentDC");
  6040. SOKOL_ASSERT(_sapp.wgl.GetCurrentDC);
  6041. _sapp.wgl.MakeCurrent = (PFN_wglMakeCurrent)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglMakeCurrent");
  6042. SOKOL_ASSERT(_sapp.wgl.MakeCurrent);
  6043. _sapp.wgl.GetIntegerv = (void(WINAPI*)(uint32_t, int32_t*)) GetProcAddress(_sapp.wgl.opengl32, "glGetIntegerv");
  6044. SOKOL_ASSERT(_sapp.wgl.GetIntegerv);
  6045. _sapp.wgl.msg_hwnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW,
  6046. L"SOKOLAPP",
  6047. L"sokol-app message window",
  6048. WS_CLIPSIBLINGS|WS_CLIPCHILDREN,
  6049. 0, 0, 1, 1,
  6050. NULL, NULL,
  6051. GetModuleHandleW(NULL),
  6052. NULL);
  6053. if (!_sapp.wgl.msg_hwnd) {
  6054. _SAPP_PANIC(WIN32_CREATE_HELPER_WINDOW_FAILED);
  6055. }
  6056. SOKOL_ASSERT(_sapp.wgl.msg_hwnd);
  6057. ShowWindow(_sapp.wgl.msg_hwnd, SW_HIDE);
  6058. MSG msg;
  6059. while (PeekMessageW(&msg, _sapp.wgl.msg_hwnd, 0, 0, PM_REMOVE)) {
  6060. TranslateMessage(&msg);
  6061. DispatchMessageW(&msg);
  6062. }
  6063. _sapp.wgl.msg_dc = GetDC(_sapp.wgl.msg_hwnd);
  6064. if (!_sapp.wgl.msg_dc) {
  6065. _SAPP_PANIC(WIN32_HELPER_WINDOW_GETDC_FAILED);
  6066. }
  6067. }
  6068. _SOKOL_PRIVATE void _sapp_wgl_shutdown(void) {
  6069. SOKOL_ASSERT(_sapp.wgl.opengl32 && _sapp.wgl.msg_hwnd);
  6070. DestroyWindow(_sapp.wgl.msg_hwnd); _sapp.wgl.msg_hwnd = 0;
  6071. FreeLibrary(_sapp.wgl.opengl32); _sapp.wgl.opengl32 = 0;
  6072. }
  6073. _SOKOL_PRIVATE bool _sapp_wgl_has_ext(const char* ext, const char* extensions) {
  6074. SOKOL_ASSERT(ext && extensions);
  6075. const char* start = extensions;
  6076. while (true) {
  6077. const char* where = strstr(start, ext);
  6078. if (!where) {
  6079. return false;
  6080. }
  6081. const char* terminator = where + strlen(ext);
  6082. if ((where == start) || (*(where - 1) == ' ')) {
  6083. if (*terminator == ' ' || *terminator == '\0') {
  6084. break;
  6085. }
  6086. }
  6087. start = terminator;
  6088. }
  6089. return true;
  6090. }
  6091. _SOKOL_PRIVATE bool _sapp_wgl_ext_supported(const char* ext) {
  6092. SOKOL_ASSERT(ext);
  6093. if (_sapp.wgl.GetExtensionsStringEXT) {
  6094. const char* extensions = _sapp.wgl.GetExtensionsStringEXT();
  6095. if (extensions) {
  6096. if (_sapp_wgl_has_ext(ext, extensions)) {
  6097. return true;
  6098. }
  6099. }
  6100. }
  6101. if (_sapp.wgl.GetExtensionsStringARB) {
  6102. const char* extensions = _sapp.wgl.GetExtensionsStringARB(_sapp.wgl.GetCurrentDC());
  6103. if (extensions) {
  6104. if (_sapp_wgl_has_ext(ext, extensions)) {
  6105. return true;
  6106. }
  6107. }
  6108. }
  6109. return false;
  6110. }
  6111. _SOKOL_PRIVATE void _sapp_wgl_load_extensions(void) {
  6112. SOKOL_ASSERT(_sapp.wgl.msg_dc);
  6113. PIXELFORMATDESCRIPTOR pfd;
  6114. _sapp_clear(&pfd, sizeof(pfd));
  6115. pfd.nSize = sizeof(pfd);
  6116. pfd.nVersion = 1;
  6117. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  6118. pfd.iPixelType = PFD_TYPE_RGBA;
  6119. pfd.cColorBits = 24;
  6120. if (!SetPixelFormat(_sapp.wgl.msg_dc, ChoosePixelFormat(_sapp.wgl.msg_dc, &pfd), &pfd)) {
  6121. _SAPP_PANIC(WIN32_DUMMY_CONTEXT_SET_PIXELFORMAT_FAILED);
  6122. }
  6123. HGLRC rc = _sapp.wgl.CreateContext(_sapp.wgl.msg_dc);
  6124. if (!rc) {
  6125. _SAPP_PANIC(WIN32_CREATE_DUMMY_CONTEXT_FAILED);
  6126. }
  6127. if (!_sapp.wgl.MakeCurrent(_sapp.wgl.msg_dc, rc)) {
  6128. _SAPP_PANIC(WIN32_DUMMY_CONTEXT_MAKE_CURRENT_FAILED);
  6129. }
  6130. _sapp.wgl.GetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void*) _sapp.wgl.GetProcAddress("wglGetExtensionsStringEXT");
  6131. _sapp.wgl.GetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)(void*) _sapp.wgl.GetProcAddress("wglGetExtensionsStringARB");
  6132. _sapp.wgl.CreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)(void*) _sapp.wgl.GetProcAddress("wglCreateContextAttribsARB");
  6133. _sapp.wgl.SwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)(void*) _sapp.wgl.GetProcAddress("wglSwapIntervalEXT");
  6134. _sapp.wgl.GetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)(void*) _sapp.wgl.GetProcAddress("wglGetPixelFormatAttribivARB");
  6135. _sapp.wgl.arb_multisample = _sapp_wgl_ext_supported("WGL_ARB_multisample");
  6136. _sapp.wgl.arb_create_context = _sapp_wgl_ext_supported("WGL_ARB_create_context");
  6137. _sapp.wgl.arb_create_context_profile = _sapp_wgl_ext_supported("WGL_ARB_create_context_profile");
  6138. _sapp.wgl.ext_swap_control = _sapp_wgl_ext_supported("WGL_EXT_swap_control");
  6139. _sapp.wgl.arb_pixel_format = _sapp_wgl_ext_supported("WGL_ARB_pixel_format");
  6140. _sapp.wgl.MakeCurrent(_sapp.wgl.msg_dc, 0);
  6141. _sapp.wgl.DeleteContext(rc);
  6142. }
  6143. _SOKOL_PRIVATE int _sapp_wgl_attrib(int pixel_format, int attrib) {
  6144. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6145. int value = 0;
  6146. if (!_sapp.wgl.GetPixelFormatAttribivARB(_sapp.win32.dc, pixel_format, 0, 1, &attrib, &value)) {
  6147. _SAPP_PANIC(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED);
  6148. }
  6149. return value;
  6150. }
  6151. _SOKOL_PRIVATE void _sapp_wgl_attribiv(int pixel_format, int num_attribs, const int* attribs, int* results) {
  6152. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6153. if (!_sapp.wgl.GetPixelFormatAttribivARB(_sapp.win32.dc, pixel_format, 0, num_attribs, attribs, results)) {
  6154. _SAPP_PANIC(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED);
  6155. }
  6156. }
  6157. _SOKOL_PRIVATE int _sapp_wgl_find_pixel_format(void) {
  6158. SOKOL_ASSERT(_sapp.win32.dc);
  6159. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6160. #define _sapp_wgl_num_query_tags (12)
  6161. const int query_tags[_sapp_wgl_num_query_tags] = {
  6162. WGL_SUPPORT_OPENGL_ARB,
  6163. WGL_DRAW_TO_WINDOW_ARB,
  6164. WGL_PIXEL_TYPE_ARB,
  6165. WGL_ACCELERATION_ARB,
  6166. WGL_DOUBLE_BUFFER_ARB,
  6167. WGL_RED_BITS_ARB,
  6168. WGL_GREEN_BITS_ARB,
  6169. WGL_BLUE_BITS_ARB,
  6170. WGL_ALPHA_BITS_ARB,
  6171. WGL_DEPTH_BITS_ARB,
  6172. WGL_STENCIL_BITS_ARB,
  6173. WGL_SAMPLES_ARB,
  6174. };
  6175. const int result_support_opengl_index = 0;
  6176. const int result_draw_to_window_index = 1;
  6177. const int result_pixel_type_index = 2;
  6178. const int result_acceleration_index = 3;
  6179. const int result_double_buffer_index = 4;
  6180. const int result_red_bits_index = 5;
  6181. const int result_green_bits_index = 6;
  6182. const int result_blue_bits_index = 7;
  6183. const int result_alpha_bits_index = 8;
  6184. const int result_depth_bits_index = 9;
  6185. const int result_stencil_bits_index = 10;
  6186. const int result_samples_index = 11;
  6187. int query_results[_sapp_wgl_num_query_tags] = {0};
  6188. // Drop the last item if multisample extension is not supported.
  6189. // If in future querying with multiple extensions, will have to shuffle index values to have active extensions on the end.
  6190. int query_count = _sapp_wgl_num_query_tags;
  6191. if (!_sapp.wgl.arb_multisample) {
  6192. query_count = _sapp_wgl_num_query_tags - 1;
  6193. }
  6194. int native_count = _sapp_wgl_attrib(1, WGL_NUMBER_PIXEL_FORMATS_ARB);
  6195. _sapp_gl_fbconfig desired;
  6196. _sapp_gl_init_fbconfig(&desired);
  6197. desired.red_bits = 8;
  6198. desired.green_bits = 8;
  6199. desired.blue_bits = 8;
  6200. desired.alpha_bits = 8;
  6201. desired.depth_bits = 24;
  6202. desired.stencil_bits = 8;
  6203. desired.doublebuffer = true;
  6204. desired.samples = (_sapp.sample_count > 1) ? _sapp.sample_count : 0;
  6205. int pixel_format = 0;
  6206. _sapp_gl_fbselect fbselect;
  6207. _sapp_gl_init_fbselect(&fbselect);
  6208. for (int i = 0; i < native_count; i++) {
  6209. const int n = i + 1;
  6210. _sapp_wgl_attribiv(n, query_count, query_tags, query_results);
  6211. if (query_results[result_support_opengl_index] == 0
  6212. || query_results[result_draw_to_window_index] == 0
  6213. || query_results[result_pixel_type_index] != WGL_TYPE_RGBA_ARB
  6214. || query_results[result_acceleration_index] == WGL_NO_ACCELERATION_ARB)
  6215. {
  6216. continue;
  6217. }
  6218. _sapp_gl_fbconfig u;
  6219. _sapp_clear(&u, sizeof(u));
  6220. u.red_bits = query_results[result_red_bits_index];
  6221. u.green_bits = query_results[result_green_bits_index];
  6222. u.blue_bits = query_results[result_blue_bits_index];
  6223. u.alpha_bits = query_results[result_alpha_bits_index];
  6224. u.depth_bits = query_results[result_depth_bits_index];
  6225. u.stencil_bits = query_results[result_stencil_bits_index];
  6226. u.doublebuffer = 0 != query_results[result_double_buffer_index];
  6227. u.samples = query_results[result_samples_index]; // NOTE: If arb_multisample is not supported - just takes the default 0
  6228. // Test if this pixel format is better than the previous one
  6229. if (_sapp_gl_select_fbconfig(&fbselect, &desired, &u)) {
  6230. pixel_format = (uintptr_t)n;
  6231. // Early exit if matching as good as possible
  6232. if (fbselect.best_match) {
  6233. break;
  6234. }
  6235. }
  6236. }
  6237. return pixel_format;
  6238. }
  6239. _SOKOL_PRIVATE void _sapp_wgl_create_context(void) {
  6240. int pixel_format = _sapp_wgl_find_pixel_format();
  6241. if (0 == pixel_format) {
  6242. _SAPP_PANIC(WIN32_WGL_FIND_PIXELFORMAT_FAILED);
  6243. }
  6244. PIXELFORMATDESCRIPTOR pfd;
  6245. if (!DescribePixelFormat(_sapp.win32.dc, pixel_format, sizeof(pfd), &pfd)) {
  6246. _SAPP_PANIC(WIN32_WGL_DESCRIBE_PIXELFORMAT_FAILED);
  6247. }
  6248. if (!SetPixelFormat(_sapp.win32.dc, pixel_format, &pfd)) {
  6249. _SAPP_PANIC(WIN32_WGL_SET_PIXELFORMAT_FAILED);
  6250. }
  6251. if (!_sapp.wgl.arb_create_context) {
  6252. _SAPP_PANIC(WIN32_WGL_ARB_CREATE_CONTEXT_REQUIRED);
  6253. }
  6254. if (!_sapp.wgl.arb_create_context_profile) {
  6255. _SAPP_PANIC(WIN32_WGL_ARB_CREATE_CONTEXT_PROFILE_REQUIRED);
  6256. }
  6257. const int attrs[] = {
  6258. WGL_CONTEXT_MAJOR_VERSION_ARB, _sapp.desc.gl_major_version,
  6259. WGL_CONTEXT_MINOR_VERSION_ARB, _sapp.desc.gl_minor_version,
  6260. #if defined(SOKOL_DEBUG)
  6261. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,
  6262. #else
  6263. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
  6264. #endif
  6265. WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
  6266. 0, 0
  6267. };
  6268. _sapp.wgl.gl_ctx = _sapp.wgl.CreateContextAttribsARB(_sapp.win32.dc, 0, attrs);
  6269. if (!_sapp.wgl.gl_ctx) {
  6270. const DWORD err = GetLastError();
  6271. if (err == (0xc0070000 | ERROR_INVALID_VERSION_ARB)) {
  6272. _SAPP_PANIC(WIN32_WGL_OPENGL_VERSION_NOT_SUPPORTED);
  6273. }
  6274. else if (err == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) {
  6275. _SAPP_PANIC(WIN32_WGL_OPENGL_PROFILE_NOT_SUPPORTED);
  6276. }
  6277. else if (err == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) {
  6278. _SAPP_PANIC(WIN32_WGL_INCOMPATIBLE_DEVICE_CONTEXT);
  6279. }
  6280. else {
  6281. _SAPP_PANIC(WIN32_WGL_CREATE_CONTEXT_ATTRIBS_FAILED_OTHER);
  6282. }
  6283. }
  6284. _sapp.wgl.MakeCurrent(_sapp.win32.dc, _sapp.wgl.gl_ctx);
  6285. if (_sapp.wgl.ext_swap_control) {
  6286. /* FIXME: DwmIsCompositionEnabled() (see GLFW) */
  6287. _sapp.wgl.SwapIntervalEXT(_sapp.swap_interval);
  6288. }
  6289. const uint32_t gl_framebuffer_binding = 0x8CA6;
  6290. _sapp.wgl.GetIntegerv(gl_framebuffer_binding, (int32_t*)&_sapp.gl.framebuffer);
  6291. }
  6292. _SOKOL_PRIVATE void _sapp_wgl_destroy_context(void) {
  6293. SOKOL_ASSERT(_sapp.wgl.gl_ctx);
  6294. _sapp.wgl.DeleteContext(_sapp.wgl.gl_ctx);
  6295. _sapp.wgl.gl_ctx = 0;
  6296. }
  6297. _SOKOL_PRIVATE void _sapp_wgl_swap_buffers(void) {
  6298. SOKOL_ASSERT(_sapp.win32.dc);
  6299. /* FIXME: DwmIsCompositionEnabled? (see GLFW) */
  6300. SwapBuffers(_sapp.win32.dc);
  6301. }
  6302. #endif /* SOKOL_GLCORE */
  6303. _SOKOL_PRIVATE bool _sapp_win32_wide_to_utf8(const wchar_t* src, char* dst, int dst_num_bytes) {
  6304. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  6305. _sapp_clear(dst, (size_t)dst_num_bytes);
  6306. const int bytes_needed = WideCharToMultiByte(CP_UTF8, 0, src, -1, NULL, 0, NULL, NULL);
  6307. if (bytes_needed <= dst_num_bytes) {
  6308. WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, dst_num_bytes, NULL, NULL);
  6309. return true;
  6310. }
  6311. else {
  6312. return false;
  6313. }
  6314. }
  6315. /* updates current window and framebuffer size from the window's client rect, returns true if size has changed */
  6316. _SOKOL_PRIVATE bool _sapp_win32_update_dimensions(void) {
  6317. RECT rect;
  6318. if (GetClientRect(_sapp.win32.hwnd, &rect)) {
  6319. float window_width = (float)(rect.right - rect.left) / _sapp.win32.dpi.window_scale;
  6320. float window_height = (float)(rect.bottom - rect.top) / _sapp.win32.dpi.window_scale;
  6321. _sapp.window_width = (int)roundf(window_width);
  6322. _sapp.window_height = (int)roundf(window_height);
  6323. int fb_width = (int)roundf(window_width * _sapp.win32.dpi.content_scale);
  6324. int fb_height = (int)roundf(window_height * _sapp.win32.dpi.content_scale);
  6325. /* prevent a framebuffer size of 0 when window is minimized */
  6326. if (0 == fb_width) {
  6327. fb_width = 1;
  6328. }
  6329. if (0 == fb_height) {
  6330. fb_height = 1;
  6331. }
  6332. if ((fb_width != _sapp.framebuffer_width) || (fb_height != _sapp.framebuffer_height)) {
  6333. _sapp.framebuffer_width = fb_width;
  6334. _sapp.framebuffer_height = fb_height;
  6335. return true;
  6336. }
  6337. }
  6338. else {
  6339. _sapp.window_width = _sapp.window_height = 1;
  6340. _sapp.framebuffer_width = _sapp.framebuffer_height = 1;
  6341. }
  6342. return false;
  6343. }
  6344. _SOKOL_PRIVATE void _sapp_win32_set_fullscreen(bool fullscreen, UINT swp_flags) {
  6345. HMONITOR monitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONEAREST);
  6346. MONITORINFO minfo;
  6347. _sapp_clear(&minfo, sizeof(minfo));
  6348. minfo.cbSize = sizeof(MONITORINFO);
  6349. GetMonitorInfo(monitor, &minfo);
  6350. const RECT mr = minfo.rcMonitor;
  6351. const int monitor_w = mr.right - mr.left;
  6352. const int monitor_h = mr.bottom - mr.top;
  6353. const DWORD win_ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  6354. DWORD win_style;
  6355. RECT rect = { 0, 0, 0, 0 };
  6356. _sapp.fullscreen = fullscreen;
  6357. if (!_sapp.fullscreen) {
  6358. win_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
  6359. rect = _sapp.win32.stored_window_rect;
  6360. }
  6361. else {
  6362. GetWindowRect(_sapp.win32.hwnd, &_sapp.win32.stored_window_rect);
  6363. win_style = WS_POPUP | WS_SYSMENU | WS_VISIBLE;
  6364. rect.left = mr.left;
  6365. rect.top = mr.top;
  6366. rect.right = rect.left + monitor_w;
  6367. rect.bottom = rect.top + monitor_h;
  6368. AdjustWindowRectEx(&rect, win_style, FALSE, win_ex_style);
  6369. }
  6370. const int win_w = rect.right - rect.left;
  6371. const int win_h = rect.bottom - rect.top;
  6372. const int win_x = rect.left;
  6373. const int win_y = rect.top;
  6374. SetWindowLongPtr(_sapp.win32.hwnd, GWL_STYLE, win_style);
  6375. SetWindowPos(_sapp.win32.hwnd, HWND_TOP, win_x, win_y, win_w, win_h, swp_flags | SWP_FRAMECHANGED);
  6376. }
  6377. _SOKOL_PRIVATE void _sapp_win32_toggle_fullscreen(void) {
  6378. _sapp_win32_set_fullscreen(!_sapp.fullscreen, SWP_SHOWWINDOW);
  6379. }
  6380. _SOKOL_PRIVATE void _sapp_win32_init_cursor(sapp_mouse_cursor cursor) {
  6381. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  6382. // NOTE: the OCR_* constants are only defined if OEMRESOURCE is defined
  6383. // before windows.h is included, but we can't guarantee that because
  6384. // the sokol_app.h implementation may be included with other implementations
  6385. // in the same compilation unit
  6386. int id = 0;
  6387. switch (cursor) {
  6388. case SAPP_MOUSECURSOR_ARROW: id = 32512; break; // OCR_NORMAL
  6389. case SAPP_MOUSECURSOR_IBEAM: id = 32513; break; // OCR_IBEAM
  6390. case SAPP_MOUSECURSOR_CROSSHAIR: id = 32515; break; // OCR_CROSS
  6391. case SAPP_MOUSECURSOR_POINTING_HAND: id = 32649; break; // OCR_HAND
  6392. case SAPP_MOUSECURSOR_RESIZE_EW: id = 32644; break; // OCR_SIZEWE
  6393. case SAPP_MOUSECURSOR_RESIZE_NS: id = 32645; break; // OCR_SIZENS
  6394. case SAPP_MOUSECURSOR_RESIZE_NWSE: id = 32642; break; // OCR_SIZENWSE
  6395. case SAPP_MOUSECURSOR_RESIZE_NESW: id = 32643; break; // OCR_SIZENESW
  6396. case SAPP_MOUSECURSOR_RESIZE_ALL: id = 32646; break; // OCR_SIZEALL
  6397. case SAPP_MOUSECURSOR_NOT_ALLOWED: id = 32648; break; // OCR_NO
  6398. default: break;
  6399. }
  6400. if (id != 0) {
  6401. _sapp.win32.cursors[cursor] = (HCURSOR)LoadImageW(NULL, MAKEINTRESOURCEW(id), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE|LR_SHARED);
  6402. }
  6403. // fallback: default cursor
  6404. if (0 == _sapp.win32.cursors[cursor]) {
  6405. // 32512 => IDC_ARROW
  6406. _sapp.win32.cursors[cursor] = LoadCursorW(NULL, MAKEINTRESOURCEW(32512));
  6407. }
  6408. SOKOL_ASSERT(0 != _sapp.win32.cursors[cursor]);
  6409. }
  6410. _SOKOL_PRIVATE void _sapp_win32_init_cursors(void) {
  6411. for (int i = 0; i < _SAPP_MOUSECURSOR_NUM; i++) {
  6412. _sapp_win32_init_cursor((sapp_mouse_cursor)i);
  6413. }
  6414. }
  6415. _SOKOL_PRIVATE bool _sapp_win32_cursor_in_content_area(void) {
  6416. POINT pos;
  6417. if (!GetCursorPos(&pos)) {
  6418. return false;
  6419. }
  6420. if (WindowFromPoint(pos) != _sapp.win32.hwnd) {
  6421. return false;
  6422. }
  6423. RECT area;
  6424. GetClientRect(_sapp.win32.hwnd, &area);
  6425. ClientToScreen(_sapp.win32.hwnd, (POINT*)&area.left);
  6426. ClientToScreen(_sapp.win32.hwnd, (POINT*)&area.right);
  6427. return PtInRect(&area, pos) == TRUE;
  6428. }
  6429. _SOKOL_PRIVATE void _sapp_win32_update_cursor(sapp_mouse_cursor cursor, bool shown, bool skip_area_test) {
  6430. // NOTE: when called from WM_SETCURSOR, the area test would be redundant
  6431. if (!skip_area_test) {
  6432. if (!_sapp_win32_cursor_in_content_area()) {
  6433. return;
  6434. }
  6435. }
  6436. if (!shown) {
  6437. SetCursor(NULL);
  6438. }
  6439. else {
  6440. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  6441. SOKOL_ASSERT(0 != _sapp.win32.cursors[cursor]);
  6442. SetCursor(_sapp.win32.cursors[cursor]);
  6443. }
  6444. }
  6445. _SOKOL_PRIVATE void _sapp_win32_capture_mouse(uint8_t btn_mask) {
  6446. if (0 == _sapp.win32.mouse_capture_mask) {
  6447. SetCapture(_sapp.win32.hwnd);
  6448. }
  6449. _sapp.win32.mouse_capture_mask |= btn_mask;
  6450. }
  6451. _SOKOL_PRIVATE void _sapp_win32_release_mouse(uint8_t btn_mask) {
  6452. if (0 != _sapp.win32.mouse_capture_mask) {
  6453. _sapp.win32.mouse_capture_mask &= ~btn_mask;
  6454. if (0 == _sapp.win32.mouse_capture_mask) {
  6455. ReleaseCapture();
  6456. }
  6457. }
  6458. }
  6459. _SOKOL_PRIVATE void _sapp_win32_lock_mouse(bool lock) {
  6460. if (lock == _sapp.mouse.locked) {
  6461. return;
  6462. }
  6463. _sapp.mouse.dx = 0.0f;
  6464. _sapp.mouse.dy = 0.0f;
  6465. _sapp.mouse.locked = lock;
  6466. _sapp_win32_release_mouse(0xFF);
  6467. if (_sapp.mouse.locked) {
  6468. /* store the current mouse position, so it can be restored when unlocked */
  6469. POINT pos;
  6470. BOOL res = GetCursorPos(&pos);
  6471. SOKOL_ASSERT(res); _SOKOL_UNUSED(res);
  6472. _sapp.win32.mouse_locked_x = pos.x;
  6473. _sapp.win32.mouse_locked_y = pos.y;
  6474. /* while the mouse is locked, make the mouse cursor invisible and
  6475. confine the mouse movement to a small rectangle inside our window
  6476. (so that we don't miss any mouse up events)
  6477. */
  6478. RECT client_rect = {
  6479. _sapp.win32.mouse_locked_x,
  6480. _sapp.win32.mouse_locked_y,
  6481. _sapp.win32.mouse_locked_x,
  6482. _sapp.win32.mouse_locked_y
  6483. };
  6484. ClipCursor(&client_rect);
  6485. /* make the mouse cursor invisible, this will stack with sapp_show_mouse() */
  6486. ShowCursor(FALSE);
  6487. /* enable raw input for mouse, starts sending WM_INPUT messages to WinProc (see GLFW) */
  6488. const RAWINPUTDEVICE rid = {
  6489. 0x01, // usUsagePage: HID_USAGE_PAGE_GENERIC
  6490. 0x02, // usUsage: HID_USAGE_GENERIC_MOUSE
  6491. 0, // dwFlags
  6492. _sapp.win32.hwnd // hwndTarget
  6493. };
  6494. if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
  6495. _SAPP_ERROR(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_LOCK);
  6496. }
  6497. /* in case the raw mouse device only supports absolute position reporting,
  6498. we need to skip the dx/dy compution for the first WM_INPUT event
  6499. */
  6500. _sapp.win32.raw_input_mousepos_valid = false;
  6501. }
  6502. else {
  6503. /* disable raw input for mouse */
  6504. const RAWINPUTDEVICE rid = { 0x01, 0x02, RIDEV_REMOVE, NULL };
  6505. if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
  6506. _SAPP_ERROR(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_UNLOCK);
  6507. }
  6508. /* let the mouse roam freely again */
  6509. ClipCursor(NULL);
  6510. ShowCursor(TRUE);
  6511. /* restore the 'pre-locked' mouse position */
  6512. BOOL res = SetCursorPos(_sapp.win32.mouse_locked_x, _sapp.win32.mouse_locked_y);
  6513. SOKOL_ASSERT(res); _SOKOL_UNUSED(res);
  6514. }
  6515. }
  6516. _SOKOL_PRIVATE bool _sapp_win32_update_monitor(void) {
  6517. const HMONITOR cur_monitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONULL);
  6518. if (cur_monitor != _sapp.win32.hmonitor) {
  6519. _sapp.win32.hmonitor = cur_monitor;
  6520. return true;
  6521. }
  6522. else {
  6523. return false;
  6524. }
  6525. }
  6526. _SOKOL_PRIVATE uint32_t _sapp_win32_mods(void) {
  6527. uint32_t mods = 0;
  6528. if (GetKeyState(VK_SHIFT) & (1<<15)) {
  6529. mods |= SAPP_MODIFIER_SHIFT;
  6530. }
  6531. if (GetKeyState(VK_CONTROL) & (1<<15)) {
  6532. mods |= SAPP_MODIFIER_CTRL;
  6533. }
  6534. if (GetKeyState(VK_MENU) & (1<<15)) {
  6535. mods |= SAPP_MODIFIER_ALT;
  6536. }
  6537. if ((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & (1<<15)) {
  6538. mods |= SAPP_MODIFIER_SUPER;
  6539. }
  6540. const bool swapped = (TRUE == GetSystemMetrics(SM_SWAPBUTTON));
  6541. if (GetAsyncKeyState(VK_LBUTTON)) {
  6542. mods |= swapped ? SAPP_MODIFIER_RMB : SAPP_MODIFIER_LMB;
  6543. }
  6544. if (GetAsyncKeyState(VK_RBUTTON)) {
  6545. mods |= swapped ? SAPP_MODIFIER_LMB : SAPP_MODIFIER_RMB;
  6546. }
  6547. if (GetAsyncKeyState(VK_MBUTTON)) {
  6548. mods |= SAPP_MODIFIER_MMB;
  6549. }
  6550. return mods;
  6551. }
  6552. _SOKOL_PRIVATE void _sapp_win32_mouse_update(LPARAM lParam) {
  6553. if (!_sapp.mouse.locked) {
  6554. const float new_x = (float)GET_X_LPARAM(lParam) * _sapp.win32.dpi.mouse_scale;
  6555. const float new_y = (float)GET_Y_LPARAM(lParam) * _sapp.win32.dpi.mouse_scale;
  6556. if (_sapp.mouse.pos_valid) {
  6557. // don't update dx/dy in the very first event
  6558. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  6559. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  6560. }
  6561. _sapp.mouse.x = new_x;
  6562. _sapp.mouse.y = new_y;
  6563. _sapp.mouse.pos_valid = true;
  6564. }
  6565. }
  6566. _SOKOL_PRIVATE void _sapp_win32_mouse_event(sapp_event_type type, sapp_mousebutton btn) {
  6567. if (_sapp_events_enabled()) {
  6568. _sapp_init_event(type);
  6569. _sapp.event.modifiers = _sapp_win32_mods();
  6570. _sapp.event.mouse_button = btn;
  6571. _sapp_call_event(&_sapp.event);
  6572. }
  6573. }
  6574. _SOKOL_PRIVATE void _sapp_win32_scroll_event(float x, float y) {
  6575. if (_sapp_events_enabled()) {
  6576. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  6577. _sapp.event.modifiers = _sapp_win32_mods();
  6578. _sapp.event.scroll_x = -x / 30.0f;
  6579. _sapp.event.scroll_y = y / 30.0f;
  6580. _sapp_call_event(&_sapp.event);
  6581. }
  6582. }
  6583. _SOKOL_PRIVATE void _sapp_win32_key_event(sapp_event_type type, int vk, bool repeat) {
  6584. if (_sapp_events_enabled() && (vk < SAPP_MAX_KEYCODES)) {
  6585. _sapp_init_event(type);
  6586. _sapp.event.modifiers = _sapp_win32_mods();
  6587. _sapp.event.key_code = _sapp.keycodes[vk];
  6588. _sapp.event.key_repeat = repeat;
  6589. _sapp_call_event(&_sapp.event);
  6590. /* check if a CLIPBOARD_PASTED event must be sent too */
  6591. if (_sapp.clipboard.enabled &&
  6592. (type == SAPP_EVENTTYPE_KEY_DOWN) &&
  6593. (_sapp.event.modifiers == SAPP_MODIFIER_CTRL) &&
  6594. (_sapp.event.key_code == SAPP_KEYCODE_V))
  6595. {
  6596. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  6597. _sapp_call_event(&_sapp.event);
  6598. }
  6599. }
  6600. }
  6601. _SOKOL_PRIVATE void _sapp_win32_char_event(uint32_t c, bool repeat) {
  6602. if (_sapp_events_enabled() && (c >= 32)) {
  6603. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  6604. _sapp.event.modifiers = _sapp_win32_mods();
  6605. _sapp.event.char_code = c;
  6606. _sapp.event.key_repeat = repeat;
  6607. _sapp_call_event(&_sapp.event);
  6608. }
  6609. }
  6610. _SOKOL_PRIVATE void _sapp_win32_dpi_changed(HWND hWnd, LPRECT proposed_win_rect) {
  6611. /* called on WM_DPICHANGED, which will only be sent to the application
  6612. if sapp_desc.high_dpi is true and the Windows version is recent enough
  6613. to support DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  6614. */
  6615. SOKOL_ASSERT(_sapp.desc.high_dpi);
  6616. HINSTANCE user32 = LoadLibraryA("user32.dll");
  6617. if (!user32) {
  6618. return;
  6619. }
  6620. typedef UINT(WINAPI * GETDPIFORWINDOW_T)(HWND hwnd);
  6621. GETDPIFORWINDOW_T fn_getdpiforwindow = (GETDPIFORWINDOW_T)(void*)GetProcAddress(user32, "GetDpiForWindow");
  6622. if (fn_getdpiforwindow) {
  6623. UINT dpix = fn_getdpiforwindow(_sapp.win32.hwnd);
  6624. // NOTE: for high-dpi apps, mouse_scale remains one
  6625. _sapp.win32.dpi.window_scale = (float)dpix / 96.0f;
  6626. _sapp.win32.dpi.content_scale = _sapp.win32.dpi.window_scale;
  6627. _sapp.dpi_scale = _sapp.win32.dpi.window_scale;
  6628. SetWindowPos(hWnd, 0,
  6629. proposed_win_rect->left,
  6630. proposed_win_rect->top,
  6631. proposed_win_rect->right - proposed_win_rect->left,
  6632. proposed_win_rect->bottom - proposed_win_rect->top,
  6633. SWP_NOZORDER | SWP_NOACTIVATE);
  6634. }
  6635. FreeLibrary(user32);
  6636. }
  6637. _SOKOL_PRIVATE void _sapp_win32_files_dropped(HDROP hdrop) {
  6638. if (!_sapp.drop.enabled) {
  6639. return;
  6640. }
  6641. _sapp_clear_drop_buffer();
  6642. bool drop_failed = false;
  6643. const int count = (int) DragQueryFileW(hdrop, 0xffffffff, NULL, 0);
  6644. _sapp.drop.num_files = (count > _sapp.drop.max_files) ? _sapp.drop.max_files : count;
  6645. for (UINT i = 0; i < (UINT)_sapp.drop.num_files; i++) {
  6646. const UINT num_chars = DragQueryFileW(hdrop, i, NULL, 0) + 1;
  6647. WCHAR* buffer = (WCHAR*) _sapp_malloc_clear(num_chars * sizeof(WCHAR));
  6648. DragQueryFileW(hdrop, i, buffer, num_chars);
  6649. if (!_sapp_win32_wide_to_utf8(buffer, _sapp_dropped_file_path_ptr((int)i), _sapp.drop.max_path_length)) {
  6650. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  6651. drop_failed = true;
  6652. }
  6653. _sapp_free(buffer);
  6654. }
  6655. DragFinish(hdrop);
  6656. if (!drop_failed) {
  6657. if (_sapp_events_enabled()) {
  6658. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  6659. _sapp.event.modifiers = _sapp_win32_mods();
  6660. _sapp_call_event(&_sapp.event);
  6661. }
  6662. }
  6663. else {
  6664. _sapp_clear_drop_buffer();
  6665. _sapp.drop.num_files = 0;
  6666. }
  6667. }
  6668. _SOKOL_PRIVATE void _sapp_win32_timing_measure(void) {
  6669. #if defined(SOKOL_D3D11)
  6670. // on D3D11, use the more precise DXGI timestamp
  6671. if (_sapp.d3d11.use_dxgi_frame_stats) {
  6672. DXGI_FRAME_STATISTICS dxgi_stats;
  6673. _sapp_clear(&dxgi_stats, sizeof(dxgi_stats));
  6674. HRESULT hr = _sapp_dxgi_GetFrameStatistics(_sapp.d3d11.swap_chain, &dxgi_stats);
  6675. if (SUCCEEDED(hr)) {
  6676. if (dxgi_stats.SyncRefreshCount != _sapp.d3d11.sync_refresh_count) {
  6677. if ((_sapp.d3d11.sync_refresh_count + 1) != dxgi_stats.SyncRefreshCount) {
  6678. _sapp_timing_discontinuity(&_sapp.timing);
  6679. }
  6680. _sapp.d3d11.sync_refresh_count = dxgi_stats.SyncRefreshCount;
  6681. LARGE_INTEGER qpc = dxgi_stats.SyncQPCTime;
  6682. const uint64_t now = (uint64_t)_sapp_int64_muldiv(qpc.QuadPart - _sapp.timing.timestamp.win.start.QuadPart, 1000000000, _sapp.timing.timestamp.win.freq.QuadPart);
  6683. _sapp_timing_external(&_sapp.timing, (double)now / 1000000000.0);
  6684. }
  6685. return;
  6686. }
  6687. }
  6688. // fallback if swap model isn't "flip-discard" or GetFrameStatistics failed for another reason
  6689. _sapp_timing_measure(&_sapp.timing);
  6690. #endif
  6691. #if defined(SOKOL_GLCORE)
  6692. _sapp_timing_measure(&_sapp.timing);
  6693. #endif
  6694. #if defined(SOKOL_NOAPI)
  6695. _sapp_timing_measure(&_sapp.timing);
  6696. #endif
  6697. }
  6698. _SOKOL_PRIVATE LRESULT CALLBACK _sapp_win32_wndproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  6699. if (!_sapp.win32.in_create_window) {
  6700. switch (uMsg) {
  6701. case WM_CLOSE:
  6702. /* only give user a chance to intervene when sapp_quit() wasn't already called */
  6703. if (!_sapp.quit_ordered) {
  6704. /* if window should be closed and event handling is enabled, give user code
  6705. a change to intervene via sapp_cancel_quit()
  6706. */
  6707. _sapp.quit_requested = true;
  6708. _sapp_win32_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  6709. /* if user code hasn't intervened, quit the app */
  6710. if (_sapp.quit_requested) {
  6711. _sapp.quit_ordered = true;
  6712. }
  6713. }
  6714. if (_sapp.quit_ordered) {
  6715. PostQuitMessage(0);
  6716. }
  6717. return 0;
  6718. case WM_SYSCOMMAND:
  6719. switch (wParam & 0xFFF0) {
  6720. case SC_SCREENSAVE:
  6721. case SC_MONITORPOWER:
  6722. if (_sapp.fullscreen) {
  6723. /* disable screen saver and blanking in fullscreen mode */
  6724. return 0;
  6725. }
  6726. break;
  6727. case SC_KEYMENU:
  6728. /* user trying to access menu via ALT */
  6729. return 0;
  6730. }
  6731. break;
  6732. case WM_ERASEBKGND:
  6733. return 1;
  6734. case WM_SIZE:
  6735. {
  6736. const bool iconified = wParam == SIZE_MINIMIZED;
  6737. if (iconified != _sapp.win32.iconified) {
  6738. _sapp.win32.iconified = iconified;
  6739. if (iconified) {
  6740. _sapp_win32_app_event(SAPP_EVENTTYPE_ICONIFIED);
  6741. }
  6742. else {
  6743. _sapp_win32_app_event(SAPP_EVENTTYPE_RESTORED);
  6744. }
  6745. }
  6746. }
  6747. break;
  6748. case WM_SETFOCUS:
  6749. _sapp_win32_app_event(SAPP_EVENTTYPE_FOCUSED);
  6750. break;
  6751. case WM_KILLFOCUS:
  6752. /* if focus is lost for any reason, and we're in mouse locked mode, disable mouse lock */
  6753. if (_sapp.mouse.locked) {
  6754. _sapp_win32_lock_mouse(false);
  6755. }
  6756. _sapp_win32_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  6757. break;
  6758. case WM_SETCURSOR:
  6759. if (LOWORD(lParam) == HTCLIENT) {
  6760. _sapp_win32_update_cursor(_sapp.mouse.current_cursor, _sapp.mouse.shown, true);
  6761. return TRUE;
  6762. }
  6763. break;
  6764. case WM_DPICHANGED:
  6765. {
  6766. /* Update window's DPI and size if its moved to another monitor with a different DPI
  6767. Only sent if DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is used.
  6768. */
  6769. _sapp_win32_dpi_changed(hWnd, (LPRECT)lParam);
  6770. break;
  6771. }
  6772. case WM_LBUTTONDOWN:
  6773. _sapp_win32_mouse_update(lParam);
  6774. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_LEFT);
  6775. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_LEFT);
  6776. break;
  6777. case WM_RBUTTONDOWN:
  6778. _sapp_win32_mouse_update(lParam);
  6779. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_RIGHT);
  6780. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_RIGHT);
  6781. break;
  6782. case WM_MBUTTONDOWN:
  6783. _sapp_win32_mouse_update(lParam);
  6784. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_MIDDLE);
  6785. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_MIDDLE);
  6786. break;
  6787. case WM_LBUTTONUP:
  6788. _sapp_win32_mouse_update(lParam);
  6789. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_LEFT);
  6790. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_LEFT);
  6791. break;
  6792. case WM_RBUTTONUP:
  6793. _sapp_win32_mouse_update(lParam);
  6794. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_RIGHT);
  6795. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_RIGHT);
  6796. break;
  6797. case WM_MBUTTONUP:
  6798. _sapp_win32_mouse_update(lParam);
  6799. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_MIDDLE);
  6800. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_MIDDLE);
  6801. break;
  6802. case WM_MOUSEMOVE:
  6803. if (!_sapp.mouse.locked) {
  6804. _sapp_win32_mouse_update(lParam);
  6805. if (!_sapp.win32.mouse_tracked) {
  6806. _sapp.win32.mouse_tracked = true;
  6807. TRACKMOUSEEVENT tme;
  6808. _sapp_clear(&tme, sizeof(tme));
  6809. tme.cbSize = sizeof(tme);
  6810. tme.dwFlags = TME_LEAVE;
  6811. tme.hwndTrack = _sapp.win32.hwnd;
  6812. TrackMouseEvent(&tme);
  6813. _sapp.mouse.dx = 0.0f;
  6814. _sapp.mouse.dy = 0.0f;
  6815. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID);
  6816. }
  6817. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID);
  6818. }
  6819. break;
  6820. case WM_INPUT:
  6821. /* raw mouse input during mouse-lock */
  6822. if (_sapp.mouse.locked) {
  6823. HRAWINPUT ri = (HRAWINPUT) lParam;
  6824. UINT size = sizeof(_sapp.win32.raw_input_data);
  6825. // see: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getrawinputdata
  6826. if ((UINT)-1 == GetRawInputData(ri, RID_INPUT, &_sapp.win32.raw_input_data, &size, sizeof(RAWINPUTHEADER))) {
  6827. _SAPP_ERROR(WIN32_GET_RAW_INPUT_DATA_FAILED);
  6828. break;
  6829. }
  6830. const RAWINPUT* raw_mouse_data = (const RAWINPUT*) &_sapp.win32.raw_input_data;
  6831. if (raw_mouse_data->data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE) {
  6832. /* mouse only reports absolute position
  6833. NOTE: This code is untested and will most likely behave wrong in Remote Desktop sessions.
  6834. (such remote desktop sessions are setting the MOUSE_MOVE_ABSOLUTE flag).
  6835. See: https://github.com/floooh/sokol/issues/806 and
  6836. https://github.com/microsoft/DirectXTK/commit/ef56b63f3739381e451f7a5a5bd2c9779d2a7555)
  6837. */
  6838. LONG new_x = raw_mouse_data->data.mouse.lLastX;
  6839. LONG new_y = raw_mouse_data->data.mouse.lLastY;
  6840. if (_sapp.win32.raw_input_mousepos_valid) {
  6841. _sapp.mouse.dx = (float) (new_x - _sapp.win32.raw_input_mousepos_x);
  6842. _sapp.mouse.dy = (float) (new_y - _sapp.win32.raw_input_mousepos_y);
  6843. }
  6844. _sapp.win32.raw_input_mousepos_x = new_x;
  6845. _sapp.win32.raw_input_mousepos_y = new_y;
  6846. _sapp.win32.raw_input_mousepos_valid = true;
  6847. }
  6848. else {
  6849. /* mouse reports movement delta (this seems to be the common case) */
  6850. _sapp.mouse.dx = (float) raw_mouse_data->data.mouse.lLastX;
  6851. _sapp.mouse.dy = (float) raw_mouse_data->data.mouse.lLastY;
  6852. }
  6853. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID);
  6854. }
  6855. break;
  6856. case WM_MOUSELEAVE:
  6857. if (!_sapp.mouse.locked) {
  6858. _sapp.mouse.dx = 0.0f;
  6859. _sapp.mouse.dy = 0.0f;
  6860. _sapp.win32.mouse_tracked = false;
  6861. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID);
  6862. }
  6863. break;
  6864. case WM_MOUSEWHEEL:
  6865. _sapp_win32_scroll_event(0.0f, (float)((SHORT)HIWORD(wParam)));
  6866. break;
  6867. case WM_MOUSEHWHEEL:
  6868. _sapp_win32_scroll_event((float)((SHORT)HIWORD(wParam)), 0.0f);
  6869. break;
  6870. case WM_CHAR:
  6871. _sapp_win32_char_event((uint32_t)wParam, !!(lParam&0x40000000));
  6872. break;
  6873. case WM_KEYDOWN:
  6874. case WM_SYSKEYDOWN:
  6875. _sapp_win32_key_event(SAPP_EVENTTYPE_KEY_DOWN, (int)(HIWORD(lParam)&0x1FF), !!(lParam&0x40000000));
  6876. break;
  6877. case WM_KEYUP:
  6878. case WM_SYSKEYUP:
  6879. _sapp_win32_key_event(SAPP_EVENTTYPE_KEY_UP, (int)(HIWORD(lParam)&0x1FF), false);
  6880. break;
  6881. case WM_ENTERSIZEMOVE:
  6882. SetTimer(_sapp.win32.hwnd, 1, USER_TIMER_MINIMUM, NULL);
  6883. break;
  6884. case WM_EXITSIZEMOVE:
  6885. KillTimer(_sapp.win32.hwnd, 1);
  6886. break;
  6887. case WM_TIMER:
  6888. _sapp_win32_timing_measure();
  6889. _sapp_frame();
  6890. #if defined(SOKOL_D3D11)
  6891. // present with DXGI_PRESENT_DO_NOT_WAIT
  6892. _sapp_d3d11_present(true);
  6893. #endif
  6894. #if defined(SOKOL_GLCORE)
  6895. _sapp_wgl_swap_buffers();
  6896. #endif
  6897. /* NOTE: resizing the swap-chain during resize leads to a substantial
  6898. memory spike (hundreds of megabytes for a few seconds).
  6899. if (_sapp_win32_update_dimensions()) {
  6900. #if defined(SOKOL_D3D11)
  6901. _sapp_d3d11_resize_default_render_target();
  6902. #endif
  6903. _sapp_win32_app_event(SAPP_EVENTTYPE_RESIZED);
  6904. }
  6905. */
  6906. break;
  6907. case WM_NCLBUTTONDOWN:
  6908. /* workaround for half-second pause when starting to move window
  6909. see: https://gamedev.net/forums/topic/672094-keeping-things-moving-during-win32-moveresize-events/5254386/
  6910. */
  6911. if (SendMessage(_sapp.win32.hwnd, WM_NCHITTEST, wParam, lParam) == HTCAPTION) {
  6912. POINT point;
  6913. GetCursorPos(&point);
  6914. ScreenToClient(_sapp.win32.hwnd, &point);
  6915. PostMessage(_sapp.win32.hwnd, WM_MOUSEMOVE, 0, ((uint32_t)point.x)|(((uint32_t)point.y) << 16));
  6916. }
  6917. break;
  6918. case WM_DROPFILES:
  6919. _sapp_win32_files_dropped((HDROP)wParam);
  6920. break;
  6921. case WM_DISPLAYCHANGE:
  6922. // refresh rate might have changed
  6923. _sapp_timing_reset(&_sapp.timing);
  6924. break;
  6925. default:
  6926. break;
  6927. }
  6928. }
  6929. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  6930. }
  6931. _SOKOL_PRIVATE void _sapp_win32_create_window(void) {
  6932. WNDCLASSW wndclassw;
  6933. _sapp_clear(&wndclassw, sizeof(wndclassw));
  6934. wndclassw.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  6935. wndclassw.lpfnWndProc = (WNDPROC) _sapp_win32_wndproc;
  6936. wndclassw.hInstance = GetModuleHandleW(NULL);
  6937. wndclassw.hCursor = LoadCursor(NULL, IDC_ARROW);
  6938. wndclassw.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  6939. wndclassw.lpszClassName = L"SOKOLAPP";
  6940. RegisterClassW(&wndclassw);
  6941. /* NOTE: regardless whether fullscreen is requested or not, a regular
  6942. windowed-mode window will always be created first (however in hidden
  6943. mode, so that no windowed-mode window pops up before the fullscreen window)
  6944. */
  6945. const DWORD win_ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  6946. RECT rect = { 0, 0, 0, 0 };
  6947. DWORD win_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
  6948. rect.right = (int) ((float)_sapp.window_width * _sapp.win32.dpi.window_scale);
  6949. rect.bottom = (int) ((float)_sapp.window_height * _sapp.win32.dpi.window_scale);
  6950. const bool use_default_width = 0 == _sapp.window_width;
  6951. const bool use_default_height = 0 == _sapp.window_height;
  6952. AdjustWindowRectEx(&rect, win_style, FALSE, win_ex_style);
  6953. const int win_width = rect.right - rect.left;
  6954. const int win_height = rect.bottom - rect.top;
  6955. _sapp.win32.in_create_window = true;
  6956. _sapp.win32.hwnd = CreateWindowExW(
  6957. win_ex_style, // dwExStyle
  6958. L"SOKOLAPP", // lpClassName
  6959. _sapp.window_title_wide, // lpWindowName
  6960. win_style, // dwStyle
  6961. CW_USEDEFAULT, // X
  6962. SW_HIDE, // Y (NOTE: CW_USEDEFAULT is not used for position here, but internally calls ShowWindow!
  6963. use_default_width ? CW_USEDEFAULT : win_width, // nWidth
  6964. use_default_height ? CW_USEDEFAULT : win_height, // nHeight (NOTE: if width is CW_USEDEFAULT, height is actually ignored)
  6965. NULL, // hWndParent
  6966. NULL, // hMenu
  6967. GetModuleHandle(NULL), // hInstance
  6968. NULL); // lParam
  6969. _sapp.win32.in_create_window = false;
  6970. _sapp.win32.dc = GetDC(_sapp.win32.hwnd);
  6971. _sapp.win32.hmonitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONULL);
  6972. SOKOL_ASSERT(_sapp.win32.dc);
  6973. /* this will get the actual windowed-mode window size, if fullscreen
  6974. is requested, the set_fullscreen function will then capture the
  6975. current window rectangle, which then might be used later to
  6976. restore the window position when switching back to windowed
  6977. */
  6978. _sapp_win32_update_dimensions();
  6979. if (_sapp.fullscreen) {
  6980. _sapp_win32_set_fullscreen(_sapp.fullscreen, SWP_HIDEWINDOW);
  6981. _sapp_win32_update_dimensions();
  6982. }
  6983. ShowWindow(_sapp.win32.hwnd, SW_SHOW);
  6984. DragAcceptFiles(_sapp.win32.hwnd, 1);
  6985. }
  6986. _SOKOL_PRIVATE void _sapp_win32_destroy_window(void) {
  6987. DestroyWindow(_sapp.win32.hwnd); _sapp.win32.hwnd = 0;
  6988. UnregisterClassW(L"SOKOLAPP", GetModuleHandleW(NULL));
  6989. }
  6990. _SOKOL_PRIVATE void _sapp_win32_destroy_icons(void) {
  6991. if (_sapp.win32.big_icon) {
  6992. DestroyIcon(_sapp.win32.big_icon);
  6993. _sapp.win32.big_icon = 0;
  6994. }
  6995. if (_sapp.win32.small_icon) {
  6996. DestroyIcon(_sapp.win32.small_icon);
  6997. _sapp.win32.small_icon = 0;
  6998. }
  6999. }
  7000. _SOKOL_PRIVATE void _sapp_win32_init_console(void) {
  7001. if (_sapp.desc.win32_console_create || _sapp.desc.win32_console_attach) {
  7002. BOOL con_valid = FALSE;
  7003. if (_sapp.desc.win32_console_create) {
  7004. con_valid = AllocConsole();
  7005. }
  7006. else if (_sapp.desc.win32_console_attach) {
  7007. con_valid = AttachConsole(ATTACH_PARENT_PROCESS);
  7008. }
  7009. if (con_valid) {
  7010. FILE* res_fp = 0;
  7011. errno_t err;
  7012. err = freopen_s(&res_fp, "CON", "w", stdout);
  7013. (void)err;
  7014. err = freopen_s(&res_fp, "CON", "w", stderr);
  7015. (void)err;
  7016. }
  7017. }
  7018. if (_sapp.desc.win32_console_utf8) {
  7019. _sapp.win32.orig_codepage = GetConsoleOutputCP();
  7020. SetConsoleOutputCP(CP_UTF8);
  7021. }
  7022. }
  7023. _SOKOL_PRIVATE void _sapp_win32_restore_console(void) {
  7024. if (_sapp.desc.win32_console_utf8) {
  7025. SetConsoleOutputCP(_sapp.win32.orig_codepage);
  7026. }
  7027. }
  7028. _SOKOL_PRIVATE void _sapp_win32_init_dpi(void) {
  7029. DECLARE_HANDLE(DPI_AWARENESS_CONTEXT_T);
  7030. typedef BOOL(WINAPI * SETPROCESSDPIAWARE_T)(void);
  7031. typedef bool (WINAPI * SETPROCESSDPIAWARENESSCONTEXT_T)(DPI_AWARENESS_CONTEXT_T); // since Windows 10, version 1703
  7032. typedef HRESULT(WINAPI * SETPROCESSDPIAWARENESS_T)(PROCESS_DPI_AWARENESS);
  7033. typedef HRESULT(WINAPI * GETDPIFORMONITOR_T)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*);
  7034. SETPROCESSDPIAWARE_T fn_setprocessdpiaware = 0;
  7035. SETPROCESSDPIAWARENESS_T fn_setprocessdpiawareness = 0;
  7036. GETDPIFORMONITOR_T fn_getdpiformonitor = 0;
  7037. SETPROCESSDPIAWARENESSCONTEXT_T fn_setprocessdpiawarenesscontext =0;
  7038. HINSTANCE user32 = LoadLibraryA("user32.dll");
  7039. if (user32) {
  7040. fn_setprocessdpiaware = (SETPROCESSDPIAWARE_T)(void*) GetProcAddress(user32, "SetProcessDPIAware");
  7041. fn_setprocessdpiawarenesscontext = (SETPROCESSDPIAWARENESSCONTEXT_T)(void*) GetProcAddress(user32, "SetProcessDpiAwarenessContext");
  7042. }
  7043. HINSTANCE shcore = LoadLibraryA("shcore.dll");
  7044. if (shcore) {
  7045. fn_setprocessdpiawareness = (SETPROCESSDPIAWARENESS_T)(void*) GetProcAddress(shcore, "SetProcessDpiAwareness");
  7046. fn_getdpiformonitor = (GETDPIFORMONITOR_T)(void*) GetProcAddress(shcore, "GetDpiForMonitor");
  7047. }
  7048. /*
  7049. NOTE on SetProcessDpiAware() vs SetProcessDpiAwareness() vs SetProcessDpiAwarenessContext():
  7050. These are different attempts to get DPI handling on Windows right, from oldest
  7051. to newest. SetProcessDpiAwarenessContext() is required for the new
  7052. DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 method.
  7053. */
  7054. if (fn_setprocessdpiawareness) {
  7055. if (_sapp.desc.high_dpi) {
  7056. /* app requests HighDPI rendering, first try the Win10 Creator Update per-monitor-dpi awareness,
  7057. if that fails, fall back to system-dpi-awareness
  7058. */
  7059. _sapp.win32.dpi.aware = true;
  7060. DPI_AWARENESS_CONTEXT_T per_monitor_aware_v2 = (DPI_AWARENESS_CONTEXT_T)-4;
  7061. if (!(fn_setprocessdpiawarenesscontext && fn_setprocessdpiawarenesscontext(per_monitor_aware_v2))) {
  7062. // fallback to system-dpi-aware
  7063. fn_setprocessdpiawareness(PROCESS_SYSTEM_DPI_AWARE);
  7064. }
  7065. }
  7066. else {
  7067. /* if the app didn't request HighDPI rendering, let Windows do the upscaling */
  7068. _sapp.win32.dpi.aware = false;
  7069. fn_setprocessdpiawareness(PROCESS_DPI_UNAWARE);
  7070. }
  7071. }
  7072. else if (fn_setprocessdpiaware) {
  7073. // fallback for Windows 7
  7074. _sapp.win32.dpi.aware = true;
  7075. fn_setprocessdpiaware();
  7076. }
  7077. /* get dpi scale factor for main monitor */
  7078. if (fn_getdpiformonitor && _sapp.win32.dpi.aware) {
  7079. POINT pt = { 1, 1 };
  7080. HMONITOR hm = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
  7081. UINT dpix, dpiy;
  7082. HRESULT hr = fn_getdpiformonitor(hm, MDT_EFFECTIVE_DPI, &dpix, &dpiy);
  7083. _SOKOL_UNUSED(hr);
  7084. SOKOL_ASSERT(SUCCEEDED(hr));
  7085. /* clamp window scale to an integer factor */
  7086. _sapp.win32.dpi.window_scale = (float)dpix / 96.0f;
  7087. }
  7088. else {
  7089. _sapp.win32.dpi.window_scale = 1.0f;
  7090. }
  7091. if (_sapp.desc.high_dpi) {
  7092. _sapp.win32.dpi.content_scale = _sapp.win32.dpi.window_scale;
  7093. _sapp.win32.dpi.mouse_scale = 1.0f;
  7094. }
  7095. else {
  7096. _sapp.win32.dpi.content_scale = 1.0f;
  7097. _sapp.win32.dpi.mouse_scale = 1.0f / _sapp.win32.dpi.window_scale;
  7098. }
  7099. _sapp.dpi_scale = _sapp.win32.dpi.content_scale;
  7100. if (user32) {
  7101. FreeLibrary(user32);
  7102. }
  7103. if (shcore) {
  7104. FreeLibrary(shcore);
  7105. }
  7106. }
  7107. _SOKOL_PRIVATE bool _sapp_win32_set_clipboard_string(const char* str) {
  7108. SOKOL_ASSERT(str);
  7109. SOKOL_ASSERT(_sapp.win32.hwnd);
  7110. SOKOL_ASSERT(_sapp.clipboard.enabled && (_sapp.clipboard.buf_size > 0));
  7111. if (!OpenClipboard(_sapp.win32.hwnd)) {
  7112. return false;
  7113. }
  7114. HANDLE object = 0;
  7115. wchar_t* wchar_buf = 0;
  7116. const SIZE_T wchar_buf_size = (SIZE_T)_sapp.clipboard.buf_size * sizeof(wchar_t);
  7117. object = GlobalAlloc(GMEM_MOVEABLE, wchar_buf_size);
  7118. if (NULL == object) {
  7119. goto error;
  7120. }
  7121. wchar_buf = (wchar_t*) GlobalLock(object);
  7122. if (NULL == wchar_buf) {
  7123. goto error;
  7124. }
  7125. if (!_sapp_win32_utf8_to_wide(str, wchar_buf, (int)wchar_buf_size)) {
  7126. goto error;
  7127. }
  7128. GlobalUnlock(object);
  7129. wchar_buf = 0;
  7130. EmptyClipboard();
  7131. // NOTE: when successful, SetClipboardData() takes ownership of memory object!
  7132. if (NULL == SetClipboardData(CF_UNICODETEXT, object)) {
  7133. goto error;
  7134. }
  7135. CloseClipboard();
  7136. return true;
  7137. error:
  7138. if (wchar_buf) {
  7139. GlobalUnlock(object);
  7140. }
  7141. if (object) {
  7142. GlobalFree(object);
  7143. }
  7144. CloseClipboard();
  7145. return false;
  7146. }
  7147. _SOKOL_PRIVATE const char* _sapp_win32_get_clipboard_string(void) {
  7148. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  7149. SOKOL_ASSERT(_sapp.win32.hwnd);
  7150. if (!OpenClipboard(_sapp.win32.hwnd)) {
  7151. /* silently ignore any errors and just return the current
  7152. content of the local clipboard buffer
  7153. */
  7154. return _sapp.clipboard.buffer;
  7155. }
  7156. HANDLE object = GetClipboardData(CF_UNICODETEXT);
  7157. if (!object) {
  7158. CloseClipboard();
  7159. return _sapp.clipboard.buffer;
  7160. }
  7161. const wchar_t* wchar_buf = (const wchar_t*) GlobalLock(object);
  7162. if (!wchar_buf) {
  7163. CloseClipboard();
  7164. return _sapp.clipboard.buffer;
  7165. }
  7166. if (!_sapp_win32_wide_to_utf8(wchar_buf, _sapp.clipboard.buffer, _sapp.clipboard.buf_size)) {
  7167. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  7168. }
  7169. GlobalUnlock(object);
  7170. CloseClipboard();
  7171. return _sapp.clipboard.buffer;
  7172. }
  7173. _SOKOL_PRIVATE void _sapp_win32_update_window_title(void) {
  7174. _sapp_win32_utf8_to_wide(_sapp.window_title, _sapp.window_title_wide, sizeof(_sapp.window_title_wide));
  7175. SetWindowTextW(_sapp.win32.hwnd, _sapp.window_title_wide);
  7176. }
  7177. _SOKOL_PRIVATE HICON _sapp_win32_create_icon_from_image(const sapp_image_desc* desc) {
  7178. BITMAPV5HEADER bi;
  7179. _sapp_clear(&bi, sizeof(bi));
  7180. bi.bV5Size = sizeof(bi);
  7181. bi.bV5Width = desc->width;
  7182. bi.bV5Height = -desc->height; // NOTE the '-' here to indicate that origin is top-left
  7183. bi.bV5Planes = 1;
  7184. bi.bV5BitCount = 32;
  7185. bi.bV5Compression = BI_BITFIELDS;
  7186. bi.bV5RedMask = 0x00FF0000;
  7187. bi.bV5GreenMask = 0x0000FF00;
  7188. bi.bV5BlueMask = 0x000000FF;
  7189. bi.bV5AlphaMask = 0xFF000000;
  7190. uint8_t* target = 0;
  7191. const uint8_t* source = (const uint8_t*)desc->pixels.ptr;
  7192. HDC dc = GetDC(NULL);
  7193. HBITMAP color = CreateDIBSection(dc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (void**)&target, NULL, (DWORD)0);
  7194. ReleaseDC(NULL, dc);
  7195. if (0 == color) {
  7196. return NULL;
  7197. }
  7198. SOKOL_ASSERT(target);
  7199. HBITMAP mask = CreateBitmap(desc->width, desc->height, 1, 1, NULL);
  7200. if (0 == mask) {
  7201. DeleteObject(color);
  7202. return NULL;
  7203. }
  7204. for (int i = 0; i < (desc->width*desc->height); i++) {
  7205. target[0] = source[2];
  7206. target[1] = source[1];
  7207. target[2] = source[0];
  7208. target[3] = source[3];
  7209. target += 4;
  7210. source += 4;
  7211. }
  7212. ICONINFO icon_info;
  7213. _sapp_clear(&icon_info, sizeof(icon_info));
  7214. icon_info.fIcon = true;
  7215. icon_info.xHotspot = 0;
  7216. icon_info.yHotspot = 0;
  7217. icon_info.hbmMask = mask;
  7218. icon_info.hbmColor = color;
  7219. HICON icon_handle = CreateIconIndirect(&icon_info);
  7220. DeleteObject(color);
  7221. DeleteObject(mask);
  7222. return icon_handle;
  7223. }
  7224. _SOKOL_PRIVATE void _sapp_win32_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  7225. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  7226. int big_img_index = _sapp_image_bestmatch(icon_desc->images, num_images, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
  7227. int sml_img_index = _sapp_image_bestmatch(icon_desc->images, num_images, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
  7228. HICON big_icon = _sapp_win32_create_icon_from_image(&icon_desc->images[big_img_index]);
  7229. HICON sml_icon = _sapp_win32_create_icon_from_image(&icon_desc->images[sml_img_index]);
  7230. // if icon creation or lookup has failed for some reason, leave the currently set icon untouched
  7231. if (0 != big_icon) {
  7232. SendMessage(_sapp.win32.hwnd, WM_SETICON, ICON_BIG, (LPARAM) big_icon);
  7233. if (0 != _sapp.win32.big_icon) {
  7234. DestroyIcon(_sapp.win32.big_icon);
  7235. }
  7236. _sapp.win32.big_icon = big_icon;
  7237. }
  7238. if (0 != sml_icon) {
  7239. SendMessage(_sapp.win32.hwnd, WM_SETICON, ICON_SMALL, (LPARAM) sml_icon);
  7240. if (0 != _sapp.win32.small_icon) {
  7241. DestroyIcon(_sapp.win32.small_icon);
  7242. }
  7243. _sapp.win32.small_icon = sml_icon;
  7244. }
  7245. }
  7246. /* don't laugh, but this seems to be the easiest and most robust
  7247. way to check if we're running on Win10
  7248. From: https://github.com/videolan/vlc/blob/232fb13b0d6110c4d1b683cde24cf9a7f2c5c2ea/modules/video_output/win32/d3d11_swapchain.c#L263
  7249. */
  7250. _SOKOL_PRIVATE bool _sapp_win32_is_win10_or_greater(void) {
  7251. HMODULE h = GetModuleHandleW(L"kernel32.dll");
  7252. if (NULL != h) {
  7253. return (NULL != GetProcAddress(h, "GetSystemCpuSetInformation"));
  7254. }
  7255. else {
  7256. return false;
  7257. }
  7258. }
  7259. _SOKOL_PRIVATE void _sapp_win32_run(const sapp_desc* desc) {
  7260. _sapp_init_state(desc);
  7261. _sapp_win32_init_console();
  7262. _sapp.win32.is_win10_or_greater = _sapp_win32_is_win10_or_greater();
  7263. _sapp_win32_init_keytable();
  7264. _sapp_win32_utf8_to_wide(_sapp.window_title, _sapp.window_title_wide, sizeof(_sapp.window_title_wide));
  7265. _sapp_win32_init_dpi();
  7266. _sapp_win32_init_cursors();
  7267. _sapp_win32_create_window();
  7268. sapp_set_icon(&desc->icon);
  7269. #if defined(SOKOL_D3D11)
  7270. _sapp_d3d11_create_device_and_swapchain();
  7271. _sapp_d3d11_create_default_render_target();
  7272. #endif
  7273. #if defined(SOKOL_GLCORE)
  7274. _sapp_wgl_init();
  7275. _sapp_wgl_load_extensions();
  7276. _sapp_wgl_create_context();
  7277. #endif
  7278. _sapp.valid = true;
  7279. bool done = false;
  7280. while (!(done || _sapp.quit_ordered)) {
  7281. _sapp_win32_timing_measure();
  7282. MSG msg;
  7283. while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
  7284. if (WM_QUIT == msg.message) {
  7285. done = true;
  7286. continue;
  7287. }
  7288. else {
  7289. TranslateMessage(&msg);
  7290. DispatchMessageW(&msg);
  7291. }
  7292. }
  7293. _sapp_frame();
  7294. #if defined(SOKOL_D3D11)
  7295. _sapp_d3d11_present(false);
  7296. if (IsIconic(_sapp.win32.hwnd)) {
  7297. Sleep((DWORD)(16 * _sapp.swap_interval));
  7298. }
  7299. #endif
  7300. #if defined(SOKOL_GLCORE)
  7301. _sapp_wgl_swap_buffers();
  7302. #endif
  7303. /* check for window resized, this cannot happen in WM_SIZE as it explodes memory usage */
  7304. if (_sapp_win32_update_dimensions()) {
  7305. #if defined(SOKOL_D3D11)
  7306. _sapp_d3d11_resize_default_render_target();
  7307. #endif
  7308. _sapp_win32_app_event(SAPP_EVENTTYPE_RESIZED);
  7309. }
  7310. /* check if the window monitor has changed, need to reset timing because
  7311. the new monitor might have a different refresh rate
  7312. */
  7313. if (_sapp_win32_update_monitor()) {
  7314. _sapp_timing_reset(&_sapp.timing);
  7315. }
  7316. if (_sapp.quit_requested) {
  7317. PostMessage(_sapp.win32.hwnd, WM_CLOSE, 0, 0);
  7318. }
  7319. }
  7320. _sapp_call_cleanup();
  7321. #if defined(SOKOL_D3D11)
  7322. _sapp_d3d11_destroy_default_render_target();
  7323. _sapp_d3d11_destroy_device_and_swapchain();
  7324. #elif defined(SOKOL_GLCORE)
  7325. _sapp_wgl_destroy_context();
  7326. _sapp_wgl_shutdown();
  7327. #endif
  7328. _sapp_win32_destroy_window();
  7329. _sapp_win32_destroy_icons();
  7330. _sapp_win32_restore_console();
  7331. _sapp_discard_state();
  7332. }
  7333. _SOKOL_PRIVATE char** _sapp_win32_command_line_to_utf8_argv(LPWSTR w_command_line, int* o_argc) {
  7334. int argc = 0;
  7335. char** argv = 0;
  7336. char* args;
  7337. LPWSTR* w_argv = CommandLineToArgvW(w_command_line, &argc);
  7338. if (w_argv == NULL) {
  7339. // FIXME: chicken egg problem, can't report errors before sokol_main() is called!
  7340. } else {
  7341. size_t size = wcslen(w_command_line) * 4;
  7342. argv = (char**) _sapp_malloc_clear(((size_t)argc + 1) * sizeof(char*) + size);
  7343. SOKOL_ASSERT(argv);
  7344. args = (char*) &argv[argc + 1];
  7345. int n;
  7346. for (int i = 0; i < argc; ++i) {
  7347. n = WideCharToMultiByte(CP_UTF8, 0, w_argv[i], -1, args, (int)size, NULL, NULL);
  7348. if (n == 0) {
  7349. // FIXME: chicken egg problem, can't report errors before sokol_main() is called!
  7350. break;
  7351. }
  7352. argv[i] = args;
  7353. size -= (size_t)n;
  7354. args += n;
  7355. }
  7356. LocalFree(w_argv);
  7357. }
  7358. *o_argc = argc;
  7359. return argv;
  7360. }
  7361. #if !defined(SOKOL_NO_ENTRY)
  7362. #if defined(SOKOL_WIN32_FORCE_MAIN)
  7363. int main(int argc, char* argv[]) {
  7364. sapp_desc desc = sokol_main(argc, argv);
  7365. _sapp_win32_run(&desc);
  7366. return 0;
  7367. }
  7368. #else
  7369. int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) {
  7370. _SOKOL_UNUSED(hInstance);
  7371. _SOKOL_UNUSED(hPrevInstance);
  7372. _SOKOL_UNUSED(lpCmdLine);
  7373. _SOKOL_UNUSED(nCmdShow);
  7374. int argc_utf8 = 0;
  7375. char** argv_utf8 = _sapp_win32_command_line_to_utf8_argv(GetCommandLineW(), &argc_utf8);
  7376. sapp_desc desc = sokol_main(argc_utf8, argv_utf8);
  7377. _sapp_win32_run(&desc);
  7378. _sapp_free(argv_utf8);
  7379. return 0;
  7380. }
  7381. #endif /* SOKOL_WIN32_FORCE_MAIN */
  7382. #endif /* SOKOL_NO_ENTRY */
  7383. #ifdef _MSC_VER
  7384. #pragma warning(pop)
  7385. #endif
  7386. #endif /* _SAPP_WIN32 */
  7387. // █████ ███ ██ ██████ ██████ ██████ ██ ██████
  7388. // ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7389. // ███████ ██ ██ ██ ██ ██ ██████ ██ ██ ██ ██ ██
  7390. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7391. // ██ ██ ██ ████ ██████ ██ ██ ██████ ██ ██████
  7392. //
  7393. // >>android
  7394. #if defined(_SAPP_ANDROID)
  7395. /* android loop thread */
  7396. _SOKOL_PRIVATE bool _sapp_android_init_egl(void) {
  7397. SOKOL_ASSERT(_sapp.android.display == EGL_NO_DISPLAY);
  7398. SOKOL_ASSERT(_sapp.android.context == EGL_NO_CONTEXT);
  7399. EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  7400. if (display == EGL_NO_DISPLAY) {
  7401. return false;
  7402. }
  7403. if (eglInitialize(display, NULL, NULL) == EGL_FALSE) {
  7404. return false;
  7405. }
  7406. EGLint alpha_size = _sapp.desc.alpha ? 8 : 0;
  7407. const EGLint cfg_attributes[] = {
  7408. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  7409. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  7410. EGL_RED_SIZE, 8,
  7411. EGL_GREEN_SIZE, 8,
  7412. EGL_BLUE_SIZE, 8,
  7413. EGL_ALPHA_SIZE, alpha_size,
  7414. EGL_DEPTH_SIZE, 16,
  7415. EGL_STENCIL_SIZE, 0,
  7416. EGL_NONE,
  7417. };
  7418. EGLConfig available_cfgs[32];
  7419. EGLint cfg_count;
  7420. eglChooseConfig(display, cfg_attributes, available_cfgs, 32, &cfg_count);
  7421. SOKOL_ASSERT(cfg_count > 0);
  7422. SOKOL_ASSERT(cfg_count <= 32);
  7423. /* find config with 8-bit rgb buffer if available, ndk sample does not trust egl spec */
  7424. EGLConfig config;
  7425. bool exact_cfg_found = false;
  7426. for (int i = 0; i < cfg_count; ++i) {
  7427. EGLConfig c = available_cfgs[i];
  7428. EGLint r, g, b, a, d;
  7429. if (eglGetConfigAttrib(display, c, EGL_RED_SIZE, &r) == EGL_TRUE &&
  7430. eglGetConfigAttrib(display, c, EGL_GREEN_SIZE, &g) == EGL_TRUE &&
  7431. eglGetConfigAttrib(display, c, EGL_BLUE_SIZE, &b) == EGL_TRUE &&
  7432. eglGetConfigAttrib(display, c, EGL_ALPHA_SIZE, &a) == EGL_TRUE &&
  7433. eglGetConfigAttrib(display, c, EGL_DEPTH_SIZE, &d) == EGL_TRUE &&
  7434. r == 8 && g == 8 && b == 8 && (alpha_size == 0 || a == alpha_size) && d == 16) {
  7435. exact_cfg_found = true;
  7436. config = c;
  7437. break;
  7438. }
  7439. }
  7440. if (!exact_cfg_found) {
  7441. config = available_cfgs[0];
  7442. }
  7443. EGLint ctx_attributes[] = {
  7444. EGL_CONTEXT_CLIENT_VERSION, 3,
  7445. EGL_NONE,
  7446. };
  7447. EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, ctx_attributes);
  7448. if (context == EGL_NO_CONTEXT) {
  7449. return false;
  7450. }
  7451. _sapp.android.config = config;
  7452. _sapp.android.display = display;
  7453. _sapp.android.context = context;
  7454. return true;
  7455. }
  7456. _SOKOL_PRIVATE void _sapp_android_cleanup_egl(void) {
  7457. if (_sapp.android.display != EGL_NO_DISPLAY) {
  7458. eglMakeCurrent(_sapp.android.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  7459. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7460. eglDestroySurface(_sapp.android.display, _sapp.android.surface);
  7461. _sapp.android.surface = EGL_NO_SURFACE;
  7462. }
  7463. if (_sapp.android.context != EGL_NO_CONTEXT) {
  7464. eglDestroyContext(_sapp.android.display, _sapp.android.context);
  7465. _sapp.android.context = EGL_NO_CONTEXT;
  7466. }
  7467. eglTerminate(_sapp.android.display);
  7468. _sapp.android.display = EGL_NO_DISPLAY;
  7469. }
  7470. }
  7471. _SOKOL_PRIVATE bool _sapp_android_init_egl_surface(ANativeWindow* window) {
  7472. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7473. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7474. SOKOL_ASSERT(_sapp.android.surface == EGL_NO_SURFACE);
  7475. SOKOL_ASSERT(window);
  7476. /* TODO: set window flags */
  7477. /* ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0); */
  7478. /* create egl surface and make it current */
  7479. EGLSurface surface = eglCreateWindowSurface(_sapp.android.display, _sapp.android.config, window, NULL);
  7480. if (surface == EGL_NO_SURFACE) {
  7481. return false;
  7482. }
  7483. if (eglMakeCurrent(_sapp.android.display, surface, surface, _sapp.android.context) == EGL_FALSE) {
  7484. return false;
  7485. }
  7486. _sapp.android.surface = surface;
  7487. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  7488. return true;
  7489. }
  7490. _SOKOL_PRIVATE void _sapp_android_cleanup_egl_surface(void) {
  7491. if (_sapp.android.display == EGL_NO_DISPLAY) {
  7492. return;
  7493. }
  7494. eglMakeCurrent(_sapp.android.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  7495. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7496. eglDestroySurface(_sapp.android.display, _sapp.android.surface);
  7497. _sapp.android.surface = EGL_NO_SURFACE;
  7498. }
  7499. }
  7500. _SOKOL_PRIVATE void _sapp_android_app_event(sapp_event_type type) {
  7501. if (_sapp_events_enabled()) {
  7502. _sapp_init_event(type);
  7503. _sapp_call_event(&_sapp.event);
  7504. }
  7505. }
  7506. _SOKOL_PRIVATE void _sapp_android_update_dimensions(ANativeWindow* window, bool force_update) {
  7507. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7508. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7509. SOKOL_ASSERT(_sapp.android.surface != EGL_NO_SURFACE);
  7510. SOKOL_ASSERT(window);
  7511. const int32_t win_w = ANativeWindow_getWidth(window);
  7512. const int32_t win_h = ANativeWindow_getHeight(window);
  7513. SOKOL_ASSERT(win_w >= 0 && win_h >= 0);
  7514. const bool win_changed = (win_w != _sapp.window_width) || (win_h != _sapp.window_height);
  7515. _sapp.window_width = win_w;
  7516. _sapp.window_height = win_h;
  7517. if (win_changed || force_update) {
  7518. if (!_sapp.desc.high_dpi) {
  7519. const int32_t buf_w = win_w / 2;
  7520. const int32_t buf_h = win_h / 2;
  7521. EGLint format;
  7522. EGLBoolean egl_result = eglGetConfigAttrib(_sapp.android.display, _sapp.android.config, EGL_NATIVE_VISUAL_ID, &format);
  7523. SOKOL_ASSERT(egl_result == EGL_TRUE); _SOKOL_UNUSED(egl_result);
  7524. /* NOTE: calling ANativeWindow_setBuffersGeometry() with the same dimensions
  7525. as the ANativeWindow size results in weird display artefacts, that's
  7526. why it's only called when the buffer geometry is different from
  7527. the window size
  7528. */
  7529. int32_t result = ANativeWindow_setBuffersGeometry(window, buf_w, buf_h, format);
  7530. SOKOL_ASSERT(result == 0); _SOKOL_UNUSED(result);
  7531. }
  7532. }
  7533. /* query surface size */
  7534. EGLint fb_w, fb_h;
  7535. EGLBoolean egl_result_w = eglQuerySurface(_sapp.android.display, _sapp.android.surface, EGL_WIDTH, &fb_w);
  7536. EGLBoolean egl_result_h = eglQuerySurface(_sapp.android.display, _sapp.android.surface, EGL_HEIGHT, &fb_h);
  7537. SOKOL_ASSERT(egl_result_w == EGL_TRUE); _SOKOL_UNUSED(egl_result_w);
  7538. SOKOL_ASSERT(egl_result_h == EGL_TRUE); _SOKOL_UNUSED(egl_result_h);
  7539. const bool fb_changed = (fb_w != _sapp.framebuffer_width) || (fb_h != _sapp.framebuffer_height);
  7540. _sapp.framebuffer_width = fb_w;
  7541. _sapp.framebuffer_height = fb_h;
  7542. _sapp.dpi_scale = (float)_sapp.framebuffer_width / (float)_sapp.window_width;
  7543. if (win_changed || fb_changed || force_update) {
  7544. if (!_sapp.first_frame) {
  7545. _sapp_android_app_event(SAPP_EVENTTYPE_RESIZED);
  7546. }
  7547. }
  7548. }
  7549. _SOKOL_PRIVATE void _sapp_android_cleanup(void) {
  7550. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7551. /* egl context is bound, cleanup gracefully */
  7552. if (_sapp.init_called && !_sapp.cleanup_called) {
  7553. _sapp_call_cleanup();
  7554. }
  7555. }
  7556. /* always try to cleanup by destroying egl context */
  7557. _sapp_android_cleanup_egl();
  7558. }
  7559. _SOKOL_PRIVATE void _sapp_android_shutdown(void) {
  7560. /* try to cleanup while we still have a surface and can call cleanup_cb() */
  7561. _sapp_android_cleanup();
  7562. /* request exit */
  7563. ANativeActivity_finish(_sapp.android.activity);
  7564. }
  7565. _SOKOL_PRIVATE void _sapp_android_frame(void) {
  7566. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7567. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7568. SOKOL_ASSERT(_sapp.android.surface != EGL_NO_SURFACE);
  7569. _sapp_timing_measure(&_sapp.timing);
  7570. _sapp_android_update_dimensions(_sapp.android.current.window, false);
  7571. _sapp_frame();
  7572. eglSwapBuffers(_sapp.android.display, _sapp.android.surface);
  7573. }
  7574. _SOKOL_PRIVATE bool _sapp_android_touch_event(const AInputEvent* e) {
  7575. if (AInputEvent_getType(e) != AINPUT_EVENT_TYPE_MOTION) {
  7576. return false;
  7577. }
  7578. if (!_sapp_events_enabled()) {
  7579. return false;
  7580. }
  7581. int32_t action_idx = AMotionEvent_getAction(e);
  7582. int32_t action = action_idx & AMOTION_EVENT_ACTION_MASK;
  7583. sapp_event_type type = SAPP_EVENTTYPE_INVALID;
  7584. switch (action) {
  7585. case AMOTION_EVENT_ACTION_DOWN:
  7586. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  7587. type = SAPP_EVENTTYPE_TOUCHES_BEGAN;
  7588. break;
  7589. case AMOTION_EVENT_ACTION_MOVE:
  7590. type = SAPP_EVENTTYPE_TOUCHES_MOVED;
  7591. break;
  7592. case AMOTION_EVENT_ACTION_UP:
  7593. case AMOTION_EVENT_ACTION_POINTER_UP:
  7594. type = SAPP_EVENTTYPE_TOUCHES_ENDED;
  7595. break;
  7596. case AMOTION_EVENT_ACTION_CANCEL:
  7597. type = SAPP_EVENTTYPE_TOUCHES_CANCELLED;
  7598. break;
  7599. default:
  7600. break;
  7601. }
  7602. if (type == SAPP_EVENTTYPE_INVALID) {
  7603. return false;
  7604. }
  7605. int32_t idx = action_idx >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  7606. _sapp_init_event(type);
  7607. _sapp.event.num_touches = (int)AMotionEvent_getPointerCount(e);
  7608. if (_sapp.event.num_touches > SAPP_MAX_TOUCHPOINTS) {
  7609. _sapp.event.num_touches = SAPP_MAX_TOUCHPOINTS;
  7610. }
  7611. for (int32_t i = 0; i < _sapp.event.num_touches; i++) {
  7612. sapp_touchpoint* dst = &_sapp.event.touches[i];
  7613. dst->identifier = (uintptr_t)AMotionEvent_getPointerId(e, (size_t)i);
  7614. dst->pos_x = (AMotionEvent_getX(e, (size_t)i) / _sapp.window_width) * _sapp.framebuffer_width;
  7615. dst->pos_y = (AMotionEvent_getY(e, (size_t)i) / _sapp.window_height) * _sapp.framebuffer_height;
  7616. dst->android_tooltype = (sapp_android_tooltype) AMotionEvent_getToolType(e, (size_t)i);
  7617. if (action == AMOTION_EVENT_ACTION_POINTER_DOWN ||
  7618. action == AMOTION_EVENT_ACTION_POINTER_UP) {
  7619. dst->changed = (i == idx);
  7620. } else {
  7621. dst->changed = true;
  7622. }
  7623. }
  7624. _sapp_call_event(&_sapp.event);
  7625. return true;
  7626. }
  7627. _SOKOL_PRIVATE bool _sapp_android_key_event(const AInputEvent* e) {
  7628. if (AInputEvent_getType(e) != AINPUT_EVENT_TYPE_KEY) {
  7629. return false;
  7630. }
  7631. if (AKeyEvent_getKeyCode(e) == AKEYCODE_BACK) {
  7632. /* FIXME: this should be hooked into a "really quit?" mechanism
  7633. so the app can ask the user for confirmation, this is currently
  7634. generally missing in sokol_app.h
  7635. */
  7636. _sapp_android_shutdown();
  7637. return true;
  7638. }
  7639. return false;
  7640. }
  7641. _SOKOL_PRIVATE int _sapp_android_input_cb(int fd, int events, void* data) {
  7642. _SOKOL_UNUSED(fd);
  7643. _SOKOL_UNUSED(data);
  7644. if ((events & ALOOPER_EVENT_INPUT) == 0) {
  7645. _SAPP_ERROR(ANDROID_UNSUPPORTED_INPUT_EVENT_INPUT_CB);
  7646. return 1;
  7647. }
  7648. SOKOL_ASSERT(_sapp.android.current.input);
  7649. AInputEvent* event = NULL;
  7650. while (AInputQueue_getEvent(_sapp.android.current.input, &event) >= 0) {
  7651. if (AInputQueue_preDispatchEvent(_sapp.android.current.input, event) != 0) {
  7652. continue;
  7653. }
  7654. int32_t handled = 0;
  7655. if (_sapp_android_touch_event(event) || _sapp_android_key_event(event)) {
  7656. handled = 1;
  7657. }
  7658. AInputQueue_finishEvent(_sapp.android.current.input, event, handled);
  7659. }
  7660. return 1;
  7661. }
  7662. _SOKOL_PRIVATE int _sapp_android_main_cb(int fd, int events, void* data) {
  7663. _SOKOL_UNUSED(data);
  7664. if ((events & ALOOPER_EVENT_INPUT) == 0) {
  7665. _SAPP_ERROR(ANDROID_UNSUPPORTED_INPUT_EVENT_MAIN_CB);
  7666. return 1;
  7667. }
  7668. _sapp_android_msg_t msg;
  7669. if (read(fd, &msg, sizeof(msg)) != sizeof(msg)) {
  7670. _SAPP_ERROR(ANDROID_READ_MSG_FAILED);
  7671. return 1;
  7672. }
  7673. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7674. switch (msg) {
  7675. case _SOKOL_ANDROID_MSG_CREATE:
  7676. {
  7677. _SAPP_INFO(ANDROID_MSG_CREATE);
  7678. SOKOL_ASSERT(!_sapp.valid);
  7679. bool result = _sapp_android_init_egl();
  7680. SOKOL_ASSERT(result); _SOKOL_UNUSED(result);
  7681. _sapp.valid = true;
  7682. _sapp.android.has_created = true;
  7683. }
  7684. break;
  7685. case _SOKOL_ANDROID_MSG_RESUME:
  7686. _SAPP_INFO(ANDROID_MSG_RESUME);
  7687. _sapp.android.has_resumed = true;
  7688. _sapp_android_app_event(SAPP_EVENTTYPE_RESUMED);
  7689. break;
  7690. case _SOKOL_ANDROID_MSG_PAUSE:
  7691. _SAPP_INFO(ANDROID_MSG_PAUSE);
  7692. _sapp.android.has_resumed = false;
  7693. _sapp_android_app_event(SAPP_EVENTTYPE_SUSPENDED);
  7694. break;
  7695. case _SOKOL_ANDROID_MSG_FOCUS:
  7696. _SAPP_INFO(ANDROID_MSG_FOCUS);
  7697. _sapp.android.has_focus = true;
  7698. break;
  7699. case _SOKOL_ANDROID_MSG_NO_FOCUS:
  7700. _SAPP_INFO(ANDROID_MSG_NO_FOCUS);
  7701. _sapp.android.has_focus = false;
  7702. break;
  7703. case _SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW:
  7704. _SAPP_INFO(ANDROID_MSG_SET_NATIVE_WINDOW);
  7705. if (_sapp.android.current.window != _sapp.android.pending.window) {
  7706. if (_sapp.android.current.window != NULL) {
  7707. _sapp_android_cleanup_egl_surface();
  7708. }
  7709. if (_sapp.android.pending.window != NULL) {
  7710. if (_sapp_android_init_egl_surface(_sapp.android.pending.window)) {
  7711. _sapp_android_update_dimensions(_sapp.android.pending.window, true);
  7712. } else {
  7713. _sapp_android_shutdown();
  7714. }
  7715. }
  7716. }
  7717. _sapp.android.current.window = _sapp.android.pending.window;
  7718. break;
  7719. case _SOKOL_ANDROID_MSG_SET_INPUT_QUEUE:
  7720. _SAPP_INFO(ANDROID_MSG_SET_INPUT_QUEUE);
  7721. if (_sapp.android.current.input != _sapp.android.pending.input) {
  7722. if (_sapp.android.current.input != NULL) {
  7723. AInputQueue_detachLooper(_sapp.android.current.input);
  7724. }
  7725. if (_sapp.android.pending.input != NULL) {
  7726. AInputQueue_attachLooper(
  7727. _sapp.android.pending.input,
  7728. _sapp.android.looper,
  7729. ALOOPER_POLL_CALLBACK,
  7730. _sapp_android_input_cb,
  7731. NULL); /* data */
  7732. }
  7733. }
  7734. _sapp.android.current.input = _sapp.android.pending.input;
  7735. break;
  7736. case _SOKOL_ANDROID_MSG_DESTROY:
  7737. _SAPP_INFO(ANDROID_MSG_DESTROY);
  7738. _sapp_android_cleanup();
  7739. _sapp.valid = false;
  7740. _sapp.android.is_thread_stopping = true;
  7741. break;
  7742. default:
  7743. _SAPP_WARN(ANDROID_UNKNOWN_MSG);
  7744. break;
  7745. }
  7746. pthread_cond_broadcast(&_sapp.android.pt.cond); /* signal "received" */
  7747. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7748. return 1;
  7749. }
  7750. _SOKOL_PRIVATE bool _sapp_android_should_update(void) {
  7751. bool is_in_front = _sapp.android.has_resumed && _sapp.android.has_focus;
  7752. bool has_surface = _sapp.android.surface != EGL_NO_SURFACE;
  7753. return is_in_front && has_surface;
  7754. }
  7755. _SOKOL_PRIVATE void _sapp_android_show_keyboard(bool shown) {
  7756. SOKOL_ASSERT(_sapp.valid);
  7757. /* This seems to be broken in the NDK, but there is (a very cumbersome) workaround... */
  7758. if (shown) {
  7759. ANativeActivity_showSoftInput(_sapp.android.activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED);
  7760. } else {
  7761. ANativeActivity_hideSoftInput(_sapp.android.activity, ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS);
  7762. }
  7763. }
  7764. _SOKOL_PRIVATE void* _sapp_android_loop(void* arg) {
  7765. _SOKOL_UNUSED(arg);
  7766. _SAPP_INFO(ANDROID_LOOP_THREAD_STARTED);
  7767. _sapp.android.looper = ALooper_prepare(0 /* or ALOOPER_PREPARE_ALLOW_NON_CALLBACKS*/);
  7768. ALooper_addFd(_sapp.android.looper,
  7769. _sapp.android.pt.read_from_main_fd,
  7770. ALOOPER_POLL_CALLBACK,
  7771. ALOOPER_EVENT_INPUT,
  7772. _sapp_android_main_cb,
  7773. NULL); /* data */
  7774. /* signal start to main thread */
  7775. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7776. _sapp.android.is_thread_started = true;
  7777. pthread_cond_broadcast(&_sapp.android.pt.cond);
  7778. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7779. /* main loop */
  7780. while (!_sapp.android.is_thread_stopping) {
  7781. /* sokol frame */
  7782. if (_sapp_android_should_update()) {
  7783. _sapp_android_frame();
  7784. }
  7785. /* process all events (or stop early if app is requested to quit) */
  7786. bool process_events = true;
  7787. while (process_events && !_sapp.android.is_thread_stopping) {
  7788. bool block_until_event = !_sapp.android.is_thread_stopping && !_sapp_android_should_update();
  7789. process_events = ALooper_pollOnce(block_until_event ? -1 : 0, NULL, NULL, NULL) == ALOOPER_POLL_CALLBACK;
  7790. }
  7791. }
  7792. /* cleanup thread */
  7793. if (_sapp.android.current.input != NULL) {
  7794. AInputQueue_detachLooper(_sapp.android.current.input);
  7795. }
  7796. /* the following causes heap corruption on exit, why??
  7797. ALooper_removeFd(_sapp.android.looper, _sapp.android.pt.read_from_main_fd);
  7798. ALooper_release(_sapp.android.looper);*/
  7799. /* signal "destroyed" */
  7800. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7801. _sapp.android.is_thread_stopped = true;
  7802. pthread_cond_broadcast(&_sapp.android.pt.cond);
  7803. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7804. _SAPP_INFO(ANDROID_LOOP_THREAD_DONE);
  7805. return NULL;
  7806. }
  7807. /* android main/ui thread */
  7808. _SOKOL_PRIVATE void _sapp_android_msg(_sapp_android_msg_t msg) {
  7809. if (write(_sapp.android.pt.write_from_main_fd, &msg, sizeof(msg)) != sizeof(msg)) {
  7810. _SAPP_ERROR(ANDROID_WRITE_MSG_FAILED);
  7811. }
  7812. }
  7813. _SOKOL_PRIVATE void _sapp_android_on_start(ANativeActivity* activity) {
  7814. _SOKOL_UNUSED(activity);
  7815. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSTART);
  7816. }
  7817. _SOKOL_PRIVATE void _sapp_android_on_resume(ANativeActivity* activity) {
  7818. _SOKOL_UNUSED(activity);
  7819. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONRESUME);
  7820. _sapp_android_msg(_SOKOL_ANDROID_MSG_RESUME);
  7821. }
  7822. _SOKOL_PRIVATE void* _sapp_android_on_save_instance_state(ANativeActivity* activity, size_t* out_size) {
  7823. _SOKOL_UNUSED(activity);
  7824. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSAVEINSTANCESTATE);
  7825. *out_size = 0;
  7826. return NULL;
  7827. }
  7828. _SOKOL_PRIVATE void _sapp_android_on_window_focus_changed(ANativeActivity* activity, int has_focus) {
  7829. _SOKOL_UNUSED(activity);
  7830. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONWINDOWFOCUSCHANGED);
  7831. if (has_focus) {
  7832. _sapp_android_msg(_SOKOL_ANDROID_MSG_FOCUS);
  7833. } else {
  7834. _sapp_android_msg(_SOKOL_ANDROID_MSG_NO_FOCUS);
  7835. }
  7836. }
  7837. _SOKOL_PRIVATE void _sapp_android_on_pause(ANativeActivity* activity) {
  7838. _SOKOL_UNUSED(activity);
  7839. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONPAUSE);
  7840. _sapp_android_msg(_SOKOL_ANDROID_MSG_PAUSE);
  7841. }
  7842. _SOKOL_PRIVATE void _sapp_android_on_stop(ANativeActivity* activity) {
  7843. _SOKOL_UNUSED(activity);
  7844. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSTOP);
  7845. }
  7846. _SOKOL_PRIVATE void _sapp_android_msg_set_native_window(ANativeWindow* window) {
  7847. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7848. _sapp.android.pending.window = window;
  7849. _sapp_android_msg(_SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW);
  7850. while (_sapp.android.current.window != window) {
  7851. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7852. }
  7853. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7854. }
  7855. _SOKOL_PRIVATE void _sapp_android_on_native_window_created(ANativeActivity* activity, ANativeWindow* window) {
  7856. _SOKOL_UNUSED(activity);
  7857. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWCREATED);
  7858. _sapp_android_msg_set_native_window(window);
  7859. }
  7860. _SOKOL_PRIVATE void _sapp_android_on_native_window_destroyed(ANativeActivity* activity, ANativeWindow* window) {
  7861. _SOKOL_UNUSED(activity);
  7862. _SOKOL_UNUSED(window);
  7863. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWDESTROYED);
  7864. _sapp_android_msg_set_native_window(NULL);
  7865. }
  7866. _SOKOL_PRIVATE void _sapp_android_msg_set_input_queue(AInputQueue* input) {
  7867. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7868. _sapp.android.pending.input = input;
  7869. _sapp_android_msg(_SOKOL_ANDROID_MSG_SET_INPUT_QUEUE);
  7870. while (_sapp.android.current.input != input) {
  7871. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7872. }
  7873. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7874. }
  7875. _SOKOL_PRIVATE void _sapp_android_on_input_queue_created(ANativeActivity* activity, AInputQueue* queue) {
  7876. _SOKOL_UNUSED(activity);
  7877. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUECREATED);
  7878. _sapp_android_msg_set_input_queue(queue);
  7879. }
  7880. _SOKOL_PRIVATE void _sapp_android_on_input_queue_destroyed(ANativeActivity* activity, AInputQueue* queue) {
  7881. _SOKOL_UNUSED(activity);
  7882. _SOKOL_UNUSED(queue);
  7883. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUEDESTROYED);
  7884. _sapp_android_msg_set_input_queue(NULL);
  7885. }
  7886. _SOKOL_PRIVATE void _sapp_android_on_config_changed(ANativeActivity* activity) {
  7887. _SOKOL_UNUSED(activity);
  7888. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONCONFIGURATIONCHANGED);
  7889. /* see android:configChanges in manifest */
  7890. }
  7891. _SOKOL_PRIVATE void _sapp_android_on_low_memory(ANativeActivity* activity) {
  7892. _SOKOL_UNUSED(activity);
  7893. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONLOWMEMORY);
  7894. }
  7895. _SOKOL_PRIVATE void _sapp_android_on_destroy(ANativeActivity* activity) {
  7896. /*
  7897. * For some reason even an empty app using nativeactivity.h will crash (WIN DEATH)
  7898. * on my device (Moto X 2nd gen) when the app is removed from the task view
  7899. * (TaskStackView: onTaskViewDismissed).
  7900. *
  7901. * However, if ANativeActivity_finish() is explicitly called from for example
  7902. * _sapp_android_on_stop(), the crash disappears. Is this a bug in NativeActivity?
  7903. */
  7904. _SOKOL_UNUSED(activity);
  7905. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONDESTROY);
  7906. /* send destroy msg */
  7907. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7908. _sapp_android_msg(_SOKOL_ANDROID_MSG_DESTROY);
  7909. while (!_sapp.android.is_thread_stopped) {
  7910. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7911. }
  7912. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7913. /* clean up main thread */
  7914. pthread_cond_destroy(&_sapp.android.pt.cond);
  7915. pthread_mutex_destroy(&_sapp.android.pt.mutex);
  7916. close(_sapp.android.pt.read_from_main_fd);
  7917. close(_sapp.android.pt.write_from_main_fd);
  7918. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_DONE);
  7919. /* this is a bit naughty, but causes a clean restart of the app (static globals are reset) */
  7920. exit(0);
  7921. }
  7922. JNIEXPORT
  7923. void ANativeActivity_onCreate(ANativeActivity* activity, void* saved_state, size_t saved_state_size) {
  7924. _SOKOL_UNUSED(saved_state);
  7925. _SOKOL_UNUSED(saved_state_size);
  7926. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONCREATE);
  7927. // the NativeActity pointer needs to be available inside sokol_main()
  7928. // (see https://github.com/floooh/sokol/issues/708), however _sapp_init_state()
  7929. // will clear the global _sapp_t struct, so we need to initialize the native
  7930. // activity pointer twice, once before sokol_main() and once after _sapp_init_state()
  7931. _sapp_clear(&_sapp, sizeof(_sapp));
  7932. _sapp.android.activity = activity;
  7933. sapp_desc desc = sokol_main(0, NULL);
  7934. _sapp_init_state(&desc);
  7935. _sapp.android.activity = activity;
  7936. int pipe_fd[2];
  7937. if (pipe(pipe_fd) != 0) {
  7938. _SAPP_ERROR(ANDROID_CREATE_THREAD_PIPE_FAILED);
  7939. return;
  7940. }
  7941. _sapp.android.pt.read_from_main_fd = pipe_fd[0];
  7942. _sapp.android.pt.write_from_main_fd = pipe_fd[1];
  7943. pthread_mutex_init(&_sapp.android.pt.mutex, NULL);
  7944. pthread_cond_init(&_sapp.android.pt.cond, NULL);
  7945. pthread_attr_t attr;
  7946. pthread_attr_init(&attr);
  7947. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  7948. pthread_create(&_sapp.android.pt.thread, &attr, _sapp_android_loop, 0);
  7949. pthread_attr_destroy(&attr);
  7950. /* wait until main loop has started */
  7951. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7952. while (!_sapp.android.is_thread_started) {
  7953. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7954. }
  7955. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7956. /* send create msg */
  7957. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7958. _sapp_android_msg(_SOKOL_ANDROID_MSG_CREATE);
  7959. while (!_sapp.android.has_created) {
  7960. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7961. }
  7962. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7963. /* register for callbacks */
  7964. activity->callbacks->onStart = _sapp_android_on_start;
  7965. activity->callbacks->onResume = _sapp_android_on_resume;
  7966. activity->callbacks->onSaveInstanceState = _sapp_android_on_save_instance_state;
  7967. activity->callbacks->onWindowFocusChanged = _sapp_android_on_window_focus_changed;
  7968. activity->callbacks->onPause = _sapp_android_on_pause;
  7969. activity->callbacks->onStop = _sapp_android_on_stop;
  7970. activity->callbacks->onDestroy = _sapp_android_on_destroy;
  7971. activity->callbacks->onNativeWindowCreated = _sapp_android_on_native_window_created;
  7972. /* activity->callbacks->onNativeWindowResized = _sapp_android_on_native_window_resized; */
  7973. /* activity->callbacks->onNativeWindowRedrawNeeded = _sapp_android_on_native_window_redraw_needed; */
  7974. activity->callbacks->onNativeWindowDestroyed = _sapp_android_on_native_window_destroyed;
  7975. activity->callbacks->onInputQueueCreated = _sapp_android_on_input_queue_created;
  7976. activity->callbacks->onInputQueueDestroyed = _sapp_android_on_input_queue_destroyed;
  7977. /* activity->callbacks->onContentRectChanged = _sapp_android_on_content_rect_changed; */
  7978. activity->callbacks->onConfigurationChanged = _sapp_android_on_config_changed;
  7979. activity->callbacks->onLowMemory = _sapp_android_on_low_memory;
  7980. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_CREATE_SUCCESS);
  7981. /* NOT A BUG: do NOT call sapp_discard_state() */
  7982. }
  7983. #endif /* _SAPP_ANDROID */
  7984. // ██ ██ ███ ██ ██ ██ ██ ██
  7985. // ██ ██ ████ ██ ██ ██ ██ ██
  7986. // ██ ██ ██ ██ ██ ██ ██ ███
  7987. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  7988. // ███████ ██ ██ ████ ██████ ██ ██
  7989. //
  7990. // >>linux
  7991. #if defined(_SAPP_LINUX)
  7992. /* see GLFW's xkb_unicode.c */
  7993. static const struct _sapp_x11_codepair {
  7994. uint16_t keysym;
  7995. uint16_t ucs;
  7996. } _sapp_x11_keysymtab[] = {
  7997. { 0x01a1, 0x0104 },
  7998. { 0x01a2, 0x02d8 },
  7999. { 0x01a3, 0x0141 },
  8000. { 0x01a5, 0x013d },
  8001. { 0x01a6, 0x015a },
  8002. { 0x01a9, 0x0160 },
  8003. { 0x01aa, 0x015e },
  8004. { 0x01ab, 0x0164 },
  8005. { 0x01ac, 0x0179 },
  8006. { 0x01ae, 0x017d },
  8007. { 0x01af, 0x017b },
  8008. { 0x01b1, 0x0105 },
  8009. { 0x01b2, 0x02db },
  8010. { 0x01b3, 0x0142 },
  8011. { 0x01b5, 0x013e },
  8012. { 0x01b6, 0x015b },
  8013. { 0x01b7, 0x02c7 },
  8014. { 0x01b9, 0x0161 },
  8015. { 0x01ba, 0x015f },
  8016. { 0x01bb, 0x0165 },
  8017. { 0x01bc, 0x017a },
  8018. { 0x01bd, 0x02dd },
  8019. { 0x01be, 0x017e },
  8020. { 0x01bf, 0x017c },
  8021. { 0x01c0, 0x0154 },
  8022. { 0x01c3, 0x0102 },
  8023. { 0x01c5, 0x0139 },
  8024. { 0x01c6, 0x0106 },
  8025. { 0x01c8, 0x010c },
  8026. { 0x01ca, 0x0118 },
  8027. { 0x01cc, 0x011a },
  8028. { 0x01cf, 0x010e },
  8029. { 0x01d0, 0x0110 },
  8030. { 0x01d1, 0x0143 },
  8031. { 0x01d2, 0x0147 },
  8032. { 0x01d5, 0x0150 },
  8033. { 0x01d8, 0x0158 },
  8034. { 0x01d9, 0x016e },
  8035. { 0x01db, 0x0170 },
  8036. { 0x01de, 0x0162 },
  8037. { 0x01e0, 0x0155 },
  8038. { 0x01e3, 0x0103 },
  8039. { 0x01e5, 0x013a },
  8040. { 0x01e6, 0x0107 },
  8041. { 0x01e8, 0x010d },
  8042. { 0x01ea, 0x0119 },
  8043. { 0x01ec, 0x011b },
  8044. { 0x01ef, 0x010f },
  8045. { 0x01f0, 0x0111 },
  8046. { 0x01f1, 0x0144 },
  8047. { 0x01f2, 0x0148 },
  8048. { 0x01f5, 0x0151 },
  8049. { 0x01f8, 0x0159 },
  8050. { 0x01f9, 0x016f },
  8051. { 0x01fb, 0x0171 },
  8052. { 0x01fe, 0x0163 },
  8053. { 0x01ff, 0x02d9 },
  8054. { 0x02a1, 0x0126 },
  8055. { 0x02a6, 0x0124 },
  8056. { 0x02a9, 0x0130 },
  8057. { 0x02ab, 0x011e },
  8058. { 0x02ac, 0x0134 },
  8059. { 0x02b1, 0x0127 },
  8060. { 0x02b6, 0x0125 },
  8061. { 0x02b9, 0x0131 },
  8062. { 0x02bb, 0x011f },
  8063. { 0x02bc, 0x0135 },
  8064. { 0x02c5, 0x010a },
  8065. { 0x02c6, 0x0108 },
  8066. { 0x02d5, 0x0120 },
  8067. { 0x02d8, 0x011c },
  8068. { 0x02dd, 0x016c },
  8069. { 0x02de, 0x015c },
  8070. { 0x02e5, 0x010b },
  8071. { 0x02e6, 0x0109 },
  8072. { 0x02f5, 0x0121 },
  8073. { 0x02f8, 0x011d },
  8074. { 0x02fd, 0x016d },
  8075. { 0x02fe, 0x015d },
  8076. { 0x03a2, 0x0138 },
  8077. { 0x03a3, 0x0156 },
  8078. { 0x03a5, 0x0128 },
  8079. { 0x03a6, 0x013b },
  8080. { 0x03aa, 0x0112 },
  8081. { 0x03ab, 0x0122 },
  8082. { 0x03ac, 0x0166 },
  8083. { 0x03b3, 0x0157 },
  8084. { 0x03b5, 0x0129 },
  8085. { 0x03b6, 0x013c },
  8086. { 0x03ba, 0x0113 },
  8087. { 0x03bb, 0x0123 },
  8088. { 0x03bc, 0x0167 },
  8089. { 0x03bd, 0x014a },
  8090. { 0x03bf, 0x014b },
  8091. { 0x03c0, 0x0100 },
  8092. { 0x03c7, 0x012e },
  8093. { 0x03cc, 0x0116 },
  8094. { 0x03cf, 0x012a },
  8095. { 0x03d1, 0x0145 },
  8096. { 0x03d2, 0x014c },
  8097. { 0x03d3, 0x0136 },
  8098. { 0x03d9, 0x0172 },
  8099. { 0x03dd, 0x0168 },
  8100. { 0x03de, 0x016a },
  8101. { 0x03e0, 0x0101 },
  8102. { 0x03e7, 0x012f },
  8103. { 0x03ec, 0x0117 },
  8104. { 0x03ef, 0x012b },
  8105. { 0x03f1, 0x0146 },
  8106. { 0x03f2, 0x014d },
  8107. { 0x03f3, 0x0137 },
  8108. { 0x03f9, 0x0173 },
  8109. { 0x03fd, 0x0169 },
  8110. { 0x03fe, 0x016b },
  8111. { 0x047e, 0x203e },
  8112. { 0x04a1, 0x3002 },
  8113. { 0x04a2, 0x300c },
  8114. { 0x04a3, 0x300d },
  8115. { 0x04a4, 0x3001 },
  8116. { 0x04a5, 0x30fb },
  8117. { 0x04a6, 0x30f2 },
  8118. { 0x04a7, 0x30a1 },
  8119. { 0x04a8, 0x30a3 },
  8120. { 0x04a9, 0x30a5 },
  8121. { 0x04aa, 0x30a7 },
  8122. { 0x04ab, 0x30a9 },
  8123. { 0x04ac, 0x30e3 },
  8124. { 0x04ad, 0x30e5 },
  8125. { 0x04ae, 0x30e7 },
  8126. { 0x04af, 0x30c3 },
  8127. { 0x04b0, 0x30fc },
  8128. { 0x04b1, 0x30a2 },
  8129. { 0x04b2, 0x30a4 },
  8130. { 0x04b3, 0x30a6 },
  8131. { 0x04b4, 0x30a8 },
  8132. { 0x04b5, 0x30aa },
  8133. { 0x04b6, 0x30ab },
  8134. { 0x04b7, 0x30ad },
  8135. { 0x04b8, 0x30af },
  8136. { 0x04b9, 0x30b1 },
  8137. { 0x04ba, 0x30b3 },
  8138. { 0x04bb, 0x30b5 },
  8139. { 0x04bc, 0x30b7 },
  8140. { 0x04bd, 0x30b9 },
  8141. { 0x04be, 0x30bb },
  8142. { 0x04bf, 0x30bd },
  8143. { 0x04c0, 0x30bf },
  8144. { 0x04c1, 0x30c1 },
  8145. { 0x04c2, 0x30c4 },
  8146. { 0x04c3, 0x30c6 },
  8147. { 0x04c4, 0x30c8 },
  8148. { 0x04c5, 0x30ca },
  8149. { 0x04c6, 0x30cb },
  8150. { 0x04c7, 0x30cc },
  8151. { 0x04c8, 0x30cd },
  8152. { 0x04c9, 0x30ce },
  8153. { 0x04ca, 0x30cf },
  8154. { 0x04cb, 0x30d2 },
  8155. { 0x04cc, 0x30d5 },
  8156. { 0x04cd, 0x30d8 },
  8157. { 0x04ce, 0x30db },
  8158. { 0x04cf, 0x30de },
  8159. { 0x04d0, 0x30df },
  8160. { 0x04d1, 0x30e0 },
  8161. { 0x04d2, 0x30e1 },
  8162. { 0x04d3, 0x30e2 },
  8163. { 0x04d4, 0x30e4 },
  8164. { 0x04d5, 0x30e6 },
  8165. { 0x04d6, 0x30e8 },
  8166. { 0x04d7, 0x30e9 },
  8167. { 0x04d8, 0x30ea },
  8168. { 0x04d9, 0x30eb },
  8169. { 0x04da, 0x30ec },
  8170. { 0x04db, 0x30ed },
  8171. { 0x04dc, 0x30ef },
  8172. { 0x04dd, 0x30f3 },
  8173. { 0x04de, 0x309b },
  8174. { 0x04df, 0x309c },
  8175. { 0x05ac, 0x060c },
  8176. { 0x05bb, 0x061b },
  8177. { 0x05bf, 0x061f },
  8178. { 0x05c1, 0x0621 },
  8179. { 0x05c2, 0x0622 },
  8180. { 0x05c3, 0x0623 },
  8181. { 0x05c4, 0x0624 },
  8182. { 0x05c5, 0x0625 },
  8183. { 0x05c6, 0x0626 },
  8184. { 0x05c7, 0x0627 },
  8185. { 0x05c8, 0x0628 },
  8186. { 0x05c9, 0x0629 },
  8187. { 0x05ca, 0x062a },
  8188. { 0x05cb, 0x062b },
  8189. { 0x05cc, 0x062c },
  8190. { 0x05cd, 0x062d },
  8191. { 0x05ce, 0x062e },
  8192. { 0x05cf, 0x062f },
  8193. { 0x05d0, 0x0630 },
  8194. { 0x05d1, 0x0631 },
  8195. { 0x05d2, 0x0632 },
  8196. { 0x05d3, 0x0633 },
  8197. { 0x05d4, 0x0634 },
  8198. { 0x05d5, 0x0635 },
  8199. { 0x05d6, 0x0636 },
  8200. { 0x05d7, 0x0637 },
  8201. { 0x05d8, 0x0638 },
  8202. { 0x05d9, 0x0639 },
  8203. { 0x05da, 0x063a },
  8204. { 0x05e0, 0x0640 },
  8205. { 0x05e1, 0x0641 },
  8206. { 0x05e2, 0x0642 },
  8207. { 0x05e3, 0x0643 },
  8208. { 0x05e4, 0x0644 },
  8209. { 0x05e5, 0x0645 },
  8210. { 0x05e6, 0x0646 },
  8211. { 0x05e7, 0x0647 },
  8212. { 0x05e8, 0x0648 },
  8213. { 0x05e9, 0x0649 },
  8214. { 0x05ea, 0x064a },
  8215. { 0x05eb, 0x064b },
  8216. { 0x05ec, 0x064c },
  8217. { 0x05ed, 0x064d },
  8218. { 0x05ee, 0x064e },
  8219. { 0x05ef, 0x064f },
  8220. { 0x05f0, 0x0650 },
  8221. { 0x05f1, 0x0651 },
  8222. { 0x05f2, 0x0652 },
  8223. { 0x06a1, 0x0452 },
  8224. { 0x06a2, 0x0453 },
  8225. { 0x06a3, 0x0451 },
  8226. { 0x06a4, 0x0454 },
  8227. { 0x06a5, 0x0455 },
  8228. { 0x06a6, 0x0456 },
  8229. { 0x06a7, 0x0457 },
  8230. { 0x06a8, 0x0458 },
  8231. { 0x06a9, 0x0459 },
  8232. { 0x06aa, 0x045a },
  8233. { 0x06ab, 0x045b },
  8234. { 0x06ac, 0x045c },
  8235. { 0x06ae, 0x045e },
  8236. { 0x06af, 0x045f },
  8237. { 0x06b0, 0x2116 },
  8238. { 0x06b1, 0x0402 },
  8239. { 0x06b2, 0x0403 },
  8240. { 0x06b3, 0x0401 },
  8241. { 0x06b4, 0x0404 },
  8242. { 0x06b5, 0x0405 },
  8243. { 0x06b6, 0x0406 },
  8244. { 0x06b7, 0x0407 },
  8245. { 0x06b8, 0x0408 },
  8246. { 0x06b9, 0x0409 },
  8247. { 0x06ba, 0x040a },
  8248. { 0x06bb, 0x040b },
  8249. { 0x06bc, 0x040c },
  8250. { 0x06be, 0x040e },
  8251. { 0x06bf, 0x040f },
  8252. { 0x06c0, 0x044e },
  8253. { 0x06c1, 0x0430 },
  8254. { 0x06c2, 0x0431 },
  8255. { 0x06c3, 0x0446 },
  8256. { 0x06c4, 0x0434 },
  8257. { 0x06c5, 0x0435 },
  8258. { 0x06c6, 0x0444 },
  8259. { 0x06c7, 0x0433 },
  8260. { 0x06c8, 0x0445 },
  8261. { 0x06c9, 0x0438 },
  8262. { 0x06ca, 0x0439 },
  8263. { 0x06cb, 0x043a },
  8264. { 0x06cc, 0x043b },
  8265. { 0x06cd, 0x043c },
  8266. { 0x06ce, 0x043d },
  8267. { 0x06cf, 0x043e },
  8268. { 0x06d0, 0x043f },
  8269. { 0x06d1, 0x044f },
  8270. { 0x06d2, 0x0440 },
  8271. { 0x06d3, 0x0441 },
  8272. { 0x06d4, 0x0442 },
  8273. { 0x06d5, 0x0443 },
  8274. { 0x06d6, 0x0436 },
  8275. { 0x06d7, 0x0432 },
  8276. { 0x06d8, 0x044c },
  8277. { 0x06d9, 0x044b },
  8278. { 0x06da, 0x0437 },
  8279. { 0x06db, 0x0448 },
  8280. { 0x06dc, 0x044d },
  8281. { 0x06dd, 0x0449 },
  8282. { 0x06de, 0x0447 },
  8283. { 0x06df, 0x044a },
  8284. { 0x06e0, 0x042e },
  8285. { 0x06e1, 0x0410 },
  8286. { 0x06e2, 0x0411 },
  8287. { 0x06e3, 0x0426 },
  8288. { 0x06e4, 0x0414 },
  8289. { 0x06e5, 0x0415 },
  8290. { 0x06e6, 0x0424 },
  8291. { 0x06e7, 0x0413 },
  8292. { 0x06e8, 0x0425 },
  8293. { 0x06e9, 0x0418 },
  8294. { 0x06ea, 0x0419 },
  8295. { 0x06eb, 0x041a },
  8296. { 0x06ec, 0x041b },
  8297. { 0x06ed, 0x041c },
  8298. { 0x06ee, 0x041d },
  8299. { 0x06ef, 0x041e },
  8300. { 0x06f0, 0x041f },
  8301. { 0x06f1, 0x042f },
  8302. { 0x06f2, 0x0420 },
  8303. { 0x06f3, 0x0421 },
  8304. { 0x06f4, 0x0422 },
  8305. { 0x06f5, 0x0423 },
  8306. { 0x06f6, 0x0416 },
  8307. { 0x06f7, 0x0412 },
  8308. { 0x06f8, 0x042c },
  8309. { 0x06f9, 0x042b },
  8310. { 0x06fa, 0x0417 },
  8311. { 0x06fb, 0x0428 },
  8312. { 0x06fc, 0x042d },
  8313. { 0x06fd, 0x0429 },
  8314. { 0x06fe, 0x0427 },
  8315. { 0x06ff, 0x042a },
  8316. { 0x07a1, 0x0386 },
  8317. { 0x07a2, 0x0388 },
  8318. { 0x07a3, 0x0389 },
  8319. { 0x07a4, 0x038a },
  8320. { 0x07a5, 0x03aa },
  8321. { 0x07a7, 0x038c },
  8322. { 0x07a8, 0x038e },
  8323. { 0x07a9, 0x03ab },
  8324. { 0x07ab, 0x038f },
  8325. { 0x07ae, 0x0385 },
  8326. { 0x07af, 0x2015 },
  8327. { 0x07b1, 0x03ac },
  8328. { 0x07b2, 0x03ad },
  8329. { 0x07b3, 0x03ae },
  8330. { 0x07b4, 0x03af },
  8331. { 0x07b5, 0x03ca },
  8332. { 0x07b6, 0x0390 },
  8333. { 0x07b7, 0x03cc },
  8334. { 0x07b8, 0x03cd },
  8335. { 0x07b9, 0x03cb },
  8336. { 0x07ba, 0x03b0 },
  8337. { 0x07bb, 0x03ce },
  8338. { 0x07c1, 0x0391 },
  8339. { 0x07c2, 0x0392 },
  8340. { 0x07c3, 0x0393 },
  8341. { 0x07c4, 0x0394 },
  8342. { 0x07c5, 0x0395 },
  8343. { 0x07c6, 0x0396 },
  8344. { 0x07c7, 0x0397 },
  8345. { 0x07c8, 0x0398 },
  8346. { 0x07c9, 0x0399 },
  8347. { 0x07ca, 0x039a },
  8348. { 0x07cb, 0x039b },
  8349. { 0x07cc, 0x039c },
  8350. { 0x07cd, 0x039d },
  8351. { 0x07ce, 0x039e },
  8352. { 0x07cf, 0x039f },
  8353. { 0x07d0, 0x03a0 },
  8354. { 0x07d1, 0x03a1 },
  8355. { 0x07d2, 0x03a3 },
  8356. { 0x07d4, 0x03a4 },
  8357. { 0x07d5, 0x03a5 },
  8358. { 0x07d6, 0x03a6 },
  8359. { 0x07d7, 0x03a7 },
  8360. { 0x07d8, 0x03a8 },
  8361. { 0x07d9, 0x03a9 },
  8362. { 0x07e1, 0x03b1 },
  8363. { 0x07e2, 0x03b2 },
  8364. { 0x07e3, 0x03b3 },
  8365. { 0x07e4, 0x03b4 },
  8366. { 0x07e5, 0x03b5 },
  8367. { 0x07e6, 0x03b6 },
  8368. { 0x07e7, 0x03b7 },
  8369. { 0x07e8, 0x03b8 },
  8370. { 0x07e9, 0x03b9 },
  8371. { 0x07ea, 0x03ba },
  8372. { 0x07eb, 0x03bb },
  8373. { 0x07ec, 0x03bc },
  8374. { 0x07ed, 0x03bd },
  8375. { 0x07ee, 0x03be },
  8376. { 0x07ef, 0x03bf },
  8377. { 0x07f0, 0x03c0 },
  8378. { 0x07f1, 0x03c1 },
  8379. { 0x07f2, 0x03c3 },
  8380. { 0x07f3, 0x03c2 },
  8381. { 0x07f4, 0x03c4 },
  8382. { 0x07f5, 0x03c5 },
  8383. { 0x07f6, 0x03c6 },
  8384. { 0x07f7, 0x03c7 },
  8385. { 0x07f8, 0x03c8 },
  8386. { 0x07f9, 0x03c9 },
  8387. { 0x08a1, 0x23b7 },
  8388. { 0x08a2, 0x250c },
  8389. { 0x08a3, 0x2500 },
  8390. { 0x08a4, 0x2320 },
  8391. { 0x08a5, 0x2321 },
  8392. { 0x08a6, 0x2502 },
  8393. { 0x08a7, 0x23a1 },
  8394. { 0x08a8, 0x23a3 },
  8395. { 0x08a9, 0x23a4 },
  8396. { 0x08aa, 0x23a6 },
  8397. { 0x08ab, 0x239b },
  8398. { 0x08ac, 0x239d },
  8399. { 0x08ad, 0x239e },
  8400. { 0x08ae, 0x23a0 },
  8401. { 0x08af, 0x23a8 },
  8402. { 0x08b0, 0x23ac },
  8403. { 0x08bc, 0x2264 },
  8404. { 0x08bd, 0x2260 },
  8405. { 0x08be, 0x2265 },
  8406. { 0x08bf, 0x222b },
  8407. { 0x08c0, 0x2234 },
  8408. { 0x08c1, 0x221d },
  8409. { 0x08c2, 0x221e },
  8410. { 0x08c5, 0x2207 },
  8411. { 0x08c8, 0x223c },
  8412. { 0x08c9, 0x2243 },
  8413. { 0x08cd, 0x21d4 },
  8414. { 0x08ce, 0x21d2 },
  8415. { 0x08cf, 0x2261 },
  8416. { 0x08d6, 0x221a },
  8417. { 0x08da, 0x2282 },
  8418. { 0x08db, 0x2283 },
  8419. { 0x08dc, 0x2229 },
  8420. { 0x08dd, 0x222a },
  8421. { 0x08de, 0x2227 },
  8422. { 0x08df, 0x2228 },
  8423. { 0x08ef, 0x2202 },
  8424. { 0x08f6, 0x0192 },
  8425. { 0x08fb, 0x2190 },
  8426. { 0x08fc, 0x2191 },
  8427. { 0x08fd, 0x2192 },
  8428. { 0x08fe, 0x2193 },
  8429. { 0x09e0, 0x25c6 },
  8430. { 0x09e1, 0x2592 },
  8431. { 0x09e2, 0x2409 },
  8432. { 0x09e3, 0x240c },
  8433. { 0x09e4, 0x240d },
  8434. { 0x09e5, 0x240a },
  8435. { 0x09e8, 0x2424 },
  8436. { 0x09e9, 0x240b },
  8437. { 0x09ea, 0x2518 },
  8438. { 0x09eb, 0x2510 },
  8439. { 0x09ec, 0x250c },
  8440. { 0x09ed, 0x2514 },
  8441. { 0x09ee, 0x253c },
  8442. { 0x09ef, 0x23ba },
  8443. { 0x09f0, 0x23bb },
  8444. { 0x09f1, 0x2500 },
  8445. { 0x09f2, 0x23bc },
  8446. { 0x09f3, 0x23bd },
  8447. { 0x09f4, 0x251c },
  8448. { 0x09f5, 0x2524 },
  8449. { 0x09f6, 0x2534 },
  8450. { 0x09f7, 0x252c },
  8451. { 0x09f8, 0x2502 },
  8452. { 0x0aa1, 0x2003 },
  8453. { 0x0aa2, 0x2002 },
  8454. { 0x0aa3, 0x2004 },
  8455. { 0x0aa4, 0x2005 },
  8456. { 0x0aa5, 0x2007 },
  8457. { 0x0aa6, 0x2008 },
  8458. { 0x0aa7, 0x2009 },
  8459. { 0x0aa8, 0x200a },
  8460. { 0x0aa9, 0x2014 },
  8461. { 0x0aaa, 0x2013 },
  8462. { 0x0aae, 0x2026 },
  8463. { 0x0aaf, 0x2025 },
  8464. { 0x0ab0, 0x2153 },
  8465. { 0x0ab1, 0x2154 },
  8466. { 0x0ab2, 0x2155 },
  8467. { 0x0ab3, 0x2156 },
  8468. { 0x0ab4, 0x2157 },
  8469. { 0x0ab5, 0x2158 },
  8470. { 0x0ab6, 0x2159 },
  8471. { 0x0ab7, 0x215a },
  8472. { 0x0ab8, 0x2105 },
  8473. { 0x0abb, 0x2012 },
  8474. { 0x0abc, 0x2329 },
  8475. { 0x0abe, 0x232a },
  8476. { 0x0ac3, 0x215b },
  8477. { 0x0ac4, 0x215c },
  8478. { 0x0ac5, 0x215d },
  8479. { 0x0ac6, 0x215e },
  8480. { 0x0ac9, 0x2122 },
  8481. { 0x0aca, 0x2613 },
  8482. { 0x0acc, 0x25c1 },
  8483. { 0x0acd, 0x25b7 },
  8484. { 0x0ace, 0x25cb },
  8485. { 0x0acf, 0x25af },
  8486. { 0x0ad0, 0x2018 },
  8487. { 0x0ad1, 0x2019 },
  8488. { 0x0ad2, 0x201c },
  8489. { 0x0ad3, 0x201d },
  8490. { 0x0ad4, 0x211e },
  8491. { 0x0ad6, 0x2032 },
  8492. { 0x0ad7, 0x2033 },
  8493. { 0x0ad9, 0x271d },
  8494. { 0x0adb, 0x25ac },
  8495. { 0x0adc, 0x25c0 },
  8496. { 0x0add, 0x25b6 },
  8497. { 0x0ade, 0x25cf },
  8498. { 0x0adf, 0x25ae },
  8499. { 0x0ae0, 0x25e6 },
  8500. { 0x0ae1, 0x25ab },
  8501. { 0x0ae2, 0x25ad },
  8502. { 0x0ae3, 0x25b3 },
  8503. { 0x0ae4, 0x25bd },
  8504. { 0x0ae5, 0x2606 },
  8505. { 0x0ae6, 0x2022 },
  8506. { 0x0ae7, 0x25aa },
  8507. { 0x0ae8, 0x25b2 },
  8508. { 0x0ae9, 0x25bc },
  8509. { 0x0aea, 0x261c },
  8510. { 0x0aeb, 0x261e },
  8511. { 0x0aec, 0x2663 },
  8512. { 0x0aed, 0x2666 },
  8513. { 0x0aee, 0x2665 },
  8514. { 0x0af0, 0x2720 },
  8515. { 0x0af1, 0x2020 },
  8516. { 0x0af2, 0x2021 },
  8517. { 0x0af3, 0x2713 },
  8518. { 0x0af4, 0x2717 },
  8519. { 0x0af5, 0x266f },
  8520. { 0x0af6, 0x266d },
  8521. { 0x0af7, 0x2642 },
  8522. { 0x0af8, 0x2640 },
  8523. { 0x0af9, 0x260e },
  8524. { 0x0afa, 0x2315 },
  8525. { 0x0afb, 0x2117 },
  8526. { 0x0afc, 0x2038 },
  8527. { 0x0afd, 0x201a },
  8528. { 0x0afe, 0x201e },
  8529. { 0x0ba3, 0x003c },
  8530. { 0x0ba6, 0x003e },
  8531. { 0x0ba8, 0x2228 },
  8532. { 0x0ba9, 0x2227 },
  8533. { 0x0bc0, 0x00af },
  8534. { 0x0bc2, 0x22a5 },
  8535. { 0x0bc3, 0x2229 },
  8536. { 0x0bc4, 0x230a },
  8537. { 0x0bc6, 0x005f },
  8538. { 0x0bca, 0x2218 },
  8539. { 0x0bcc, 0x2395 },
  8540. { 0x0bce, 0x22a4 },
  8541. { 0x0bcf, 0x25cb },
  8542. { 0x0bd3, 0x2308 },
  8543. { 0x0bd6, 0x222a },
  8544. { 0x0bd8, 0x2283 },
  8545. { 0x0bda, 0x2282 },
  8546. { 0x0bdc, 0x22a2 },
  8547. { 0x0bfc, 0x22a3 },
  8548. { 0x0cdf, 0x2017 },
  8549. { 0x0ce0, 0x05d0 },
  8550. { 0x0ce1, 0x05d1 },
  8551. { 0x0ce2, 0x05d2 },
  8552. { 0x0ce3, 0x05d3 },
  8553. { 0x0ce4, 0x05d4 },
  8554. { 0x0ce5, 0x05d5 },
  8555. { 0x0ce6, 0x05d6 },
  8556. { 0x0ce7, 0x05d7 },
  8557. { 0x0ce8, 0x05d8 },
  8558. { 0x0ce9, 0x05d9 },
  8559. { 0x0cea, 0x05da },
  8560. { 0x0ceb, 0x05db },
  8561. { 0x0cec, 0x05dc },
  8562. { 0x0ced, 0x05dd },
  8563. { 0x0cee, 0x05de },
  8564. { 0x0cef, 0x05df },
  8565. { 0x0cf0, 0x05e0 },
  8566. { 0x0cf1, 0x05e1 },
  8567. { 0x0cf2, 0x05e2 },
  8568. { 0x0cf3, 0x05e3 },
  8569. { 0x0cf4, 0x05e4 },
  8570. { 0x0cf5, 0x05e5 },
  8571. { 0x0cf6, 0x05e6 },
  8572. { 0x0cf7, 0x05e7 },
  8573. { 0x0cf8, 0x05e8 },
  8574. { 0x0cf9, 0x05e9 },
  8575. { 0x0cfa, 0x05ea },
  8576. { 0x0da1, 0x0e01 },
  8577. { 0x0da2, 0x0e02 },
  8578. { 0x0da3, 0x0e03 },
  8579. { 0x0da4, 0x0e04 },
  8580. { 0x0da5, 0x0e05 },
  8581. { 0x0da6, 0x0e06 },
  8582. { 0x0da7, 0x0e07 },
  8583. { 0x0da8, 0x0e08 },
  8584. { 0x0da9, 0x0e09 },
  8585. { 0x0daa, 0x0e0a },
  8586. { 0x0dab, 0x0e0b },
  8587. { 0x0dac, 0x0e0c },
  8588. { 0x0dad, 0x0e0d },
  8589. { 0x0dae, 0x0e0e },
  8590. { 0x0daf, 0x0e0f },
  8591. { 0x0db0, 0x0e10 },
  8592. { 0x0db1, 0x0e11 },
  8593. { 0x0db2, 0x0e12 },
  8594. { 0x0db3, 0x0e13 },
  8595. { 0x0db4, 0x0e14 },
  8596. { 0x0db5, 0x0e15 },
  8597. { 0x0db6, 0x0e16 },
  8598. { 0x0db7, 0x0e17 },
  8599. { 0x0db8, 0x0e18 },
  8600. { 0x0db9, 0x0e19 },
  8601. { 0x0dba, 0x0e1a },
  8602. { 0x0dbb, 0x0e1b },
  8603. { 0x0dbc, 0x0e1c },
  8604. { 0x0dbd, 0x0e1d },
  8605. { 0x0dbe, 0x0e1e },
  8606. { 0x0dbf, 0x0e1f },
  8607. { 0x0dc0, 0x0e20 },
  8608. { 0x0dc1, 0x0e21 },
  8609. { 0x0dc2, 0x0e22 },
  8610. { 0x0dc3, 0x0e23 },
  8611. { 0x0dc4, 0x0e24 },
  8612. { 0x0dc5, 0x0e25 },
  8613. { 0x0dc6, 0x0e26 },
  8614. { 0x0dc7, 0x0e27 },
  8615. { 0x0dc8, 0x0e28 },
  8616. { 0x0dc9, 0x0e29 },
  8617. { 0x0dca, 0x0e2a },
  8618. { 0x0dcb, 0x0e2b },
  8619. { 0x0dcc, 0x0e2c },
  8620. { 0x0dcd, 0x0e2d },
  8621. { 0x0dce, 0x0e2e },
  8622. { 0x0dcf, 0x0e2f },
  8623. { 0x0dd0, 0x0e30 },
  8624. { 0x0dd1, 0x0e31 },
  8625. { 0x0dd2, 0x0e32 },
  8626. { 0x0dd3, 0x0e33 },
  8627. { 0x0dd4, 0x0e34 },
  8628. { 0x0dd5, 0x0e35 },
  8629. { 0x0dd6, 0x0e36 },
  8630. { 0x0dd7, 0x0e37 },
  8631. { 0x0dd8, 0x0e38 },
  8632. { 0x0dd9, 0x0e39 },
  8633. { 0x0dda, 0x0e3a },
  8634. { 0x0ddf, 0x0e3f },
  8635. { 0x0de0, 0x0e40 },
  8636. { 0x0de1, 0x0e41 },
  8637. { 0x0de2, 0x0e42 },
  8638. { 0x0de3, 0x0e43 },
  8639. { 0x0de4, 0x0e44 },
  8640. { 0x0de5, 0x0e45 },
  8641. { 0x0de6, 0x0e46 },
  8642. { 0x0de7, 0x0e47 },
  8643. { 0x0de8, 0x0e48 },
  8644. { 0x0de9, 0x0e49 },
  8645. { 0x0dea, 0x0e4a },
  8646. { 0x0deb, 0x0e4b },
  8647. { 0x0dec, 0x0e4c },
  8648. { 0x0ded, 0x0e4d },
  8649. { 0x0df0, 0x0e50 },
  8650. { 0x0df1, 0x0e51 },
  8651. { 0x0df2, 0x0e52 },
  8652. { 0x0df3, 0x0e53 },
  8653. { 0x0df4, 0x0e54 },
  8654. { 0x0df5, 0x0e55 },
  8655. { 0x0df6, 0x0e56 },
  8656. { 0x0df7, 0x0e57 },
  8657. { 0x0df8, 0x0e58 },
  8658. { 0x0df9, 0x0e59 },
  8659. { 0x0ea1, 0x3131 },
  8660. { 0x0ea2, 0x3132 },
  8661. { 0x0ea3, 0x3133 },
  8662. { 0x0ea4, 0x3134 },
  8663. { 0x0ea5, 0x3135 },
  8664. { 0x0ea6, 0x3136 },
  8665. { 0x0ea7, 0x3137 },
  8666. { 0x0ea8, 0x3138 },
  8667. { 0x0ea9, 0x3139 },
  8668. { 0x0eaa, 0x313a },
  8669. { 0x0eab, 0x313b },
  8670. { 0x0eac, 0x313c },
  8671. { 0x0ead, 0x313d },
  8672. { 0x0eae, 0x313e },
  8673. { 0x0eaf, 0x313f },
  8674. { 0x0eb0, 0x3140 },
  8675. { 0x0eb1, 0x3141 },
  8676. { 0x0eb2, 0x3142 },
  8677. { 0x0eb3, 0x3143 },
  8678. { 0x0eb4, 0x3144 },
  8679. { 0x0eb5, 0x3145 },
  8680. { 0x0eb6, 0x3146 },
  8681. { 0x0eb7, 0x3147 },
  8682. { 0x0eb8, 0x3148 },
  8683. { 0x0eb9, 0x3149 },
  8684. { 0x0eba, 0x314a },
  8685. { 0x0ebb, 0x314b },
  8686. { 0x0ebc, 0x314c },
  8687. { 0x0ebd, 0x314d },
  8688. { 0x0ebe, 0x314e },
  8689. { 0x0ebf, 0x314f },
  8690. { 0x0ec0, 0x3150 },
  8691. { 0x0ec1, 0x3151 },
  8692. { 0x0ec2, 0x3152 },
  8693. { 0x0ec3, 0x3153 },
  8694. { 0x0ec4, 0x3154 },
  8695. { 0x0ec5, 0x3155 },
  8696. { 0x0ec6, 0x3156 },
  8697. { 0x0ec7, 0x3157 },
  8698. { 0x0ec8, 0x3158 },
  8699. { 0x0ec9, 0x3159 },
  8700. { 0x0eca, 0x315a },
  8701. { 0x0ecb, 0x315b },
  8702. { 0x0ecc, 0x315c },
  8703. { 0x0ecd, 0x315d },
  8704. { 0x0ece, 0x315e },
  8705. { 0x0ecf, 0x315f },
  8706. { 0x0ed0, 0x3160 },
  8707. { 0x0ed1, 0x3161 },
  8708. { 0x0ed2, 0x3162 },
  8709. { 0x0ed3, 0x3163 },
  8710. { 0x0ed4, 0x11a8 },
  8711. { 0x0ed5, 0x11a9 },
  8712. { 0x0ed6, 0x11aa },
  8713. { 0x0ed7, 0x11ab },
  8714. { 0x0ed8, 0x11ac },
  8715. { 0x0ed9, 0x11ad },
  8716. { 0x0eda, 0x11ae },
  8717. { 0x0edb, 0x11af },
  8718. { 0x0edc, 0x11b0 },
  8719. { 0x0edd, 0x11b1 },
  8720. { 0x0ede, 0x11b2 },
  8721. { 0x0edf, 0x11b3 },
  8722. { 0x0ee0, 0x11b4 },
  8723. { 0x0ee1, 0x11b5 },
  8724. { 0x0ee2, 0x11b6 },
  8725. { 0x0ee3, 0x11b7 },
  8726. { 0x0ee4, 0x11b8 },
  8727. { 0x0ee5, 0x11b9 },
  8728. { 0x0ee6, 0x11ba },
  8729. { 0x0ee7, 0x11bb },
  8730. { 0x0ee8, 0x11bc },
  8731. { 0x0ee9, 0x11bd },
  8732. { 0x0eea, 0x11be },
  8733. { 0x0eeb, 0x11bf },
  8734. { 0x0eec, 0x11c0 },
  8735. { 0x0eed, 0x11c1 },
  8736. { 0x0eee, 0x11c2 },
  8737. { 0x0eef, 0x316d },
  8738. { 0x0ef0, 0x3171 },
  8739. { 0x0ef1, 0x3178 },
  8740. { 0x0ef2, 0x317f },
  8741. { 0x0ef3, 0x3181 },
  8742. { 0x0ef4, 0x3184 },
  8743. { 0x0ef5, 0x3186 },
  8744. { 0x0ef6, 0x318d },
  8745. { 0x0ef7, 0x318e },
  8746. { 0x0ef8, 0x11eb },
  8747. { 0x0ef9, 0x11f0 },
  8748. { 0x0efa, 0x11f9 },
  8749. { 0x0eff, 0x20a9 },
  8750. { 0x13a4, 0x20ac },
  8751. { 0x13bc, 0x0152 },
  8752. { 0x13bd, 0x0153 },
  8753. { 0x13be, 0x0178 },
  8754. { 0x20ac, 0x20ac },
  8755. { 0xfe50, '`' },
  8756. { 0xfe51, 0x00b4 },
  8757. { 0xfe52, '^' },
  8758. { 0xfe53, '~' },
  8759. { 0xfe54, 0x00af },
  8760. { 0xfe55, 0x02d8 },
  8761. { 0xfe56, 0x02d9 },
  8762. { 0xfe57, 0x00a8 },
  8763. { 0xfe58, 0x02da },
  8764. { 0xfe59, 0x02dd },
  8765. { 0xfe5a, 0x02c7 },
  8766. { 0xfe5b, 0x00b8 },
  8767. { 0xfe5c, 0x02db },
  8768. { 0xfe5d, 0x037a },
  8769. { 0xfe5e, 0x309b },
  8770. { 0xfe5f, 0x309c },
  8771. { 0xfe63, '/' },
  8772. { 0xfe64, 0x02bc },
  8773. { 0xfe65, 0x02bd },
  8774. { 0xfe66, 0x02f5 },
  8775. { 0xfe67, 0x02f3 },
  8776. { 0xfe68, 0x02cd },
  8777. { 0xfe69, 0xa788 },
  8778. { 0xfe6a, 0x02f7 },
  8779. { 0xfe6e, ',' },
  8780. { 0xfe6f, 0x00a4 },
  8781. { 0xfe80, 'a' }, /* XK_dead_a */
  8782. { 0xfe81, 'A' }, /* XK_dead_A */
  8783. { 0xfe82, 'e' }, /* XK_dead_e */
  8784. { 0xfe83, 'E' }, /* XK_dead_E */
  8785. { 0xfe84, 'i' }, /* XK_dead_i */
  8786. { 0xfe85, 'I' }, /* XK_dead_I */
  8787. { 0xfe86, 'o' }, /* XK_dead_o */
  8788. { 0xfe87, 'O' }, /* XK_dead_O */
  8789. { 0xfe88, 'u' }, /* XK_dead_u */
  8790. { 0xfe89, 'U' }, /* XK_dead_U */
  8791. { 0xfe8a, 0x0259 },
  8792. { 0xfe8b, 0x018f },
  8793. { 0xfe8c, 0x00b5 },
  8794. { 0xfe90, '_' },
  8795. { 0xfe91, 0x02c8 },
  8796. { 0xfe92, 0x02cc },
  8797. { 0xff80 /*XKB_KEY_KP_Space*/, ' ' },
  8798. { 0xff95 /*XKB_KEY_KP_7*/, 0x0037 },
  8799. { 0xff96 /*XKB_KEY_KP_4*/, 0x0034 },
  8800. { 0xff97 /*XKB_KEY_KP_8*/, 0x0038 },
  8801. { 0xff98 /*XKB_KEY_KP_6*/, 0x0036 },
  8802. { 0xff99 /*XKB_KEY_KP_2*/, 0x0032 },
  8803. { 0xff9a /*XKB_KEY_KP_9*/, 0x0039 },
  8804. { 0xff9b /*XKB_KEY_KP_3*/, 0x0033 },
  8805. { 0xff9c /*XKB_KEY_KP_1*/, 0x0031 },
  8806. { 0xff9d /*XKB_KEY_KP_5*/, 0x0035 },
  8807. { 0xff9e /*XKB_KEY_KP_0*/, 0x0030 },
  8808. { 0xffaa /*XKB_KEY_KP_Multiply*/, '*' },
  8809. { 0xffab /*XKB_KEY_KP_Add*/, '+' },
  8810. { 0xffac /*XKB_KEY_KP_Separator*/, ',' },
  8811. { 0xffad /*XKB_KEY_KP_Subtract*/, '-' },
  8812. { 0xffae /*XKB_KEY_KP_Decimal*/, '.' },
  8813. { 0xffaf /*XKB_KEY_KP_Divide*/, '/' },
  8814. { 0xffb0 /*XKB_KEY_KP_0*/, 0x0030 },
  8815. { 0xffb1 /*XKB_KEY_KP_1*/, 0x0031 },
  8816. { 0xffb2 /*XKB_KEY_KP_2*/, 0x0032 },
  8817. { 0xffb3 /*XKB_KEY_KP_3*/, 0x0033 },
  8818. { 0xffb4 /*XKB_KEY_KP_4*/, 0x0034 },
  8819. { 0xffb5 /*XKB_KEY_KP_5*/, 0x0035 },
  8820. { 0xffb6 /*XKB_KEY_KP_6*/, 0x0036 },
  8821. { 0xffb7 /*XKB_KEY_KP_7*/, 0x0037 },
  8822. { 0xffb8 /*XKB_KEY_KP_8*/, 0x0038 },
  8823. { 0xffb9 /*XKB_KEY_KP_9*/, 0x0039 },
  8824. { 0xffbd /*XKB_KEY_KP_Equal*/, '=' }
  8825. };
  8826. _SOKOL_PRIVATE int _sapp_x11_error_handler(Display* display, XErrorEvent* event) {
  8827. _SOKOL_UNUSED(display);
  8828. _sapp.x11.error_code = event->error_code;
  8829. return 0;
  8830. }
  8831. _SOKOL_PRIVATE void _sapp_x11_grab_error_handler(void) {
  8832. _sapp.x11.error_code = Success;
  8833. XSetErrorHandler(_sapp_x11_error_handler);
  8834. }
  8835. _SOKOL_PRIVATE void _sapp_x11_release_error_handler(void) {
  8836. XSync(_sapp.x11.display, False);
  8837. XSetErrorHandler(NULL);
  8838. }
  8839. _SOKOL_PRIVATE void _sapp_x11_init_extensions(void) {
  8840. _sapp.x11.UTF8_STRING = XInternAtom(_sapp.x11.display, "UTF8_STRING", False);
  8841. _sapp.x11.WM_PROTOCOLS = XInternAtom(_sapp.x11.display, "WM_PROTOCOLS", False);
  8842. _sapp.x11.WM_DELETE_WINDOW = XInternAtom(_sapp.x11.display, "WM_DELETE_WINDOW", False);
  8843. _sapp.x11.WM_STATE = XInternAtom(_sapp.x11.display, "WM_STATE", False);
  8844. _sapp.x11.NET_WM_NAME = XInternAtom(_sapp.x11.display, "_NET_WM_NAME", False);
  8845. _sapp.x11.NET_WM_ICON_NAME = XInternAtom(_sapp.x11.display, "_NET_WM_ICON_NAME", False);
  8846. _sapp.x11.NET_WM_ICON = XInternAtom(_sapp.x11.display, "_NET_WM_ICON", False);
  8847. _sapp.x11.NET_WM_STATE = XInternAtom(_sapp.x11.display, "_NET_WM_STATE", False);
  8848. _sapp.x11.NET_WM_STATE_FULLSCREEN = XInternAtom(_sapp.x11.display, "_NET_WM_STATE_FULLSCREEN", False);
  8849. _sapp.x11.CLIPBOARD = XInternAtom(_sapp.x11.display, "CLIPBOARD", False);
  8850. _sapp.x11.TARGETS = XInternAtom(_sapp.x11.display, "TARGETS", False);
  8851. if (_sapp.drop.enabled) {
  8852. _sapp.x11.xdnd.XdndAware = XInternAtom(_sapp.x11.display, "XdndAware", False);
  8853. _sapp.x11.xdnd.XdndEnter = XInternAtom(_sapp.x11.display, "XdndEnter", False);
  8854. _sapp.x11.xdnd.XdndPosition = XInternAtom(_sapp.x11.display, "XdndPosition", False);
  8855. _sapp.x11.xdnd.XdndStatus = XInternAtom(_sapp.x11.display, "XdndStatus", False);
  8856. _sapp.x11.xdnd.XdndActionCopy = XInternAtom(_sapp.x11.display, "XdndActionCopy", False);
  8857. _sapp.x11.xdnd.XdndDrop = XInternAtom(_sapp.x11.display, "XdndDrop", False);
  8858. _sapp.x11.xdnd.XdndFinished = XInternAtom(_sapp.x11.display, "XdndFinished", False);
  8859. _sapp.x11.xdnd.XdndSelection = XInternAtom(_sapp.x11.display, "XdndSelection", False);
  8860. _sapp.x11.xdnd.XdndTypeList = XInternAtom(_sapp.x11.display, "XdndTypeList", False);
  8861. _sapp.x11.xdnd.text_uri_list = XInternAtom(_sapp.x11.display, "text/uri-list", False);
  8862. }
  8863. /* check Xi extension for raw mouse input */
  8864. if (XQueryExtension(_sapp.x11.display, "XInputExtension", &_sapp.x11.xi.major_opcode, &_sapp.x11.xi.event_base, &_sapp.x11.xi.error_base)) {
  8865. _sapp.x11.xi.major = 2;
  8866. _sapp.x11.xi.minor = 0;
  8867. if (XIQueryVersion(_sapp.x11.display, &_sapp.x11.xi.major, &_sapp.x11.xi.minor) == Success) {
  8868. _sapp.x11.xi.available = true;
  8869. }
  8870. }
  8871. }
  8872. // translate the X11 KeySyms for a key to sokol-app key code
  8873. // NOTE: this is only used as a fallback, in case the XBK method fails
  8874. // it is layout-dependent and will fail partially on most non-US layouts.
  8875. //
  8876. _SOKOL_PRIVATE sapp_keycode _sapp_x11_translate_keysyms(const KeySym* keysyms, int width) {
  8877. if (width > 1) {
  8878. switch (keysyms[1]) {
  8879. case XK_KP_0: return SAPP_KEYCODE_KP_0;
  8880. case XK_KP_1: return SAPP_KEYCODE_KP_1;
  8881. case XK_KP_2: return SAPP_KEYCODE_KP_2;
  8882. case XK_KP_3: return SAPP_KEYCODE_KP_3;
  8883. case XK_KP_4: return SAPP_KEYCODE_KP_4;
  8884. case XK_KP_5: return SAPP_KEYCODE_KP_5;
  8885. case XK_KP_6: return SAPP_KEYCODE_KP_6;
  8886. case XK_KP_7: return SAPP_KEYCODE_KP_7;
  8887. case XK_KP_8: return SAPP_KEYCODE_KP_8;
  8888. case XK_KP_9: return SAPP_KEYCODE_KP_9;
  8889. case XK_KP_Separator:
  8890. case XK_KP_Decimal: return SAPP_KEYCODE_KP_DECIMAL;
  8891. case XK_KP_Equal: return SAPP_KEYCODE_KP_EQUAL;
  8892. case XK_KP_Enter: return SAPP_KEYCODE_KP_ENTER;
  8893. default: break;
  8894. }
  8895. }
  8896. switch (keysyms[0]) {
  8897. case XK_Escape: return SAPP_KEYCODE_ESCAPE;
  8898. case XK_Tab: return SAPP_KEYCODE_TAB;
  8899. case XK_Shift_L: return SAPP_KEYCODE_LEFT_SHIFT;
  8900. case XK_Shift_R: return SAPP_KEYCODE_RIGHT_SHIFT;
  8901. case XK_Control_L: return SAPP_KEYCODE_LEFT_CONTROL;
  8902. case XK_Control_R: return SAPP_KEYCODE_RIGHT_CONTROL;
  8903. case XK_Meta_L:
  8904. case XK_Alt_L: return SAPP_KEYCODE_LEFT_ALT;
  8905. case XK_Mode_switch: // Mapped to Alt_R on many keyboards
  8906. case XK_ISO_Level3_Shift: // AltGr on at least some machines
  8907. case XK_Meta_R:
  8908. case XK_Alt_R: return SAPP_KEYCODE_RIGHT_ALT;
  8909. case XK_Super_L: return SAPP_KEYCODE_LEFT_SUPER;
  8910. case XK_Super_R: return SAPP_KEYCODE_RIGHT_SUPER;
  8911. case XK_Menu: return SAPP_KEYCODE_MENU;
  8912. case XK_Num_Lock: return SAPP_KEYCODE_NUM_LOCK;
  8913. case XK_Caps_Lock: return SAPP_KEYCODE_CAPS_LOCK;
  8914. case XK_Print: return SAPP_KEYCODE_PRINT_SCREEN;
  8915. case XK_Scroll_Lock: return SAPP_KEYCODE_SCROLL_LOCK;
  8916. case XK_Pause: return SAPP_KEYCODE_PAUSE;
  8917. case XK_Delete: return SAPP_KEYCODE_DELETE;
  8918. case XK_BackSpace: return SAPP_KEYCODE_BACKSPACE;
  8919. case XK_Return: return SAPP_KEYCODE_ENTER;
  8920. case XK_Home: return SAPP_KEYCODE_HOME;
  8921. case XK_End: return SAPP_KEYCODE_END;
  8922. case XK_Page_Up: return SAPP_KEYCODE_PAGE_UP;
  8923. case XK_Page_Down: return SAPP_KEYCODE_PAGE_DOWN;
  8924. case XK_Insert: return SAPP_KEYCODE_INSERT;
  8925. case XK_Left: return SAPP_KEYCODE_LEFT;
  8926. case XK_Right: return SAPP_KEYCODE_RIGHT;
  8927. case XK_Down: return SAPP_KEYCODE_DOWN;
  8928. case XK_Up: return SAPP_KEYCODE_UP;
  8929. case XK_F1: return SAPP_KEYCODE_F1;
  8930. case XK_F2: return SAPP_KEYCODE_F2;
  8931. case XK_F3: return SAPP_KEYCODE_F3;
  8932. case XK_F4: return SAPP_KEYCODE_F4;
  8933. case XK_F5: return SAPP_KEYCODE_F5;
  8934. case XK_F6: return SAPP_KEYCODE_F6;
  8935. case XK_F7: return SAPP_KEYCODE_F7;
  8936. case XK_F8: return SAPP_KEYCODE_F8;
  8937. case XK_F9: return SAPP_KEYCODE_F9;
  8938. case XK_F10: return SAPP_KEYCODE_F10;
  8939. case XK_F11: return SAPP_KEYCODE_F11;
  8940. case XK_F12: return SAPP_KEYCODE_F12;
  8941. case XK_F13: return SAPP_KEYCODE_F13;
  8942. case XK_F14: return SAPP_KEYCODE_F14;
  8943. case XK_F15: return SAPP_KEYCODE_F15;
  8944. case XK_F16: return SAPP_KEYCODE_F16;
  8945. case XK_F17: return SAPP_KEYCODE_F17;
  8946. case XK_F18: return SAPP_KEYCODE_F18;
  8947. case XK_F19: return SAPP_KEYCODE_F19;
  8948. case XK_F20: return SAPP_KEYCODE_F20;
  8949. case XK_F21: return SAPP_KEYCODE_F21;
  8950. case XK_F22: return SAPP_KEYCODE_F22;
  8951. case XK_F23: return SAPP_KEYCODE_F23;
  8952. case XK_F24: return SAPP_KEYCODE_F24;
  8953. case XK_F25: return SAPP_KEYCODE_F25;
  8954. // numeric keypad
  8955. case XK_KP_Divide: return SAPP_KEYCODE_KP_DIVIDE;
  8956. case XK_KP_Multiply: return SAPP_KEYCODE_KP_MULTIPLY;
  8957. case XK_KP_Subtract: return SAPP_KEYCODE_KP_SUBTRACT;
  8958. case XK_KP_Add: return SAPP_KEYCODE_KP_ADD;
  8959. // these should have been detected in secondary keysym test above!
  8960. case XK_KP_Insert: return SAPP_KEYCODE_KP_0;
  8961. case XK_KP_End: return SAPP_KEYCODE_KP_1;
  8962. case XK_KP_Down: return SAPP_KEYCODE_KP_2;
  8963. case XK_KP_Page_Down: return SAPP_KEYCODE_KP_3;
  8964. case XK_KP_Left: return SAPP_KEYCODE_KP_4;
  8965. case XK_KP_Right: return SAPP_KEYCODE_KP_6;
  8966. case XK_KP_Home: return SAPP_KEYCODE_KP_7;
  8967. case XK_KP_Up: return SAPP_KEYCODE_KP_8;
  8968. case XK_KP_Page_Up: return SAPP_KEYCODE_KP_9;
  8969. case XK_KP_Delete: return SAPP_KEYCODE_KP_DECIMAL;
  8970. case XK_KP_Equal: return SAPP_KEYCODE_KP_EQUAL;
  8971. case XK_KP_Enter: return SAPP_KEYCODE_KP_ENTER;
  8972. // last resort: Check for printable keys (should not happen if the XKB
  8973. // extension is available). This will give a layout dependent mapping
  8974. // (which is wrong, and we may miss some keys, especially on non-US
  8975. // keyboards), but it's better than nothing...
  8976. case XK_a: return SAPP_KEYCODE_A;
  8977. case XK_b: return SAPP_KEYCODE_B;
  8978. case XK_c: return SAPP_KEYCODE_C;
  8979. case XK_d: return SAPP_KEYCODE_D;
  8980. case XK_e: return SAPP_KEYCODE_E;
  8981. case XK_f: return SAPP_KEYCODE_F;
  8982. case XK_g: return SAPP_KEYCODE_G;
  8983. case XK_h: return SAPP_KEYCODE_H;
  8984. case XK_i: return SAPP_KEYCODE_I;
  8985. case XK_j: return SAPP_KEYCODE_J;
  8986. case XK_k: return SAPP_KEYCODE_K;
  8987. case XK_l: return SAPP_KEYCODE_L;
  8988. case XK_m: return SAPP_KEYCODE_M;
  8989. case XK_n: return SAPP_KEYCODE_N;
  8990. case XK_o: return SAPP_KEYCODE_O;
  8991. case XK_p: return SAPP_KEYCODE_P;
  8992. case XK_q: return SAPP_KEYCODE_Q;
  8993. case XK_r: return SAPP_KEYCODE_R;
  8994. case XK_s: return SAPP_KEYCODE_S;
  8995. case XK_t: return SAPP_KEYCODE_T;
  8996. case XK_u: return SAPP_KEYCODE_U;
  8997. case XK_v: return SAPP_KEYCODE_V;
  8998. case XK_w: return SAPP_KEYCODE_W;
  8999. case XK_x: return SAPP_KEYCODE_X;
  9000. case XK_y: return SAPP_KEYCODE_Y;
  9001. case XK_z: return SAPP_KEYCODE_Z;
  9002. case XK_1: return SAPP_KEYCODE_1;
  9003. case XK_2: return SAPP_KEYCODE_2;
  9004. case XK_3: return SAPP_KEYCODE_3;
  9005. case XK_4: return SAPP_KEYCODE_4;
  9006. case XK_5: return SAPP_KEYCODE_5;
  9007. case XK_6: return SAPP_KEYCODE_6;
  9008. case XK_7: return SAPP_KEYCODE_7;
  9009. case XK_8: return SAPP_KEYCODE_8;
  9010. case XK_9: return SAPP_KEYCODE_9;
  9011. case XK_0: return SAPP_KEYCODE_0;
  9012. case XK_space: return SAPP_KEYCODE_SPACE;
  9013. case XK_minus: return SAPP_KEYCODE_MINUS;
  9014. case XK_equal: return SAPP_KEYCODE_EQUAL;
  9015. case XK_bracketleft: return SAPP_KEYCODE_LEFT_BRACKET;
  9016. case XK_bracketright: return SAPP_KEYCODE_RIGHT_BRACKET;
  9017. case XK_backslash: return SAPP_KEYCODE_BACKSLASH;
  9018. case XK_semicolon: return SAPP_KEYCODE_SEMICOLON;
  9019. case XK_apostrophe: return SAPP_KEYCODE_APOSTROPHE;
  9020. case XK_grave: return SAPP_KEYCODE_GRAVE_ACCENT;
  9021. case XK_comma: return SAPP_KEYCODE_COMMA;
  9022. case XK_period: return SAPP_KEYCODE_PERIOD;
  9023. case XK_slash: return SAPP_KEYCODE_SLASH;
  9024. case XK_less: return SAPP_KEYCODE_WORLD_1; // At least in some layouts...
  9025. default: break;
  9026. }
  9027. // no matching translation was found
  9028. return SAPP_KEYCODE_INVALID;
  9029. }
  9030. // setup dynamic keycode/scancode mapping tables, this is required
  9031. // for getting layout-independent keycodes on X11.
  9032. //
  9033. // see GLFW x11_init.c/createKeyTables()
  9034. _SOKOL_PRIVATE void _sapp_x11_init_keytable(void) {
  9035. for (int i = 0; i < SAPP_MAX_KEYCODES; i++) {
  9036. _sapp.keycodes[i] = SAPP_KEYCODE_INVALID;
  9037. }
  9038. // use XKB to determine physical key locations independently of the current keyboard layout
  9039. XkbDescPtr desc = XkbGetMap(_sapp.x11.display, 0, XkbUseCoreKbd);
  9040. SOKOL_ASSERT(desc);
  9041. XkbGetNames(_sapp.x11.display, XkbKeyNamesMask | XkbKeyAliasesMask, desc);
  9042. const int scancode_min = desc->min_key_code;
  9043. const int scancode_max = desc->max_key_code;
  9044. const struct { sapp_keycode key; const char* name; } keymap[] = {
  9045. { SAPP_KEYCODE_GRAVE_ACCENT, "TLDE" },
  9046. { SAPP_KEYCODE_1, "AE01" },
  9047. { SAPP_KEYCODE_2, "AE02" },
  9048. { SAPP_KEYCODE_3, "AE03" },
  9049. { SAPP_KEYCODE_4, "AE04" },
  9050. { SAPP_KEYCODE_5, "AE05" },
  9051. { SAPP_KEYCODE_6, "AE06" },
  9052. { SAPP_KEYCODE_7, "AE07" },
  9053. { SAPP_KEYCODE_8, "AE08" },
  9054. { SAPP_KEYCODE_9, "AE09" },
  9055. { SAPP_KEYCODE_0, "AE10" },
  9056. { SAPP_KEYCODE_MINUS, "AE11" },
  9057. { SAPP_KEYCODE_EQUAL, "AE12" },
  9058. { SAPP_KEYCODE_Q, "AD01" },
  9059. { SAPP_KEYCODE_W, "AD02" },
  9060. { SAPP_KEYCODE_E, "AD03" },
  9061. { SAPP_KEYCODE_R, "AD04" },
  9062. { SAPP_KEYCODE_T, "AD05" },
  9063. { SAPP_KEYCODE_Y, "AD06" },
  9064. { SAPP_KEYCODE_U, "AD07" },
  9065. { SAPP_KEYCODE_I, "AD08" },
  9066. { SAPP_KEYCODE_O, "AD09" },
  9067. { SAPP_KEYCODE_P, "AD10" },
  9068. { SAPP_KEYCODE_LEFT_BRACKET, "AD11" },
  9069. { SAPP_KEYCODE_RIGHT_BRACKET, "AD12" },
  9070. { SAPP_KEYCODE_A, "AC01" },
  9071. { SAPP_KEYCODE_S, "AC02" },
  9072. { SAPP_KEYCODE_D, "AC03" },
  9073. { SAPP_KEYCODE_F, "AC04" },
  9074. { SAPP_KEYCODE_G, "AC05" },
  9075. { SAPP_KEYCODE_H, "AC06" },
  9076. { SAPP_KEYCODE_J, "AC07" },
  9077. { SAPP_KEYCODE_K, "AC08" },
  9078. { SAPP_KEYCODE_L, "AC09" },
  9079. { SAPP_KEYCODE_SEMICOLON, "AC10" },
  9080. { SAPP_KEYCODE_APOSTROPHE, "AC11" },
  9081. { SAPP_KEYCODE_Z, "AB01" },
  9082. { SAPP_KEYCODE_X, "AB02" },
  9083. { SAPP_KEYCODE_C, "AB03" },
  9084. { SAPP_KEYCODE_V, "AB04" },
  9085. { SAPP_KEYCODE_B, "AB05" },
  9086. { SAPP_KEYCODE_N, "AB06" },
  9087. { SAPP_KEYCODE_M, "AB07" },
  9088. { SAPP_KEYCODE_COMMA, "AB08" },
  9089. { SAPP_KEYCODE_PERIOD, "AB09" },
  9090. { SAPP_KEYCODE_SLASH, "AB10" },
  9091. { SAPP_KEYCODE_BACKSLASH, "BKSL" },
  9092. { SAPP_KEYCODE_WORLD_1, "LSGT" },
  9093. { SAPP_KEYCODE_SPACE, "SPCE" },
  9094. { SAPP_KEYCODE_ESCAPE, "ESC" },
  9095. { SAPP_KEYCODE_ENTER, "RTRN" },
  9096. { SAPP_KEYCODE_TAB, "TAB" },
  9097. { SAPP_KEYCODE_BACKSPACE, "BKSP" },
  9098. { SAPP_KEYCODE_INSERT, "INS" },
  9099. { SAPP_KEYCODE_DELETE, "DELE" },
  9100. { SAPP_KEYCODE_RIGHT, "RGHT" },
  9101. { SAPP_KEYCODE_LEFT, "LEFT" },
  9102. { SAPP_KEYCODE_DOWN, "DOWN" },
  9103. { SAPP_KEYCODE_UP, "UP" },
  9104. { SAPP_KEYCODE_PAGE_UP, "PGUP" },
  9105. { SAPP_KEYCODE_PAGE_DOWN, "PGDN" },
  9106. { SAPP_KEYCODE_HOME, "HOME" },
  9107. { SAPP_KEYCODE_END, "END" },
  9108. { SAPP_KEYCODE_CAPS_LOCK, "CAPS" },
  9109. { SAPP_KEYCODE_SCROLL_LOCK, "SCLK" },
  9110. { SAPP_KEYCODE_NUM_LOCK, "NMLK" },
  9111. { SAPP_KEYCODE_PRINT_SCREEN, "PRSC" },
  9112. { SAPP_KEYCODE_PAUSE, "PAUS" },
  9113. { SAPP_KEYCODE_F1, "FK01" },
  9114. { SAPP_KEYCODE_F2, "FK02" },
  9115. { SAPP_KEYCODE_F3, "FK03" },
  9116. { SAPP_KEYCODE_F4, "FK04" },
  9117. { SAPP_KEYCODE_F5, "FK05" },
  9118. { SAPP_KEYCODE_F6, "FK06" },
  9119. { SAPP_KEYCODE_F7, "FK07" },
  9120. { SAPP_KEYCODE_F8, "FK08" },
  9121. { SAPP_KEYCODE_F9, "FK09" },
  9122. { SAPP_KEYCODE_F10, "FK10" },
  9123. { SAPP_KEYCODE_F11, "FK11" },
  9124. { SAPP_KEYCODE_F12, "FK12" },
  9125. { SAPP_KEYCODE_F13, "FK13" },
  9126. { SAPP_KEYCODE_F14, "FK14" },
  9127. { SAPP_KEYCODE_F15, "FK15" },
  9128. { SAPP_KEYCODE_F16, "FK16" },
  9129. { SAPP_KEYCODE_F17, "FK17" },
  9130. { SAPP_KEYCODE_F18, "FK18" },
  9131. { SAPP_KEYCODE_F19, "FK19" },
  9132. { SAPP_KEYCODE_F20, "FK20" },
  9133. { SAPP_KEYCODE_F21, "FK21" },
  9134. { SAPP_KEYCODE_F22, "FK22" },
  9135. { SAPP_KEYCODE_F23, "FK23" },
  9136. { SAPP_KEYCODE_F24, "FK24" },
  9137. { SAPP_KEYCODE_F25, "FK25" },
  9138. { SAPP_KEYCODE_KP_0, "KP0" },
  9139. { SAPP_KEYCODE_KP_1, "KP1" },
  9140. { SAPP_KEYCODE_KP_2, "KP2" },
  9141. { SAPP_KEYCODE_KP_3, "KP3" },
  9142. { SAPP_KEYCODE_KP_4, "KP4" },
  9143. { SAPP_KEYCODE_KP_5, "KP5" },
  9144. { SAPP_KEYCODE_KP_6, "KP6" },
  9145. { SAPP_KEYCODE_KP_7, "KP7" },
  9146. { SAPP_KEYCODE_KP_8, "KP8" },
  9147. { SAPP_KEYCODE_KP_9, "KP9" },
  9148. { SAPP_KEYCODE_KP_DECIMAL, "KPDL" },
  9149. { SAPP_KEYCODE_KP_DIVIDE, "KPDV" },
  9150. { SAPP_KEYCODE_KP_MULTIPLY, "KPMU" },
  9151. { SAPP_KEYCODE_KP_SUBTRACT, "KPSU" },
  9152. { SAPP_KEYCODE_KP_ADD, "KPAD" },
  9153. { SAPP_KEYCODE_KP_ENTER, "KPEN" },
  9154. { SAPP_KEYCODE_KP_EQUAL, "KPEQ" },
  9155. { SAPP_KEYCODE_LEFT_SHIFT, "LFSH" },
  9156. { SAPP_KEYCODE_LEFT_CONTROL, "LCTL" },
  9157. { SAPP_KEYCODE_LEFT_ALT, "LALT" },
  9158. { SAPP_KEYCODE_LEFT_SUPER, "LWIN" },
  9159. { SAPP_KEYCODE_RIGHT_SHIFT, "RTSH" },
  9160. { SAPP_KEYCODE_RIGHT_CONTROL, "RCTL" },
  9161. { SAPP_KEYCODE_RIGHT_ALT, "RALT" },
  9162. { SAPP_KEYCODE_RIGHT_ALT, "LVL3" },
  9163. { SAPP_KEYCODE_RIGHT_ALT, "MDSW" },
  9164. { SAPP_KEYCODE_RIGHT_SUPER, "RWIN" },
  9165. { SAPP_KEYCODE_MENU, "MENU" }
  9166. };
  9167. const int num_keymap_items = (int)(sizeof(keymap) / sizeof(keymap[0]));
  9168. // find X11 keycode to sokol-app key code mapping
  9169. for (int scancode = scancode_min; scancode <= scancode_max; scancode++) {
  9170. sapp_keycode key = SAPP_KEYCODE_INVALID;
  9171. for (int i = 0; i < num_keymap_items; i++) {
  9172. if (strncmp(desc->names->keys[scancode].name, keymap[i].name, XkbKeyNameLength) == 0) {
  9173. key = keymap[i].key;
  9174. break;
  9175. }
  9176. }
  9177. // fall back to key aliases in case the key name did not match
  9178. for (int i = 0; i < desc->names->num_key_aliases; i++) {
  9179. if (key != SAPP_KEYCODE_INVALID) {
  9180. break;
  9181. }
  9182. if (strncmp(desc->names->key_aliases[i].real, desc->names->keys[scancode].name, XkbKeyNameLength) != 0) {
  9183. continue;
  9184. }
  9185. for (int j = 0; j < num_keymap_items; j++) {
  9186. if (strncmp(desc->names->key_aliases[i].alias, keymap[i].name, XkbKeyNameLength) == 0) {
  9187. key = keymap[i].key;
  9188. break;
  9189. }
  9190. }
  9191. }
  9192. _sapp.keycodes[scancode] = key;
  9193. }
  9194. XkbFreeNames(desc, XkbKeyNamesMask, True);
  9195. XkbFreeKeyboard(desc, 0, True);
  9196. int width = 0;
  9197. KeySym* keysyms = XGetKeyboardMapping(_sapp.x11.display, scancode_min, scancode_max - scancode_min + 1, &width);
  9198. for (int scancode = scancode_min; scancode <= scancode_max; scancode++) {
  9199. // translate untranslated key codes using the traditional X11 KeySym lookups
  9200. if (_sapp.keycodes[scancode] == SAPP_KEYCODE_INVALID) {
  9201. const size_t base = (size_t)((scancode - scancode_min) * width);
  9202. _sapp.keycodes[scancode] = _sapp_x11_translate_keysyms(&keysyms[base], width);
  9203. }
  9204. }
  9205. XFree(keysyms);
  9206. }
  9207. _SOKOL_PRIVATE void _sapp_x11_query_system_dpi(void) {
  9208. /* from GLFW:
  9209. NOTE: Default to the display-wide DPI as we don't currently have a policy
  9210. for which monitor a window is considered to be on
  9211. _sapp.x11.dpi = DisplayWidth(_sapp.x11.display, _sapp.x11.screen) *
  9212. 25.4f / DisplayWidthMM(_sapp.x11.display, _sapp.x11.screen);
  9213. NOTE: Basing the scale on Xft.dpi where available should provide the most
  9214. consistent user experience (matches Qt, Gtk, etc), although not
  9215. always the most accurate one
  9216. */
  9217. bool dpi_ok = false;
  9218. char* rms = XResourceManagerString(_sapp.x11.display);
  9219. if (rms) {
  9220. XrmDatabase db = XrmGetStringDatabase(rms);
  9221. if (db) {
  9222. XrmValue value;
  9223. char* type = NULL;
  9224. if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value)) {
  9225. if (type && strcmp(type, "String") == 0) {
  9226. _sapp.x11.dpi = atof(value.addr);
  9227. dpi_ok = true;
  9228. }
  9229. }
  9230. XrmDestroyDatabase(db);
  9231. }
  9232. }
  9233. // fallback if querying DPI had failed: assume the standard DPI 96.0f
  9234. if (!dpi_ok) {
  9235. _sapp.x11.dpi = 96.0f;
  9236. _SAPP_WARN(LINUX_X11_QUERY_SYSTEM_DPI_FAILED);
  9237. }
  9238. }
  9239. #if defined(_SAPP_GLX)
  9240. _SOKOL_PRIVATE bool _sapp_glx_has_ext(const char* ext, const char* extensions) {
  9241. SOKOL_ASSERT(ext);
  9242. const char* start = extensions;
  9243. while (true) {
  9244. const char* where = strstr(start, ext);
  9245. if (!where) {
  9246. return false;
  9247. }
  9248. const char* terminator = where + strlen(ext);
  9249. if ((where == start) || (*(where - 1) == ' ')) {
  9250. if (*terminator == ' ' || *terminator == '\0') {
  9251. break;
  9252. }
  9253. }
  9254. start = terminator;
  9255. }
  9256. return true;
  9257. }
  9258. _SOKOL_PRIVATE bool _sapp_glx_extsupported(const char* ext, const char* extensions) {
  9259. if (extensions) {
  9260. return _sapp_glx_has_ext(ext, extensions);
  9261. }
  9262. else {
  9263. return false;
  9264. }
  9265. }
  9266. _SOKOL_PRIVATE void* _sapp_glx_getprocaddr(const char* procname)
  9267. {
  9268. if (_sapp.glx.GetProcAddress) {
  9269. return (void*) _sapp.glx.GetProcAddress(procname);
  9270. }
  9271. else if (_sapp.glx.GetProcAddressARB) {
  9272. return (void*) _sapp.glx.GetProcAddressARB(procname);
  9273. }
  9274. else {
  9275. return dlsym(_sapp.glx.libgl, procname);
  9276. }
  9277. }
  9278. _SOKOL_PRIVATE void _sapp_glx_init(void) {
  9279. const char* sonames[] = { "libGL.so.1", "libGL.so", 0 };
  9280. for (int i = 0; sonames[i]; i++) {
  9281. _sapp.glx.libgl = dlopen(sonames[i], RTLD_LAZY|RTLD_GLOBAL);
  9282. if (_sapp.glx.libgl) {
  9283. break;
  9284. }
  9285. }
  9286. if (!_sapp.glx.libgl) {
  9287. _SAPP_PANIC(LINUX_GLX_LOAD_LIBGL_FAILED);
  9288. }
  9289. _sapp.glx.GetFBConfigs = (PFNGLXGETFBCONFIGSPROC) dlsym(_sapp.glx.libgl, "glXGetFBConfigs");
  9290. _sapp.glx.GetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) dlsym(_sapp.glx.libgl, "glXGetFBConfigAttrib");
  9291. _sapp.glx.GetClientString = (PFNGLXGETCLIENTSTRINGPROC) dlsym(_sapp.glx.libgl, "glXGetClientString");
  9292. _sapp.glx.QueryExtension = (PFNGLXQUERYEXTENSIONPROC) dlsym(_sapp.glx.libgl, "glXQueryExtension");
  9293. _sapp.glx.QueryVersion = (PFNGLXQUERYVERSIONPROC) dlsym(_sapp.glx.libgl, "glXQueryVersion");
  9294. _sapp.glx.DestroyContext = (PFNGLXDESTROYCONTEXTPROC) dlsym(_sapp.glx.libgl, "glXDestroyContext");
  9295. _sapp.glx.MakeCurrent = (PFNGLXMAKECURRENTPROC) dlsym(_sapp.glx.libgl, "glXMakeCurrent");
  9296. _sapp.glx.SwapBuffers = (PFNGLXSWAPBUFFERSPROC) dlsym(_sapp.glx.libgl, "glXSwapBuffers");
  9297. _sapp.glx.QueryExtensionsString = (PFNGLXQUERYEXTENSIONSSTRINGPROC) dlsym(_sapp.glx.libgl, "glXQueryExtensionsString");
  9298. _sapp.glx.CreateWindow = (PFNGLXCREATEWINDOWPROC) dlsym(_sapp.glx.libgl, "glXCreateWindow");
  9299. _sapp.glx.DestroyWindow = (PFNGLXDESTROYWINDOWPROC) dlsym(_sapp.glx.libgl, "glXDestroyWindow");
  9300. _sapp.glx.GetProcAddress = (PFNGLXGETPROCADDRESSPROC) dlsym(_sapp.glx.libgl, "glXGetProcAddress");
  9301. _sapp.glx.GetProcAddressARB = (PFNGLXGETPROCADDRESSPROC) dlsym(_sapp.glx.libgl, "glXGetProcAddressARB");
  9302. _sapp.glx.GetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) dlsym(_sapp.glx.libgl, "glXGetVisualFromFBConfig");
  9303. if (!_sapp.glx.GetFBConfigs ||
  9304. !_sapp.glx.GetFBConfigAttrib ||
  9305. !_sapp.glx.GetClientString ||
  9306. !_sapp.glx.QueryExtension ||
  9307. !_sapp.glx.QueryVersion ||
  9308. !_sapp.glx.DestroyContext ||
  9309. !_sapp.glx.MakeCurrent ||
  9310. !_sapp.glx.SwapBuffers ||
  9311. !_sapp.glx.QueryExtensionsString ||
  9312. !_sapp.glx.CreateWindow ||
  9313. !_sapp.glx.DestroyWindow ||
  9314. !_sapp.glx.GetProcAddress ||
  9315. !_sapp.glx.GetProcAddressARB ||
  9316. !_sapp.glx.GetVisualFromFBConfig)
  9317. {
  9318. _SAPP_PANIC(LINUX_GLX_LOAD_ENTRY_POINTS_FAILED);
  9319. }
  9320. if (!_sapp.glx.QueryExtension(_sapp.x11.display, &_sapp.glx.error_base, &_sapp.glx.event_base)) {
  9321. _SAPP_PANIC(LINUX_GLX_EXTENSION_NOT_FOUND);
  9322. }
  9323. if (!_sapp.glx.QueryVersion(_sapp.x11.display, &_sapp.glx.major, &_sapp.glx.minor)) {
  9324. _SAPP_PANIC(LINUX_GLX_QUERY_VERSION_FAILED);
  9325. }
  9326. if (_sapp.glx.major == 1 && _sapp.glx.minor < 3) {
  9327. _SAPP_PANIC(LINUX_GLX_VERSION_TOO_LOW);
  9328. }
  9329. const char* exts = _sapp.glx.QueryExtensionsString(_sapp.x11.display, _sapp.x11.screen);
  9330. if (_sapp_glx_extsupported("GLX_EXT_swap_control", exts)) {
  9331. _sapp.glx.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) _sapp_glx_getprocaddr("glXSwapIntervalEXT");
  9332. _sapp.glx.EXT_swap_control = 0 != _sapp.glx.SwapIntervalEXT;
  9333. }
  9334. if (_sapp_glx_extsupported("GLX_MESA_swap_control", exts)) {
  9335. _sapp.glx.SwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC) _sapp_glx_getprocaddr("glXSwapIntervalMESA");
  9336. _sapp.glx.MESA_swap_control = 0 != _sapp.glx.SwapIntervalMESA;
  9337. }
  9338. _sapp.glx.ARB_multisample = _sapp_glx_extsupported("GLX_ARB_multisample", exts);
  9339. if (_sapp_glx_extsupported("GLX_ARB_create_context", exts)) {
  9340. _sapp.glx.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) _sapp_glx_getprocaddr("glXCreateContextAttribsARB");
  9341. _sapp.glx.ARB_create_context = 0 != _sapp.glx.CreateContextAttribsARB;
  9342. }
  9343. _sapp.glx.ARB_create_context_profile = _sapp_glx_extsupported("GLX_ARB_create_context_profile", exts);
  9344. }
  9345. _SOKOL_PRIVATE int _sapp_glx_attrib(GLXFBConfig fbconfig, int attrib) {
  9346. int value;
  9347. _sapp.glx.GetFBConfigAttrib(_sapp.x11.display, fbconfig, attrib, &value);
  9348. return value;
  9349. }
  9350. _SOKOL_PRIVATE GLXFBConfig _sapp_glx_choosefbconfig(void) {
  9351. GLXFBConfig* native_configs;
  9352. _sapp_gl_fbconfig* usable_configs;
  9353. const _sapp_gl_fbconfig* closest;
  9354. int i, native_count, usable_count;
  9355. const char* vendor;
  9356. bool trust_window_bit = true;
  9357. /* HACK: This is a (hopefully temporary) workaround for Chromium
  9358. (VirtualBox GL) not setting the window bit on any GLXFBConfigs
  9359. */
  9360. vendor = _sapp.glx.GetClientString(_sapp.x11.display, GLX_VENDOR);
  9361. if (vendor && strcmp(vendor, "Chromium") == 0) {
  9362. trust_window_bit = false;
  9363. }
  9364. native_configs = _sapp.glx.GetFBConfigs(_sapp.x11.display, _sapp.x11.screen, &native_count);
  9365. if (!native_configs || !native_count) {
  9366. _SAPP_PANIC(LINUX_GLX_NO_GLXFBCONFIGS);
  9367. }
  9368. usable_configs = (_sapp_gl_fbconfig*) _sapp_malloc_clear((size_t)native_count * sizeof(_sapp_gl_fbconfig));
  9369. usable_count = 0;
  9370. for (i = 0; i < native_count; i++) {
  9371. const GLXFBConfig n = native_configs[i];
  9372. _sapp_gl_fbconfig* u = usable_configs + usable_count;
  9373. _sapp_gl_init_fbconfig(u);
  9374. /* Only consider RGBA GLXFBConfigs */
  9375. if (0 == (_sapp_glx_attrib(n, GLX_RENDER_TYPE) & GLX_RGBA_BIT)) {
  9376. continue;
  9377. }
  9378. /* Only consider window GLXFBConfigs */
  9379. if (0 == (_sapp_glx_attrib(n, GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT)) {
  9380. if (trust_window_bit) {
  9381. continue;
  9382. }
  9383. }
  9384. u->red_bits = _sapp_glx_attrib(n, GLX_RED_SIZE);
  9385. u->green_bits = _sapp_glx_attrib(n, GLX_GREEN_SIZE);
  9386. u->blue_bits = _sapp_glx_attrib(n, GLX_BLUE_SIZE);
  9387. u->alpha_bits = _sapp_glx_attrib(n, GLX_ALPHA_SIZE);
  9388. u->depth_bits = _sapp_glx_attrib(n, GLX_DEPTH_SIZE);
  9389. u->stencil_bits = _sapp_glx_attrib(n, GLX_STENCIL_SIZE);
  9390. if (_sapp_glx_attrib(n, GLX_DOUBLEBUFFER)) {
  9391. u->doublebuffer = true;
  9392. }
  9393. if (_sapp.glx.ARB_multisample) {
  9394. u->samples = _sapp_glx_attrib(n, GLX_SAMPLES);
  9395. }
  9396. u->handle = (uintptr_t) n;
  9397. usable_count++;
  9398. }
  9399. _sapp_gl_fbconfig desired;
  9400. _sapp_gl_init_fbconfig(&desired);
  9401. desired.red_bits = 8;
  9402. desired.green_bits = 8;
  9403. desired.blue_bits = 8;
  9404. desired.alpha_bits = 8;
  9405. desired.depth_bits = 24;
  9406. desired.stencil_bits = 8;
  9407. desired.doublebuffer = true;
  9408. desired.samples = _sapp.sample_count > 1 ? _sapp.sample_count : 0;
  9409. closest = _sapp_gl_choose_fbconfig(&desired, usable_configs, usable_count);
  9410. GLXFBConfig result = 0;
  9411. if (closest) {
  9412. result = (GLXFBConfig) closest->handle;
  9413. }
  9414. XFree(native_configs);
  9415. _sapp_free(usable_configs);
  9416. return result;
  9417. }
  9418. _SOKOL_PRIVATE void _sapp_glx_choose_visual(Visual** visual, int* depth) {
  9419. GLXFBConfig native = _sapp_glx_choosefbconfig();
  9420. if (0 == native) {
  9421. _SAPP_PANIC(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG);
  9422. }
  9423. XVisualInfo* result = _sapp.glx.GetVisualFromFBConfig(_sapp.x11.display, native);
  9424. if (!result) {
  9425. _SAPP_PANIC(LINUX_GLX_GET_VISUAL_FROM_FBCONFIG_FAILED);
  9426. }
  9427. *visual = result->visual;
  9428. *depth = result->depth;
  9429. XFree(result);
  9430. }
  9431. _SOKOL_PRIVATE void _sapp_glx_make_current(void) {
  9432. _sapp.glx.MakeCurrent(_sapp.x11.display, _sapp.glx.window, _sapp.glx.ctx);
  9433. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  9434. }
  9435. _SOKOL_PRIVATE void _sapp_glx_create_context(void) {
  9436. GLXFBConfig native = _sapp_glx_choosefbconfig();
  9437. if (0 == native){
  9438. _SAPP_PANIC(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG);
  9439. }
  9440. if (!(_sapp.glx.ARB_create_context && _sapp.glx.ARB_create_context_profile)) {
  9441. _SAPP_PANIC(LINUX_GLX_REQUIRED_EXTENSIONS_MISSING);
  9442. }
  9443. _sapp_x11_grab_error_handler();
  9444. const int attribs[] = {
  9445. GLX_CONTEXT_MAJOR_VERSION_ARB, _sapp.desc.gl_major_version,
  9446. GLX_CONTEXT_MINOR_VERSION_ARB, _sapp.desc.gl_minor_version,
  9447. GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
  9448. GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
  9449. 0, 0
  9450. };
  9451. _sapp.glx.ctx = _sapp.glx.CreateContextAttribsARB(_sapp.x11.display, native, NULL, True, attribs);
  9452. if (!_sapp.glx.ctx) {
  9453. _SAPP_PANIC(LINUX_GLX_CREATE_CONTEXT_FAILED);
  9454. }
  9455. _sapp_x11_release_error_handler();
  9456. _sapp.glx.window = _sapp.glx.CreateWindow(_sapp.x11.display, native, _sapp.x11.window, NULL);
  9457. if (!_sapp.glx.window) {
  9458. _SAPP_PANIC(LINUX_GLX_CREATE_WINDOW_FAILED);
  9459. }
  9460. _sapp_glx_make_current();
  9461. }
  9462. _SOKOL_PRIVATE void _sapp_glx_destroy_context(void) {
  9463. if (_sapp.glx.window) {
  9464. _sapp.glx.DestroyWindow(_sapp.x11.display, _sapp.glx.window);
  9465. _sapp.glx.window = 0;
  9466. }
  9467. if (_sapp.glx.ctx) {
  9468. _sapp.glx.DestroyContext(_sapp.x11.display, _sapp.glx.ctx);
  9469. _sapp.glx.ctx = 0;
  9470. }
  9471. }
  9472. _SOKOL_PRIVATE void _sapp_glx_swap_buffers(void) {
  9473. _sapp.glx.SwapBuffers(_sapp.x11.display, _sapp.glx.window);
  9474. }
  9475. _SOKOL_PRIVATE void _sapp_glx_swapinterval(int interval) {
  9476. if (_sapp.glx.EXT_swap_control) {
  9477. _sapp.glx.SwapIntervalEXT(_sapp.x11.display, _sapp.glx.window, interval);
  9478. }
  9479. else if (_sapp.glx.MESA_swap_control) {
  9480. _sapp.glx.SwapIntervalMESA(interval);
  9481. }
  9482. }
  9483. #endif /* _SAPP_GLX */
  9484. _SOKOL_PRIVATE void _sapp_x11_send_event(Atom type, int a, int b, int c, int d, int e) {
  9485. XEvent event;
  9486. _sapp_clear(&event, sizeof(event));
  9487. event.type = ClientMessage;
  9488. event.xclient.window = _sapp.x11.window;
  9489. event.xclient.format = 32;
  9490. event.xclient.message_type = type;
  9491. event.xclient.data.l[0] = a;
  9492. event.xclient.data.l[1] = b;
  9493. event.xclient.data.l[2] = c;
  9494. event.xclient.data.l[3] = d;
  9495. event.xclient.data.l[4] = e;
  9496. XSendEvent(_sapp.x11.display, _sapp.x11.root,
  9497. False,
  9498. SubstructureNotifyMask | SubstructureRedirectMask,
  9499. &event);
  9500. }
  9501. _SOKOL_PRIVATE void _sapp_x11_query_window_size(void) {
  9502. XWindowAttributes attribs;
  9503. XGetWindowAttributes(_sapp.x11.display, _sapp.x11.window, &attribs);
  9504. _sapp.window_width = attribs.width;
  9505. _sapp.window_height = attribs.height;
  9506. _sapp.framebuffer_width = _sapp.window_width;
  9507. _sapp.framebuffer_height = _sapp.window_height;
  9508. }
  9509. _SOKOL_PRIVATE void _sapp_x11_set_fullscreen(bool enable) {
  9510. /* NOTE: this function must be called after XMapWindow (which happens in _sapp_x11_show_window()) */
  9511. if (_sapp.x11.NET_WM_STATE && _sapp.x11.NET_WM_STATE_FULLSCREEN) {
  9512. if (enable) {
  9513. const int _NET_WM_STATE_ADD = 1;
  9514. _sapp_x11_send_event(_sapp.x11.NET_WM_STATE,
  9515. _NET_WM_STATE_ADD,
  9516. _sapp.x11.NET_WM_STATE_FULLSCREEN,
  9517. 0, 1, 0);
  9518. }
  9519. else {
  9520. const int _NET_WM_STATE_REMOVE = 0;
  9521. _sapp_x11_send_event(_sapp.x11.NET_WM_STATE,
  9522. _NET_WM_STATE_REMOVE,
  9523. _sapp.x11.NET_WM_STATE_FULLSCREEN,
  9524. 0, 1, 0);
  9525. }
  9526. }
  9527. XFlush(_sapp.x11.display);
  9528. }
  9529. _SOKOL_PRIVATE void _sapp_x11_create_hidden_cursor(void) {
  9530. SOKOL_ASSERT(0 == _sapp.x11.hidden_cursor);
  9531. const int w = 16;
  9532. const int h = 16;
  9533. XcursorImage* img = XcursorImageCreate(w, h);
  9534. SOKOL_ASSERT(img && (img->width == 16) && (img->height == 16) && img->pixels);
  9535. img->xhot = 0;
  9536. img->yhot = 0;
  9537. const size_t num_bytes = (size_t)(w * h) * sizeof(XcursorPixel);
  9538. _sapp_clear(img->pixels, num_bytes);
  9539. _sapp.x11.hidden_cursor = XcursorImageLoadCursor(_sapp.x11.display, img);
  9540. XcursorImageDestroy(img);
  9541. }
  9542. _SOKOL_PRIVATE void _sapp_x11_create_standard_cursor(sapp_mouse_cursor cursor, const char* name, const char* theme, int size, uint32_t fallback_native) {
  9543. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  9544. SOKOL_ASSERT(_sapp.x11.display);
  9545. if (theme) {
  9546. XcursorImage* img = XcursorLibraryLoadImage(name, theme, size);
  9547. if (img) {
  9548. _sapp.x11.cursors[cursor] = XcursorImageLoadCursor(_sapp.x11.display, img);
  9549. XcursorImageDestroy(img);
  9550. }
  9551. }
  9552. if (0 == _sapp.x11.cursors[cursor]) {
  9553. _sapp.x11.cursors[cursor] = XCreateFontCursor(_sapp.x11.display, fallback_native);
  9554. }
  9555. }
  9556. _SOKOL_PRIVATE void _sapp_x11_create_cursors(void) {
  9557. SOKOL_ASSERT(_sapp.x11.display);
  9558. const char* cursor_theme = XcursorGetTheme(_sapp.x11.display);
  9559. const int size = XcursorGetDefaultSize(_sapp.x11.display);
  9560. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_ARROW, "default", cursor_theme, size, XC_left_ptr);
  9561. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_IBEAM, "text", cursor_theme, size, XC_xterm);
  9562. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_CROSSHAIR, "crosshair", cursor_theme, size, XC_crosshair);
  9563. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_POINTING_HAND, "pointer", cursor_theme, size, XC_hand2);
  9564. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_EW, "ew-resize", cursor_theme, size, XC_sb_h_double_arrow);
  9565. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NS, "ns-resize", cursor_theme, size, XC_sb_v_double_arrow);
  9566. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NWSE, "nwse-resize", cursor_theme, size, 0);
  9567. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NESW, "nesw-resize", cursor_theme, size, 0);
  9568. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_ALL, "all-scroll", cursor_theme, size, XC_fleur);
  9569. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_NOT_ALLOWED, "no-allowed", cursor_theme, size, 0);
  9570. _sapp_x11_create_hidden_cursor();
  9571. }
  9572. _SOKOL_PRIVATE void _sapp_x11_destroy_cursors(void) {
  9573. SOKOL_ASSERT(_sapp.x11.display);
  9574. if (_sapp.x11.hidden_cursor) {
  9575. XFreeCursor(_sapp.x11.display, _sapp.x11.hidden_cursor);
  9576. _sapp.x11.hidden_cursor = 0;
  9577. }
  9578. for (int i = 0; i < _SAPP_MOUSECURSOR_NUM; i++) {
  9579. if (_sapp.x11.cursors[i]) {
  9580. XFreeCursor(_sapp.x11.display, _sapp.x11.cursors[i]);
  9581. _sapp.x11.cursors[i] = 0;
  9582. }
  9583. }
  9584. }
  9585. _SOKOL_PRIVATE void _sapp_x11_toggle_fullscreen(void) {
  9586. _sapp.fullscreen = !_sapp.fullscreen;
  9587. _sapp_x11_set_fullscreen(_sapp.fullscreen);
  9588. _sapp_x11_query_window_size();
  9589. }
  9590. _SOKOL_PRIVATE void _sapp_x11_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  9591. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  9592. if (shown) {
  9593. if (_sapp.x11.cursors[cursor]) {
  9594. XDefineCursor(_sapp.x11.display, _sapp.x11.window, _sapp.x11.cursors[cursor]);
  9595. }
  9596. else {
  9597. XUndefineCursor(_sapp.x11.display, _sapp.x11.window);
  9598. }
  9599. }
  9600. else {
  9601. XDefineCursor(_sapp.x11.display, _sapp.x11.window, _sapp.x11.hidden_cursor);
  9602. }
  9603. XFlush(_sapp.x11.display);
  9604. }
  9605. _SOKOL_PRIVATE void _sapp_x11_lock_mouse(bool lock) {
  9606. if (lock == _sapp.mouse.locked) {
  9607. return;
  9608. }
  9609. _sapp.mouse.dx = 0.0f;
  9610. _sapp.mouse.dy = 0.0f;
  9611. _sapp.mouse.locked = lock;
  9612. if (_sapp.mouse.locked) {
  9613. if (_sapp.x11.xi.available) {
  9614. XIEventMask em;
  9615. unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 }; // XIMaskLen is a macro
  9616. em.deviceid = XIAllMasterDevices;
  9617. em.mask_len = sizeof(mask);
  9618. em.mask = mask;
  9619. XISetMask(mask, XI_RawMotion);
  9620. XISelectEvents(_sapp.x11.display, _sapp.x11.root, &em, 1);
  9621. }
  9622. XGrabPointer(_sapp.x11.display, // display
  9623. _sapp.x11.window, // grab_window
  9624. True, // owner_events
  9625. ButtonPressMask | ButtonReleaseMask | PointerMotionMask, // event_mask
  9626. GrabModeAsync, // pointer_mode
  9627. GrabModeAsync, // keyboard_mode
  9628. _sapp.x11.window, // confine_to
  9629. _sapp.x11.hidden_cursor, // cursor
  9630. CurrentTime); // time
  9631. }
  9632. else {
  9633. if (_sapp.x11.xi.available) {
  9634. XIEventMask em;
  9635. unsigned char mask[] = { 0 };
  9636. em.deviceid = XIAllMasterDevices;
  9637. em.mask_len = sizeof(mask);
  9638. em.mask = mask;
  9639. XISelectEvents(_sapp.x11.display, _sapp.x11.root, &em, 1);
  9640. }
  9641. XWarpPointer(_sapp.x11.display, None, _sapp.x11.window, 0, 0, 0, 0, (int) _sapp.mouse.x, _sapp.mouse.y);
  9642. XUngrabPointer(_sapp.x11.display, CurrentTime);
  9643. }
  9644. XFlush(_sapp.x11.display);
  9645. }
  9646. _SOKOL_PRIVATE void _sapp_x11_set_clipboard_string(const char* str) {
  9647. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  9648. if (strlen(str) >= (size_t)_sapp.clipboard.buf_size) {
  9649. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  9650. }
  9651. XSetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD, _sapp.x11.window, CurrentTime);
  9652. if (XGetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD) != _sapp.x11.window) {
  9653. _SAPP_ERROR(LINUX_X11_FAILED_TO_BECOME_OWNER_OF_CLIPBOARD);
  9654. }
  9655. }
  9656. _SOKOL_PRIVATE const char* _sapp_x11_get_clipboard_string(void) {
  9657. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  9658. Atom none = XInternAtom(_sapp.x11.display, "SAPP_SELECTION", False);
  9659. Atom incremental = XInternAtom(_sapp.x11.display, "INCR", False);
  9660. if (XGetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD) == _sapp.x11.window) {
  9661. // Instead of doing a large number of X round-trips just to put this
  9662. // string into a window property and then read it back, just return it
  9663. return _sapp.clipboard.buffer;
  9664. }
  9665. XConvertSelection(_sapp.x11.display,
  9666. _sapp.x11.CLIPBOARD,
  9667. _sapp.x11.UTF8_STRING,
  9668. none,
  9669. _sapp.x11.window,
  9670. CurrentTime);
  9671. XEvent event;
  9672. while (!XCheckTypedWindowEvent(_sapp.x11.display, _sapp.x11.window, SelectionNotify, &event)) {
  9673. // Wait for event data to arrive on the X11 display socket
  9674. struct pollfd fd = { ConnectionNumber(_sapp.x11.display), POLLIN };
  9675. while (!XPending(_sapp.x11.display)) {
  9676. poll(&fd, 1, -1);
  9677. }
  9678. }
  9679. if (event.xselection.property == None) {
  9680. return NULL;
  9681. }
  9682. char* data = NULL;
  9683. Atom actualType;
  9684. int actualFormat;
  9685. unsigned long itemCount, bytesAfter;
  9686. const bool ret = XGetWindowProperty(_sapp.x11.display,
  9687. event.xselection.requestor,
  9688. event.xselection.property,
  9689. 0,
  9690. LONG_MAX,
  9691. True,
  9692. _sapp.x11.UTF8_STRING,
  9693. &actualType,
  9694. &actualFormat,
  9695. &itemCount,
  9696. &bytesAfter,
  9697. (unsigned char**) &data);
  9698. if (ret != Success || data == NULL) {
  9699. if (data != NULL) {
  9700. XFree(data);
  9701. }
  9702. return NULL;
  9703. }
  9704. if ((actualType == incremental) || (itemCount >= (size_t)_sapp.clipboard.buf_size)) {
  9705. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  9706. XFree(data);
  9707. return NULL;
  9708. }
  9709. _sapp_strcpy(data, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  9710. XFree(data);
  9711. return _sapp.clipboard.buffer;
  9712. }
  9713. _SOKOL_PRIVATE void _sapp_x11_update_window_title(void) {
  9714. Xutf8SetWMProperties(_sapp.x11.display,
  9715. _sapp.x11.window,
  9716. _sapp.window_title, _sapp.window_title,
  9717. NULL, 0, NULL, NULL, NULL);
  9718. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9719. _sapp.x11.NET_WM_NAME, _sapp.x11.UTF8_STRING, 8,
  9720. PropModeReplace,
  9721. (unsigned char*)_sapp.window_title,
  9722. strlen(_sapp.window_title));
  9723. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9724. _sapp.x11.NET_WM_ICON_NAME, _sapp.x11.UTF8_STRING, 8,
  9725. PropModeReplace,
  9726. (unsigned char*)_sapp.window_title,
  9727. strlen(_sapp.window_title));
  9728. XFlush(_sapp.x11.display);
  9729. }
  9730. _SOKOL_PRIVATE void _sapp_x11_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  9731. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  9732. int long_count = 0;
  9733. for (int i = 0; i < num_images; i++) {
  9734. const sapp_image_desc* img_desc = &icon_desc->images[i];
  9735. long_count += 2 + (img_desc->width * img_desc->height);
  9736. }
  9737. long* icon_data = (long*) _sapp_malloc_clear((size_t)long_count * sizeof(long));
  9738. SOKOL_ASSERT(icon_data);
  9739. long* dst = icon_data;
  9740. for (int img_index = 0; img_index < num_images; img_index++) {
  9741. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  9742. const uint8_t* src = (const uint8_t*) img_desc->pixels.ptr;
  9743. *dst++ = img_desc->width;
  9744. *dst++ = img_desc->height;
  9745. const int num_pixels = img_desc->width * img_desc->height;
  9746. for (int pixel_index = 0; pixel_index < num_pixels; pixel_index++) {
  9747. *dst++ = ((long)(src[pixel_index * 4 + 0]) << 16) |
  9748. ((long)(src[pixel_index * 4 + 1]) << 8) |
  9749. ((long)(src[pixel_index * 4 + 2]) << 0) |
  9750. ((long)(src[pixel_index * 4 + 3]) << 24);
  9751. }
  9752. }
  9753. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9754. _sapp.x11.NET_WM_ICON,
  9755. XA_CARDINAL, 32,
  9756. PropModeReplace,
  9757. (unsigned char*)icon_data,
  9758. long_count);
  9759. _sapp_free(icon_data);
  9760. XFlush(_sapp.x11.display);
  9761. }
  9762. _SOKOL_PRIVATE void _sapp_x11_create_window(Visual* visual, int depth) {
  9763. _sapp.x11.colormap = XCreateColormap(_sapp.x11.display, _sapp.x11.root, visual, AllocNone);
  9764. XSetWindowAttributes wa;
  9765. _sapp_clear(&wa, sizeof(wa));
  9766. const uint32_t wamask = CWBorderPixel | CWColormap | CWEventMask;
  9767. wa.colormap = _sapp.x11.colormap;
  9768. wa.border_pixel = 0;
  9769. wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
  9770. PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
  9771. ExposureMask | FocusChangeMask | VisibilityChangeMask |
  9772. EnterWindowMask | LeaveWindowMask | PropertyChangeMask;
  9773. int display_width = DisplayWidth(_sapp.x11.display, _sapp.x11.screen);
  9774. int display_height = DisplayHeight(_sapp.x11.display, _sapp.x11.screen);
  9775. int window_width = _sapp.window_width;
  9776. int window_height = _sapp.window_height;
  9777. if (0 == window_width) {
  9778. window_width = (display_width * 4) / 5;
  9779. }
  9780. if (0 == window_height) {
  9781. window_height = (display_height * 4) / 5;
  9782. }
  9783. int window_xpos = (display_width - window_width) / 2;
  9784. int window_ypos = (display_height - window_height) / 2;
  9785. if (window_xpos < 0) {
  9786. window_xpos = 0;
  9787. }
  9788. if (window_ypos < 0) {
  9789. window_ypos = 0;
  9790. }
  9791. _sapp_x11_grab_error_handler();
  9792. _sapp.x11.window = XCreateWindow(_sapp.x11.display,
  9793. _sapp.x11.root,
  9794. window_xpos,
  9795. window_ypos,
  9796. (uint32_t)window_width,
  9797. (uint32_t)window_height,
  9798. 0, /* border width */
  9799. depth, /* color depth */
  9800. InputOutput,
  9801. visual,
  9802. wamask,
  9803. &wa);
  9804. _sapp_x11_release_error_handler();
  9805. if (!_sapp.x11.window) {
  9806. _SAPP_PANIC(LINUX_X11_CREATE_WINDOW_FAILED);
  9807. }
  9808. Atom protocols[] = {
  9809. _sapp.x11.WM_DELETE_WINDOW
  9810. };
  9811. XSetWMProtocols(_sapp.x11.display, _sapp.x11.window, protocols, 1);
  9812. XSizeHints* hints = XAllocSizeHints();
  9813. hints->flags = (PWinGravity | PPosition | PSize);
  9814. hints->win_gravity = StaticGravity;
  9815. hints->x = window_xpos;
  9816. hints->y = window_ypos;
  9817. hints->width = window_width;
  9818. hints->height = window_height;
  9819. XSetWMNormalHints(_sapp.x11.display, _sapp.x11.window, hints);
  9820. XFree(hints);
  9821. /* announce support for drag'n'drop */
  9822. if (_sapp.drop.enabled) {
  9823. const Atom version = _SAPP_X11_XDND_VERSION;
  9824. XChangeProperty(_sapp.x11.display, _sapp.x11.window, _sapp.x11.xdnd.XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char*) &version, 1);
  9825. }
  9826. _sapp_x11_update_window_title();
  9827. _sapp_x11_query_window_size();
  9828. }
  9829. _SOKOL_PRIVATE void _sapp_x11_destroy_window(void) {
  9830. if (_sapp.x11.window) {
  9831. XUnmapWindow(_sapp.x11.display, _sapp.x11.window);
  9832. XDestroyWindow(_sapp.x11.display, _sapp.x11.window);
  9833. _sapp.x11.window = 0;
  9834. }
  9835. if (_sapp.x11.colormap) {
  9836. XFreeColormap(_sapp.x11.display, _sapp.x11.colormap);
  9837. _sapp.x11.colormap = 0;
  9838. }
  9839. XFlush(_sapp.x11.display);
  9840. }
  9841. _SOKOL_PRIVATE bool _sapp_x11_window_visible(void) {
  9842. XWindowAttributes wa;
  9843. XGetWindowAttributes(_sapp.x11.display, _sapp.x11.window, &wa);
  9844. return wa.map_state == IsViewable;
  9845. }
  9846. _SOKOL_PRIVATE void _sapp_x11_show_window(void) {
  9847. if (!_sapp_x11_window_visible()) {
  9848. XMapWindow(_sapp.x11.display, _sapp.x11.window);
  9849. XRaiseWindow(_sapp.x11.display, _sapp.x11.window);
  9850. XFlush(_sapp.x11.display);
  9851. }
  9852. }
  9853. _SOKOL_PRIVATE void _sapp_x11_hide_window(void) {
  9854. XUnmapWindow(_sapp.x11.display, _sapp.x11.window);
  9855. XFlush(_sapp.x11.display);
  9856. }
  9857. _SOKOL_PRIVATE unsigned long _sapp_x11_get_window_property(Window window, Atom property, Atom type, unsigned char** value) {
  9858. Atom actualType;
  9859. int actualFormat;
  9860. unsigned long itemCount, bytesAfter;
  9861. XGetWindowProperty(_sapp.x11.display,
  9862. window,
  9863. property,
  9864. 0,
  9865. LONG_MAX,
  9866. False,
  9867. type,
  9868. &actualType,
  9869. &actualFormat,
  9870. &itemCount,
  9871. &bytesAfter,
  9872. value);
  9873. return itemCount;
  9874. }
  9875. _SOKOL_PRIVATE int _sapp_x11_get_window_state(void) {
  9876. int result = WithdrawnState;
  9877. struct {
  9878. CARD32 state;
  9879. Window icon;
  9880. } *state = NULL;
  9881. if (_sapp_x11_get_window_property(_sapp.x11.window, _sapp.x11.WM_STATE, _sapp.x11.WM_STATE, (unsigned char**)&state) >= 2) {
  9882. result = (int)state->state;
  9883. }
  9884. if (state) {
  9885. XFree(state);
  9886. }
  9887. return result;
  9888. }
  9889. _SOKOL_PRIVATE uint32_t _sapp_x11_key_modifier_bit(sapp_keycode key) {
  9890. switch (key) {
  9891. case SAPP_KEYCODE_LEFT_SHIFT:
  9892. case SAPP_KEYCODE_RIGHT_SHIFT:
  9893. return SAPP_MODIFIER_SHIFT;
  9894. case SAPP_KEYCODE_LEFT_CONTROL:
  9895. case SAPP_KEYCODE_RIGHT_CONTROL:
  9896. return SAPP_MODIFIER_CTRL;
  9897. case SAPP_KEYCODE_LEFT_ALT:
  9898. case SAPP_KEYCODE_RIGHT_ALT:
  9899. return SAPP_MODIFIER_ALT;
  9900. case SAPP_KEYCODE_LEFT_SUPER:
  9901. case SAPP_KEYCODE_RIGHT_SUPER:
  9902. return SAPP_MODIFIER_SUPER;
  9903. default:
  9904. return 0;
  9905. }
  9906. }
  9907. _SOKOL_PRIVATE uint32_t _sapp_x11_button_modifier_bit(sapp_mousebutton btn) {
  9908. switch (btn) {
  9909. case SAPP_MOUSEBUTTON_LEFT: return SAPP_MODIFIER_LMB;
  9910. case SAPP_MOUSEBUTTON_RIGHT: return SAPP_MODIFIER_RMB;
  9911. case SAPP_MOUSEBUTTON_MIDDLE: return SAPP_MODIFIER_MMB;
  9912. default: return 0;
  9913. }
  9914. }
  9915. _SOKOL_PRIVATE uint32_t _sapp_x11_mods(uint32_t x11_mods) {
  9916. uint32_t mods = 0;
  9917. if (x11_mods & ShiftMask) {
  9918. mods |= SAPP_MODIFIER_SHIFT;
  9919. }
  9920. if (x11_mods & ControlMask) {
  9921. mods |= SAPP_MODIFIER_CTRL;
  9922. }
  9923. if (x11_mods & Mod1Mask) {
  9924. mods |= SAPP_MODIFIER_ALT;
  9925. }
  9926. if (x11_mods & Mod4Mask) {
  9927. mods |= SAPP_MODIFIER_SUPER;
  9928. }
  9929. if (x11_mods & Button1Mask) {
  9930. mods |= SAPP_MODIFIER_LMB;
  9931. }
  9932. if (x11_mods & Button2Mask) {
  9933. mods |= SAPP_MODIFIER_MMB;
  9934. }
  9935. if (x11_mods & Button3Mask) {
  9936. mods |= SAPP_MODIFIER_RMB;
  9937. }
  9938. return mods;
  9939. }
  9940. _SOKOL_PRIVATE void _sapp_x11_app_event(sapp_event_type type) {
  9941. if (_sapp_events_enabled()) {
  9942. _sapp_init_event(type);
  9943. _sapp_call_event(&_sapp.event);
  9944. }
  9945. }
  9946. _SOKOL_PRIVATE sapp_mousebutton _sapp_x11_translate_button(const XEvent* event) {
  9947. switch (event->xbutton.button) {
  9948. case Button1: return SAPP_MOUSEBUTTON_LEFT;
  9949. case Button2: return SAPP_MOUSEBUTTON_MIDDLE;
  9950. case Button3: return SAPP_MOUSEBUTTON_RIGHT;
  9951. default: return SAPP_MOUSEBUTTON_INVALID;
  9952. }
  9953. }
  9954. _SOKOL_PRIVATE void _sapp_x11_mouse_update(int x, int y, bool clear_dxdy) {
  9955. if (!_sapp.mouse.locked) {
  9956. const float new_x = (float) x;
  9957. const float new_y = (float) y;
  9958. if (clear_dxdy) {
  9959. _sapp.mouse.dx = 0.0f;
  9960. _sapp.mouse.dy = 0.0f;
  9961. } else if (_sapp.mouse.pos_valid) {
  9962. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  9963. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  9964. }
  9965. _sapp.mouse.x = new_x;
  9966. _sapp.mouse.y = new_y;
  9967. _sapp.mouse.pos_valid = true;
  9968. }
  9969. }
  9970. _SOKOL_PRIVATE void _sapp_x11_mouse_event(sapp_event_type type, sapp_mousebutton btn, uint32_t mods) {
  9971. if (_sapp_events_enabled()) {
  9972. _sapp_init_event(type);
  9973. _sapp.event.mouse_button = btn;
  9974. _sapp.event.modifiers = mods;
  9975. _sapp_call_event(&_sapp.event);
  9976. }
  9977. }
  9978. _SOKOL_PRIVATE void _sapp_x11_scroll_event(float x, float y, uint32_t mods) {
  9979. if (_sapp_events_enabled()) {
  9980. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  9981. _sapp.event.modifiers = mods;
  9982. _sapp.event.scroll_x = x;
  9983. _sapp.event.scroll_y = y;
  9984. _sapp_call_event(&_sapp.event);
  9985. }
  9986. }
  9987. _SOKOL_PRIVATE void _sapp_x11_key_event(sapp_event_type type, sapp_keycode key, bool repeat, uint32_t mods) {
  9988. if (_sapp_events_enabled()) {
  9989. _sapp_init_event(type);
  9990. _sapp.event.key_code = key;
  9991. _sapp.event.key_repeat = repeat;
  9992. _sapp.event.modifiers = mods;
  9993. _sapp_call_event(&_sapp.event);
  9994. /* check if a CLIPBOARD_PASTED event must be sent too */
  9995. if (_sapp.clipboard.enabled &&
  9996. (type == SAPP_EVENTTYPE_KEY_DOWN) &&
  9997. (_sapp.event.modifiers == SAPP_MODIFIER_CTRL) &&
  9998. (_sapp.event.key_code == SAPP_KEYCODE_V))
  9999. {
  10000. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  10001. _sapp_call_event(&_sapp.event);
  10002. }
  10003. }
  10004. }
  10005. _SOKOL_PRIVATE void _sapp_x11_char_event(uint32_t chr, bool repeat, uint32_t mods) {
  10006. if (_sapp_events_enabled()) {
  10007. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  10008. _sapp.event.char_code = chr;
  10009. _sapp.event.key_repeat = repeat;
  10010. _sapp.event.modifiers = mods;
  10011. _sapp_call_event(&_sapp.event);
  10012. }
  10013. }
  10014. _SOKOL_PRIVATE sapp_keycode _sapp_x11_translate_key(int scancode) {
  10015. if ((scancode >= 0) && (scancode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10016. return _sapp.keycodes[scancode];
  10017. } else {
  10018. return SAPP_KEYCODE_INVALID;
  10019. }
  10020. }
  10021. _SOKOL_PRIVATE int32_t _sapp_x11_keysym_to_unicode(KeySym keysym) {
  10022. int min = 0;
  10023. int max = sizeof(_sapp_x11_keysymtab) / sizeof(struct _sapp_x11_codepair) - 1;
  10024. int mid;
  10025. /* First check for Latin-1 characters (1:1 mapping) */
  10026. if ((keysym >= 0x0020 && keysym <= 0x007e) ||
  10027. (keysym >= 0x00a0 && keysym <= 0x00ff))
  10028. {
  10029. return keysym;
  10030. }
  10031. /* Also check for directly encoded 24-bit UCS characters */
  10032. if ((keysym & 0xff000000) == 0x01000000) {
  10033. return keysym & 0x00ffffff;
  10034. }
  10035. /* Binary search in table */
  10036. while (max >= min) {
  10037. mid = (min + max) / 2;
  10038. if (_sapp_x11_keysymtab[mid].keysym < keysym) {
  10039. min = mid + 1;
  10040. }
  10041. else if (_sapp_x11_keysymtab[mid].keysym > keysym) {
  10042. max = mid - 1;
  10043. }
  10044. else {
  10045. return _sapp_x11_keysymtab[mid].ucs;
  10046. }
  10047. }
  10048. /* No matching Unicode value found */
  10049. return -1;
  10050. }
  10051. _SOKOL_PRIVATE bool _sapp_x11_keypress_repeat(int keycode) {
  10052. bool repeat = false;
  10053. if ((keycode >= 0) && (keycode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10054. repeat = _sapp.x11.key_repeat[keycode];
  10055. _sapp.x11.key_repeat[keycode] = true;
  10056. }
  10057. return repeat;
  10058. }
  10059. _SOKOL_PRIVATE void _sapp_x11_keyrelease_repeat(int keycode) {
  10060. if ((keycode >= 0) && (keycode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10061. _sapp.x11.key_repeat[keycode] = false;
  10062. }
  10063. }
  10064. _SOKOL_PRIVATE bool _sapp_x11_parse_dropped_files_list(const char* src) {
  10065. SOKOL_ASSERT(src);
  10066. SOKOL_ASSERT(_sapp.drop.buffer);
  10067. _sapp_clear_drop_buffer();
  10068. _sapp.drop.num_files = 0;
  10069. /*
  10070. src is (potentially percent-encoded) string made of one or multiple paths
  10071. separated by \r\n, each path starting with 'file://'
  10072. */
  10073. bool err = false;
  10074. int src_count = 0;
  10075. char src_chr = 0;
  10076. char* dst_ptr = _sapp.drop.buffer;
  10077. const char* dst_end_ptr = dst_ptr + (_sapp.drop.max_path_length - 1); // room for terminating 0
  10078. while (0 != (src_chr = *src++)) {
  10079. src_count++;
  10080. char dst_chr = 0;
  10081. /* check leading 'file://' */
  10082. if (src_count <= 7) {
  10083. if (((src_count == 1) && (src_chr != 'f')) ||
  10084. ((src_count == 2) && (src_chr != 'i')) ||
  10085. ((src_count == 3) && (src_chr != 'l')) ||
  10086. ((src_count == 4) && (src_chr != 'e')) ||
  10087. ((src_count == 5) && (src_chr != ':')) ||
  10088. ((src_count == 6) && (src_chr != '/')) ||
  10089. ((src_count == 7) && (src_chr != '/')))
  10090. {
  10091. _SAPP_ERROR(LINUX_X11_DROPPED_FILE_URI_WRONG_SCHEME);
  10092. err = true;
  10093. break;
  10094. }
  10095. }
  10096. else if (src_chr == '\r') {
  10097. // skip
  10098. }
  10099. else if (src_chr == '\n') {
  10100. src_count = 0;
  10101. _sapp.drop.num_files++;
  10102. // too many files is not an error
  10103. if (_sapp.drop.num_files >= _sapp.drop.max_files) {
  10104. break;
  10105. }
  10106. dst_ptr = _sapp.drop.buffer + _sapp.drop.num_files * _sapp.drop.max_path_length;
  10107. dst_end_ptr = dst_ptr + (_sapp.drop.max_path_length - 1);
  10108. }
  10109. else if ((src_chr == '%') && src[0] && src[1]) {
  10110. // a percent-encoded byte (most likely UTF-8 multibyte sequence)
  10111. const char digits[3] = { src[0], src[1], 0 };
  10112. src += 2;
  10113. dst_chr = (char) strtol(digits, 0, 16);
  10114. }
  10115. else {
  10116. dst_chr = src_chr;
  10117. }
  10118. if (dst_chr) {
  10119. // dst_end_ptr already has adjustment for terminating zero
  10120. if (dst_ptr < dst_end_ptr) {
  10121. *dst_ptr++ = dst_chr;
  10122. }
  10123. else {
  10124. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  10125. err = true;
  10126. break;
  10127. }
  10128. }
  10129. }
  10130. if (err) {
  10131. _sapp_clear_drop_buffer();
  10132. _sapp.drop.num_files = 0;
  10133. return false;
  10134. }
  10135. else {
  10136. return true;
  10137. }
  10138. }
  10139. _SOKOL_PRIVATE void _sapp_x11_on_genericevent(XEvent* event) {
  10140. if (_sapp.mouse.locked && _sapp.x11.xi.available) {
  10141. if (event->xcookie.extension == _sapp.x11.xi.major_opcode) {
  10142. if (XGetEventData(_sapp.x11.display, &event->xcookie)) {
  10143. if (event->xcookie.evtype == XI_RawMotion) {
  10144. XIRawEvent* re = (XIRawEvent*) event->xcookie.data;
  10145. if (re->valuators.mask_len) {
  10146. const double* values = re->raw_values;
  10147. if (XIMaskIsSet(re->valuators.mask, 0)) {
  10148. _sapp.mouse.dx = (float) *values;
  10149. values++;
  10150. }
  10151. if (XIMaskIsSet(re->valuators.mask, 1)) {
  10152. _sapp.mouse.dy = (float) *values;
  10153. }
  10154. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xmotion.state));
  10155. }
  10156. }
  10157. XFreeEventData(_sapp.x11.display, &event->xcookie);
  10158. }
  10159. }
  10160. }
  10161. }
  10162. _SOKOL_PRIVATE void _sapp_x11_on_focusin(XEvent* event) {
  10163. // NOTE: ignoring NotifyGrab and NotifyUngrab is same behaviour as GLFW
  10164. if ((event->xfocus.mode != NotifyGrab) && (event->xfocus.mode != NotifyUngrab)) {
  10165. _sapp_x11_app_event(SAPP_EVENTTYPE_FOCUSED);
  10166. }
  10167. }
  10168. _SOKOL_PRIVATE void _sapp_x11_on_focusout(XEvent* event) {
  10169. // if focus is lost for any reason, and we're in mouse locked mode, disable mouse lock
  10170. if (_sapp.mouse.locked) {
  10171. _sapp_x11_lock_mouse(false);
  10172. }
  10173. // NOTE: ignoring NotifyGrab and NotifyUngrab is same behaviour as GLFW
  10174. if ((event->xfocus.mode != NotifyGrab) && (event->xfocus.mode != NotifyUngrab)) {
  10175. _sapp_x11_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  10176. }
  10177. }
  10178. _SOKOL_PRIVATE void _sapp_x11_on_keypress(XEvent* event) {
  10179. int keycode = (int)event->xkey.keycode;
  10180. const sapp_keycode key = _sapp_x11_translate_key(keycode);
  10181. const bool repeat = _sapp_x11_keypress_repeat(keycode);
  10182. uint32_t mods = _sapp_x11_mods(event->xkey.state);
  10183. // X11 doesn't set modifier bit on key down, so emulate that
  10184. mods |= _sapp_x11_key_modifier_bit(key);
  10185. if (key != SAPP_KEYCODE_INVALID) {
  10186. _sapp_x11_key_event(SAPP_EVENTTYPE_KEY_DOWN, key, repeat, mods);
  10187. }
  10188. KeySym keysym;
  10189. XLookupString(&event->xkey, NULL, 0, &keysym, NULL);
  10190. int32_t chr = _sapp_x11_keysym_to_unicode(keysym);
  10191. if (chr > 0) {
  10192. _sapp_x11_char_event((uint32_t)chr, repeat, mods);
  10193. }
  10194. }
  10195. _SOKOL_PRIVATE void _sapp_x11_on_keyrelease(XEvent* event) {
  10196. int keycode = (int)event->xkey.keycode;
  10197. const sapp_keycode key = _sapp_x11_translate_key(keycode);
  10198. _sapp_x11_keyrelease_repeat(keycode);
  10199. if (key != SAPP_KEYCODE_INVALID) {
  10200. uint32_t mods = _sapp_x11_mods(event->xkey.state);
  10201. // X11 doesn't clear modifier bit on key up, so emulate that
  10202. mods &= ~_sapp_x11_key_modifier_bit(key);
  10203. _sapp_x11_key_event(SAPP_EVENTTYPE_KEY_UP, key, false, mods);
  10204. }
  10205. }
  10206. _SOKOL_PRIVATE void _sapp_x11_on_buttonpress(XEvent* event) {
  10207. _sapp_x11_mouse_update(event->xbutton.x, event->xbutton.y, false);
  10208. const sapp_mousebutton btn = _sapp_x11_translate_button(event);
  10209. uint32_t mods = _sapp_x11_mods(event->xbutton.state);
  10210. // X11 doesn't set modifier bit on button down, so emulate that
  10211. mods |= _sapp_x11_button_modifier_bit(btn);
  10212. if (btn != SAPP_MOUSEBUTTON_INVALID) {
  10213. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, btn, mods);
  10214. _sapp.x11.mouse_buttons |= (1 << btn);
  10215. }
  10216. else {
  10217. // might be a scroll event
  10218. switch (event->xbutton.button) {
  10219. case 4: _sapp_x11_scroll_event(0.0f, 1.0f, mods); break;
  10220. case 5: _sapp_x11_scroll_event(0.0f, -1.0f, mods); break;
  10221. case 6: _sapp_x11_scroll_event(1.0f, 0.0f, mods); break;
  10222. case 7: _sapp_x11_scroll_event(-1.0f, 0.0f, mods); break;
  10223. }
  10224. }
  10225. }
  10226. _SOKOL_PRIVATE void _sapp_x11_on_buttonrelease(XEvent* event) {
  10227. _sapp_x11_mouse_update(event->xbutton.x, event->xbutton.y, false);
  10228. const sapp_mousebutton btn = _sapp_x11_translate_button(event);
  10229. if (btn != SAPP_MOUSEBUTTON_INVALID) {
  10230. uint32_t mods = _sapp_x11_mods(event->xbutton.state);
  10231. // X11 doesn't clear modifier bit on button up, so emulate that
  10232. mods &= ~_sapp_x11_button_modifier_bit(btn);
  10233. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, btn, mods);
  10234. _sapp.x11.mouse_buttons &= ~(1 << btn);
  10235. }
  10236. }
  10237. _SOKOL_PRIVATE void _sapp_x11_on_enternotify(XEvent* event) {
  10238. // don't send enter/leave events while mouse button held down
  10239. if (0 == _sapp.x11.mouse_buttons) {
  10240. _sapp_x11_mouse_update(event->xcrossing.x, event->xcrossing.y, true);
  10241. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xcrossing.state));
  10242. }
  10243. }
  10244. _SOKOL_PRIVATE void _sapp_x11_on_leavenotify(XEvent* event) {
  10245. if (0 == _sapp.x11.mouse_buttons) {
  10246. _sapp_x11_mouse_update(event->xcrossing.x, event->xcrossing.y, true);
  10247. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xcrossing.state));
  10248. }
  10249. }
  10250. _SOKOL_PRIVATE void _sapp_x11_on_motionnotify(XEvent* event) {
  10251. if (!_sapp.mouse.locked) {
  10252. _sapp_x11_mouse_update(event->xmotion.x, event->xmotion.y, false);
  10253. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xmotion.state));
  10254. }
  10255. }
  10256. _SOKOL_PRIVATE void _sapp_x11_on_configurenotify(XEvent* event) {
  10257. if ((event->xconfigure.width != _sapp.window_width) || (event->xconfigure.height != _sapp.window_height)) {
  10258. _sapp.window_width = event->xconfigure.width;
  10259. _sapp.window_height = event->xconfigure.height;
  10260. _sapp.framebuffer_width = _sapp.window_width;
  10261. _sapp.framebuffer_height = _sapp.window_height;
  10262. _sapp_x11_app_event(SAPP_EVENTTYPE_RESIZED);
  10263. }
  10264. }
  10265. _SOKOL_PRIVATE void _sapp_x11_on_propertynotify(XEvent* event) {
  10266. if (event->xproperty.state == PropertyNewValue) {
  10267. if (event->xproperty.atom == _sapp.x11.WM_STATE) {
  10268. const int state = _sapp_x11_get_window_state();
  10269. if (state != _sapp.x11.window_state) {
  10270. _sapp.x11.window_state = state;
  10271. if (state == IconicState) {
  10272. _sapp_x11_app_event(SAPP_EVENTTYPE_ICONIFIED);
  10273. }
  10274. else if (state == NormalState) {
  10275. _sapp_x11_app_event(SAPP_EVENTTYPE_RESTORED);
  10276. }
  10277. }
  10278. }
  10279. }
  10280. }
  10281. _SOKOL_PRIVATE void _sapp_x11_on_selectionnotify(XEvent* event) {
  10282. if (event->xselection.property == _sapp.x11.xdnd.XdndSelection) {
  10283. char* data = 0;
  10284. uint32_t result = _sapp_x11_get_window_property(event->xselection.requestor,
  10285. event->xselection.property,
  10286. event->xselection.target,
  10287. (unsigned char**) &data);
  10288. if (_sapp.drop.enabled && result) {
  10289. if (_sapp_x11_parse_dropped_files_list(data)) {
  10290. _sapp.mouse.dx = 0.0f;
  10291. _sapp.mouse.dy = 0.0f;
  10292. if (_sapp_events_enabled()) {
  10293. // FIXME: Figure out how to get modifier key state here.
  10294. // The XSelection event has no 'state' item, and
  10295. // XQueryKeymap() always returns a zeroed array.
  10296. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  10297. _sapp_call_event(&_sapp.event);
  10298. }
  10299. }
  10300. }
  10301. if (_sapp.x11.xdnd.version >= 2) {
  10302. XEvent reply;
  10303. _sapp_clear(&reply, sizeof(reply));
  10304. reply.type = ClientMessage;
  10305. reply.xclient.window = _sapp.x11.xdnd.source;
  10306. reply.xclient.message_type = _sapp.x11.xdnd.XdndFinished;
  10307. reply.xclient.format = 32;
  10308. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10309. reply.xclient.data.l[1] = result;
  10310. reply.xclient.data.l[2] = (long)_sapp.x11.xdnd.XdndActionCopy;
  10311. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10312. XFlush(_sapp.x11.display);
  10313. }
  10314. }
  10315. }
  10316. _SOKOL_PRIVATE void _sapp_x11_on_clientmessage(XEvent* event) {
  10317. if (XFilterEvent(event, None)) {
  10318. return;
  10319. }
  10320. if (event->xclient.message_type == _sapp.x11.WM_PROTOCOLS) {
  10321. const Atom protocol = (Atom)event->xclient.data.l[0];
  10322. if (protocol == _sapp.x11.WM_DELETE_WINDOW) {
  10323. _sapp.quit_requested = true;
  10324. }
  10325. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndEnter) {
  10326. const bool is_list = 0 != (event->xclient.data.l[1] & 1);
  10327. _sapp.x11.xdnd.source = (Window)event->xclient.data.l[0];
  10328. _sapp.x11.xdnd.version = event->xclient.data.l[1] >> 24;
  10329. _sapp.x11.xdnd.format = None;
  10330. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10331. return;
  10332. }
  10333. uint32_t count = 0;
  10334. Atom* formats = 0;
  10335. if (is_list) {
  10336. count = _sapp_x11_get_window_property(_sapp.x11.xdnd.source, _sapp.x11.xdnd.XdndTypeList, XA_ATOM, (unsigned char**)&formats);
  10337. } else {
  10338. count = 3;
  10339. formats = (Atom*) event->xclient.data.l + 2;
  10340. }
  10341. for (uint32_t i = 0; i < count; i++) {
  10342. if (formats[i] == _sapp.x11.xdnd.text_uri_list) {
  10343. _sapp.x11.xdnd.format = _sapp.x11.xdnd.text_uri_list;
  10344. break;
  10345. }
  10346. }
  10347. if (is_list && formats) {
  10348. XFree(formats);
  10349. }
  10350. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndDrop) {
  10351. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10352. return;
  10353. }
  10354. Time time = CurrentTime;
  10355. if (_sapp.x11.xdnd.format) {
  10356. if (_sapp.x11.xdnd.version >= 1) {
  10357. time = (Time)event->xclient.data.l[2];
  10358. }
  10359. XConvertSelection(_sapp.x11.display,
  10360. _sapp.x11.xdnd.XdndSelection,
  10361. _sapp.x11.xdnd.format,
  10362. _sapp.x11.xdnd.XdndSelection,
  10363. _sapp.x11.window,
  10364. time);
  10365. } else if (_sapp.x11.xdnd.version >= 2) {
  10366. XEvent reply;
  10367. _sapp_clear(&reply, sizeof(reply));
  10368. reply.type = ClientMessage;
  10369. reply.xclient.window = _sapp.x11.xdnd.source;
  10370. reply.xclient.message_type = _sapp.x11.xdnd.XdndFinished;
  10371. reply.xclient.format = 32;
  10372. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10373. reply.xclient.data.l[1] = 0; // drag was rejected
  10374. reply.xclient.data.l[2] = None;
  10375. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10376. XFlush(_sapp.x11.display);
  10377. }
  10378. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndPosition) {
  10379. // drag operation has moved over the window
  10380. // FIXME: we could track the mouse position here, but
  10381. // this isn't implemented on other platforms either so far
  10382. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10383. return;
  10384. }
  10385. XEvent reply;
  10386. _sapp_clear(&reply, sizeof(reply));
  10387. reply.type = ClientMessage;
  10388. reply.xclient.window = _sapp.x11.xdnd.source;
  10389. reply.xclient.message_type = _sapp.x11.xdnd.XdndStatus;
  10390. reply.xclient.format = 32;
  10391. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10392. if (_sapp.x11.xdnd.format) {
  10393. /* reply that we are ready to copy the dragged data */
  10394. reply.xclient.data.l[1] = 1; // accept with no rectangle
  10395. if (_sapp.x11.xdnd.version >= 2) {
  10396. reply.xclient.data.l[4] = (long)_sapp.x11.xdnd.XdndActionCopy;
  10397. }
  10398. }
  10399. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10400. XFlush(_sapp.x11.display);
  10401. }
  10402. }
  10403. _SOKOL_PRIVATE void _sapp_x11_on_selectionrequest(XEvent* event) {
  10404. XSelectionRequestEvent* req = &event->xselectionrequest;
  10405. if (req->selection != _sapp.x11.CLIPBOARD) {
  10406. return;
  10407. }
  10408. if (!_sapp.clipboard.enabled) {
  10409. return;
  10410. }
  10411. SOKOL_ASSERT(_sapp.clipboard.buffer);
  10412. XSelectionEvent reply;
  10413. _sapp_clear(&reply, sizeof(reply));
  10414. reply.type = SelectionNotify;
  10415. reply.display = req->display;
  10416. reply.requestor = req->requestor;
  10417. reply.selection = req->selection;
  10418. reply.target = req->target;
  10419. reply.property = req->property;
  10420. reply.time = req->time;
  10421. if (req->target == _sapp.x11.UTF8_STRING) {
  10422. XChangeProperty(_sapp.x11.display,
  10423. req->requestor,
  10424. req->property,
  10425. _sapp.x11.UTF8_STRING,
  10426. 8,
  10427. PropModeReplace,
  10428. (unsigned char*) _sapp.clipboard.buffer,
  10429. strlen(_sapp.clipboard.buffer));
  10430. } else if (req->target == _sapp.x11.TARGETS) {
  10431. XChangeProperty(_sapp.x11.display,
  10432. req->requestor,
  10433. req->property,
  10434. XA_ATOM,
  10435. 32,
  10436. PropModeReplace,
  10437. (unsigned char*) &_sapp.x11.UTF8_STRING,
  10438. 1);
  10439. } else {
  10440. reply.property = None;
  10441. }
  10442. XSendEvent(_sapp.x11.display, req->requestor, False, 0, (XEvent*) &reply);
  10443. }
  10444. _SOKOL_PRIVATE void _sapp_x11_process_event(XEvent* event) {
  10445. switch (event->type) {
  10446. case GenericEvent:
  10447. _sapp_x11_on_genericevent(event);
  10448. break;
  10449. case FocusIn:
  10450. _sapp_x11_on_focusin(event);
  10451. break;
  10452. case FocusOut:
  10453. _sapp_x11_on_focusout(event);
  10454. break;
  10455. case KeyPress:
  10456. _sapp_x11_on_keypress(event);
  10457. break;
  10458. case KeyRelease:
  10459. _sapp_x11_on_keyrelease(event);
  10460. break;
  10461. case ButtonPress:
  10462. _sapp_x11_on_buttonpress(event);
  10463. break;
  10464. case ButtonRelease:
  10465. _sapp_x11_on_buttonrelease(event);
  10466. break;
  10467. case EnterNotify:
  10468. _sapp_x11_on_enternotify(event);
  10469. break;
  10470. case LeaveNotify:
  10471. _sapp_x11_on_leavenotify(event);
  10472. break;
  10473. case MotionNotify:
  10474. _sapp_x11_on_motionnotify(event);
  10475. break;
  10476. case ConfigureNotify:
  10477. _sapp_x11_on_configurenotify(event);
  10478. break;
  10479. case PropertyNotify:
  10480. _sapp_x11_on_propertynotify(event);
  10481. break;
  10482. case SelectionNotify:
  10483. _sapp_x11_on_selectionnotify(event);
  10484. break;
  10485. case SelectionRequest:
  10486. _sapp_x11_on_selectionrequest(event);
  10487. break;
  10488. case DestroyNotify:
  10489. // not a bug
  10490. break;
  10491. case ClientMessage:
  10492. _sapp_x11_on_clientmessage(event);
  10493. break;
  10494. }
  10495. }
  10496. #if !defined(_SAPP_GLX)
  10497. _SOKOL_PRIVATE void _sapp_egl_init(void) {
  10498. #if defined(SOKOL_GLCORE)
  10499. if (!eglBindAPI(EGL_OPENGL_API)) {
  10500. _SAPP_PANIC(LINUX_EGL_BIND_OPENGL_API_FAILED);
  10501. }
  10502. #else
  10503. if (!eglBindAPI(EGL_OPENGL_ES_API)) {
  10504. _SAPP_PANIC(LINUX_EGL_BIND_OPENGL_ES_API_FAILED);
  10505. }
  10506. #endif
  10507. _sapp.egl.display = eglGetDisplay((EGLNativeDisplayType)_sapp.x11.display);
  10508. if (EGL_NO_DISPLAY == _sapp.egl.display) {
  10509. _SAPP_PANIC(LINUX_EGL_GET_DISPLAY_FAILED);
  10510. }
  10511. EGLint major, minor;
  10512. if (!eglInitialize(_sapp.egl.display, &major, &minor)) {
  10513. _SAPP_PANIC(LINUX_EGL_INITIALIZE_FAILED);
  10514. }
  10515. EGLint sample_count = _sapp.desc.sample_count > 1 ? _sapp.desc.sample_count : 0;
  10516. EGLint alpha_size = _sapp.desc.alpha ? 8 : 0;
  10517. const EGLint config_attrs[] = {
  10518. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  10519. #if defined(SOKOL_GLCORE)
  10520. EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
  10521. #elif defined(SOKOL_GLES3)
  10522. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  10523. #endif
  10524. EGL_RED_SIZE, 8,
  10525. EGL_GREEN_SIZE, 8,
  10526. EGL_BLUE_SIZE, 8,
  10527. EGL_ALPHA_SIZE, alpha_size,
  10528. EGL_DEPTH_SIZE, 24,
  10529. EGL_STENCIL_SIZE, 8,
  10530. EGL_SAMPLE_BUFFERS, _sapp.desc.sample_count > 1 ? 1 : 0,
  10531. EGL_SAMPLES, sample_count,
  10532. EGL_NONE,
  10533. };
  10534. EGLConfig egl_configs[32];
  10535. EGLint config_count;
  10536. if (!eglChooseConfig(_sapp.egl.display, config_attrs, egl_configs, 32, &config_count) || config_count == 0) {
  10537. _SAPP_PANIC(LINUX_EGL_NO_CONFIGS);
  10538. }
  10539. EGLConfig config = egl_configs[0];
  10540. for (int i = 0; i < config_count; ++i) {
  10541. EGLConfig c = egl_configs[i];
  10542. EGLint r, g, b, a, d, s, n;
  10543. if (eglGetConfigAttrib(_sapp.egl.display, c, EGL_RED_SIZE, &r) &&
  10544. eglGetConfigAttrib(_sapp.egl.display, c, EGL_GREEN_SIZE, &g) &&
  10545. eglGetConfigAttrib(_sapp.egl.display, c, EGL_BLUE_SIZE, &b) &&
  10546. eglGetConfigAttrib(_sapp.egl.display, c, EGL_ALPHA_SIZE, &a) &&
  10547. eglGetConfigAttrib(_sapp.egl.display, c, EGL_DEPTH_SIZE, &d) &&
  10548. eglGetConfigAttrib(_sapp.egl.display, c, EGL_STENCIL_SIZE, &s) &&
  10549. eglGetConfigAttrib(_sapp.egl.display, c, EGL_SAMPLES, &n) &&
  10550. (r == 8) && (g == 8) && (b == 8) && (a == alpha_size) && (d == 24) && (s == 8) && (n == sample_count)) {
  10551. config = c;
  10552. break;
  10553. }
  10554. }
  10555. EGLint visual_id;
  10556. if (!eglGetConfigAttrib(_sapp.egl.display, config, EGL_NATIVE_VISUAL_ID, &visual_id)) {
  10557. _SAPP_PANIC(LINUX_EGL_NO_NATIVE_VISUAL);
  10558. }
  10559. XVisualInfo visual_info_template;
  10560. _sapp_clear(&visual_info_template, sizeof(visual_info_template));
  10561. visual_info_template.visualid = (VisualID)visual_id;
  10562. int num_visuals;
  10563. XVisualInfo* visual_info = XGetVisualInfo(_sapp.x11.display, VisualIDMask, &visual_info_template, &num_visuals);
  10564. if (!visual_info) {
  10565. _SAPP_PANIC(LINUX_EGL_GET_VISUAL_INFO_FAILED);
  10566. }
  10567. _sapp_x11_create_window(visual_info->visual, visual_info->depth);
  10568. XFree(visual_info);
  10569. _sapp.egl.surface = eglCreateWindowSurface(_sapp.egl.display, config, (EGLNativeWindowType)_sapp.x11.window, NULL);
  10570. if (EGL_NO_SURFACE == _sapp.egl.surface) {
  10571. _SAPP_PANIC(LINUX_EGL_CREATE_WINDOW_SURFACE_FAILED);
  10572. }
  10573. EGLint ctx_attrs[] = {
  10574. #if defined(SOKOL_GLCORE)
  10575. EGL_CONTEXT_MAJOR_VERSION, _sapp.desc.gl_major_version,
  10576. EGL_CONTEXT_MINOR_VERSION, _sapp.desc.gl_minor_version,
  10577. EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
  10578. #elif defined(SOKOL_GLES3)
  10579. EGL_CONTEXT_CLIENT_VERSION, 3,
  10580. #endif
  10581. EGL_NONE,
  10582. };
  10583. _sapp.egl.context = eglCreateContext(_sapp.egl.display, config, EGL_NO_CONTEXT, ctx_attrs);
  10584. if (EGL_NO_CONTEXT == _sapp.egl.context) {
  10585. _SAPP_PANIC(LINUX_EGL_CREATE_CONTEXT_FAILED);
  10586. }
  10587. if (!eglMakeCurrent(_sapp.egl.display, _sapp.egl.surface, _sapp.egl.surface, _sapp.egl.context)) {
  10588. _SAPP_PANIC(LINUX_EGL_MAKE_CURRENT_FAILED);
  10589. }
  10590. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  10591. eglSwapInterval(_sapp.egl.display, _sapp.swap_interval);
  10592. }
  10593. _SOKOL_PRIVATE void _sapp_egl_destroy(void) {
  10594. if (_sapp.egl.display != EGL_NO_DISPLAY) {
  10595. eglMakeCurrent(_sapp.egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  10596. if (_sapp.egl.context != EGL_NO_CONTEXT) {
  10597. eglDestroyContext(_sapp.egl.display, _sapp.egl.context);
  10598. _sapp.egl.context = EGL_NO_CONTEXT;
  10599. }
  10600. if (_sapp.egl.surface != EGL_NO_SURFACE) {
  10601. eglDestroySurface(_sapp.egl.display, _sapp.egl.surface);
  10602. _sapp.egl.surface = EGL_NO_SURFACE;
  10603. }
  10604. eglTerminate(_sapp.egl.display);
  10605. _sapp.egl.display = EGL_NO_DISPLAY;
  10606. }
  10607. }
  10608. #endif /* _SAPP_GLX */
  10609. _SOKOL_PRIVATE void _sapp_linux_run(const sapp_desc* desc) {
  10610. /* The following lines are here to trigger a linker error instead of an
  10611. obscure runtime error if the user has forgotten to add -pthread to
  10612. the compiler or linker options. They have no other purpose.
  10613. */
  10614. pthread_attr_t pthread_attr;
  10615. pthread_attr_init(&pthread_attr);
  10616. pthread_attr_destroy(&pthread_attr);
  10617. _sapp_init_state(desc);
  10618. _sapp.x11.window_state = NormalState;
  10619. XInitThreads();
  10620. XrmInitialize();
  10621. _sapp.x11.display = XOpenDisplay(NULL);
  10622. if (!_sapp.x11.display) {
  10623. _SAPP_PANIC(LINUX_X11_OPEN_DISPLAY_FAILED);
  10624. }
  10625. _sapp.x11.screen = DefaultScreen(_sapp.x11.display);
  10626. _sapp.x11.root = DefaultRootWindow(_sapp.x11.display);
  10627. _sapp_x11_query_system_dpi();
  10628. _sapp.dpi_scale = _sapp.x11.dpi / 96.0f;
  10629. _sapp_x11_init_extensions();
  10630. _sapp_x11_create_cursors();
  10631. XkbSetDetectableAutoRepeat(_sapp.x11.display, true, NULL);
  10632. _sapp_x11_init_keytable();
  10633. #if defined(_SAPP_GLX)
  10634. _sapp_glx_init();
  10635. Visual* visual = 0;
  10636. int depth = 0;
  10637. _sapp_glx_choose_visual(&visual, &depth);
  10638. _sapp_x11_create_window(visual, depth);
  10639. _sapp_glx_create_context();
  10640. _sapp_glx_swapinterval(_sapp.swap_interval);
  10641. #else
  10642. _sapp_egl_init();
  10643. #endif
  10644. sapp_set_icon(&desc->icon);
  10645. _sapp.valid = true;
  10646. _sapp_x11_show_window();
  10647. if (_sapp.fullscreen) {
  10648. _sapp_x11_set_fullscreen(true);
  10649. }
  10650. XFlush(_sapp.x11.display);
  10651. while (!_sapp.quit_ordered) {
  10652. _sapp_timing_measure(&_sapp.timing);
  10653. int count = XPending(_sapp.x11.display);
  10654. while (count--) {
  10655. XEvent event;
  10656. XNextEvent(_sapp.x11.display, &event);
  10657. _sapp_x11_process_event(&event);
  10658. }
  10659. _sapp_frame();
  10660. #if defined(_SAPP_GLX)
  10661. _sapp_glx_swap_buffers();
  10662. #else
  10663. eglSwapBuffers(_sapp.egl.display, _sapp.egl.surface);
  10664. #endif
  10665. XFlush(_sapp.x11.display);
  10666. /* handle quit-requested, either from window or from sapp_request_quit() */
  10667. if (_sapp.quit_requested && !_sapp.quit_ordered) {
  10668. /* give user code a chance to intervene */
  10669. _sapp_x11_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  10670. /* if user code hasn't intervened, quit the app */
  10671. if (_sapp.quit_requested) {
  10672. _sapp.quit_ordered = true;
  10673. }
  10674. }
  10675. }
  10676. _sapp_call_cleanup();
  10677. #if defined(_SAPP_GLX)
  10678. _sapp_glx_destroy_context();
  10679. #else
  10680. _sapp_egl_destroy();
  10681. #endif
  10682. _sapp_x11_destroy_window();
  10683. _sapp_x11_destroy_cursors();
  10684. XCloseDisplay(_sapp.x11.display);
  10685. _sapp_discard_state();
  10686. }
  10687. #if !defined(SOKOL_NO_ENTRY)
  10688. int main(int argc, char* argv[]) {
  10689. sapp_desc desc = sokol_main(argc, argv);
  10690. _sapp_linux_run(&desc);
  10691. return 0;
  10692. }
  10693. #endif /* SOKOL_NO_ENTRY */
  10694. #endif /* _SAPP_LINUX */
  10695. // ██████ ██ ██ ██████ ██ ██ ██████
  10696. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  10697. // ██████ ██ ██ ██████ ██ ██ ██
  10698. // ██ ██ ██ ██ ██ ██ ██ ██
  10699. // ██ ██████ ██████ ███████ ██ ██████
  10700. //
  10701. // >>public
  10702. #if defined(SOKOL_NO_ENTRY)
  10703. SOKOL_API_IMPL void sapp_run(const sapp_desc* desc) {
  10704. SOKOL_ASSERT(desc);
  10705. #if defined(_SAPP_MACOS)
  10706. _sapp_macos_run(desc);
  10707. #elif defined(_SAPP_IOS)
  10708. _sapp_ios_run(desc);
  10709. #elif defined(_SAPP_EMSCRIPTEN)
  10710. _sapp_emsc_run(desc);
  10711. #elif defined(_SAPP_WIN32)
  10712. _sapp_win32_run(desc);
  10713. #elif defined(_SAPP_LINUX)
  10714. _sapp_linux_run(desc);
  10715. #else
  10716. #error "sapp_run() not supported on this platform"
  10717. #endif
  10718. }
  10719. /* this is just a stub so the linker doesn't complain */
  10720. sapp_desc sokol_main(int argc, char* argv[]) {
  10721. _SOKOL_UNUSED(argc);
  10722. _SOKOL_UNUSED(argv);
  10723. sapp_desc desc;
  10724. _sapp_clear(&desc, sizeof(desc));
  10725. return desc;
  10726. }
  10727. #else
  10728. /* likewise, in normal mode, sapp_run() is just an empty stub */
  10729. SOKOL_API_IMPL void sapp_run(const sapp_desc* desc) {
  10730. _SOKOL_UNUSED(desc);
  10731. }
  10732. #endif
  10733. SOKOL_API_IMPL bool sapp_isvalid(void) {
  10734. return _sapp.valid;
  10735. }
  10736. SOKOL_API_IMPL void* sapp_userdata(void) {
  10737. return _sapp.desc.user_data;
  10738. }
  10739. SOKOL_API_IMPL sapp_desc sapp_query_desc(void) {
  10740. return _sapp.desc;
  10741. }
  10742. SOKOL_API_IMPL uint64_t sapp_frame_count(void) {
  10743. return _sapp.frame_count;
  10744. }
  10745. SOKOL_API_IMPL double sapp_frame_duration(void) {
  10746. return _sapp_timing_get_avg(&_sapp.timing);
  10747. }
  10748. SOKOL_API_IMPL int sapp_width(void) {
  10749. return (_sapp.framebuffer_width > 0) ? _sapp.framebuffer_width : 1;
  10750. }
  10751. SOKOL_API_IMPL float sapp_widthf(void) {
  10752. return (float)sapp_width();
  10753. }
  10754. SOKOL_API_IMPL int sapp_height(void) {
  10755. return (_sapp.framebuffer_height > 0) ? _sapp.framebuffer_height : 1;
  10756. }
  10757. SOKOL_API_IMPL float sapp_heightf(void) {
  10758. return (float)sapp_height();
  10759. }
  10760. SOKOL_API_IMPL int sapp_color_format(void) {
  10761. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  10762. switch (_sapp.wgpu.render_format) {
  10763. case WGPUTextureFormat_RGBA8Unorm:
  10764. return _SAPP_PIXELFORMAT_RGBA8;
  10765. case WGPUTextureFormat_BGRA8Unorm:
  10766. return _SAPP_PIXELFORMAT_BGRA8;
  10767. default:
  10768. SOKOL_UNREACHABLE;
  10769. return 0;
  10770. }
  10771. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  10772. return _SAPP_PIXELFORMAT_BGRA8;
  10773. #else
  10774. return _SAPP_PIXELFORMAT_RGBA8;
  10775. #endif
  10776. }
  10777. SOKOL_API_IMPL int sapp_depth_format(void) {
  10778. return _SAPP_PIXELFORMAT_DEPTH_STENCIL;
  10779. }
  10780. SOKOL_API_IMPL int sapp_sample_count(void) {
  10781. return _sapp.sample_count;
  10782. }
  10783. SOKOL_API_IMPL bool sapp_high_dpi(void) {
  10784. return _sapp.desc.high_dpi && (_sapp.dpi_scale >= 1.5f);
  10785. }
  10786. SOKOL_API_IMPL float sapp_dpi_scale(void) {
  10787. return _sapp.dpi_scale;
  10788. }
  10789. SOKOL_API_IMPL const void* sapp_egl_get_display(void) {
  10790. SOKOL_ASSERT(_sapp.valid);
  10791. #if defined(_SAPP_ANDROID)
  10792. return _sapp.android.display;
  10793. #elif defined(_SAPP_LINUX) && !defined(_SAPP_GLX)
  10794. return _sapp.egl.display;
  10795. #else
  10796. return 0;
  10797. #endif
  10798. }
  10799. SOKOL_API_IMPL const void* sapp_egl_get_context(void) {
  10800. SOKOL_ASSERT(_sapp.valid);
  10801. #if defined(_SAPP_ANDROID)
  10802. return _sapp.android.context;
  10803. #elif defined(_SAPP_LINUX) && !defined(_SAPP_GLX)
  10804. return _sapp.egl.context;
  10805. #else
  10806. return 0;
  10807. #endif
  10808. }
  10809. SOKOL_API_IMPL void sapp_show_keyboard(bool show) {
  10810. #if defined(_SAPP_IOS)
  10811. _sapp_ios_show_keyboard(show);
  10812. #elif defined(_SAPP_ANDROID)
  10813. _sapp_android_show_keyboard(show);
  10814. #else
  10815. _SOKOL_UNUSED(show);
  10816. #endif
  10817. }
  10818. SOKOL_API_IMPL bool sapp_keyboard_shown(void) {
  10819. return _sapp.onscreen_keyboard_shown;
  10820. }
  10821. SOKOL_API_IMPL bool sapp_is_fullscreen(void) {
  10822. return _sapp.fullscreen;
  10823. }
  10824. SOKOL_API_IMPL void sapp_toggle_fullscreen(void) {
  10825. #if defined(_SAPP_MACOS)
  10826. _sapp_macos_toggle_fullscreen();
  10827. #elif defined(_SAPP_WIN32)
  10828. _sapp_win32_toggle_fullscreen();
  10829. #elif defined(_SAPP_LINUX)
  10830. _sapp_x11_toggle_fullscreen();
  10831. #endif
  10832. }
  10833. /* NOTE that sapp_show_mouse() does not "stack" like the Win32 or macOS API functions! */
  10834. SOKOL_API_IMPL void sapp_show_mouse(bool show) {
  10835. if (_sapp.mouse.shown != show) {
  10836. #if defined(_SAPP_MACOS)
  10837. _sapp_macos_update_cursor(_sapp.mouse.current_cursor, show);
  10838. #elif defined(_SAPP_WIN32)
  10839. _sapp_win32_update_cursor(_sapp.mouse.current_cursor, show, false);
  10840. #elif defined(_SAPP_LINUX)
  10841. _sapp_x11_update_cursor(_sapp.mouse.current_cursor, show);
  10842. #elif defined(_SAPP_EMSCRIPTEN)
  10843. _sapp_emsc_update_cursor(_sapp.mouse.current_cursor, show);
  10844. #endif
  10845. _sapp.mouse.shown = show;
  10846. }
  10847. }
  10848. SOKOL_API_IMPL bool sapp_mouse_shown(void) {
  10849. return _sapp.mouse.shown;
  10850. }
  10851. SOKOL_API_IMPL void sapp_lock_mouse(bool lock) {
  10852. #if defined(_SAPP_MACOS)
  10853. _sapp_macos_lock_mouse(lock);
  10854. #elif defined(_SAPP_EMSCRIPTEN)
  10855. _sapp_emsc_lock_mouse(lock);
  10856. #elif defined(_SAPP_WIN32)
  10857. _sapp_win32_lock_mouse(lock);
  10858. #elif defined(_SAPP_LINUX)
  10859. _sapp_x11_lock_mouse(lock);
  10860. #else
  10861. _sapp.mouse.locked = lock;
  10862. #endif
  10863. }
  10864. SOKOL_API_IMPL bool sapp_mouse_locked(void) {
  10865. return _sapp.mouse.locked;
  10866. }
  10867. SOKOL_API_IMPL void sapp_set_mouse_cursor(sapp_mouse_cursor cursor) {
  10868. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  10869. if (_sapp.mouse.current_cursor != cursor) {
  10870. #if defined(_SAPP_MACOS)
  10871. _sapp_macos_update_cursor(cursor, _sapp.mouse.shown);
  10872. #elif defined(_SAPP_WIN32)
  10873. _sapp_win32_update_cursor(cursor, _sapp.mouse.shown, false);
  10874. #elif defined(_SAPP_LINUX)
  10875. _sapp_x11_update_cursor(cursor, _sapp.mouse.shown);
  10876. #elif defined(_SAPP_EMSCRIPTEN)
  10877. _sapp_emsc_update_cursor(cursor, _sapp.mouse.shown);
  10878. #endif
  10879. _sapp.mouse.current_cursor = cursor;
  10880. }
  10881. }
  10882. SOKOL_API_IMPL sapp_mouse_cursor sapp_get_mouse_cursor(void) {
  10883. return _sapp.mouse.current_cursor;
  10884. }
  10885. SOKOL_API_IMPL void sapp_request_quit(void) {
  10886. _sapp.quit_requested = true;
  10887. }
  10888. SOKOL_API_IMPL void sapp_cancel_quit(void) {
  10889. _sapp.quit_requested = false;
  10890. }
  10891. SOKOL_API_IMPL void sapp_quit(void) {
  10892. _sapp.quit_ordered = true;
  10893. }
  10894. SOKOL_API_IMPL void sapp_consume_event(void) {
  10895. _sapp.event_consumed = true;
  10896. }
  10897. /* NOTE: on HTML5, sapp_set_clipboard_string() must be called from within event handler! */
  10898. SOKOL_API_IMPL void sapp_set_clipboard_string(const char* str) {
  10899. if (!_sapp.clipboard.enabled) {
  10900. return;
  10901. }
  10902. SOKOL_ASSERT(str);
  10903. #if defined(_SAPP_MACOS)
  10904. _sapp_macos_set_clipboard_string(str);
  10905. #elif defined(_SAPP_EMSCRIPTEN)
  10906. _sapp_emsc_set_clipboard_string(str);
  10907. #elif defined(_SAPP_WIN32)
  10908. _sapp_win32_set_clipboard_string(str);
  10909. #elif defined(_SAPP_LINUX)
  10910. _sapp_x11_set_clipboard_string(str);
  10911. #else
  10912. /* not implemented */
  10913. #endif
  10914. _sapp_strcpy(str, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  10915. }
  10916. SOKOL_API_IMPL const char* sapp_get_clipboard_string(void) {
  10917. if (!_sapp.clipboard.enabled) {
  10918. return "";
  10919. }
  10920. #if defined(_SAPP_MACOS)
  10921. return _sapp_macos_get_clipboard_string();
  10922. #elif defined(_SAPP_EMSCRIPTEN)
  10923. return _sapp.clipboard.buffer;
  10924. #elif defined(_SAPP_WIN32)
  10925. return _sapp_win32_get_clipboard_string();
  10926. #elif defined(_SAPP_LINUX)
  10927. return _sapp_x11_get_clipboard_string();
  10928. #else
  10929. /* not implemented */
  10930. return _sapp.clipboard.buffer;
  10931. #endif
  10932. }
  10933. SOKOL_API_IMPL void sapp_set_window_title(const char* title) {
  10934. SOKOL_ASSERT(title);
  10935. _sapp_strcpy(title, _sapp.window_title, sizeof(_sapp.window_title));
  10936. #if defined(_SAPP_MACOS)
  10937. _sapp_macos_update_window_title();
  10938. #elif defined(_SAPP_WIN32)
  10939. _sapp_win32_update_window_title();
  10940. #elif defined(_SAPP_LINUX)
  10941. _sapp_x11_update_window_title();
  10942. #endif
  10943. }
  10944. SOKOL_API_IMPL void sapp_set_icon(const sapp_icon_desc* desc) {
  10945. SOKOL_ASSERT(desc);
  10946. if (desc->sokol_default) {
  10947. if (0 == _sapp.default_icon_pixels) {
  10948. _sapp_setup_default_icon();
  10949. }
  10950. SOKOL_ASSERT(0 != _sapp.default_icon_pixels);
  10951. desc = &_sapp.default_icon_desc;
  10952. }
  10953. const int num_images = _sapp_icon_num_images(desc);
  10954. if (num_images == 0) {
  10955. return;
  10956. }
  10957. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  10958. if (!_sapp_validate_icon_desc(desc, num_images)) {
  10959. return;
  10960. }
  10961. #if defined(_SAPP_MACOS)
  10962. _sapp_macos_set_icon(desc, num_images);
  10963. #elif defined(_SAPP_WIN32)
  10964. _sapp_win32_set_icon(desc, num_images);
  10965. #elif defined(_SAPP_LINUX)
  10966. _sapp_x11_set_icon(desc, num_images);
  10967. #elif defined(_SAPP_EMSCRIPTEN)
  10968. _sapp_emsc_set_icon(desc, num_images);
  10969. #endif
  10970. }
  10971. SOKOL_API_IMPL int sapp_get_num_dropped_files(void) {
  10972. SOKOL_ASSERT(_sapp.drop.enabled);
  10973. return _sapp.drop.num_files;
  10974. }
  10975. SOKOL_API_IMPL const char* sapp_get_dropped_file_path(int index) {
  10976. SOKOL_ASSERT(_sapp.drop.enabled);
  10977. SOKOL_ASSERT((index >= 0) && (index < _sapp.drop.num_files));
  10978. SOKOL_ASSERT(_sapp.drop.buffer);
  10979. if (!_sapp.drop.enabled) {
  10980. return "";
  10981. }
  10982. if ((index < 0) || (index >= _sapp.drop.max_files)) {
  10983. return "";
  10984. }
  10985. return (const char*) _sapp_dropped_file_path_ptr(index);
  10986. }
  10987. SOKOL_API_IMPL uint32_t sapp_html5_get_dropped_file_size(int index) {
  10988. SOKOL_ASSERT(_sapp.drop.enabled);
  10989. SOKOL_ASSERT((index >= 0) && (index < _sapp.drop.num_files));
  10990. #if defined(_SAPP_EMSCRIPTEN)
  10991. if (!_sapp.drop.enabled) {
  10992. return 0;
  10993. }
  10994. return sapp_js_dropped_file_size(index);
  10995. #else
  10996. (void)index;
  10997. return 0;
  10998. #endif
  10999. }
  11000. SOKOL_API_IMPL void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request) {
  11001. SOKOL_ASSERT(_sapp.drop.enabled);
  11002. SOKOL_ASSERT(request);
  11003. SOKOL_ASSERT(request->callback);
  11004. SOKOL_ASSERT(request->buffer.ptr);
  11005. SOKOL_ASSERT(request->buffer.size > 0);
  11006. #if defined(_SAPP_EMSCRIPTEN)
  11007. const int index = request->dropped_file_index;
  11008. sapp_html5_fetch_error error_code = SAPP_HTML5_FETCH_ERROR_NO_ERROR;
  11009. if ((index < 0) || (index >= _sapp.drop.num_files)) {
  11010. error_code = SAPP_HTML5_FETCH_ERROR_OTHER;
  11011. }
  11012. if (sapp_html5_get_dropped_file_size(index) > request->buffer.size) {
  11013. error_code = SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL;
  11014. }
  11015. if (SAPP_HTML5_FETCH_ERROR_NO_ERROR != error_code) {
  11016. _sapp_emsc_invoke_fetch_cb(index,
  11017. false, // success
  11018. (int)error_code,
  11019. request->callback,
  11020. 0, // fetched_size
  11021. (void*)request->buffer.ptr,
  11022. request->buffer.size,
  11023. request->user_data);
  11024. }
  11025. else {
  11026. sapp_js_fetch_dropped_file(index,
  11027. request->callback,
  11028. (void*)request->buffer.ptr,
  11029. request->buffer.size,
  11030. request->user_data);
  11031. }
  11032. #else
  11033. (void)request;
  11034. #endif
  11035. }
  11036. SOKOL_API_IMPL const void* sapp_metal_get_device(void) {
  11037. SOKOL_ASSERT(_sapp.valid);
  11038. #if defined(SOKOL_METAL)
  11039. #if defined(_SAPP_MACOS)
  11040. const void* obj = (__bridge const void*) _sapp.macos.mtl_device;
  11041. #else
  11042. const void* obj = (__bridge const void*) _sapp.ios.mtl_device;
  11043. #endif
  11044. SOKOL_ASSERT(obj);
  11045. return obj;
  11046. #else
  11047. return 0;
  11048. #endif
  11049. }
  11050. SOKOL_API_IMPL const void* sapp_metal_get_current_drawable(void) {
  11051. SOKOL_ASSERT(_sapp.valid);
  11052. #if defined(SOKOL_METAL)
  11053. #if defined(_SAPP_MACOS)
  11054. const void* obj = (__bridge const void*) [_sapp.macos.view currentDrawable];
  11055. #else
  11056. const void* obj = (__bridge const void*) [_sapp.ios.view currentDrawable];
  11057. #endif
  11058. SOKOL_ASSERT(obj);
  11059. return obj;
  11060. #else
  11061. return 0;
  11062. #endif
  11063. }
  11064. SOKOL_API_IMPL const void* sapp_metal_get_depth_stencil_texture(void) {
  11065. SOKOL_ASSERT(_sapp.valid);
  11066. #if defined(SOKOL_METAL)
  11067. #if defined(_SAPP_MACOS)
  11068. const void* obj = (__bridge const void*) [_sapp.macos.view depthStencilTexture];
  11069. #else
  11070. const void* obj = (__bridge const void*) [_sapp.ios.view depthStencilTexture];
  11071. #endif
  11072. return obj;
  11073. #else
  11074. return 0;
  11075. #endif
  11076. }
  11077. SOKOL_API_IMPL const void* sapp_metal_get_msaa_color_texture(void) {
  11078. SOKOL_ASSERT(_sapp.valid);
  11079. #if defined(SOKOL_METAL)
  11080. #if defined(_SAPP_MACOS)
  11081. const void* obj = (__bridge const void*) [_sapp.macos.view multisampleColorTexture];
  11082. #else
  11083. const void* obj = (__bridge const void*) [_sapp.ios.view multisampleColorTexture];
  11084. #endif
  11085. return obj;
  11086. #else
  11087. return 0;
  11088. #endif
  11089. }
  11090. SOKOL_API_IMPL const void* sapp_macos_get_window(void) {
  11091. #if defined(_SAPP_MACOS)
  11092. const void* obj = (__bridge const void*) _sapp.macos.window;
  11093. SOKOL_ASSERT(obj);
  11094. return obj;
  11095. #else
  11096. return 0;
  11097. #endif
  11098. }
  11099. SOKOL_API_IMPL const void* sapp_ios_get_window(void) {
  11100. #if defined(_SAPP_IOS)
  11101. const void* obj = (__bridge const void*) _sapp.ios.window;
  11102. SOKOL_ASSERT(obj);
  11103. return obj;
  11104. #else
  11105. return 0;
  11106. #endif
  11107. }
  11108. SOKOL_API_IMPL const void* sapp_d3d11_get_device(void) {
  11109. SOKOL_ASSERT(_sapp.valid);
  11110. #if defined(SOKOL_D3D11)
  11111. return _sapp.d3d11.device;
  11112. #else
  11113. return 0;
  11114. #endif
  11115. }
  11116. SOKOL_API_IMPL const void* sapp_d3d11_get_device_context(void) {
  11117. SOKOL_ASSERT(_sapp.valid);
  11118. #if defined(SOKOL_D3D11)
  11119. return _sapp.d3d11.device_context;
  11120. #else
  11121. return 0;
  11122. #endif
  11123. }
  11124. SOKOL_API_IMPL const void* sapp_d3d11_get_swap_chain(void) {
  11125. SOKOL_ASSERT(_sapp.valid);
  11126. #if defined(SOKOL_D3D11)
  11127. return _sapp.d3d11.swap_chain;
  11128. #else
  11129. return 0;
  11130. #endif
  11131. }
  11132. SOKOL_API_IMPL const void* sapp_d3d11_get_render_view(void) {
  11133. SOKOL_ASSERT(_sapp.valid);
  11134. #if defined(SOKOL_D3D11)
  11135. if (_sapp.sample_count > 1) {
  11136. SOKOL_ASSERT(_sapp.d3d11.msaa_rtv);
  11137. return _sapp.d3d11.msaa_rtv;
  11138. } else {
  11139. SOKOL_ASSERT(_sapp.d3d11.rtv);
  11140. return _sapp.d3d11.rtv;
  11141. }
  11142. #else
  11143. return 0;
  11144. #endif
  11145. }
  11146. SOKOL_API_IMPL const void* sapp_d3d11_get_resolve_view(void) {
  11147. SOKOL_ASSERT(_sapp.valid);
  11148. #if defined(SOKOL_D3D11)
  11149. if (_sapp.sample_count > 1) {
  11150. SOKOL_ASSERT(_sapp.d3d11.rtv);
  11151. return _sapp.d3d11.rtv;
  11152. } else {
  11153. return 0;
  11154. }
  11155. #else
  11156. return 0;
  11157. #endif
  11158. }
  11159. SOKOL_API_IMPL const void* sapp_d3d11_get_depth_stencil_view(void) {
  11160. SOKOL_ASSERT(_sapp.valid);
  11161. #if defined(SOKOL_D3D11)
  11162. return _sapp.d3d11.dsv;
  11163. #else
  11164. return 0;
  11165. #endif
  11166. }
  11167. SOKOL_API_IMPL const void* sapp_win32_get_hwnd(void) {
  11168. SOKOL_ASSERT(_sapp.valid);
  11169. #if defined(_SAPP_WIN32)
  11170. return _sapp.win32.hwnd;
  11171. #else
  11172. return 0;
  11173. #endif
  11174. }
  11175. SOKOL_API_IMPL const void* sapp_wgpu_get_device(void) {
  11176. SOKOL_ASSERT(_sapp.valid);
  11177. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11178. return (const void*) _sapp.wgpu.device;
  11179. #else
  11180. return 0;
  11181. #endif
  11182. }
  11183. SOKOL_API_IMPL const void* sapp_wgpu_get_render_view(void) {
  11184. SOKOL_ASSERT(_sapp.valid);
  11185. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11186. if (_sapp.sample_count > 1) {
  11187. SOKOL_ASSERT(_sapp.wgpu.msaa_view);
  11188. return (const void*) _sapp.wgpu.msaa_view;
  11189. } else {
  11190. SOKOL_ASSERT(_sapp.wgpu.swapchain_view);
  11191. return (const void*) _sapp.wgpu.swapchain_view;
  11192. }
  11193. #else
  11194. return 0;
  11195. #endif
  11196. }
  11197. SOKOL_API_IMPL const void* sapp_wgpu_get_resolve_view(void) {
  11198. SOKOL_ASSERT(_sapp.valid);
  11199. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11200. if (_sapp.sample_count > 1) {
  11201. SOKOL_ASSERT(_sapp.wgpu.swapchain_view);
  11202. return (const void*) _sapp.wgpu.swapchain_view;
  11203. } else {
  11204. return 0;
  11205. }
  11206. #else
  11207. return 0;
  11208. #endif
  11209. }
  11210. SOKOL_API_IMPL const void* sapp_wgpu_get_depth_stencil_view(void) {
  11211. SOKOL_ASSERT(_sapp.valid);
  11212. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11213. return (const void*) _sapp.wgpu.depth_stencil_view;
  11214. #else
  11215. return 0;
  11216. #endif
  11217. }
  11218. SOKOL_API_IMPL uint32_t sapp_gl_get_framebuffer(void) {
  11219. SOKOL_ASSERT(_sapp.valid);
  11220. #if defined(_SAPP_ANY_GL)
  11221. return _sapp.gl.framebuffer;
  11222. #else
  11223. return 0;
  11224. #endif
  11225. }
  11226. SOKOL_API_IMPL int sapp_gl_get_major_version(void) {
  11227. SOKOL_ASSERT(_sapp.valid);
  11228. #if defined(SOKOL_GLCORE)
  11229. return _sapp.desc.gl_major_version;
  11230. #else
  11231. return 0;
  11232. #endif
  11233. }
  11234. SOKOL_API_IMPL int sapp_gl_get_minor_version(void) {
  11235. SOKOL_ASSERT(_sapp.valid);
  11236. #if defined(SOKOL_GLCORE)
  11237. return _sapp.desc.gl_minor_version;
  11238. #else
  11239. return 0;
  11240. #endif
  11241. }
  11242. SOKOL_API_IMPL const void* sapp_android_get_native_activity(void) {
  11243. // NOTE: _sapp.valid is not asserted here because sapp_android_get_native_activity()
  11244. // needs to be callable from within sokol_main() (see: https://github.com/floooh/sokol/issues/708)
  11245. #if defined(_SAPP_ANDROID)
  11246. return (void*)_sapp.android.activity;
  11247. #else
  11248. return 0;
  11249. #endif
  11250. }
  11251. SOKOL_API_IMPL void sapp_html5_ask_leave_site(bool ask) {
  11252. _sapp.html5_ask_leave_site = ask;
  11253. }
  11254. #endif /* SOKOL_APP_IMPL */