2
0

sokol_app.h 479 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542
  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 add a main() entry point
  27. SOKOL_WIN32_FORCE_WINMAIN - define this on Win32 to add a WinMain() entry point (enabled by default unless
  28. SOKOL_WIN32_FORCE_MAIN or SOKOL_NO_ENTRY is defined)
  29. SOKOL_NO_ENTRY - define this if sokol_app.h shouldn't "hijack" the main() function
  30. SOKOL_APP_API_DECL - public function declaration prefix (default: extern)
  31. SOKOL_API_DECL - same as SOKOL_APP_API_DECL
  32. SOKOL_API_IMPL - public function implementation prefix (default: -)
  33. Optionally define the following to force debug checks and validations
  34. even in release mode:
  35. SOKOL_DEBUG - by default this is defined if _DEBUG is defined
  36. If sokol_app.h is compiled as a DLL, define the following before
  37. including the declaration or implementation:
  38. SOKOL_DLL
  39. On Windows, SOKOL_DLL will define SOKOL_APP_API_DECL as __declspec(dllexport)
  40. or __declspec(dllimport) as needed.
  41. if SOKOL_WIN32_FORCE_MAIN and SOKOL_WIN32_FORCE_WINMAIN are both defined,
  42. it is up to the developer to define the desired subsystem.
  43. On Linux, SOKOL_GLCORE can use either GLX or EGL.
  44. GLX is default, set SOKOL_FORCE_EGL to override.
  45. For example code, see https://github.com/floooh/sokol-samples/tree/master/sapp
  46. Portions of the Windows and Linux GL initialization, event-, icon- etc... code
  47. have been taken from GLFW (http://www.glfw.org/).
  48. iOS onscreen keyboard support 'inspired' by libgdx.
  49. Link with the following system libraries:
  50. - on macOS with Metal: Cocoa, QuartzCore, Metal, MetalKit
  51. - on macOS with GL: Cocoa, QuartzCore, OpenGL
  52. - on iOS with Metal: Foundation, UIKit, Metal, MetalKit
  53. - on iOS with GL: Foundation, UIKit, OpenGLES, GLKit
  54. - on Linux with EGL: X11, Xi, Xcursor, EGL, GL (or GLESv2), dl, pthread, m(?)
  55. - on Linux with GLX: X11, Xi, Xcursor, GL, dl, pthread, m(?)
  56. - on Android: GLESv3, EGL, log, android
  57. - on Windows with the MSVC or Clang toolchains: no action needed, libs are defined in-source via pragma-comment-lib
  58. - on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' so that _WIN32 is defined
  59. - link with the following libs: -lkernel32 -luser32 -lshell32
  60. - additionally with the GL backend: -lgdi32
  61. - additionally with the D3D11 backend: -ld3d11 -ldxgi
  62. On Linux, you also need to use the -pthread compiler and linker option, otherwise weird
  63. things will happen, see here for details: https://github.com/floooh/sokol/issues/376
  64. On macOS and iOS, the implementation must be compiled as Objective-C.
  65. On Emscripten:
  66. - for WebGL2: add the linker option `-s USE_WEBGL2=1`
  67. - for WebGPU: compile and link with `--use-port=emdawnwebgpu`
  68. (for more exotic situations, read: https://dawn.googlesource.com/dawn/+/refs/heads/main/src/emdawnwebgpu/pkg/README.md)
  69. FEATURE OVERVIEW
  70. ================
  71. sokol_app.h provides a minimalistic cross-platform API which
  72. implements the 'application-wrapper' parts of a 3D application:
  73. - a common application entry function
  74. - creates a window and 3D-API context/device with a 'default framebuffer'
  75. - makes the rendered frame visible
  76. - provides keyboard-, mouse- and low-level touch-events
  77. - platforms: MacOS, iOS, HTML5, Win32, Linux/RaspberryPi, Android
  78. - 3D-APIs: Metal, D3D11, GL4.1, GL4.3, GLES3, WebGL, WebGL2, NOAPI
  79. FEATURE/PLATFORM MATRIX
  80. =======================
  81. | Windows | macOS | Linux | iOS | Android | HTML5
  82. --------------------+---------+-------+-------+-------+---------+--------
  83. gl 4.x | YES | YES | YES | --- | --- | ---
  84. gles3/webgl2 | --- | --- | YES(2)| YES | YES | YES
  85. metal | --- | YES | --- | YES | --- | ---
  86. d3d11 | YES | --- | --- | --- | --- | ---
  87. noapi | YES | TODO | TODO | --- | TODO | ---
  88. KEY_DOWN | YES | YES | YES | SOME | TODO | YES
  89. KEY_UP | YES | YES | YES | SOME | TODO | YES
  90. CHAR | YES | YES | YES | YES | TODO | YES
  91. MOUSE_DOWN | YES | YES | YES | --- | --- | YES
  92. MOUSE_UP | YES | YES | YES | --- | --- | YES
  93. MOUSE_SCROLL | YES | YES | YES | --- | --- | YES
  94. MOUSE_MOVE | YES | YES | YES | --- | --- | YES
  95. MOUSE_ENTER | YES | YES | YES | --- | --- | YES
  96. MOUSE_LEAVE | YES | YES | YES | --- | --- | YES
  97. TOUCHES_BEGAN | --- | --- | --- | YES | YES | YES
  98. TOUCHES_MOVED | --- | --- | --- | YES | YES | YES
  99. TOUCHES_ENDED | --- | --- | --- | YES | YES | YES
  100. TOUCHES_CANCELLED | --- | --- | --- | YES | YES | YES
  101. RESIZED | YES | YES | YES | YES | YES | YES
  102. ICONIFIED | YES | YES | YES | --- | --- | ---
  103. RESTORED | YES | YES | YES | --- | --- | ---
  104. FOCUSED | YES | YES | YES | --- | --- | YES
  105. UNFOCUSED | YES | YES | YES | --- | --- | YES
  106. SUSPENDED | --- | --- | --- | YES | YES | TODO
  107. RESUMED | --- | --- | --- | YES | YES | TODO
  108. QUIT_REQUESTED | YES | YES | YES | --- | --- | YES
  109. IME | TODO | TODO? | TODO | ??? | TODO | ???
  110. key repeat flag | YES | YES | YES | --- | --- | YES
  111. windowed | YES | YES | YES | --- | --- | YES
  112. fullscreen | YES | YES | YES | YES | YES | ---
  113. mouse hide | YES | YES | YES | --- | --- | YES
  114. mouse lock | YES | YES | YES | --- | --- | YES
  115. set cursor type | YES | YES | YES | --- | --- | YES
  116. screen keyboard | --- | --- | --- | YES | TODO | YES
  117. swap interval | YES | YES | YES | YES | TODO | YES
  118. high-dpi | YES | YES | TODO | YES | YES | YES
  119. clipboard | YES | YES | YES | --- | --- | YES
  120. MSAA | YES | YES | YES | YES | YES | YES
  121. drag'n'drop | YES | YES | YES | --- | --- | YES
  122. window icon | YES | YES(1)| YES | --- | --- | YES
  123. (1) macOS has no regular window icons, instead the dock icon is changed
  124. (2) supported with EGL only (not GLX)
  125. STEP BY STEP
  126. ============
  127. --- Add a sokol_main() function to your code which returns a sapp_desc structure
  128. with initialization parameters and callback function pointers. This
  129. function is called very early, usually at the start of the
  130. platform's entry function (e.g. main or WinMain). You should do as
  131. little as possible here, since the rest of your code might be called
  132. from another thread (this depends on the platform):
  133. sapp_desc sokol_main(int argc, char* argv[]) {
  134. return (sapp_desc) {
  135. .width = 640,
  136. .height = 480,
  137. .init_cb = my_init_func,
  138. .frame_cb = my_frame_func,
  139. .cleanup_cb = my_cleanup_func,
  140. .event_cb = my_event_func,
  141. ...
  142. };
  143. }
  144. To get any logging output in case of errors you need to provide a log
  145. callback. The easiest way is via sokol_log.h:
  146. #include "sokol_log.h"
  147. sapp_desc sokol_main(int argc, char* argv[]) {
  148. return (sapp_desc) {
  149. ...
  150. .logger.func = slog_func,
  151. };
  152. }
  153. There are many more setup parameters, but these are the most important.
  154. For a complete list search for the sapp_desc structure declaration
  155. below.
  156. DO NOT call any sokol-app function from inside sokol_main(), since
  157. sokol-app will not be initialized at this point.
  158. The .width and .height parameters are the preferred size of the 3D
  159. rendering canvas. The actual size may differ from this depending on
  160. platform and other circumstances. Also the canvas size may change at
  161. any time (for instance when the user resizes the application window,
  162. or rotates the mobile device). You can just keep .width and .height
  163. zero-initialized to open a default-sized window (what "default-size"
  164. exactly means is platform-specific, but usually it's a size that covers
  165. most of, but not all, of the display).
  166. All provided function callbacks will be called from the same thread,
  167. but this may be different from the thread where sokol_main() was called.
  168. .init_cb (void (*)(void))
  169. This function is called once after the application window,
  170. 3D rendering context and swap chain have been created. The
  171. function takes no arguments and has no return value.
  172. .frame_cb (void (*)(void))
  173. This is the per-frame callback, which is usually called 60
  174. times per second. This is where your application would update
  175. most of its state and perform all rendering.
  176. .cleanup_cb (void (*)(void))
  177. The cleanup callback is called once right before the application
  178. quits.
  179. .event_cb (void (*)(const sapp_event* event))
  180. The event callback is mainly for input handling, but is also
  181. used to communicate other types of events to the application. Keep the
  182. event_cb struct member zero-initialized if your application doesn't require
  183. event handling.
  184. As you can see, those 'standard callbacks' don't have a user_data
  185. argument, so any data that needs to be preserved between callbacks
  186. must live in global variables. If keeping state in global variables
  187. is not an option, there's an alternative set of callbacks with
  188. an additional user_data pointer argument:
  189. .user_data (void*)
  190. The user-data argument for the callbacks below
  191. .init_userdata_cb (void (*)(void* user_data))
  192. .frame_userdata_cb (void (*)(void* user_data))
  193. .cleanup_userdata_cb (void (*)(void* user_data))
  194. .event_userdata_cb (void(*)(const sapp_event* event, void* user_data))
  195. The function sapp_userdata() can be used to query the user_data
  196. pointer provided in the sapp_desc struct.
  197. You can also call sapp_query_desc() to get a copy of the
  198. original sapp_desc structure.
  199. NOTE that there's also an alternative compile mode where sokol_app.h
  200. doesn't "hijack" the main() function. Search below for SOKOL_NO_ENTRY.
  201. --- Implement the initialization callback function (init_cb), this is called
  202. once after the rendering surface, 3D API and swap chain have been
  203. initialized by sokol_app. All sokol-app functions can be called
  204. from inside the initialization callback, the most useful functions
  205. at this point are:
  206. int sapp_width(void)
  207. int sapp_height(void)
  208. Returns the current width and height of the default framebuffer in pixels,
  209. this may change from one frame to the next, and it may be different
  210. from the initial size provided in the sapp_desc struct.
  211. float sapp_widthf(void)
  212. float sapp_heightf(void)
  213. These are alternatives to sapp_width() and sapp_height() which return
  214. the default framebuffer size as float values instead of integer. This
  215. may help to prevent casting back and forth between int and float
  216. in more strongly typed languages than C and C++.
  217. double sapp_frame_duration(void)
  218. Returns the frame duration in seconds averaged over a number of
  219. frames to smooth out any jittering spikes.
  220. int sapp_color_format(void)
  221. int sapp_depth_format(void)
  222. The color and depth-stencil pixelformats of the default framebuffer,
  223. as integer values which are compatible with sokol-gfx's
  224. sg_pixel_format enum (so that they can be plugged directly in places
  225. where sg_pixel_format is expected). Possible values are:
  226. 23 == SG_PIXELFORMAT_RGBA8
  227. 28 == SG_PIXELFORMAT_BGRA8
  228. 42 == SG_PIXELFORMAT_DEPTH
  229. 43 == SG_PIXELFORMAT_DEPTH_STENCIL
  230. int sapp_sample_count(void)
  231. Return the MSAA sample count of the default framebuffer.
  232. const void* sapp_metal_get_device(void)
  233. const void* sapp_metal_get_current_drawable(void)
  234. const void* sapp_metal_get_depth_stencil_texture(void)
  235. const void* sapp_metal_get_msaa_color_texture(void)
  236. If the Metal backend has been selected, these functions return pointers
  237. to various Metal API objects required for rendering, otherwise
  238. they return a null pointer. These void pointers are actually
  239. Objective-C ids converted with a (ARC) __bridge cast so that
  240. the ids can be tunneled through C code. Also note that the returned
  241. pointers may change from one frame to the next, only the Metal device
  242. object is guaranteed to stay the same.
  243. const void* sapp_macos_get_window(void)
  244. On macOS, get the NSWindow object pointer, otherwise a null pointer.
  245. Before being used as Objective-C object, the void* must be converted
  246. back with a (ARC) __bridge cast.
  247. const void* sapp_ios_get_window(void)
  248. On iOS, get the UIWindow object pointer, otherwise a null pointer.
  249. Before being used as Objective-C object, the void* must be converted
  250. back with a (ARC) __bridge cast.
  251. const void* sapp_d3d11_get_device(void)
  252. const void* sapp_d3d11_get_device_context(void)
  253. const void* sapp_d3d11_get_render_view(void)
  254. const void* sapp_d3d11_get_resolve_view(void);
  255. const void* sapp_d3d11_get_depth_stencil_view(void)
  256. Similar to the sapp_metal_* functions, the sapp_d3d11_* functions
  257. return pointers to D3D11 API objects required for rendering,
  258. only if the D3D11 backend has been selected. Otherwise they
  259. return a null pointer. Note that the returned pointers to the
  260. render-target-view and depth-stencil-view may change from one
  261. frame to the next!
  262. const void* sapp_win32_get_hwnd(void)
  263. On Windows, get the window's HWND, otherwise a null pointer. The
  264. HWND has been cast to a void pointer in order to be tunneled
  265. through code which doesn't include Windows.h.
  266. const void* sapp_x11_get_window(void)
  267. On Linux, get the X11 Window, otherwise a null pointer. The
  268. Window has been cast to a void pointer in order to be tunneled
  269. through code which doesn't include X11/Xlib.h.
  270. const void* sapp_x11_get_display(void)
  271. On Linux, get the X11 Display, otherwise a null pointer. The
  272. Display has been cast to a void pointer in order to be tunneled
  273. through code which doesn't include X11/Xlib.h.
  274. const void* sapp_wgpu_get_device(void)
  275. const void* sapp_wgpu_get_render_view(void)
  276. const void* sapp_wgpu_get_resolve_view(void)
  277. const void* sapp_wgpu_get_depth_stencil_view(void)
  278. These are the WebGPU-specific functions to get the WebGPU
  279. objects and values required for rendering. If sokol_app.h
  280. is not compiled with SOKOL_WGPU, these functions return null.
  281. uint32_t sapp_gl_get_framebuffer(void)
  282. This returns the 'default framebuffer' of the GL context.
  283. Typically this will be zero.
  284. int sapp_gl_get_major_version(void)
  285. int sapp_gl_get_minor_version(void)
  286. bool sapp_gl_is_gles(void)
  287. Returns the major and minor version of the GL context and
  288. whether the GL context is a GLES context
  289. const void* sapp_android_get_native_activity(void);
  290. On Android, get the native activity ANativeActivity pointer, otherwise
  291. a null pointer.
  292. --- Implement the frame-callback function, this function will be called
  293. on the same thread as the init callback, but might be on a different
  294. thread than the sokol_main() function. Note that the size of
  295. the rendering framebuffer might have changed since the frame callback
  296. was called last. Call the functions sapp_width() and sapp_height()
  297. each frame to get the current size.
  298. --- Optionally implement the event-callback to handle input events.
  299. sokol-app provides the following type of input events:
  300. - a 'virtual key' was pressed down or released
  301. - a single text character was entered (provided as UTF-32 encoded
  302. UNICODE code point)
  303. - a mouse button was pressed down or released (left, right, middle)
  304. - mouse-wheel or 2D scrolling events
  305. - the mouse was moved
  306. - the mouse has entered or left the application window boundaries
  307. - low-level, portable multi-touch events (began, moved, ended, cancelled)
  308. - the application window was resized, iconified or restored
  309. - the application was suspended or restored (on mobile platforms)
  310. - the user or application code has asked to quit the application
  311. - a string was pasted to the system clipboard
  312. - one or more files have been dropped onto the application window
  313. To explicitly 'consume' an event and prevent that the event is
  314. forwarded for further handling to the operating system, call
  315. sapp_consume_event() from inside the event handler (NOTE that
  316. this behaviour is currently only implemented for some HTML5
  317. events, support for other platforms and event types will
  318. be added as needed, please open a GitHub ticket and/or provide
  319. a PR if needed).
  320. NOTE: Do *not* call any 3D API rendering functions in the event
  321. callback function, since the 3D API context may not be active when the
  322. event callback is called (it may work on some platforms and 3D APIs,
  323. but not others, and the exact behaviour may change between
  324. sokol-app versions).
  325. --- Implement the cleanup-callback function, this is called once
  326. after the user quits the application (see the section
  327. "APPLICATION QUIT" for detailed information on quitting
  328. behaviour, and how to intercept a pending quit - for instance to show a
  329. "Really Quit?" dialog box). Note that the cleanup-callback isn't
  330. guaranteed to be called on the web and mobile platforms.
  331. MOUSE CURSOR TYPE AND VISIBILITY
  332. ================================
  333. You can show and hide the mouse cursor with
  334. void sapp_show_mouse(bool show)
  335. And to get the current shown status:
  336. bool sapp_mouse_shown(void)
  337. NOTE that hiding the mouse cursor is different and independent from
  338. the MOUSE/POINTER LOCK feature which will also hide the mouse pointer when
  339. active (MOUSE LOCK is described below).
  340. To change the mouse cursor to one of several predefined types, call
  341. the function:
  342. void sapp_set_mouse_cursor(sapp_mouse_cursor cursor)
  343. Setting the default mouse cursor SAPP_MOUSECURSOR_DEFAULT will restore
  344. the standard look.
  345. To get the currently active mouse cursor type, call:
  346. sapp_mouse_cursor sapp_get_mouse_cursor(void)
  347. MOUSE LOCK (AKA POINTER LOCK, AKA MOUSE CAPTURE)
  348. ================================================
  349. In normal mouse mode, no mouse movement events are reported when the
  350. mouse leaves the windows client area or hits the screen border (whether
  351. it's one or the other depends on the platform), and the mouse move events
  352. (SAPP_EVENTTYPE_MOUSE_MOVE) contain absolute mouse positions in
  353. framebuffer pixels in the sapp_event items mouse_x and mouse_y, and
  354. relative movement in framebuffer pixels in the sapp_event items mouse_dx
  355. and mouse_dy.
  356. To get continuous mouse movement (also when the mouse leaves the window
  357. client area or hits the screen border), activate mouse-lock mode
  358. by calling:
  359. sapp_lock_mouse(true)
  360. When mouse lock is activated, the mouse pointer is hidden, the
  361. reported absolute mouse position (sapp_event.mouse_x/y) appears
  362. frozen, and the relative mouse movement in sapp_event.mouse_dx/dy
  363. no longer has a direct relation to framebuffer pixels but instead
  364. uses "raw mouse input" (what "raw mouse input" exactly means also
  365. differs by platform).
  366. To deactivate mouse lock and return to normal mouse mode, call
  367. sapp_lock_mouse(false)
  368. And finally, to check if mouse lock is currently active, call
  369. if (sapp_mouse_locked()) { ... }
  370. Note that mouse-lock state may not change immediately after sapp_lock_mouse(true/false)
  371. is called, instead on some platforms the actual state switch may be delayed
  372. to the end of the current frame or even to a later frame.
  373. The mouse may also be unlocked automatically without calling sapp_lock_mouse(false),
  374. most notably when the application window becomes inactive.
  375. On the web platform there are further restrictions to be aware of, caused
  376. by the limitations of the HTML5 Pointer Lock API:
  377. - sapp_lock_mouse(true) can be called at any time, but it will
  378. only take effect in a 'short-lived input event handler of a specific
  379. type', meaning when one of the following events happens:
  380. - SAPP_EVENTTYPE_MOUSE_DOWN
  381. - SAPP_EVENTTYPE_MOUSE_UP
  382. - SAPP_EVENTTYPE_MOUSE_SCROLL
  383. - SAPP_EVENTTYPE_KEY_UP
  384. - SAPP_EVENTTYPE_KEY_DOWN
  385. - The mouse lock/unlock action on the web platform is asynchronous,
  386. this means that sapp_mouse_locked() won't immediately return
  387. the new status after calling sapp_lock_mouse(), instead the
  388. reported status will only change when the pointer lock has actually
  389. been activated or deactivated in the browser.
  390. - On the web, mouse lock can be deactivated by the user at any time
  391. by pressing the Esc key. When this happens, sokol_app.h behaves
  392. the same as if sapp_lock_mouse(false) is called.
  393. For things like camera manipulation it's most straightforward to lock
  394. and unlock the mouse right from the sokol_app.h event handler, for
  395. instance the following code enters and leaves mouse lock when the
  396. left mouse button is pressed and released, and then uses the relative
  397. movement information to manipulate a camera (taken from the
  398. cgltf-sapp.c sample in the sokol-samples repository
  399. at https://github.com/floooh/sokol-samples):
  400. static void input(const sapp_event* ev) {
  401. switch (ev->type) {
  402. case SAPP_EVENTTYPE_MOUSE_DOWN:
  403. if (ev->mouse_button == SAPP_MOUSEBUTTON_LEFT) {
  404. sapp_lock_mouse(true);
  405. }
  406. break;
  407. case SAPP_EVENTTYPE_MOUSE_UP:
  408. if (ev->mouse_button == SAPP_MOUSEBUTTON_LEFT) {
  409. sapp_lock_mouse(false);
  410. }
  411. break;
  412. case SAPP_EVENTTYPE_MOUSE_MOVE:
  413. if (sapp_mouse_locked()) {
  414. cam_orbit(&state.camera, ev->mouse_dx * 0.25f, ev->mouse_dy * 0.25f);
  415. }
  416. break;
  417. default:
  418. break;
  419. }
  420. }
  421. For a 'first person shooter mouse' the following code inside the sokol-app event handler
  422. is recommended somewhere in your frame callback:
  423. if (!sapp_mouse_locked()) {
  424. sapp_lock_mouse(true);
  425. }
  426. CLIPBOARD SUPPORT
  427. =================
  428. Applications can send and receive UTF-8 encoded text data from and to the
  429. system clipboard. By default, clipboard support is disabled and
  430. must be enabled at startup via the following sapp_desc struct
  431. members:
  432. sapp_desc.enable_clipboard - set to true to enable clipboard support
  433. sapp_desc.clipboard_size - size of the internal clipboard buffer in bytes
  434. Enabling the clipboard will dynamically allocate a clipboard buffer
  435. for UTF-8 encoded text data of the requested size in bytes, the default
  436. size is 8 KBytes. Strings that don't fit into the clipboard buffer
  437. (including the terminating zero) will be silently clipped, so it's
  438. important that you provide a big enough clipboard size for your
  439. use case.
  440. To send data to the clipboard, call sapp_set_clipboard_string() with
  441. a pointer to an UTF-8 encoded, null-terminated C-string.
  442. NOTE that on the HTML5 platform, sapp_set_clipboard_string() must be
  443. called from inside a 'short-lived event handler', and there are a few
  444. other HTML5-specific caveats to workaround. You'll basically have to
  445. tinker until it works in all browsers :/ (maybe the situation will
  446. improve when all browsers agree on and implement the new
  447. HTML5 navigator.clipboard API).
  448. To get data from the clipboard, check for the SAPP_EVENTTYPE_CLIPBOARD_PASTED
  449. event in your event handler function, and then call sapp_get_clipboard_string()
  450. to obtain the pasted UTF-8 encoded text.
  451. NOTE that behaviour of sapp_get_clipboard_string() is slightly different
  452. depending on platform:
  453. - on the HTML5 platform, the internal clipboard buffer will only be updated
  454. right before the SAPP_EVENTTYPE_CLIPBOARD_PASTED event is sent,
  455. and sapp_get_clipboard_string() will simply return the current content
  456. of the clipboard buffer
  457. - on 'native' platforms, the call to sapp_get_clipboard_string() will
  458. update the internal clipboard buffer with the most recent data
  459. from the system clipboard
  460. Portable code should check for the SAPP_EVENTTYPE_CLIPBOARD_PASTED event,
  461. and then call sapp_get_clipboard_string() right in the event handler.
  462. The SAPP_EVENTTYPE_CLIPBOARD_PASTED event will be generated by sokol-app
  463. as follows:
  464. - on macOS: when the Cmd+V key is pressed down
  465. - on HTML5: when the browser sends a 'paste' event to the global 'window' object
  466. - on all other platforms: when the Ctrl+V key is pressed down
  467. DRAG AND DROP SUPPORT
  468. =====================
  469. PLEASE NOTE: the drag'n'drop feature works differently on WASM/HTML5
  470. and on the native desktop platforms (Win32, Linux and macOS) because
  471. of security-related restrictions in the HTML5 drag'n'drop API. The
  472. WASM/HTML5 specifics are described at the end of this documentation
  473. section:
  474. Like clipboard support, drag'n'drop support must be explicitly enabled
  475. at startup in the sapp_desc struct.
  476. sapp_desc sokol_main(void) {
  477. return (sapp_desc) {
  478. .enable_dragndrop = true, // default is false
  479. ...
  480. };
  481. }
  482. You can also adjust the maximum number of files that are accepted
  483. in a drop operation, and the maximum path length in bytes if needed:
  484. sapp_desc sokol_main(void) {
  485. return (sapp_desc) {
  486. .enable_dragndrop = true, // default is false
  487. .max_dropped_files = 8, // default is 1
  488. .max_dropped_file_path_length = 8192, // in bytes, default is 2048
  489. ...
  490. };
  491. }
  492. When drag'n'drop is enabled, the event callback will be invoked with an
  493. event of type SAPP_EVENTTYPE_FILES_DROPPED whenever the user drops files on
  494. the application window.
  495. After the SAPP_EVENTTYPE_FILES_DROPPED is received, you can query the
  496. number of dropped files, and their absolute paths by calling separate
  497. functions:
  498. void on_event(const sapp_event* ev) {
  499. if (ev->type == SAPP_EVENTTYPE_FILES_DROPPED) {
  500. // the mouse position where the drop happened
  501. float x = ev->mouse_x;
  502. float y = ev->mouse_y;
  503. // get the number of files and their paths like this:
  504. const int num_dropped_files = sapp_get_num_dropped_files();
  505. for (int i = 0; i < num_dropped_files; i++) {
  506. const char* path = sapp_get_dropped_file_path(i);
  507. ...
  508. }
  509. }
  510. }
  511. The returned file paths are UTF-8 encoded strings.
  512. You can call sapp_get_num_dropped_files() and sapp_get_dropped_file_path()
  513. anywhere, also outside the event handler callback, but be aware that the
  514. file path strings will be overwritten with the next drop operation.
  515. In any case, sapp_get_dropped_file_path() will never return a null pointer,
  516. instead an empty string "" will be returned if the drag'n'drop feature
  517. hasn't been enabled, the last drop-operation failed, or the file path index
  518. is out of range.
  519. Drag'n'drop caveats:
  520. - if more files are dropped in a single drop-action
  521. than sapp_desc.max_dropped_files, the additional
  522. files will be silently ignored
  523. - if any of the file paths is longer than
  524. sapp_desc.max_dropped_file_path_length (in number of bytes, after UTF-8
  525. encoding) the entire drop operation will be silently ignored (this
  526. needs some sort of error feedback in the future)
  527. - no mouse positions are reported while the drag is in
  528. process, this may change in the future
  529. Drag'n'drop on HTML5/WASM:
  530. The HTML5 drag'n'drop API doesn't return file paths, but instead
  531. black-box 'file objects' which must be used to load the content
  532. of dropped files. This is the reason why sokol_app.h adds two
  533. HTML5-specific functions to the drag'n'drop API:
  534. uint32_t sapp_html5_get_dropped_file_size(int index)
  535. Returns the size in bytes of a dropped file.
  536. void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request)
  537. Asynchronously loads the content of a dropped file into a
  538. provided memory buffer (which must be big enough to hold
  539. the file content)
  540. To start loading the first dropped file after an SAPP_EVENTTYPE_FILES_DROPPED
  541. event is received:
  542. sapp_html5_fetch_dropped_file(&(sapp_html5_fetch_request){
  543. .dropped_file_index = 0,
  544. .callback = fetch_cb
  545. .buffer = {
  546. .ptr = buf,
  547. .size = sizeof(buf)
  548. },
  549. .user_data = ...
  550. });
  551. Make sure that the memory pointed to by 'buf' stays valid until the
  552. callback function is called!
  553. As result of the asynchronous loading operation (no matter if succeeded or
  554. failed) the 'fetch_cb' function will be called:
  555. void fetch_cb(const sapp_html5_fetch_response* response) {
  556. // IMPORTANT: check if the loading operation actually succeeded:
  557. if (response->succeeded) {
  558. // the size of the loaded file:
  559. const size_t num_bytes = response->data.size;
  560. // and the pointer to the data (same as 'buf' in the fetch-call):
  561. const void* ptr = response->data.ptr;
  562. }
  563. else {
  564. // on error check the error code:
  565. switch (response->error_code) {
  566. case SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL:
  567. ...
  568. break;
  569. case SAPP_HTML5_FETCH_ERROR_OTHER:
  570. ...
  571. break;
  572. }
  573. }
  574. }
  575. Check the droptest-sapp example for a real-world example which works
  576. both on native platforms and the web:
  577. https://github.com/floooh/sokol-samples/blob/master/sapp/droptest-sapp.c
  578. HIGH-DPI RENDERING
  579. ==================
  580. You can set the sapp_desc.high_dpi flag during initialization to request
  581. a full-resolution framebuffer on HighDPI displays. The default behaviour
  582. is sapp_desc.high_dpi=false, this means that the application will
  583. render to a lower-resolution framebuffer on HighDPI displays and the
  584. rendered content will be upscaled by the window system composer.
  585. In a HighDPI scenario, you still request the same window size during
  586. sokol_main(), but the framebuffer sizes returned by sapp_width()
  587. and sapp_height() will be scaled up according to the DPI scaling
  588. ratio.
  589. Note that on some platforms the DPI scaling factor may change at any
  590. time (for instance when a window is moved from a high-dpi display
  591. to a low-dpi display).
  592. To query the current DPI scaling factor, call the function:
  593. float sapp_dpi_scale(void);
  594. For instance on a Retina Mac, returning the following sapp_desc
  595. struct from sokol_main():
  596. sapp_desc sokol_main(void) {
  597. return (sapp_desc) {
  598. .width = 640,
  599. .height = 480,
  600. .high_dpi = true,
  601. ...
  602. };
  603. }
  604. ...the functions the functions sapp_width(), sapp_height()
  605. and sapp_dpi_scale() will return the following values:
  606. sapp_width: 1280
  607. sapp_height: 960
  608. sapp_dpi_scale: 2.0
  609. If the high_dpi flag is false, or you're not running on a Retina display,
  610. the values would be:
  611. sapp_width: 640
  612. sapp_height: 480
  613. sapp_dpi_scale: 1.0
  614. If the window is moved from the Retina display to a low-dpi external display,
  615. the values would change as follows:
  616. sapp_width: 1280 => 640
  617. sapp_height: 960 => 480
  618. sapp_dpi_scale: 2.0 => 1.0
  619. Currently there is no event associated with a DPI change, but an
  620. SAPP_EVENTTYPE_RESIZED will be sent as a side effect of the
  621. framebuffer size changing.
  622. Per-monitor DPI is currently supported on macOS and Windows.
  623. APPLICATION QUIT
  624. ================
  625. Without special quit handling, a sokol_app.h application will quit
  626. 'gracefully' when the user clicks the window close-button unless a
  627. platform's application model prevents this (e.g. on web or mobile).
  628. 'Graceful exit' means that the application-provided cleanup callback will
  629. be called before the application quits.
  630. On native desktop platforms sokol_app.h provides more control over the
  631. application-quit-process. It's possible to initiate a 'programmatic quit'
  632. from the application code, and a quit initiated by the application user can
  633. be intercepted (for instance to show a custom dialog box).
  634. This 'programmatic quit protocol' is implemented through 3 functions
  635. and 1 event:
  636. - sapp_quit(): This function simply quits the application without
  637. giving the user a chance to intervene. Usually this might
  638. be called when the user clicks the 'Ok' button in a 'Really Quit?'
  639. dialog box
  640. - sapp_request_quit(): Calling sapp_request_quit() will send the
  641. event SAPP_EVENTTYPE_QUIT_REQUESTED to the applications event handler
  642. callback, giving the user code a chance to intervene and cancel the
  643. pending quit process (for instance to show a 'Really Quit?' dialog
  644. box). If the event handler callback does nothing, the application
  645. will be quit as usual. To prevent this, call the function
  646. sapp_cancel_quit() from inside the event handler.
  647. - sapp_cancel_quit(): Cancels a pending quit request, either initiated
  648. by the user clicking the window close button, or programmatically
  649. by calling sapp_request_quit(). The only place where calling this
  650. function makes sense is from inside the event handler callback when
  651. the SAPP_EVENTTYPE_QUIT_REQUESTED event has been received.
  652. - SAPP_EVENTTYPE_QUIT_REQUESTED: this event is sent when the user
  653. clicks the window's close button or application code calls the
  654. sapp_request_quit() function. The event handler callback code can handle
  655. this event by calling sapp_cancel_quit() to cancel the quit.
  656. If the event is ignored, the application will quit as usual.
  657. On the web platform, the quit behaviour differs from native platforms,
  658. because of web-specific restrictions:
  659. A `programmatic quit` initiated by calling sapp_quit() or
  660. sapp_request_quit() will work as described above: the cleanup callback is
  661. called, platform-specific cleanup is performed (on the web
  662. this means that JS event handlers are unregistered), and then
  663. the request-animation-loop will be exited. However that's all. The
  664. web page itself will continue to exist (e.g. it's not possible to
  665. programmatically close the browser tab).
  666. On the web it's also not possible to run custom code when the user
  667. closes a browser tab, so it's not possible to prevent this with a
  668. fancy custom dialog box.
  669. Instead the standard "Leave Site?" dialog box can be activated (or
  670. deactivated) with the following function:
  671. sapp_html5_ask_leave_site(bool ask);
  672. The initial state of the associated internal flag can be provided
  673. at startup via sapp_desc.html5_ask_leave_site.
  674. This feature should only be used sparingly in critical situations - for
  675. instance when the user would loose data - since popping up modal dialog
  676. boxes is considered quite rude in the web world. Note that there's no way
  677. to customize the content of this dialog box or run any code as a result
  678. of the user's decision. Also note that the user must have interacted with
  679. the site before the dialog box will appear. These are all security measures
  680. to prevent fishing.
  681. The Dear ImGui HighDPI sample contains example code of how to
  682. implement a 'Really Quit?' dialog box with Dear ImGui (native desktop
  683. platforms only), and for showing the hardwired "Leave Site?" dialog box
  684. when running on the web platform:
  685. https://floooh.github.io/sokol-html5/wasm/imgui-highdpi-sapp.html
  686. FULLSCREEN
  687. ==========
  688. If the sapp_desc.fullscreen flag is true, sokol-app will try to create
  689. a fullscreen window on platforms with a 'proper' window system
  690. (mobile devices will always use fullscreen). The implementation details
  691. depend on the target platform, in general sokol-app will use a
  692. 'soft approach' which doesn't interfere too much with the platform's
  693. window system (for instance borderless fullscreen window instead of
  694. a 'real' fullscreen mode). Such details might change over time
  695. as sokol-app is adapted for different needs.
  696. The most important effect of fullscreen mode to keep in mind is that
  697. the requested canvas width and height will be ignored for the initial
  698. window size, calling sapp_width() and sapp_height() will instead return
  699. the resolution of the fullscreen canvas (however the provided size
  700. might still be used for the non-fullscreen window, in case the user can
  701. switch back from fullscreen- to windowed-mode).
  702. To toggle fullscreen mode programmatically, call sapp_toggle_fullscreen().
  703. To check if the application window is currently in fullscreen mode,
  704. call sapp_is_fullscreen().
  705. WINDOW ICON SUPPORT
  706. ===================
  707. Some sokol_app.h backends allow to change the window icon programmatically:
  708. - on Win32: the small icon in the window's title bar, and the
  709. bigger icon in the task bar
  710. - on Linux: highly dependent on the used window manager, but usually
  711. the window's title bar icon and/or the task bar icon
  712. - on HTML5: the favicon shown in the page's browser tab
  713. - on macOS: the application icon shown in the dock, but only
  714. for currently running applications
  715. NOTE that it is not possible to set the actual application icon which is
  716. displayed by the operating system on the desktop or 'home screen'. Those
  717. icons must be provided 'traditionally' through operating-system-specific
  718. resources which are associated with the application (sokol_app.h might
  719. later support setting the window icon from platform specific resource data
  720. though).
  721. There are two ways to set the window icon:
  722. - at application start in the sokol_main() function by initializing
  723. the sapp_desc.icon nested struct
  724. - or later by calling the function sapp_set_icon()
  725. As a convenient shortcut, sokol_app.h comes with a builtin default-icon
  726. (a rainbow-colored 'S', which at least looks a bit better than the Windows
  727. default icon for applications), which can be activated like this:
  728. At startup in sokol_main():
  729. sapp_desc sokol_main(...) {
  730. return (sapp_desc){
  731. ...
  732. icon.sokol_default = true
  733. };
  734. }
  735. Or later by calling:
  736. sapp_set_icon(&(sapp_icon_desc){ .sokol_default = true });
  737. NOTE that a completely zero-initialized sapp_icon_desc struct will not
  738. update the window icon in any way. This is an 'escape hatch' so that you
  739. can handle the window icon update yourself (or if you do this already,
  740. sokol_app.h won't get in your way, in this case just leave the
  741. sapp_desc.icon struct zero-initialized).
  742. Providing your own icon images works exactly like in GLFW (down to the
  743. data format):
  744. You provide one or more 'candidate images' in different sizes, and the
  745. sokol_app.h platform backends pick the best match for the specific backend
  746. and icon type.
  747. For each candidate image, you need to provide:
  748. - the width in pixels
  749. - the height in pixels
  750. - and the actual pixel data in RGBA8 pixel format (e.g. 0xFFCC8844
  751. on a little-endian CPU means: alpha=0xFF, blue=0xCC, green=0x88, red=0x44)
  752. For instance, if you have 3 candidate images (small, medium, big) of
  753. sizes 16x16, 32x32 and 64x64 the corresponding sapp_icon_desc struct is setup
  754. like this:
  755. // the actual pixel data (RGBA8, origin top-left)
  756. const uint32_t small[16][16] = { ... };
  757. const uint32_t medium[32][32] = { ... };
  758. const uint32_t big[64][64] = { ... };
  759. const sapp_icon_desc icon_desc = {
  760. .images = {
  761. { .width = 16, .height = 16, .pixels = SAPP_RANGE(small) },
  762. { .width = 32, .height = 32, .pixels = SAPP_RANGE(medium) },
  763. // ...or without the SAPP_RANGE helper macro:
  764. { .width = 64, .height = 64, .pixels = { .ptr=big, .size=sizeof(big) } }
  765. }
  766. };
  767. An sapp_icon_desc struct initialized like this can then either be applied
  768. at application start in sokol_main:
  769. sapp_desc sokol_main(...) {
  770. return (sapp_desc){
  771. ...
  772. icon = icon_desc
  773. };
  774. }
  775. ...or later by calling sapp_set_icon():
  776. sapp_set_icon(&icon_desc);
  777. Some window icon caveats:
  778. - once the window icon has been updated, there's no way to go back to
  779. the platform's default icon, this is because some platforms (Linux
  780. and HTML5) don't switch the icon visual back to the default even if
  781. the custom icon is deleted or removed
  782. - on HTML5, if the sokol_app.h icon doesn't show up in the browser
  783. tab, check that there's no traditional favicon 'link' element
  784. is defined in the page's index.html, sokol_app.h will only
  785. append a new favicon link element, but not delete any manually
  786. defined favicon in the page
  787. For an example and test of the window icon feature, check out the
  788. 'icon-sapp' sample on the sokol-samples git repository.
  789. ONSCREEN KEYBOARD
  790. =================
  791. On some platforms which don't provide a physical keyboard, sokol-app
  792. can display the platform's integrated onscreen keyboard for text
  793. input. To request that the onscreen keyboard is shown, call
  794. sapp_show_keyboard(true);
  795. Likewise, to hide the keyboard call:
  796. sapp_show_keyboard(false);
  797. Note that onscreen keyboard functionality is no longer supported
  798. on the browser platform (the previous hacks and workarounds to make browser
  799. keyboards work for on web applications that don't use HTML UIs
  800. never really worked across browsers).
  801. INPUT EVENT BUBBLING ON THE WEB PLATFORM
  802. ========================================
  803. By default, input event bubbling on the web platform is configured in
  804. a way that makes the most sense for 'full-canvas' apps that cover the
  805. entire browser client window area:
  806. - mouse, touch and wheel events do not bubble up, this prevents various
  807. ugly side events, like:
  808. - HTML text overlays being selected on double- or triple-click into
  809. the canvas
  810. - 'scroll bumping' even when the canvas covers the entire client area
  811. - key_up/down events for 'character keys' *do* bubble up (otherwise
  812. the browser will not generate UNICODE character events)
  813. - all other key events *do not* bubble up by default (this prevents side effects
  814. like F1 opening help, or F7 starting 'caret browsing')
  815. - character events do not bubble up (although I haven't noticed any side effects
  816. otherwise)
  817. Event bubbling can be enabled for input event categories during initialization
  818. in the sapp_desc struct:
  819. sapp_desc sokol_main(int argc, char* argv[]) {
  820. return (sapp_desc){
  821. //...
  822. .html5_bubble_mouse_events = true,
  823. .html5_bubble_touch_events = true,
  824. .html5_bubble_wheel_events = true,
  825. .html5_bubble_key_events = true,
  826. .html5_bubble_char_events = true,
  827. };
  828. }
  829. This basically opens the floodgates and lets *all* input events bubble up to the browser.
  830. To prevent individual events from bubbling, call sapp_consume_event() from within
  831. the sokol_app.h event callback when that specific event is reported.
  832. SETTING THE CANVAS OBJECT ON THE WEB PLATFORM
  833. =============================================
  834. On the web, sokol_app.h and the Emscripten SDK functions need to find
  835. the WebGL/WebGPU canvas intended for rendering and attaching event
  836. handlers. This can happen in four ways:
  837. 1. do nothing and just set the id of the canvas object to 'canvas' (preferred)
  838. 2. via a CSS Selector string (preferred)
  839. 3. by setting the `Module.canvas` property to the canvas object
  840. 4. by adding the canvas object to the global variable `specialHTMLTargets[]`
  841. (this is a special variable used by the Emscripten runtime to lookup
  842. event target objects for which document.querySelector() cannot be used)
  843. The easiest way is to just name your canvas object 'canvas':
  844. <canvas id="canvas" ...></canvas>
  845. This works because the default css selector string used by sokol_app.h
  846. is '#canvas'.
  847. If you name your canvas differently, you need to communicate that name to
  848. sokol_app.h via `sapp_desc.html5_canvas_selector` as a regular css selector
  849. string that's compatible with `document.querySelector()`. E.g. if your canvas
  850. object looks like this:
  851. <canvas id="bla" ...></canvas>
  852. The `sapp_desc.html5_canvas_selector` string must be set to '#bla':
  853. .html5_canvas_selector = "#bla"
  854. If the canvas object cannot be looked up via `document.querySelector()` you
  855. need to use one of the alternative methods, both involve the special
  856. Emscripten runtime `Module` object which is usually setup in the index.html
  857. like this before the WASM blob is loaded and instantiated:
  858. <script type='text/javascript'>
  859. var Module = {
  860. // ...
  861. };
  862. </script>
  863. The first option is to set the `Module.canvas` property to your canvas object:
  864. <script type='text/javascript'>
  865. var Module = {
  866. canvas: my_canvas_object,
  867. };
  868. </script>
  869. When sokol_app.h initializes, it will check the global Module object whether
  870. a `Module.canvas` property exists and is an object. This method will add
  871. a new entry to the `specialHTMLTargets[]` object
  872. The other option is to add the canvas under a name chosen by you to the
  873. special `specialHTMLTargets[]` map, which is used by the Emscripten runtime
  874. to lookup 'event target objects' which are not visible to `document.querySelector()`.
  875. Note that `specialHTMLTargets[]` must be updated after the Emscripten runtime
  876. has started but before the WASM code is running. A good place for this is
  877. the special `Module.preRun` array in index.html:
  878. <script type='text/javascript'>
  879. var Module = {
  880. preRun: [
  881. () => {
  882. specialHTMLTargets['my_canvas'] = my_canvas_object;
  883. }
  884. ],
  885. };
  886. </script>
  887. In that case, pass the same string to sokol_app.h which is used as key
  888. in the specialHTMLTargets[] map:
  889. .html5_canvas_selector = "my_canvas"
  890. If sokol_app.h can't find your canvas for some reason check for warning
  891. messages on the browser console.
  892. OPTIONAL: DON'T HIJACK main() (#define SOKOL_NO_ENTRY)
  893. ======================================================
  894. NOTE: SOKOL_NO_ENTRY and sapp_run() is currently not supported on Android.
  895. In its default configuration, sokol_app.h "hijacks" the platform's
  896. standard main() function. This was done because different platforms
  897. have different entry point conventions which are not compatible with
  898. C's main() (for instance WinMain on Windows has completely different
  899. arguments). However, this "main hijacking" posed a problem for
  900. usage scenarios like integrating sokol_app.h with other languages than
  901. C or C++, so an alternative SOKOL_NO_ENTRY mode has been added
  902. in which the user code provides the platform's main function:
  903. - define SOKOL_NO_ENTRY before including the sokol_app.h implementation
  904. - do *not* provide a sokol_main() function
  905. - instead provide the standard main() function of the platform
  906. - from the main function, call the function ```sapp_run()``` which
  907. takes a pointer to an ```sapp_desc``` structure.
  908. - from here on```sapp_run()``` takes over control and calls the provided
  909. init-, frame-, event- and cleanup-callbacks just like in the default model.
  910. sapp_run() behaves differently across platforms:
  911. - on some platforms, sapp_run() will return when the application quits
  912. - on other platforms, sapp_run() will never return, even when the
  913. application quits (the operating system is free to simply terminate
  914. the application at any time)
  915. - on Emscripten specifically, sapp_run() will return immediately while
  916. the frame callback keeps being called
  917. This different behaviour of sapp_run() essentially means that there shouldn't
  918. be any code *after* sapp_run(), because that may either never be called, or in
  919. case of Emscripten will be called at an unexpected time (at application start).
  920. An application also should not depend on the cleanup-callback being called
  921. when cross-platform compatibility is required.
  922. Since sapp_run() returns immediately on Emscripten you shouldn't activate
  923. the 'EXIT_RUNTIME' linker option (this is disabled by default when compiling
  924. for the browser target), since the C/C++ exit runtime would be called immediately at
  925. application start, causing any global objects to be destroyed and global
  926. variables to be zeroed.
  927. WINDOWS CONSOLE OUTPUT
  928. ======================
  929. On Windows, regular windowed applications don't show any stdout/stderr text
  930. output, which can be a bit of a hassle for printf() debugging or generally
  931. logging text to the console. Also, console output by default uses a local
  932. codepage setting and thus international UTF-8 encoded text is printed
  933. as garbage.
  934. To help with these issues, sokol_app.h can be configured at startup
  935. via the following Windows-specific sapp_desc flags:
  936. sapp_desc.win32_console_utf8 (default: false)
  937. When set to true, the output console codepage will be switched
  938. to UTF-8 (and restored to the original codepage on exit)
  939. sapp_desc.win32_console_attach (default: false)
  940. When set to true, stdout and stderr will be attached to the
  941. console of the parent process (if the parent process actually
  942. has a console). This means that if the application was started
  943. in a command line window, stdout and stderr output will be printed
  944. to the terminal, just like a regular command line program. But if
  945. the application is started via double-click, it will behave like
  946. a regular UI application, and stdout/stderr will not be visible.
  947. sapp_desc.win32_console_create (default: false)
  948. When set to true, a new console window will be created and
  949. stdout/stderr will be redirected to that console window. It
  950. doesn't matter if the application is started from the command
  951. line or via double-click.
  952. MEMORY ALLOCATION OVERRIDE
  953. ==========================
  954. You can override the memory allocation functions at initialization time
  955. like this:
  956. void* my_alloc(size_t size, void* user_data) {
  957. return malloc(size);
  958. }
  959. void my_free(void* ptr, void* user_data) {
  960. free(ptr);
  961. }
  962. sapp_desc sokol_main(int argc, char* argv[]) {
  963. return (sapp_desc){
  964. // ...
  965. .allocator = {
  966. .alloc_fn = my_alloc,
  967. .free_fn = my_free,
  968. .user_data = ...,
  969. }
  970. };
  971. }
  972. If no overrides are provided, malloc and free will be used.
  973. This only affects memory allocation calls done by sokol_app.h
  974. itself though, not any allocations in OS libraries.
  975. ERROR REPORTING AND LOGGING
  976. ===========================
  977. To get any logging information at all you need to provide a logging callback in the setup call
  978. the easiest way is to use sokol_log.h:
  979. #include "sokol_log.h"
  980. sapp_desc sokol_main(int argc, char* argv[]) {
  981. return (sapp_desc) {
  982. ...
  983. .logger.func = slog_func,
  984. };
  985. }
  986. To override logging with your own callback, first write a logging function like this:
  987. void my_log(const char* tag, // e.g. 'sapp'
  988. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  989. uint32_t log_item_id, // SAPP_LOGITEM_*
  990. const char* message_or_null, // a message string, may be nullptr in release mode
  991. uint32_t line_nr, // line number in sokol_app.h
  992. const char* filename_or_null, // source filename, may be nullptr in release mode
  993. void* user_data)
  994. {
  995. ...
  996. }
  997. ...and then setup sokol-app like this:
  998. sapp_desc sokol_main(int argc, char* argv[]) {
  999. return (sapp_desc) {
  1000. ...
  1001. .logger = {
  1002. .func = my_log,
  1003. .user_data = my_user_data,
  1004. }
  1005. };
  1006. }
  1007. The provided logging function must be reentrant (e.g. be callable from
  1008. different threads).
  1009. If you don't want to provide your own custom logger it is highly recommended to use
  1010. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  1011. errors.
  1012. TEMP NOTE DUMP
  1013. ==============
  1014. - sapp_desc needs a bool whether to initialize depth-stencil surface
  1015. - the Android implementation calls cleanup_cb() and destroys the egl context in onDestroy
  1016. at the latest but should do it earlier, in onStop, as an app is "killable" after onStop
  1017. on Android Honeycomb and later (it can't be done at the moment as the app may be started
  1018. again after onStop and the sokol lifecycle does not yet handle context teardown/bringup)
  1019. LICENSE
  1020. =======
  1021. zlib/libpng license
  1022. Copyright (c) 2018 Andre Weissflog
  1023. This software is provided 'as-is', without any express or implied warranty.
  1024. In no event will the authors be held liable for any damages arising from the
  1025. use of this software.
  1026. Permission is granted to anyone to use this software for any purpose,
  1027. including commercial applications, and to alter it and redistribute it
  1028. freely, subject to the following restrictions:
  1029. 1. The origin of this software must not be misrepresented; you must not
  1030. claim that you wrote the original software. If you use this software in a
  1031. product, an acknowledgment in the product documentation would be
  1032. appreciated but is not required.
  1033. 2. Altered source versions must be plainly marked as such, and must not
  1034. be misrepresented as being the original software.
  1035. 3. This notice may not be removed or altered from any source
  1036. distribution.
  1037. */
  1038. #define SOKOL_APP_INCLUDED (1)
  1039. #include <stddef.h> // size_t
  1040. #include <stdint.h>
  1041. #include <stdbool.h>
  1042. #if defined(SOKOL_API_DECL) && !defined(SOKOL_APP_API_DECL)
  1043. #define SOKOL_APP_API_DECL SOKOL_API_DECL
  1044. #endif
  1045. #ifndef SOKOL_APP_API_DECL
  1046. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_APP_IMPL)
  1047. #define SOKOL_APP_API_DECL __declspec(dllexport)
  1048. #elif defined(_WIN32) && defined(SOKOL_DLL)
  1049. #define SOKOL_APP_API_DECL __declspec(dllimport)
  1050. #else
  1051. #define SOKOL_APP_API_DECL extern
  1052. #endif
  1053. #endif
  1054. #ifdef __cplusplus
  1055. extern "C" {
  1056. #endif
  1057. /* misc constants */
  1058. enum {
  1059. SAPP_MAX_TOUCHPOINTS = 8,
  1060. SAPP_MAX_MOUSEBUTTONS = 3,
  1061. SAPP_MAX_KEYCODES = 512,
  1062. SAPP_MAX_ICONIMAGES = 8,
  1063. };
  1064. /*
  1065. sapp_event_type
  1066. The type of event that's passed to the event handler callback
  1067. in the sapp_event.type field. These are not just "traditional"
  1068. input events, but also notify the application about state changes
  1069. or other user-invoked actions.
  1070. */
  1071. typedef enum sapp_event_type {
  1072. SAPP_EVENTTYPE_INVALID,
  1073. SAPP_EVENTTYPE_KEY_DOWN,
  1074. SAPP_EVENTTYPE_KEY_UP,
  1075. SAPP_EVENTTYPE_CHAR,
  1076. SAPP_EVENTTYPE_MOUSE_DOWN,
  1077. SAPP_EVENTTYPE_MOUSE_UP,
  1078. SAPP_EVENTTYPE_MOUSE_SCROLL,
  1079. SAPP_EVENTTYPE_MOUSE_MOVE,
  1080. SAPP_EVENTTYPE_MOUSE_ENTER,
  1081. SAPP_EVENTTYPE_MOUSE_LEAVE,
  1082. SAPP_EVENTTYPE_TOUCHES_BEGAN,
  1083. SAPP_EVENTTYPE_TOUCHES_MOVED,
  1084. SAPP_EVENTTYPE_TOUCHES_ENDED,
  1085. SAPP_EVENTTYPE_TOUCHES_CANCELLED,
  1086. SAPP_EVENTTYPE_RESIZED,
  1087. SAPP_EVENTTYPE_ICONIFIED,
  1088. SAPP_EVENTTYPE_RESTORED,
  1089. SAPP_EVENTTYPE_FOCUSED,
  1090. SAPP_EVENTTYPE_UNFOCUSED,
  1091. SAPP_EVENTTYPE_SUSPENDED,
  1092. SAPP_EVENTTYPE_RESUMED,
  1093. SAPP_EVENTTYPE_QUIT_REQUESTED,
  1094. SAPP_EVENTTYPE_CLIPBOARD_PASTED,
  1095. SAPP_EVENTTYPE_FILES_DROPPED,
  1096. _SAPP_EVENTTYPE_NUM,
  1097. _SAPP_EVENTTYPE_FORCE_U32 = 0x7FFFFFFF
  1098. } sapp_event_type;
  1099. /*
  1100. sapp_keycode
  1101. The 'virtual keycode' of a KEY_DOWN or KEY_UP event in the
  1102. struct field sapp_event.key_code.
  1103. Note that the keycode values are identical with GLFW.
  1104. */
  1105. typedef enum sapp_keycode {
  1106. SAPP_KEYCODE_INVALID = 0,
  1107. SAPP_KEYCODE_SPACE = 32,
  1108. SAPP_KEYCODE_APOSTROPHE = 39, /* ' */
  1109. SAPP_KEYCODE_COMMA = 44, /* , */
  1110. SAPP_KEYCODE_MINUS = 45, /* - */
  1111. SAPP_KEYCODE_PERIOD = 46, /* . */
  1112. SAPP_KEYCODE_SLASH = 47, /* / */
  1113. SAPP_KEYCODE_0 = 48,
  1114. SAPP_KEYCODE_1 = 49,
  1115. SAPP_KEYCODE_2 = 50,
  1116. SAPP_KEYCODE_3 = 51,
  1117. SAPP_KEYCODE_4 = 52,
  1118. SAPP_KEYCODE_5 = 53,
  1119. SAPP_KEYCODE_6 = 54,
  1120. SAPP_KEYCODE_7 = 55,
  1121. SAPP_KEYCODE_8 = 56,
  1122. SAPP_KEYCODE_9 = 57,
  1123. SAPP_KEYCODE_SEMICOLON = 59, /* ; */
  1124. SAPP_KEYCODE_EQUAL = 61, /* = */
  1125. SAPP_KEYCODE_A = 65,
  1126. SAPP_KEYCODE_B = 66,
  1127. SAPP_KEYCODE_C = 67,
  1128. SAPP_KEYCODE_D = 68,
  1129. SAPP_KEYCODE_E = 69,
  1130. SAPP_KEYCODE_F = 70,
  1131. SAPP_KEYCODE_G = 71,
  1132. SAPP_KEYCODE_H = 72,
  1133. SAPP_KEYCODE_I = 73,
  1134. SAPP_KEYCODE_J = 74,
  1135. SAPP_KEYCODE_K = 75,
  1136. SAPP_KEYCODE_L = 76,
  1137. SAPP_KEYCODE_M = 77,
  1138. SAPP_KEYCODE_N = 78,
  1139. SAPP_KEYCODE_O = 79,
  1140. SAPP_KEYCODE_P = 80,
  1141. SAPP_KEYCODE_Q = 81,
  1142. SAPP_KEYCODE_R = 82,
  1143. SAPP_KEYCODE_S = 83,
  1144. SAPP_KEYCODE_T = 84,
  1145. SAPP_KEYCODE_U = 85,
  1146. SAPP_KEYCODE_V = 86,
  1147. SAPP_KEYCODE_W = 87,
  1148. SAPP_KEYCODE_X = 88,
  1149. SAPP_KEYCODE_Y = 89,
  1150. SAPP_KEYCODE_Z = 90,
  1151. SAPP_KEYCODE_LEFT_BRACKET = 91, /* [ */
  1152. SAPP_KEYCODE_BACKSLASH = 92, /* \ */
  1153. SAPP_KEYCODE_RIGHT_BRACKET = 93, /* ] */
  1154. SAPP_KEYCODE_GRAVE_ACCENT = 96, /* ` */
  1155. SAPP_KEYCODE_WORLD_1 = 161, /* non-US #1 */
  1156. SAPP_KEYCODE_WORLD_2 = 162, /* non-US #2 */
  1157. SAPP_KEYCODE_ESCAPE = 256,
  1158. SAPP_KEYCODE_ENTER = 257,
  1159. SAPP_KEYCODE_TAB = 258,
  1160. SAPP_KEYCODE_BACKSPACE = 259,
  1161. SAPP_KEYCODE_INSERT = 260,
  1162. SAPP_KEYCODE_DELETE = 261,
  1163. SAPP_KEYCODE_RIGHT = 262,
  1164. SAPP_KEYCODE_LEFT = 263,
  1165. SAPP_KEYCODE_DOWN = 264,
  1166. SAPP_KEYCODE_UP = 265,
  1167. SAPP_KEYCODE_PAGE_UP = 266,
  1168. SAPP_KEYCODE_PAGE_DOWN = 267,
  1169. SAPP_KEYCODE_HOME = 268,
  1170. SAPP_KEYCODE_END = 269,
  1171. SAPP_KEYCODE_CAPS_LOCK = 280,
  1172. SAPP_KEYCODE_SCROLL_LOCK = 281,
  1173. SAPP_KEYCODE_NUM_LOCK = 282,
  1174. SAPP_KEYCODE_PRINT_SCREEN = 283,
  1175. SAPP_KEYCODE_PAUSE = 284,
  1176. SAPP_KEYCODE_F1 = 290,
  1177. SAPP_KEYCODE_F2 = 291,
  1178. SAPP_KEYCODE_F3 = 292,
  1179. SAPP_KEYCODE_F4 = 293,
  1180. SAPP_KEYCODE_F5 = 294,
  1181. SAPP_KEYCODE_F6 = 295,
  1182. SAPP_KEYCODE_F7 = 296,
  1183. SAPP_KEYCODE_F8 = 297,
  1184. SAPP_KEYCODE_F9 = 298,
  1185. SAPP_KEYCODE_F10 = 299,
  1186. SAPP_KEYCODE_F11 = 300,
  1187. SAPP_KEYCODE_F12 = 301,
  1188. SAPP_KEYCODE_F13 = 302,
  1189. SAPP_KEYCODE_F14 = 303,
  1190. SAPP_KEYCODE_F15 = 304,
  1191. SAPP_KEYCODE_F16 = 305,
  1192. SAPP_KEYCODE_F17 = 306,
  1193. SAPP_KEYCODE_F18 = 307,
  1194. SAPP_KEYCODE_F19 = 308,
  1195. SAPP_KEYCODE_F20 = 309,
  1196. SAPP_KEYCODE_F21 = 310,
  1197. SAPP_KEYCODE_F22 = 311,
  1198. SAPP_KEYCODE_F23 = 312,
  1199. SAPP_KEYCODE_F24 = 313,
  1200. SAPP_KEYCODE_F25 = 314,
  1201. SAPP_KEYCODE_KP_0 = 320,
  1202. SAPP_KEYCODE_KP_1 = 321,
  1203. SAPP_KEYCODE_KP_2 = 322,
  1204. SAPP_KEYCODE_KP_3 = 323,
  1205. SAPP_KEYCODE_KP_4 = 324,
  1206. SAPP_KEYCODE_KP_5 = 325,
  1207. SAPP_KEYCODE_KP_6 = 326,
  1208. SAPP_KEYCODE_KP_7 = 327,
  1209. SAPP_KEYCODE_KP_8 = 328,
  1210. SAPP_KEYCODE_KP_9 = 329,
  1211. SAPP_KEYCODE_KP_DECIMAL = 330,
  1212. SAPP_KEYCODE_KP_DIVIDE = 331,
  1213. SAPP_KEYCODE_KP_MULTIPLY = 332,
  1214. SAPP_KEYCODE_KP_SUBTRACT = 333,
  1215. SAPP_KEYCODE_KP_ADD = 334,
  1216. SAPP_KEYCODE_KP_ENTER = 335,
  1217. SAPP_KEYCODE_KP_EQUAL = 336,
  1218. SAPP_KEYCODE_LEFT_SHIFT = 340,
  1219. SAPP_KEYCODE_LEFT_CONTROL = 341,
  1220. SAPP_KEYCODE_LEFT_ALT = 342,
  1221. SAPP_KEYCODE_LEFT_SUPER = 343,
  1222. SAPP_KEYCODE_RIGHT_SHIFT = 344,
  1223. SAPP_KEYCODE_RIGHT_CONTROL = 345,
  1224. SAPP_KEYCODE_RIGHT_ALT = 346,
  1225. SAPP_KEYCODE_RIGHT_SUPER = 347,
  1226. SAPP_KEYCODE_MENU = 348,
  1227. } sapp_keycode;
  1228. /*
  1229. Android specific 'tool type' enum for touch events. This lets the
  1230. application check what type of input device was used for
  1231. touch events.
  1232. NOTE: the values must remain in sync with the corresponding
  1233. Android SDK type, so don't change those.
  1234. See https://developer.android.com/reference/android/view/MotionEvent#TOOL_TYPE_UNKNOWN
  1235. */
  1236. typedef enum sapp_android_tooltype {
  1237. SAPP_ANDROIDTOOLTYPE_UNKNOWN = 0, // TOOL_TYPE_UNKNOWN
  1238. SAPP_ANDROIDTOOLTYPE_FINGER = 1, // TOOL_TYPE_FINGER
  1239. SAPP_ANDROIDTOOLTYPE_STYLUS = 2, // TOOL_TYPE_STYLUS
  1240. SAPP_ANDROIDTOOLTYPE_MOUSE = 3, // TOOL_TYPE_MOUSE
  1241. } sapp_android_tooltype;
  1242. /*
  1243. sapp_touchpoint
  1244. Describes a single touchpoint in a multitouch event (TOUCHES_BEGAN,
  1245. TOUCHES_MOVED, TOUCHES_ENDED).
  1246. Touch points are stored in the nested array sapp_event.touches[],
  1247. and the number of touches is stored in sapp_event.num_touches.
  1248. */
  1249. typedef struct sapp_touchpoint {
  1250. uintptr_t identifier;
  1251. float pos_x;
  1252. float pos_y;
  1253. sapp_android_tooltype android_tooltype; // only valid on Android
  1254. bool changed;
  1255. } sapp_touchpoint;
  1256. /*
  1257. sapp_mousebutton
  1258. The currently pressed mouse button in the events MOUSE_DOWN
  1259. and MOUSE_UP, stored in the struct field sapp_event.mouse_button.
  1260. */
  1261. typedef enum sapp_mousebutton {
  1262. SAPP_MOUSEBUTTON_LEFT = 0x0,
  1263. SAPP_MOUSEBUTTON_RIGHT = 0x1,
  1264. SAPP_MOUSEBUTTON_MIDDLE = 0x2,
  1265. SAPP_MOUSEBUTTON_INVALID = 0x100,
  1266. } sapp_mousebutton;
  1267. /*
  1268. These are currently pressed modifier keys (and mouse buttons) which are
  1269. passed in the event struct field sapp_event.modifiers.
  1270. */
  1271. enum {
  1272. SAPP_MODIFIER_SHIFT = 0x1, // left or right shift key
  1273. SAPP_MODIFIER_CTRL = 0x2, // left or right control key
  1274. SAPP_MODIFIER_ALT = 0x4, // left or right alt key
  1275. SAPP_MODIFIER_SUPER = 0x8, // left or right 'super' key
  1276. SAPP_MODIFIER_LMB = 0x100, // left mouse button
  1277. SAPP_MODIFIER_RMB = 0x200, // right mouse button
  1278. SAPP_MODIFIER_MMB = 0x400, // middle mouse button
  1279. };
  1280. /*
  1281. sapp_event
  1282. This is an all-in-one event struct passed to the event handler
  1283. user callback function. Note that it depends on the event
  1284. type what struct fields actually contain useful values, so you
  1285. should first check the event type before reading other struct
  1286. fields.
  1287. */
  1288. typedef struct sapp_event {
  1289. uint64_t frame_count; // current frame counter, always valid, useful for checking if two events were issued in the same frame
  1290. sapp_event_type type; // the event type, always valid
  1291. sapp_keycode key_code; // the virtual key code, only valid in KEY_UP, KEY_DOWN
  1292. uint32_t char_code; // the UTF-32 character code, only valid in CHAR events
  1293. bool key_repeat; // true if this is a key-repeat event, valid in KEY_UP, KEY_DOWN and CHAR
  1294. uint32_t modifiers; // current modifier keys, valid in all key-, char- and mouse-events
  1295. sapp_mousebutton mouse_button; // mouse button that was pressed or released, valid in MOUSE_DOWN, MOUSE_UP
  1296. float mouse_x; // current horizontal mouse position in pixels, always valid except during mouse lock
  1297. float mouse_y; // current vertical mouse position in pixels, always valid except during mouse lock
  1298. float mouse_dx; // relative horizontal mouse movement since last frame, always valid
  1299. float mouse_dy; // relative vertical mouse movement since last frame, always valid
  1300. float scroll_x; // horizontal mouse wheel scroll distance, valid in MOUSE_SCROLL events
  1301. float scroll_y; // vertical mouse wheel scroll distance, valid in MOUSE_SCROLL events
  1302. int num_touches; // number of valid items in the touches[] array
  1303. sapp_touchpoint touches[SAPP_MAX_TOUCHPOINTS]; // current touch points, valid in TOUCHES_BEGIN, TOUCHES_MOVED, TOUCHES_ENDED
  1304. int window_width; // current window- and framebuffer sizes in pixels, always valid
  1305. int window_height;
  1306. int framebuffer_width; // = window_width * dpi_scale
  1307. int framebuffer_height; // = window_height * dpi_scale
  1308. } sapp_event;
  1309. /*
  1310. sg_range
  1311. A general pointer/size-pair struct and constructor macros for passing binary blobs
  1312. into sokol_app.h.
  1313. */
  1314. typedef struct sapp_range {
  1315. const void* ptr;
  1316. size_t size;
  1317. } sapp_range;
  1318. // disabling this for every includer isn't great, but the warnings are also quite pointless
  1319. #if defined(_MSC_VER)
  1320. #pragma warning(disable:4221) /* /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y' */
  1321. #pragma warning(disable:4204) /* VS2015: nonstandard extension used: non-constant aggregate initializer */
  1322. #endif
  1323. #if defined(__cplusplus)
  1324. #define SAPP_RANGE(x) sapp_range{ &x, sizeof(x) }
  1325. #else
  1326. #define SAPP_RANGE(x) (sapp_range){ &x, sizeof(x) }
  1327. #endif
  1328. /*
  1329. sapp_image_desc
  1330. This is used to describe image data to sokol_app.h (at first, window
  1331. icons, later maybe cursor images).
  1332. Note that the actual image pixel format depends on the use case:
  1333. - window icon pixels are RGBA8
  1334. */
  1335. typedef struct sapp_image_desc {
  1336. int width;
  1337. int height;
  1338. sapp_range pixels;
  1339. } sapp_image_desc;
  1340. /*
  1341. sapp_icon_desc
  1342. An icon description structure for use in sapp_desc.icon and
  1343. sapp_set_icon().
  1344. When setting a custom image, the application can provide a number of
  1345. candidates differing in size, and sokol_app.h will pick the image(s)
  1346. closest to the size expected by the platform's window system.
  1347. To set sokol-app's default icon, set .sokol_default to true.
  1348. Otherwise provide candidate images of different sizes in the
  1349. images[] array.
  1350. If both the sokol_default flag is set to true, any image candidates
  1351. will be ignored and the sokol_app.h default icon will be set.
  1352. */
  1353. typedef struct sapp_icon_desc {
  1354. bool sokol_default;
  1355. sapp_image_desc images[SAPP_MAX_ICONIMAGES];
  1356. } sapp_icon_desc;
  1357. /*
  1358. sapp_allocator
  1359. Used in sapp_desc to provide custom memory-alloc and -free functions
  1360. to sokol_app.h. If memory management should be overridden, both the
  1361. alloc_fn and free_fn function must be provided (e.g. it's not valid to
  1362. override one function but not the other).
  1363. */
  1364. typedef struct sapp_allocator {
  1365. void* (*alloc_fn)(size_t size, void* user_data);
  1366. void (*free_fn)(void* ptr, void* user_data);
  1367. void* user_data;
  1368. } sapp_allocator;
  1369. /*
  1370. sapp_log_item
  1371. Log items are defined via X-Macros and expanded to an enum
  1372. 'sapp_log_item', and in debug mode to corresponding
  1373. human readable error messages.
  1374. */
  1375. #define _SAPP_LOG_ITEMS \
  1376. _SAPP_LOGITEM_XMACRO(OK, "Ok") \
  1377. _SAPP_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  1378. _SAPP_LOGITEM_XMACRO(MACOS_INVALID_NSOPENGL_PROFILE, "macos: invalid NSOpenGLProfile (valid choices are 1.0 and 4.1)") \
  1379. _SAPP_LOGITEM_XMACRO(WIN32_LOAD_OPENGL32_DLL_FAILED, "failed loading opengl32.dll") \
  1380. _SAPP_LOGITEM_XMACRO(WIN32_CREATE_HELPER_WINDOW_FAILED, "failed to create helper window") \
  1381. _SAPP_LOGITEM_XMACRO(WIN32_HELPER_WINDOW_GETDC_FAILED, "failed to get helper window DC") \
  1382. _SAPP_LOGITEM_XMACRO(WIN32_DUMMY_CONTEXT_SET_PIXELFORMAT_FAILED, "failed to set pixel format for dummy GL context") \
  1383. _SAPP_LOGITEM_XMACRO(WIN32_CREATE_DUMMY_CONTEXT_FAILED, "failed to create dummy GL context") \
  1384. _SAPP_LOGITEM_XMACRO(WIN32_DUMMY_CONTEXT_MAKE_CURRENT_FAILED, "failed to make dummy GL context current") \
  1385. _SAPP_LOGITEM_XMACRO(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED, "failed to get WGL pixel format attribute") \
  1386. _SAPP_LOGITEM_XMACRO(WIN32_WGL_FIND_PIXELFORMAT_FAILED, "failed to find matching WGL pixel format") \
  1387. _SAPP_LOGITEM_XMACRO(WIN32_WGL_DESCRIBE_PIXELFORMAT_FAILED, "failed to get pixel format descriptor") \
  1388. _SAPP_LOGITEM_XMACRO(WIN32_WGL_SET_PIXELFORMAT_FAILED, "failed to set selected pixel format") \
  1389. _SAPP_LOGITEM_XMACRO(WIN32_WGL_ARB_CREATE_CONTEXT_REQUIRED, "ARB_create_context required") \
  1390. _SAPP_LOGITEM_XMACRO(WIN32_WGL_ARB_CREATE_CONTEXT_PROFILE_REQUIRED, "ARB_create_context_profile required") \
  1391. _SAPP_LOGITEM_XMACRO(WIN32_WGL_OPENGL_VERSION_NOT_SUPPORTED, "requested OpenGL version not supported by GL driver (ERROR_INVALID_VERSION_ARB)") \
  1392. _SAPP_LOGITEM_XMACRO(WIN32_WGL_OPENGL_PROFILE_NOT_SUPPORTED, "requested OpenGL profile not support by GL driver (ERROR_INVALID_PROFILE_ARB)") \
  1393. _SAPP_LOGITEM_XMACRO(WIN32_WGL_INCOMPATIBLE_DEVICE_CONTEXT, "CreateContextAttribsARB failed with ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB") \
  1394. _SAPP_LOGITEM_XMACRO(WIN32_WGL_CREATE_CONTEXT_ATTRIBS_FAILED_OTHER, "CreateContextAttribsARB failed for other reason") \
  1395. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_CREATE_DEVICE_AND_SWAPCHAIN_WITH_DEBUG_FAILED, "D3D11CreateDeviceAndSwapChain() with D3D11_CREATE_DEVICE_DEBUG failed, retrying without debug flag.") \
  1396. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_GET_IDXGIFACTORY_FAILED, "could not obtain IDXGIFactory object") \
  1397. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_GET_IDXGIADAPTER_FAILED, "could not obtain IDXGIAdapter object") \
  1398. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_QUERY_INTERFACE_IDXGIDEVICE1_FAILED, "could not obtain IDXGIDevice1 interface") \
  1399. _SAPP_LOGITEM_XMACRO(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_LOCK, "RegisterRawInputDevices() failed (on mouse lock)") \
  1400. _SAPP_LOGITEM_XMACRO(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_UNLOCK, "RegisterRawInputDevices() failed (on mouse unlock)") \
  1401. _SAPP_LOGITEM_XMACRO(WIN32_GET_RAW_INPUT_DATA_FAILED, "GetRawInputData() failed") \
  1402. _SAPP_LOGITEM_XMACRO(LINUX_GLX_LOAD_LIBGL_FAILED, "failed to load libGL") \
  1403. _SAPP_LOGITEM_XMACRO(LINUX_GLX_LOAD_ENTRY_POINTS_FAILED, "failed to load GLX entry points") \
  1404. _SAPP_LOGITEM_XMACRO(LINUX_GLX_EXTENSION_NOT_FOUND, "GLX extension not found") \
  1405. _SAPP_LOGITEM_XMACRO(LINUX_GLX_QUERY_VERSION_FAILED, "failed to query GLX version") \
  1406. _SAPP_LOGITEM_XMACRO(LINUX_GLX_VERSION_TOO_LOW, "GLX version too low (need at least 1.3)") \
  1407. _SAPP_LOGITEM_XMACRO(LINUX_GLX_NO_GLXFBCONFIGS, "glXGetFBConfigs() returned no configs") \
  1408. _SAPP_LOGITEM_XMACRO(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG, "failed to find a suitable GLXFBConfig") \
  1409. _SAPP_LOGITEM_XMACRO(LINUX_GLX_GET_VISUAL_FROM_FBCONFIG_FAILED, "glXGetVisualFromFBConfig failed") \
  1410. _SAPP_LOGITEM_XMACRO(LINUX_GLX_REQUIRED_EXTENSIONS_MISSING, "GLX extensions ARB_create_context and ARB_create_context_profile missing") \
  1411. _SAPP_LOGITEM_XMACRO(LINUX_GLX_CREATE_CONTEXT_FAILED, "Failed to create GL context via glXCreateContextAttribsARB") \
  1412. _SAPP_LOGITEM_XMACRO(LINUX_GLX_CREATE_WINDOW_FAILED, "glXCreateWindow() failed") \
  1413. _SAPP_LOGITEM_XMACRO(LINUX_X11_CREATE_WINDOW_FAILED, "XCreateWindow() failed") \
  1414. _SAPP_LOGITEM_XMACRO(LINUX_EGL_BIND_OPENGL_API_FAILED, "eglBindAPI(EGL_OPENGL_API) failed") \
  1415. _SAPP_LOGITEM_XMACRO(LINUX_EGL_BIND_OPENGL_ES_API_FAILED, "eglBindAPI(EGL_OPENGL_ES_API) failed") \
  1416. _SAPP_LOGITEM_XMACRO(LINUX_EGL_GET_DISPLAY_FAILED, "eglGetDisplay() failed") \
  1417. _SAPP_LOGITEM_XMACRO(LINUX_EGL_INITIALIZE_FAILED, "eglInitialize() failed") \
  1418. _SAPP_LOGITEM_XMACRO(LINUX_EGL_NO_CONFIGS, "eglChooseConfig() returned no configs") \
  1419. _SAPP_LOGITEM_XMACRO(LINUX_EGL_NO_NATIVE_VISUAL, "eglGetConfigAttrib() for EGL_NATIVE_VISUAL_ID failed") \
  1420. _SAPP_LOGITEM_XMACRO(LINUX_EGL_GET_VISUAL_INFO_FAILED, "XGetVisualInfo() failed") \
  1421. _SAPP_LOGITEM_XMACRO(LINUX_EGL_CREATE_WINDOW_SURFACE_FAILED, "eglCreateWindowSurface() failed") \
  1422. _SAPP_LOGITEM_XMACRO(LINUX_EGL_CREATE_CONTEXT_FAILED, "eglCreateContext() failed") \
  1423. _SAPP_LOGITEM_XMACRO(LINUX_EGL_MAKE_CURRENT_FAILED, "eglMakeCurrent() failed") \
  1424. _SAPP_LOGITEM_XMACRO(LINUX_X11_OPEN_DISPLAY_FAILED, "XOpenDisplay() failed") \
  1425. _SAPP_LOGITEM_XMACRO(LINUX_X11_QUERY_SYSTEM_DPI_FAILED, "failed to query system dpi value, assuming default 96.0") \
  1426. _SAPP_LOGITEM_XMACRO(LINUX_X11_DROPPED_FILE_URI_WRONG_SCHEME, "dropped file URL doesn't start with 'file://'") \
  1427. _SAPP_LOGITEM_XMACRO(LINUX_X11_FAILED_TO_BECOME_OWNER_OF_CLIPBOARD, "X11: Failed to become owner of clipboard selection") \
  1428. _SAPP_LOGITEM_XMACRO(ANDROID_UNSUPPORTED_INPUT_EVENT_INPUT_CB, "unsupported input event encountered in _sapp_android_input_cb()") \
  1429. _SAPP_LOGITEM_XMACRO(ANDROID_UNSUPPORTED_INPUT_EVENT_MAIN_CB, "unsupported input event encountered in _sapp_android_main_cb()") \
  1430. _SAPP_LOGITEM_XMACRO(ANDROID_READ_MSG_FAILED, "failed to read message in _sapp_android_main_cb()") \
  1431. _SAPP_LOGITEM_XMACRO(ANDROID_WRITE_MSG_FAILED, "failed to write message in _sapp_android_msg") \
  1432. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_CREATE, "MSG_CREATE") \
  1433. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_RESUME, "MSG_RESUME") \
  1434. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_PAUSE, "MSG_PAUSE") \
  1435. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_FOCUS, "MSG_FOCUS") \
  1436. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_NO_FOCUS, "MSG_NO_FOCUS") \
  1437. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_SET_NATIVE_WINDOW, "MSG_SET_NATIVE_WINDOW") \
  1438. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_SET_INPUT_QUEUE, "MSG_SET_INPUT_QUEUE") \
  1439. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_DESTROY, "MSG_DESTROY") \
  1440. _SAPP_LOGITEM_XMACRO(ANDROID_UNKNOWN_MSG, "unknown msg type received") \
  1441. _SAPP_LOGITEM_XMACRO(ANDROID_LOOP_THREAD_STARTED, "loop thread started") \
  1442. _SAPP_LOGITEM_XMACRO(ANDROID_LOOP_THREAD_DONE, "loop thread done") \
  1443. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSTART, "NativeActivity onStart()") \
  1444. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONRESUME, "NativeActivity onResume") \
  1445. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSAVEINSTANCESTATE, "NativeActivity onSaveInstanceState") \
  1446. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONWINDOWFOCUSCHANGED, "NativeActivity onWindowFocusChanged") \
  1447. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONPAUSE, "NativeActivity onPause") \
  1448. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSTOP, "NativeActivity onStop()") \
  1449. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWCREATED, "NativeActivity onNativeWindowCreated") \
  1450. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWDESTROYED, "NativeActivity onNativeWindowDestroyed") \
  1451. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUECREATED, "NativeActivity onInputQueueCreated") \
  1452. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUEDESTROYED, "NativeActivity onInputQueueDestroyed") \
  1453. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONCONFIGURATIONCHANGED, "NativeActivity onConfigurationChanged") \
  1454. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONLOWMEMORY, "NativeActivity onLowMemory") \
  1455. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONDESTROY, "NativeActivity onDestroy") \
  1456. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_DONE, "NativeActivity done") \
  1457. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONCREATE, "NativeActivity onCreate") \
  1458. _SAPP_LOGITEM_XMACRO(ANDROID_CREATE_THREAD_PIPE_FAILED, "failed to create thread pipe") \
  1459. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_CREATE_SUCCESS, "NativeActivity successfully created") \
  1460. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_SURFACE_FAILED, "wgpu: failed to create surface for swapchain") \
  1461. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_SURFACE_GET_CAPABILITIES_FAILED, "wgpu: wgpuSurfaceGetCapabilities failed") \
  1462. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_TEXTURE_FAILED, "wgpu: failed to create depth-stencil texture for swapchain") \
  1463. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_VIEW_FAILED, "wgpu: failed to create view object for swapchain depth-stencil texture") \
  1464. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_MSAA_TEXTURE_FAILED, "wgpu: failed to create msaa texture for swapchain") \
  1465. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_MSAA_VIEW_FAILED, "wgpu: failed to create view object for swapchain msaa texture") \
  1466. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_GETCURRENTTEXTURE_FAILED, "wgpu: wgpuSurfaceGetCurrentTexture() failed") \
  1467. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_DEVICE_STATUS_ERROR, "wgpu: requesting device failed with status 'error'") \
  1468. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_DEVICE_STATUS_UNKNOWN, "wgpu: requesting device failed with status 'unknown'") \
  1469. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_UNAVAILABLE, "wgpu: requesting adapter failed with 'unavailable'") \
  1470. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_ERROR, "wgpu: requesting adapter failed with status 'error'") \
  1471. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_UNKNOWN, "wgpu: requesting adapter failed with status 'unknown'") \
  1472. _SAPP_LOGITEM_XMACRO(WGPU_CREATE_INSTANCE_FAILED, "wgpu: failed to create instance") \
  1473. _SAPP_LOGITEM_XMACRO(IMAGE_DATA_SIZE_MISMATCH, "image data size mismatch (must be width*height*4 bytes)") \
  1474. _SAPP_LOGITEM_XMACRO(DROPPED_FILE_PATH_TOO_LONG, "dropped file path too long (sapp_desc.max_dropped_filed_path_length)") \
  1475. _SAPP_LOGITEM_XMACRO(CLIPBOARD_STRING_TOO_BIG, "clipboard string didn't fit into clipboard buffer") \
  1476. #define _SAPP_LOGITEM_XMACRO(item,msg) SAPP_LOGITEM_##item,
  1477. typedef enum sapp_log_item {
  1478. _SAPP_LOG_ITEMS
  1479. } sapp_log_item;
  1480. #undef _SAPP_LOGITEM_XMACRO
  1481. /*
  1482. sapp_logger
  1483. Used in sapp_desc to provide a logging function. Please be aware that
  1484. without logging function, sokol-app will be completely silent, e.g. it will
  1485. not report errors or warnings. For maximum error verbosity, compile in
  1486. debug mode (e.g. NDEBUG *not* defined) and install a logger (for instance
  1487. the standard logging function from sokol_log.h).
  1488. */
  1489. typedef struct sapp_logger {
  1490. void (*func)(
  1491. const char* tag, // always "sapp"
  1492. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  1493. uint32_t log_item_id, // SAPP_LOGITEM_*
  1494. const char* message_or_null, // a message string, may be nullptr in release mode
  1495. uint32_t line_nr, // line number in sokol_app.h
  1496. const char* filename_or_null, // source filename, may be nullptr in release mode
  1497. void* user_data);
  1498. void* user_data;
  1499. } sapp_logger;
  1500. /*
  1501. sokol-app initialization options, used as return value of sokol_main()
  1502. or sapp_run() argument.
  1503. */
  1504. typedef struct sapp_desc {
  1505. void (*init_cb)(void); // these are the user-provided callbacks without user data
  1506. void (*frame_cb)(void);
  1507. void (*cleanup_cb)(void);
  1508. void (*event_cb)(const sapp_event*);
  1509. void* user_data; // these are the user-provided callbacks with user data
  1510. void (*init_userdata_cb)(void*);
  1511. void (*frame_userdata_cb)(void*);
  1512. void (*cleanup_userdata_cb)(void*);
  1513. void (*event_userdata_cb)(const sapp_event*, void*);
  1514. int width; // the preferred width of the window / canvas
  1515. int height; // the preferred height of the window / canvas
  1516. int sample_count; // MSAA sample count
  1517. int swap_interval; // the preferred swap interval (ignored on some platforms)
  1518. bool high_dpi; // whether the rendering canvas is full-resolution on HighDPI displays
  1519. bool fullscreen; // whether the window should be created in fullscreen mode
  1520. bool alpha; // whether the framebuffer should have an alpha channel (ignored on some platforms)
  1521. const char* window_title; // the window title as UTF-8 encoded string
  1522. bool enable_clipboard; // enable clipboard access, default is false
  1523. int clipboard_size; // max size of clipboard content in bytes
  1524. bool enable_dragndrop; // enable file dropping (drag'n'drop), default is false
  1525. int max_dropped_files; // max number of dropped files to process (default: 1)
  1526. int max_dropped_file_path_length; // max length in bytes of a dropped UTF-8 file path (default: 2048)
  1527. sapp_icon_desc icon; // the initial window icon to set
  1528. sapp_allocator allocator; // optional memory allocation overrides (default: malloc/free)
  1529. sapp_logger logger; // logging callback override (default: NO LOGGING!)
  1530. // backend-specific options
  1531. int gl_major_version; // override GL/GLES major and minor version (defaults: GL4.1 (macOS) or GL4.3, GLES3.1 (Android) or GLES3.0
  1532. int gl_minor_version;
  1533. bool win32_console_utf8; // if true, set the output console codepage to UTF-8
  1534. bool win32_console_create; // if true, attach stdout/stderr to a new console window
  1535. bool win32_console_attach; // if true, attach stdout/stderr to parent process
  1536. const char* html5_canvas_selector; // css selector of the HTML5 canvas element, default is "#canvas"
  1537. bool html5_canvas_resize; // if true, the HTML5 canvas size is set to sapp_desc.width/height, otherwise canvas size is tracked
  1538. bool html5_preserve_drawing_buffer; // HTML5 only: whether to preserve default framebuffer content between frames
  1539. bool html5_premultiplied_alpha; // HTML5 only: whether the rendered pixels use premultiplied alpha convention
  1540. bool html5_ask_leave_site; // initial state of the internal html5_ask_leave_site flag (see sapp_html5_ask_leave_site())
  1541. bool html5_update_document_title; // if true, update the HTML document.title with sapp_desc.window_title
  1542. bool html5_bubble_mouse_events; // if true, mouse events will bubble up to the web page
  1543. bool html5_bubble_touch_events; // same for touch events
  1544. bool html5_bubble_wheel_events; // same for wheel events
  1545. bool html5_bubble_key_events; // if true, bubble up *all* key events to browser, not just key events that represent characters
  1546. bool html5_bubble_char_events; // if true, bubble up character events to browser
  1547. bool html5_use_emsc_set_main_loop; // if true, use emscripten_set_main_loop() instead of emscripten_request_animation_frame_loop()
  1548. bool html5_emsc_set_main_loop_simulate_infinite_loop; // this will be passed as the simulate_infinite_loop arg to emscripten_set_main_loop()
  1549. bool ios_keyboard_resizes_canvas; // if true, showing the iOS keyboard shrinks the canvas
  1550. } sapp_desc;
  1551. /* HTML5 specific: request and response structs for
  1552. asynchronously loading dropped-file content.
  1553. */
  1554. typedef enum sapp_html5_fetch_error {
  1555. SAPP_HTML5_FETCH_ERROR_NO_ERROR,
  1556. SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL,
  1557. SAPP_HTML5_FETCH_ERROR_OTHER,
  1558. } sapp_html5_fetch_error;
  1559. typedef struct sapp_html5_fetch_response {
  1560. bool succeeded; // true if the loading operation has succeeded
  1561. sapp_html5_fetch_error error_code;
  1562. int file_index; // index of the dropped file (0..sapp_get_num_dropped_filed()-1)
  1563. sapp_range data; // pointer and size of the fetched data (data.ptr == buffer.ptr, data.size <= buffer.size)
  1564. sapp_range buffer; // the user-provided buffer ptr/size pair (buffer.ptr == data.ptr, buffer.size >= data.size)
  1565. void* user_data; // user-provided user data pointer
  1566. } sapp_html5_fetch_response;
  1567. typedef struct sapp_html5_fetch_request {
  1568. int dropped_file_index; // 0..sapp_get_num_dropped_files()-1
  1569. void (*callback)(const sapp_html5_fetch_response*); // response callback function pointer (required)
  1570. sapp_range buffer; // ptr/size of a memory buffer to load the data into
  1571. void* user_data; // optional userdata pointer
  1572. } sapp_html5_fetch_request;
  1573. /*
  1574. sapp_mouse_cursor
  1575. Predefined cursor image definitions, set with sapp_set_mouse_cursor(sapp_mouse_cursor cursor)
  1576. */
  1577. typedef enum sapp_mouse_cursor {
  1578. SAPP_MOUSECURSOR_DEFAULT = 0, // equivalent with system default cursor
  1579. SAPP_MOUSECURSOR_ARROW,
  1580. SAPP_MOUSECURSOR_IBEAM,
  1581. SAPP_MOUSECURSOR_CROSSHAIR,
  1582. SAPP_MOUSECURSOR_POINTING_HAND,
  1583. SAPP_MOUSECURSOR_RESIZE_EW,
  1584. SAPP_MOUSECURSOR_RESIZE_NS,
  1585. SAPP_MOUSECURSOR_RESIZE_NWSE,
  1586. SAPP_MOUSECURSOR_RESIZE_NESW,
  1587. SAPP_MOUSECURSOR_RESIZE_ALL,
  1588. SAPP_MOUSECURSOR_NOT_ALLOWED,
  1589. _SAPP_MOUSECURSOR_NUM,
  1590. } sapp_mouse_cursor;
  1591. /* user-provided functions */
  1592. extern sapp_desc sokol_main(int argc, char* argv[]);
  1593. /* returns true after sokol-app has been initialized */
  1594. SOKOL_APP_API_DECL bool sapp_isvalid(void);
  1595. /* returns the current framebuffer width in pixels */
  1596. SOKOL_APP_API_DECL int sapp_width(void);
  1597. /* same as sapp_width(), but returns float */
  1598. SOKOL_APP_API_DECL float sapp_widthf(void);
  1599. /* returns the current framebuffer height in pixels */
  1600. SOKOL_APP_API_DECL int sapp_height(void);
  1601. /* same as sapp_height(), but returns float */
  1602. SOKOL_APP_API_DECL float sapp_heightf(void);
  1603. /* get default framebuffer color pixel format */
  1604. SOKOL_APP_API_DECL int sapp_color_format(void);
  1605. /* get default framebuffer depth pixel format */
  1606. SOKOL_APP_API_DECL int sapp_depth_format(void);
  1607. /* get default framebuffer sample count */
  1608. SOKOL_APP_API_DECL int sapp_sample_count(void);
  1609. /* returns true when high_dpi was requested and actually running in a high-dpi scenario */
  1610. SOKOL_APP_API_DECL bool sapp_high_dpi(void);
  1611. /* returns the dpi scaling factor (window pixels to framebuffer pixels) */
  1612. SOKOL_APP_API_DECL float sapp_dpi_scale(void);
  1613. /* show or hide the mobile device onscreen keyboard */
  1614. SOKOL_APP_API_DECL void sapp_show_keyboard(bool show);
  1615. /* return true if the mobile device onscreen keyboard is currently shown */
  1616. SOKOL_APP_API_DECL bool sapp_keyboard_shown(void);
  1617. /* query fullscreen mode */
  1618. SOKOL_APP_API_DECL bool sapp_is_fullscreen(void);
  1619. /* toggle fullscreen mode */
  1620. SOKOL_APP_API_DECL void sapp_toggle_fullscreen(void);
  1621. /* show or hide the mouse cursor */
  1622. SOKOL_APP_API_DECL void sapp_show_mouse(bool show);
  1623. /* show or hide the mouse cursor */
  1624. SOKOL_APP_API_DECL bool sapp_mouse_shown(void);
  1625. /* enable/disable mouse-pointer-lock mode */
  1626. SOKOL_APP_API_DECL void sapp_lock_mouse(bool lock);
  1627. /* return true if in mouse-pointer-lock mode (this may toggle a few frames later) */
  1628. SOKOL_APP_API_DECL bool sapp_mouse_locked(void);
  1629. /* set mouse cursor type */
  1630. SOKOL_APP_API_DECL void sapp_set_mouse_cursor(sapp_mouse_cursor cursor);
  1631. /* get current mouse cursor type */
  1632. SOKOL_APP_API_DECL sapp_mouse_cursor sapp_get_mouse_cursor(void);
  1633. /* return the userdata pointer optionally provided in sapp_desc */
  1634. SOKOL_APP_API_DECL void* sapp_userdata(void);
  1635. /* return a copy of the sapp_desc structure */
  1636. SOKOL_APP_API_DECL sapp_desc sapp_query_desc(void);
  1637. /* initiate a "soft quit" (sends SAPP_EVENTTYPE_QUIT_REQUESTED) */
  1638. SOKOL_APP_API_DECL void sapp_request_quit(void);
  1639. /* cancel a pending quit (when SAPP_EVENTTYPE_QUIT_REQUESTED has been received) */
  1640. SOKOL_APP_API_DECL void sapp_cancel_quit(void);
  1641. /* initiate a "hard quit" (quit application without sending SAPP_EVENTTYPE_QUIT_REQUESTED) */
  1642. SOKOL_APP_API_DECL void sapp_quit(void);
  1643. /* call from inside event callback to consume the current event (don't forward to platform) */
  1644. SOKOL_APP_API_DECL void sapp_consume_event(void);
  1645. /* get the current frame counter (for comparison with sapp_event.frame_count) */
  1646. SOKOL_APP_API_DECL uint64_t sapp_frame_count(void);
  1647. /* get an averaged/smoothed frame duration in seconds */
  1648. SOKOL_APP_API_DECL double sapp_frame_duration(void);
  1649. /* write string into clipboard */
  1650. SOKOL_APP_API_DECL void sapp_set_clipboard_string(const char* str);
  1651. /* read string from clipboard (usually during SAPP_EVENTTYPE_CLIPBOARD_PASTED) */
  1652. SOKOL_APP_API_DECL const char* sapp_get_clipboard_string(void);
  1653. /* set the window title (only on desktop platforms) */
  1654. SOKOL_APP_API_DECL void sapp_set_window_title(const char* str);
  1655. /* set the window icon (only on Windows and Linux) */
  1656. SOKOL_APP_API_DECL void sapp_set_icon(const sapp_icon_desc* icon_desc);
  1657. /* gets the total number of dropped files (after an SAPP_EVENTTYPE_FILES_DROPPED event) */
  1658. SOKOL_APP_API_DECL int sapp_get_num_dropped_files(void);
  1659. /* gets the dropped file paths */
  1660. SOKOL_APP_API_DECL const char* sapp_get_dropped_file_path(int index);
  1661. /* special run-function for SOKOL_NO_ENTRY (in standard mode this is an empty stub) */
  1662. SOKOL_APP_API_DECL void sapp_run(const sapp_desc* desc);
  1663. /* EGL: get EGLDisplay object */
  1664. SOKOL_APP_API_DECL const void* sapp_egl_get_display(void);
  1665. /* EGL: get EGLContext object */
  1666. SOKOL_APP_API_DECL const void* sapp_egl_get_context(void);
  1667. /* HTML5: enable or disable the hardwired "Leave Site?" dialog box */
  1668. SOKOL_APP_API_DECL void sapp_html5_ask_leave_site(bool ask);
  1669. /* HTML5: get byte size of a dropped file */
  1670. SOKOL_APP_API_DECL uint32_t sapp_html5_get_dropped_file_size(int index);
  1671. /* HTML5: asynchronously load the content of a dropped file */
  1672. SOKOL_APP_API_DECL void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request);
  1673. /* Metal: get bridged pointer to Metal device object */
  1674. SOKOL_APP_API_DECL const void* sapp_metal_get_device(void);
  1675. /* Metal: get bridged pointer to MTKView's current drawable of type CAMetalDrawable */
  1676. SOKOL_APP_API_DECL const void* sapp_metal_get_current_drawable(void);
  1677. /* Metal: get bridged pointer to MTKView's depth-stencil texture of type MTLTexture */
  1678. SOKOL_APP_API_DECL const void* sapp_metal_get_depth_stencil_texture(void);
  1679. /* Metal: get bridged pointer to MTKView's msaa-color-texture of type MTLTexture (may be null) */
  1680. SOKOL_APP_API_DECL const void* sapp_metal_get_msaa_color_texture(void);
  1681. /* macOS: get bridged pointer to macOS NSWindow */
  1682. SOKOL_APP_API_DECL const void* sapp_macos_get_window(void);
  1683. /* iOS: get bridged pointer to iOS UIWindow */
  1684. SOKOL_APP_API_DECL const void* sapp_ios_get_window(void);
  1685. /* D3D11: get pointer to ID3D11Device object */
  1686. SOKOL_APP_API_DECL const void* sapp_d3d11_get_device(void);
  1687. /* D3D11: get pointer to ID3D11DeviceContext object */
  1688. SOKOL_APP_API_DECL const void* sapp_d3d11_get_device_context(void);
  1689. /* D3D11: get pointer to IDXGISwapChain object */
  1690. SOKOL_APP_API_DECL const void* sapp_d3d11_get_swap_chain(void);
  1691. /* D3D11: get pointer to ID3D11RenderTargetView object for rendering */
  1692. SOKOL_APP_API_DECL const void* sapp_d3d11_get_render_view(void);
  1693. /* D3D11: get pointer ID3D11RenderTargetView object for msaa-resolve (may return null) */
  1694. SOKOL_APP_API_DECL const void* sapp_d3d11_get_resolve_view(void);
  1695. /* D3D11: get pointer ID3D11DepthStencilView */
  1696. SOKOL_APP_API_DECL const void* sapp_d3d11_get_depth_stencil_view(void);
  1697. /* Win32: get the HWND window handle */
  1698. SOKOL_APP_API_DECL const void* sapp_win32_get_hwnd(void);
  1699. /* WebGPU: get WGPUDevice handle */
  1700. SOKOL_APP_API_DECL const void* sapp_wgpu_get_device(void);
  1701. /* WebGPU: get swapchain's WGPUTextureView handle for rendering */
  1702. SOKOL_APP_API_DECL const void* sapp_wgpu_get_render_view(void);
  1703. /* WebGPU: get swapchain's MSAA-resolve WGPUTextureView (may return null) */
  1704. SOKOL_APP_API_DECL const void* sapp_wgpu_get_resolve_view(void);
  1705. /* WebGPU: get swapchain's WGPUTextureView for the depth-stencil surface */
  1706. SOKOL_APP_API_DECL const void* sapp_wgpu_get_depth_stencil_view(void);
  1707. /* GL: get framebuffer object */
  1708. SOKOL_APP_API_DECL uint32_t sapp_gl_get_framebuffer(void);
  1709. /* GL: get major version */
  1710. SOKOL_APP_API_DECL int sapp_gl_get_major_version(void);
  1711. /* GL: get minor version */
  1712. SOKOL_APP_API_DECL int sapp_gl_get_minor_version(void);
  1713. /* GL: return true if the context is GLES */
  1714. SOKOL_APP_API_DECL bool sapp_gl_is_gles(void);
  1715. /* X11: get Window */
  1716. SOKOL_APP_API_DECL const void* sapp_x11_get_window(void);
  1717. /* X11: get Display */
  1718. SOKOL_APP_API_DECL const void* sapp_x11_get_display(void);
  1719. /* Android: get native activity handle */
  1720. SOKOL_APP_API_DECL const void* sapp_android_get_native_activity(void);
  1721. #ifdef __cplusplus
  1722. } /* extern "C" */
  1723. /* reference-based equivalents for C++ */
  1724. inline void sapp_run(const sapp_desc& desc) { return sapp_run(&desc); }
  1725. #endif
  1726. #endif // SOKOL_APP_INCLUDED
  1727. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  1728. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  1729. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  1730. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1731. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  1732. //
  1733. // >>implementation
  1734. #ifdef SOKOL_APP_IMPL
  1735. #define SOKOL_APP_IMPL_INCLUDED (1)
  1736. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  1737. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sapp_desc.allocator to override memory allocation functions"
  1738. #endif
  1739. #include <stdlib.h> // malloc, free
  1740. #include <string.h> // memset, strncmp
  1741. #include <stddef.h> // size_t
  1742. #include <math.h> // roundf
  1743. // helper macros
  1744. #define _sapp_def(val, def) (((val) == 0) ? (def) : (val))
  1745. #define _sapp_absf(a) (((a)<0.0f)?-(a):(a))
  1746. #define _SAPP_MAX_TITLE_LENGTH (128)
  1747. #define _SAPP_FALLBACK_DEFAULT_WINDOW_WIDTH (640)
  1748. #define _SAPP_FALLBACK_DEFAULT_WINDOW_HEIGHT (480)
  1749. // NOTE: the pixel format values *must* be compatible with sg_pixel_format
  1750. #define _SAPP_PIXELFORMAT_RGBA8 (23)
  1751. #define _SAPP_PIXELFORMAT_BGRA8 (28)
  1752. #define _SAPP_PIXELFORMAT_DEPTH (43)
  1753. #define _SAPP_PIXELFORMAT_DEPTH_STENCIL (44)
  1754. // check if the config defines are alright
  1755. #if defined(__APPLE__)
  1756. // see https://clang.llvm.org/docs/LanguageExtensions.html#automatic-reference-counting
  1757. #if !defined(__cplusplus)
  1758. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  1759. #error "sokol_app.h requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  1760. #endif
  1761. #endif
  1762. #define _SAPP_APPLE (1)
  1763. #include <TargetConditionals.h>
  1764. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  1765. /* MacOS */
  1766. #define _SAPP_MACOS (1)
  1767. #if !defined(SOKOL_METAL) && !defined(SOKOL_GLCORE)
  1768. #error("sokol_app.h: unknown 3D API selected for MacOS, must be SOKOL_METAL or SOKOL_GLCORE")
  1769. #endif
  1770. #else
  1771. /* iOS or iOS Simulator */
  1772. #define _SAPP_IOS (1)
  1773. #if !defined(SOKOL_METAL) && !defined(SOKOL_GLES3)
  1774. #error("sokol_app.h: unknown 3D API selected for iOS, must be SOKOL_METAL or SOKOL_GLES3")
  1775. #endif
  1776. #endif
  1777. #elif defined(__EMSCRIPTEN__)
  1778. /* emscripten (asm.js or wasm) */
  1779. #define _SAPP_EMSCRIPTEN (1)
  1780. #if !defined(SOKOL_GLES3) && !defined(SOKOL_WGPU)
  1781. #error("sokol_app.h: unknown 3D API selected for emscripten, must be SOKOL_GLES3 or SOKOL_WGPU")
  1782. #endif
  1783. #elif defined(_WIN32)
  1784. /* Windows (D3D11 or GL) */
  1785. #define _SAPP_WIN32 (1)
  1786. #if !defined(SOKOL_D3D11) && !defined(SOKOL_GLCORE) && !defined(SOKOL_NOAPI)
  1787. #error("sokol_app.h: unknown 3D API selected for Win32, must be SOKOL_D3D11, SOKOL_GLCORE or SOKOL_NOAPI")
  1788. #endif
  1789. #elif defined(__ANDROID__)
  1790. /* Android */
  1791. #define _SAPP_ANDROID (1)
  1792. #if !defined(SOKOL_GLES3)
  1793. #error("sokol_app.h: unknown 3D API selected for Android, must be SOKOL_GLES3")
  1794. #endif
  1795. #if defined(SOKOL_NO_ENTRY)
  1796. #error("sokol_app.h: SOKOL_NO_ENTRY is not supported on Android")
  1797. #endif
  1798. #elif defined(__linux__) || defined(__unix__)
  1799. /* Linux */
  1800. #define _SAPP_LINUX (1)
  1801. #if defined(SOKOL_GLCORE)
  1802. #if !defined(SOKOL_FORCE_EGL)
  1803. #define _SAPP_GLX (1)
  1804. #endif
  1805. #define GL_GLEXT_PROTOTYPES
  1806. #include <GL/gl.h>
  1807. #elif defined(SOKOL_GLES3)
  1808. #include <GLES3/gl3.h>
  1809. #include <GLES3/gl3ext.h>
  1810. #else
  1811. #error("sokol_app.h: unknown 3D API selected for Linux, must be SOKOL_GLCORE, SOKOL_GLES3")
  1812. #endif
  1813. #else
  1814. #error "sokol_app.h: Unknown platform"
  1815. #endif
  1816. #if defined(SOKOL_GLCORE) || defined(SOKOL_GLES3)
  1817. #define _SAPP_ANY_GL (1)
  1818. #endif
  1819. #ifndef SOKOL_API_IMPL
  1820. #define SOKOL_API_IMPL
  1821. #endif
  1822. #ifndef SOKOL_DEBUG
  1823. #ifndef NDEBUG
  1824. #define SOKOL_DEBUG
  1825. #endif
  1826. #endif
  1827. #ifndef SOKOL_ASSERT
  1828. #include <assert.h>
  1829. #define SOKOL_ASSERT(c) assert(c)
  1830. #endif
  1831. #ifndef SOKOL_UNREACHABLE
  1832. #define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
  1833. #endif
  1834. #ifndef _SOKOL_PRIVATE
  1835. #if defined(__GNUC__) || defined(__clang__)
  1836. #define _SOKOL_PRIVATE __attribute__((unused)) static
  1837. #else
  1838. #define _SOKOL_PRIVATE static
  1839. #endif
  1840. #endif
  1841. #ifndef _SOKOL_UNUSED
  1842. #define _SOKOL_UNUSED(x) (void)(x)
  1843. #endif
  1844. #if defined(SOKOL_WGPU)
  1845. #include <webgpu/webgpu.h>
  1846. #endif
  1847. #if defined(_SAPP_APPLE)
  1848. #if defined(SOKOL_METAL)
  1849. #import <Metal/Metal.h>
  1850. #import <MetalKit/MetalKit.h>
  1851. #endif
  1852. #if defined(_SAPP_MACOS)
  1853. #if defined(_SAPP_ANY_GL)
  1854. #ifndef GL_SILENCE_DEPRECATION
  1855. #define GL_SILENCE_DEPRECATION
  1856. #endif
  1857. #include <Cocoa/Cocoa.h>
  1858. #include <OpenGL/gl3.h>
  1859. #endif
  1860. #elif defined(_SAPP_IOS)
  1861. #import <UIKit/UIKit.h>
  1862. #if defined(_SAPP_ANY_GL)
  1863. #import <GLKit/GLKit.h>
  1864. #include <OpenGLES/ES3/gl.h>
  1865. #endif
  1866. #endif
  1867. #include <AvailabilityMacros.h>
  1868. #include <mach/mach_time.h>
  1869. #elif defined(_SAPP_EMSCRIPTEN)
  1870. #if defined(SOKOL_GLES3)
  1871. #include <GLES3/gl3.h>
  1872. #endif
  1873. #include <emscripten/emscripten.h>
  1874. #include <emscripten/html5.h>
  1875. #elif defined(_SAPP_WIN32)
  1876. #ifdef _MSC_VER
  1877. #pragma warning(push)
  1878. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  1879. #pragma warning(disable:4204) /* nonstandard extension used: non-constant aggregate initializer */
  1880. #pragma warning(disable:4054) /* 'type cast': from function pointer */
  1881. #pragma warning(disable:4055) /* 'type cast': from data pointer */
  1882. #pragma warning(disable:4505) /* unreferenced local function has been removed */
  1883. #pragma warning(disable:4115) /* /W4: 'ID3D11ModuleInstance': named type definition in parentheses (in d3d11.h) */
  1884. #endif
  1885. #ifndef WIN32_LEAN_AND_MEAN
  1886. #define WIN32_LEAN_AND_MEAN
  1887. #endif
  1888. #ifndef NOMINMAX
  1889. #define NOMINMAX
  1890. #endif
  1891. #include <windows.h>
  1892. #include <windowsx.h>
  1893. #include <shellapi.h>
  1894. #if !defined(SOKOL_NO_ENTRY) // if SOKOL_NO_ENTRY is defined, it's the application's responsibility to use the right subsystem
  1895. #if defined(SOKOL_WIN32_FORCE_MAIN) && defined(SOKOL_WIN32_FORCE_WINMAIN)
  1896. // If both are defined, it's the application's responsibility to use the right subsystem
  1897. #elif defined(SOKOL_WIN32_FORCE_MAIN)
  1898. #pragma comment (linker, "/subsystem:console")
  1899. #else
  1900. #pragma comment (linker, "/subsystem:windows")
  1901. #endif
  1902. #endif
  1903. #include <stdio.h> /* freopen_s() */
  1904. #include <wchar.h> /* wcslen() */
  1905. #pragma comment (lib, "kernel32")
  1906. #pragma comment (lib, "user32")
  1907. #pragma comment (lib, "shell32") /* CommandLineToArgvW, DragQueryFileW, DragFinished */
  1908. #pragma comment (lib, "gdi32")
  1909. #if defined(SOKOL_D3D11)
  1910. #pragma comment (lib, "dxgi")
  1911. #pragma comment (lib, "d3d11")
  1912. #endif
  1913. #if defined(SOKOL_D3D11)
  1914. #ifndef D3D11_NO_HELPERS
  1915. #define D3D11_NO_HELPERS
  1916. #endif
  1917. #include <d3d11.h>
  1918. #include <dxgi.h>
  1919. // DXGI_SWAP_EFFECT_FLIP_DISCARD is only defined in newer Windows SDKs, so don't depend on it
  1920. #define _SAPP_DXGI_SWAP_EFFECT_FLIP_DISCARD (4)
  1921. #endif
  1922. #ifndef WM_MOUSEHWHEEL /* see https://github.com/floooh/sokol/issues/138 */
  1923. #define WM_MOUSEHWHEEL (0x020E)
  1924. #endif
  1925. #ifndef WM_DPICHANGED
  1926. #define WM_DPICHANGED (0x02E0)
  1927. #endif
  1928. #elif defined(_SAPP_ANDROID)
  1929. #include <pthread.h>
  1930. #include <unistd.h>
  1931. #include <time.h>
  1932. #include <android/native_activity.h>
  1933. #include <android/looper.h>
  1934. #include <EGL/egl.h>
  1935. #include <GLES3/gl3.h>
  1936. #elif defined(_SAPP_LINUX)
  1937. #define GL_GLEXT_PROTOTYPES
  1938. #include <X11/Xlib.h>
  1939. #include <X11/Xutil.h>
  1940. #include <X11/XKBlib.h>
  1941. #include <X11/keysym.h>
  1942. #include <X11/Xresource.h>
  1943. #include <X11/Xatom.h>
  1944. #include <X11/extensions/XInput2.h>
  1945. #include <X11/Xcursor/Xcursor.h>
  1946. #include <X11/cursorfont.h> /* XC_* font cursors */
  1947. #include <X11/Xmd.h> /* CARD32 */
  1948. #if !defined(_SAPP_GLX)
  1949. #include <EGL/egl.h>
  1950. #endif
  1951. #include <dlfcn.h> /* dlopen, dlsym, dlclose */
  1952. #include <limits.h> /* LONG_MAX */
  1953. #include <pthread.h> /* only used a linker-guard, search for _sapp_linux_run() and see first comment */
  1954. #include <time.h>
  1955. #include <poll.h>
  1956. #endif
  1957. #if defined(_SAPP_APPLE)
  1958. // this is ARC compatible
  1959. #if defined(__cplusplus)
  1960. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { item = type(); }
  1961. #else
  1962. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { item = (type) { 0 }; }
  1963. #endif
  1964. #else
  1965. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { _sapp_clear(&item, sizeof(item)); }
  1966. #endif
  1967. // ███████ ██████ █████ ███ ███ ███████ ████████ ██ ███ ███ ██ ███ ██ ██████
  1968. // ██ ██ ██ ██ ██ ████ ████ ██ ██ ██ ████ ████ ██ ████ ██ ██
  1969. // █████ ██████ ███████ ██ ████ ██ █████ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ███
  1970. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1971. // ██ ██ ██ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ████ ██████
  1972. //
  1973. // >>frame timing
  1974. #define _SAPP_RING_NUM_SLOTS (256)
  1975. typedef struct {
  1976. int head;
  1977. int tail;
  1978. double buf[_SAPP_RING_NUM_SLOTS];
  1979. } _sapp_ring_t;
  1980. _SOKOL_PRIVATE int _sapp_ring_idx(int i) {
  1981. return i % _SAPP_RING_NUM_SLOTS;
  1982. }
  1983. _SOKOL_PRIVATE void _sapp_ring_init(_sapp_ring_t* ring) {
  1984. ring->head = 0;
  1985. ring->tail = 0;
  1986. }
  1987. _SOKOL_PRIVATE bool _sapp_ring_full(_sapp_ring_t* ring) {
  1988. return _sapp_ring_idx(ring->head + 1) == ring->tail;
  1989. }
  1990. _SOKOL_PRIVATE bool _sapp_ring_empty(_sapp_ring_t* ring) {
  1991. return ring->head == ring->tail;
  1992. }
  1993. _SOKOL_PRIVATE int _sapp_ring_count(_sapp_ring_t* ring) {
  1994. int count;
  1995. if (ring->head >= ring->tail) {
  1996. count = ring->head - ring->tail;
  1997. }
  1998. else {
  1999. count = (ring->head + _SAPP_RING_NUM_SLOTS) - ring->tail;
  2000. }
  2001. SOKOL_ASSERT((count >= 0) && (count < _SAPP_RING_NUM_SLOTS));
  2002. return count;
  2003. }
  2004. _SOKOL_PRIVATE void _sapp_ring_enqueue(_sapp_ring_t* ring, double val) {
  2005. SOKOL_ASSERT(!_sapp_ring_full(ring));
  2006. ring->buf[ring->head] = val;
  2007. ring->head = _sapp_ring_idx(ring->head + 1);
  2008. }
  2009. _SOKOL_PRIVATE double _sapp_ring_dequeue(_sapp_ring_t* ring) {
  2010. SOKOL_ASSERT(!_sapp_ring_empty(ring));
  2011. double val = ring->buf[ring->tail];
  2012. ring->tail = _sapp_ring_idx(ring->tail + 1);
  2013. return val;
  2014. }
  2015. /*
  2016. NOTE:
  2017. Q: Why not use CAMetalDrawable.presentedTime on macOS and iOS?
  2018. A: The value appears to be highly unstable during the first few
  2019. seconds, sometimes several frames are dropped in sequence, or
  2020. switch between 120 and 60 Hz for a few frames. Simply measuring
  2021. and averaging the frame time yielded a more stable frame duration.
  2022. Maybe switching to CVDisplayLink would yield better results.
  2023. Until then just measure the time.
  2024. */
  2025. typedef struct {
  2026. #if defined(_SAPP_APPLE)
  2027. struct {
  2028. mach_timebase_info_data_t timebase;
  2029. uint64_t start;
  2030. } mach;
  2031. #elif defined(_SAPP_EMSCRIPTEN)
  2032. // empty
  2033. #elif defined(_SAPP_WIN32)
  2034. struct {
  2035. LARGE_INTEGER freq;
  2036. LARGE_INTEGER start;
  2037. } win;
  2038. #else // Linux, Android, ...
  2039. #ifdef CLOCK_MONOTONIC
  2040. #define _SAPP_CLOCK_MONOTONIC CLOCK_MONOTONIC
  2041. #else
  2042. // on some embedded platforms, CLOCK_MONOTONIC isn't defined
  2043. #define _SAPP_CLOCK_MONOTONIC (1)
  2044. #endif
  2045. struct {
  2046. uint64_t start;
  2047. } posix;
  2048. #endif
  2049. } _sapp_timestamp_t;
  2050. _SOKOL_PRIVATE int64_t _sapp_int64_muldiv(int64_t value, int64_t numer, int64_t denom) {
  2051. int64_t q = value / denom;
  2052. int64_t r = value % denom;
  2053. return q * numer + r * numer / denom;
  2054. }
  2055. _SOKOL_PRIVATE void _sapp_timestamp_init(_sapp_timestamp_t* ts) {
  2056. #if defined(_SAPP_APPLE)
  2057. mach_timebase_info(&ts->mach.timebase);
  2058. ts->mach.start = mach_absolute_time();
  2059. #elif defined(_SAPP_EMSCRIPTEN)
  2060. (void)ts;
  2061. #elif defined(_SAPP_WIN32)
  2062. QueryPerformanceFrequency(&ts->win.freq);
  2063. QueryPerformanceCounter(&ts->win.start);
  2064. #else
  2065. struct timespec tspec;
  2066. clock_gettime(_SAPP_CLOCK_MONOTONIC, &tspec);
  2067. ts->posix.start = (uint64_t)tspec.tv_sec*1000000000 + (uint64_t)tspec.tv_nsec;
  2068. #endif
  2069. }
  2070. _SOKOL_PRIVATE double _sapp_timestamp_now(_sapp_timestamp_t* ts) {
  2071. #if defined(_SAPP_APPLE)
  2072. const uint64_t traw = mach_absolute_time() - ts->mach.start;
  2073. const uint64_t now = (uint64_t) _sapp_int64_muldiv((int64_t)traw, (int64_t)ts->mach.timebase.numer, (int64_t)ts->mach.timebase.denom);
  2074. return (double)now / 1000000000.0;
  2075. #elif defined(_SAPP_EMSCRIPTEN)
  2076. (void)ts;
  2077. SOKOL_ASSERT(false);
  2078. return 0.0;
  2079. #elif defined(_SAPP_WIN32)
  2080. LARGE_INTEGER qpc;
  2081. QueryPerformanceCounter(&qpc);
  2082. const uint64_t now = (uint64_t)_sapp_int64_muldiv(qpc.QuadPart - ts->win.start.QuadPart, 1000000000, ts->win.freq.QuadPart);
  2083. return (double)now / 1000000000.0;
  2084. #else
  2085. struct timespec tspec;
  2086. clock_gettime(_SAPP_CLOCK_MONOTONIC, &tspec);
  2087. const uint64_t now = ((uint64_t)tspec.tv_sec*1000000000 + (uint64_t)tspec.tv_nsec) - ts->posix.start;
  2088. return (double)now / 1000000000.0;
  2089. #endif
  2090. }
  2091. typedef struct {
  2092. double last;
  2093. double accum;
  2094. double avg;
  2095. int spike_count;
  2096. int num;
  2097. _sapp_timestamp_t timestamp;
  2098. _sapp_ring_t ring;
  2099. } _sapp_timing_t;
  2100. _SOKOL_PRIVATE void _sapp_timing_reset(_sapp_timing_t* t) {
  2101. t->last = 0.0;
  2102. t->accum = 0.0;
  2103. t->spike_count = 0;
  2104. t->num = 0;
  2105. _sapp_ring_init(&t->ring);
  2106. }
  2107. _SOKOL_PRIVATE void _sapp_timing_init(_sapp_timing_t* t) {
  2108. t->avg = 1.0 / 60.0; // dummy value until first actual value is available
  2109. _sapp_timing_reset(t);
  2110. _sapp_timestamp_init(&t->timestamp);
  2111. }
  2112. _SOKOL_PRIVATE void _sapp_timing_put(_sapp_timing_t* t, double dur) {
  2113. // arbitrary upper limit to ignore outliers (e.g. during window resizing, or debugging)
  2114. double min_dur = 0.0;
  2115. double max_dur = 0.1;
  2116. // if we have enough samples for a useful average, use a much tighter 'valid window'
  2117. if (_sapp_ring_full(&t->ring)) {
  2118. min_dur = t->avg * 0.8;
  2119. max_dur = t->avg * 1.2;
  2120. }
  2121. if ((dur < min_dur) || (dur > max_dur)) {
  2122. t->spike_count++;
  2123. // if there have been many spikes in a row, the display refresh rate
  2124. // might have changed, so a timing reset is needed
  2125. if (t->spike_count > 20) {
  2126. _sapp_timing_reset(t);
  2127. }
  2128. return;
  2129. }
  2130. if (_sapp_ring_full(&t->ring)) {
  2131. double old_val = _sapp_ring_dequeue(&t->ring);
  2132. t->accum -= old_val;
  2133. t->num -= 1;
  2134. }
  2135. _sapp_ring_enqueue(&t->ring, dur);
  2136. t->accum += dur;
  2137. t->num += 1;
  2138. SOKOL_ASSERT(t->num > 0);
  2139. t->avg = t->accum / t->num;
  2140. t->spike_count = 0;
  2141. }
  2142. _SOKOL_PRIVATE void _sapp_timing_discontinuity(_sapp_timing_t* t) {
  2143. t->last = 0.0;
  2144. }
  2145. _SOKOL_PRIVATE void _sapp_timing_measure(_sapp_timing_t* t) {
  2146. const double now = _sapp_timestamp_now(&t->timestamp);
  2147. if (t->last > 0.0) {
  2148. double dur = now - t->last;
  2149. _sapp_timing_put(t, dur);
  2150. }
  2151. t->last = now;
  2152. }
  2153. _SOKOL_PRIVATE void _sapp_timing_external(_sapp_timing_t* t, double now) {
  2154. if (t->last > 0.0) {
  2155. double dur = now - t->last;
  2156. _sapp_timing_put(t, dur);
  2157. }
  2158. t->last = now;
  2159. }
  2160. _SOKOL_PRIVATE double _sapp_timing_get_avg(_sapp_timing_t* t) {
  2161. return t->avg;
  2162. }
  2163. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  2164. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2165. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  2166. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2167. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  2168. //
  2169. // >> structs
  2170. #if defined(SOKOL_WGPU)
  2171. typedef struct {
  2172. WGPUInstance instance;
  2173. WGPUAdapter adapter;
  2174. WGPUDevice device;
  2175. WGPUSurface surface;
  2176. WGPUTextureFormat render_format;
  2177. WGPUTexture msaa_tex;
  2178. WGPUTextureView msaa_view;
  2179. WGPUTexture depth_stencil_tex;
  2180. WGPUTextureView depth_stencil_view;
  2181. WGPUTextureView swapchain_view;
  2182. bool async_init_done;
  2183. } _sapp_wgpu_t;
  2184. #endif
  2185. #if defined(_SAPP_MACOS)
  2186. @interface _sapp_macos_app_delegate : NSObject<NSApplicationDelegate>
  2187. @end
  2188. @interface _sapp_macos_window : NSWindow
  2189. @end
  2190. @interface _sapp_macos_window_delegate : NSObject<NSWindowDelegate>
  2191. @end
  2192. #if defined(SOKOL_METAL)
  2193. @interface _sapp_macos_view : MTKView
  2194. @end
  2195. #elif defined(SOKOL_GLCORE)
  2196. @interface _sapp_macos_view : NSOpenGLView
  2197. - (void)timerFired:(id)sender;
  2198. @end
  2199. #endif // SOKOL_GLCORE
  2200. typedef struct {
  2201. uint32_t flags_changed_store;
  2202. uint8_t mouse_buttons;
  2203. NSWindow* window;
  2204. NSTrackingArea* tracking_area;
  2205. id keyup_monitor;
  2206. _sapp_macos_app_delegate* app_dlg;
  2207. _sapp_macos_window_delegate* win_dlg;
  2208. _sapp_macos_view* view;
  2209. NSCursor* cursors[_SAPP_MOUSECURSOR_NUM];
  2210. #if defined(SOKOL_METAL)
  2211. id<MTLDevice> mtl_device;
  2212. #endif
  2213. } _sapp_macos_t;
  2214. #endif // _SAPP_MACOS
  2215. #if defined(_SAPP_IOS)
  2216. @interface _sapp_app_delegate : NSObject<UIApplicationDelegate>
  2217. @end
  2218. @interface _sapp_textfield_dlg : NSObject<UITextFieldDelegate>
  2219. - (void)keyboardWasShown:(NSNotification*)notif;
  2220. - (void)keyboardWillBeHidden:(NSNotification*)notif;
  2221. - (void)keyboardDidChangeFrame:(NSNotification*)notif;
  2222. @end
  2223. #if defined(SOKOL_METAL)
  2224. @interface _sapp_ios_view : MTKView;
  2225. @end
  2226. #else
  2227. @interface _sapp_ios_view : GLKView
  2228. @end
  2229. #endif
  2230. typedef struct {
  2231. UIWindow* window;
  2232. _sapp_ios_view* view;
  2233. UITextField* textfield;
  2234. _sapp_textfield_dlg* textfield_dlg;
  2235. #if defined(SOKOL_METAL)
  2236. UIViewController* view_ctrl;
  2237. id<MTLDevice> mtl_device;
  2238. #else
  2239. GLKViewController* view_ctrl;
  2240. EAGLContext* eagl_ctx;
  2241. #endif
  2242. bool suspended;
  2243. } _sapp_ios_t;
  2244. #endif // _SAPP_IOS
  2245. #if defined(_SAPP_EMSCRIPTEN)
  2246. typedef struct {
  2247. bool mouse_lock_requested;
  2248. uint16_t mouse_buttons;
  2249. } _sapp_emsc_t;
  2250. #endif // _SAPP_EMSCRIPTEN
  2251. #if defined(SOKOL_D3D11) && defined(_SAPP_WIN32)
  2252. typedef struct {
  2253. ID3D11Device* device;
  2254. ID3D11DeviceContext* device_context;
  2255. ID3D11Texture2D* rt;
  2256. ID3D11RenderTargetView* rtv;
  2257. ID3D11Texture2D* msaa_rt;
  2258. ID3D11RenderTargetView* msaa_rtv;
  2259. ID3D11Texture2D* ds;
  2260. ID3D11DepthStencilView* dsv;
  2261. DXGI_SWAP_CHAIN_DESC swap_chain_desc;
  2262. IDXGISwapChain* swap_chain;
  2263. IDXGIDevice1* dxgi_device;
  2264. bool use_dxgi_frame_stats;
  2265. UINT sync_refresh_count;
  2266. } _sapp_d3d11_t;
  2267. #endif
  2268. #if defined(_SAPP_WIN32)
  2269. #ifndef DPI_ENUMS_DECLARED
  2270. typedef enum PROCESS_DPI_AWARENESS
  2271. {
  2272. PROCESS_DPI_UNAWARE = 0,
  2273. PROCESS_SYSTEM_DPI_AWARE = 1,
  2274. PROCESS_PER_MONITOR_DPI_AWARE = 2
  2275. } PROCESS_DPI_AWARENESS;
  2276. typedef enum MONITOR_DPI_TYPE {
  2277. MDT_EFFECTIVE_DPI = 0,
  2278. MDT_ANGULAR_DPI = 1,
  2279. MDT_RAW_DPI = 2,
  2280. MDT_DEFAULT = MDT_EFFECTIVE_DPI
  2281. } MONITOR_DPI_TYPE;
  2282. #endif // DPI_ENUMS_DECLARED
  2283. typedef struct {
  2284. bool aware;
  2285. float content_scale;
  2286. float window_scale;
  2287. float mouse_scale;
  2288. } _sapp_win32_dpi_t;
  2289. typedef struct {
  2290. HWND hwnd;
  2291. HMONITOR hmonitor;
  2292. HDC dc;
  2293. HICON big_icon;
  2294. HICON small_icon;
  2295. HCURSOR cursors[_SAPP_MOUSECURSOR_NUM];
  2296. UINT orig_codepage;
  2297. RECT stored_window_rect; // used to restore window pos/size when toggling fullscreen => windowed
  2298. bool is_win10_or_greater;
  2299. bool in_create_window;
  2300. bool iconified;
  2301. _sapp_win32_dpi_t dpi;
  2302. struct {
  2303. struct {
  2304. LONG pos_x, pos_y;
  2305. bool pos_valid;
  2306. } lock;
  2307. struct {
  2308. LONG pos_x, pos_y;
  2309. bool pos_valid;
  2310. } raw_input;
  2311. bool requested_lock;
  2312. bool tracked;
  2313. uint8_t capture_mask;
  2314. } mouse;
  2315. struct {
  2316. size_t size;
  2317. void* ptr;
  2318. } raw_input_data;
  2319. } _sapp_win32_t;
  2320. #if defined(SOKOL_GLCORE)
  2321. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  2322. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  2323. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  2324. #define WGL_PIXEL_TYPE_ARB 0x2013
  2325. #define WGL_TYPE_RGBA_ARB 0x202b
  2326. #define WGL_ACCELERATION_ARB 0x2003
  2327. #define WGL_NO_ACCELERATION_ARB 0x2025
  2328. #define WGL_RED_BITS_ARB 0x2015
  2329. #define WGL_GREEN_BITS_ARB 0x2017
  2330. #define WGL_BLUE_BITS_ARB 0x2019
  2331. #define WGL_ALPHA_BITS_ARB 0x201b
  2332. #define WGL_DEPTH_BITS_ARB 0x2022
  2333. #define WGL_STENCIL_BITS_ARB 0x2023
  2334. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  2335. #define WGL_SAMPLES_ARB 0x2042
  2336. #define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
  2337. #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  2338. #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
  2339. #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  2340. #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
  2341. #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
  2342. #define WGL_CONTEXT_FLAGS_ARB 0x2094
  2343. #define ERROR_INVALID_VERSION_ARB 0x2095
  2344. #define ERROR_INVALID_PROFILE_ARB 0x2096
  2345. #define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
  2346. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int);
  2347. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC)(HDC,int,int,UINT,const int*,int*);
  2348. typedef const char* (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void);
  2349. typedef const char* (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC)(HDC);
  2350. typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC,HGLRC,const int*);
  2351. typedef HGLRC (WINAPI * PFN_wglCreateContext)(HDC);
  2352. typedef BOOL (WINAPI * PFN_wglDeleteContext)(HGLRC);
  2353. typedef PROC (WINAPI * PFN_wglGetProcAddress)(LPCSTR);
  2354. typedef HDC (WINAPI * PFN_wglGetCurrentDC)(void);
  2355. typedef BOOL (WINAPI * PFN_wglMakeCurrent)(HDC,HGLRC);
  2356. typedef struct {
  2357. HINSTANCE opengl32;
  2358. HGLRC gl_ctx;
  2359. PFN_wglCreateContext CreateContext;
  2360. PFN_wglDeleteContext DeleteContext;
  2361. PFN_wglGetProcAddress GetProcAddress;
  2362. PFN_wglGetCurrentDC GetCurrentDC;
  2363. PFN_wglMakeCurrent MakeCurrent;
  2364. PFNWGLSWAPINTERVALEXTPROC SwapIntervalEXT;
  2365. PFNWGLGETPIXELFORMATATTRIBIVARBPROC GetPixelFormatAttribivARB;
  2366. PFNWGLGETEXTENSIONSSTRINGEXTPROC GetExtensionsStringEXT;
  2367. PFNWGLGETEXTENSIONSSTRINGARBPROC GetExtensionsStringARB;
  2368. PFNWGLCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
  2369. // special case glGetIntegerv
  2370. void (WINAPI *GetIntegerv)(uint32_t pname, int32_t* data);
  2371. bool ext_swap_control;
  2372. bool arb_multisample;
  2373. bool arb_pixel_format;
  2374. bool arb_create_context;
  2375. bool arb_create_context_profile;
  2376. HWND msg_hwnd;
  2377. HDC msg_dc;
  2378. } _sapp_wgl_t;
  2379. #endif // SOKOL_GLCORE
  2380. #endif // _SAPP_WIN32
  2381. #if defined(_SAPP_ANDROID)
  2382. typedef enum {
  2383. _SOKOL_ANDROID_MSG_CREATE,
  2384. _SOKOL_ANDROID_MSG_RESUME,
  2385. _SOKOL_ANDROID_MSG_PAUSE,
  2386. _SOKOL_ANDROID_MSG_FOCUS,
  2387. _SOKOL_ANDROID_MSG_NO_FOCUS,
  2388. _SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW,
  2389. _SOKOL_ANDROID_MSG_SET_INPUT_QUEUE,
  2390. _SOKOL_ANDROID_MSG_DESTROY,
  2391. } _sapp_android_msg_t;
  2392. typedef struct {
  2393. pthread_t thread;
  2394. pthread_mutex_t mutex;
  2395. pthread_cond_t cond;
  2396. int read_from_main_fd;
  2397. int write_from_main_fd;
  2398. } _sapp_android_pt_t;
  2399. typedef struct {
  2400. ANativeWindow* window;
  2401. AInputQueue* input;
  2402. } _sapp_android_resources_t;
  2403. typedef struct {
  2404. ANativeActivity* activity;
  2405. _sapp_android_pt_t pt;
  2406. _sapp_android_resources_t pending;
  2407. _sapp_android_resources_t current;
  2408. ALooper* looper;
  2409. bool is_thread_started;
  2410. bool is_thread_stopping;
  2411. bool is_thread_stopped;
  2412. bool has_created;
  2413. bool has_resumed;
  2414. bool has_focus;
  2415. EGLConfig config;
  2416. EGLDisplay display;
  2417. EGLContext context;
  2418. EGLSurface surface;
  2419. } _sapp_android_t;
  2420. #endif // _SAPP_ANDROID
  2421. #if defined(_SAPP_LINUX)
  2422. #define _SAPP_X11_XDND_VERSION (5)
  2423. #define _SAPP_X11_MAX_X11_KEYCODES (256)
  2424. #define GLX_VENDOR 1
  2425. #define GLX_RGBA_BIT 0x00000001
  2426. #define GLX_WINDOW_BIT 0x00000001
  2427. #define GLX_DRAWABLE_TYPE 0x8010
  2428. #define GLX_RENDER_TYPE 0x8011
  2429. #define GLX_DOUBLEBUFFER 5
  2430. #define GLX_RED_SIZE 8
  2431. #define GLX_GREEN_SIZE 9
  2432. #define GLX_BLUE_SIZE 10
  2433. #define GLX_ALPHA_SIZE 11
  2434. #define GLX_DEPTH_SIZE 12
  2435. #define GLX_STENCIL_SIZE 13
  2436. #define GLX_SAMPLES 0x186a1
  2437. #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  2438. #define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
  2439. #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  2440. #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
  2441. #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
  2442. #define GLX_CONTEXT_FLAGS_ARB 0x2094
  2443. typedef XID GLXWindow;
  2444. typedef XID GLXDrawable;
  2445. typedef struct __GLXFBConfig* GLXFBConfig;
  2446. typedef struct __GLXcontext* GLXContext;
  2447. typedef void (*__GLXextproc)(void);
  2448. typedef int (*PFNGLXGETFBCONFIGATTRIBPROC)(Display*,GLXFBConfig,int,int*);
  2449. typedef const char* (*PFNGLXGETCLIENTSTRINGPROC)(Display*,int);
  2450. typedef Bool (*PFNGLXQUERYEXTENSIONPROC)(Display*,int*,int*);
  2451. typedef Bool (*PFNGLXQUERYVERSIONPROC)(Display*,int*,int*);
  2452. typedef void (*PFNGLXDESTROYCONTEXTPROC)(Display*,GLXContext);
  2453. typedef Bool (*PFNGLXMAKECURRENTPROC)(Display*,GLXDrawable,GLXContext);
  2454. typedef void (*PFNGLXSWAPBUFFERSPROC)(Display*,GLXDrawable);
  2455. typedef const char* (*PFNGLXQUERYEXTENSIONSSTRINGPROC)(Display*,int);
  2456. typedef GLXFBConfig* (*PFNGLXGETFBCONFIGSPROC)(Display*,int,int*);
  2457. typedef __GLXextproc (* PFNGLXGETPROCADDRESSPROC)(const char *procName);
  2458. typedef void (*PFNGLXSWAPINTERVALEXTPROC)(Display*,GLXDrawable,int);
  2459. typedef XVisualInfo* (*PFNGLXGETVISUALFROMFBCONFIGPROC)(Display*,GLXFBConfig);
  2460. typedef GLXWindow (*PFNGLXCREATEWINDOWPROC)(Display*,GLXFBConfig,Window,const int*);
  2461. typedef void (*PFNGLXDESTROYWINDOWPROC)(Display*,GLXWindow);
  2462. typedef int (*PFNGLXSWAPINTERVALMESAPROC)(int);
  2463. typedef GLXContext (*PFNGLXCREATECONTEXTATTRIBSARBPROC)(Display*,GLXFBConfig,GLXContext,Bool,const int*);
  2464. typedef struct {
  2465. bool available;
  2466. int major_opcode;
  2467. int event_base;
  2468. int error_base;
  2469. int major;
  2470. int minor;
  2471. } _sapp_xi_t;
  2472. typedef struct {
  2473. int version;
  2474. Window source;
  2475. Atom format;
  2476. Atom XdndAware;
  2477. Atom XdndEnter;
  2478. Atom XdndPosition;
  2479. Atom XdndStatus;
  2480. Atom XdndActionCopy;
  2481. Atom XdndDrop;
  2482. Atom XdndFinished;
  2483. Atom XdndSelection;
  2484. Atom XdndTypeList;
  2485. Atom text_uri_list;
  2486. } _sapp_xdnd_t;
  2487. typedef struct {
  2488. uint8_t mouse_buttons;
  2489. Display* display;
  2490. int screen;
  2491. Window root;
  2492. Colormap colormap;
  2493. Window window;
  2494. Cursor hidden_cursor;
  2495. Cursor cursors[_SAPP_MOUSECURSOR_NUM];
  2496. int window_state;
  2497. float dpi;
  2498. unsigned char error_code;
  2499. Atom UTF8_STRING;
  2500. Atom CLIPBOARD;
  2501. Atom TARGETS;
  2502. Atom WM_PROTOCOLS;
  2503. Atom WM_DELETE_WINDOW;
  2504. Atom WM_STATE;
  2505. Atom NET_WM_NAME;
  2506. Atom NET_WM_ICON_NAME;
  2507. Atom NET_WM_ICON;
  2508. Atom NET_WM_STATE;
  2509. Atom NET_WM_STATE_FULLSCREEN;
  2510. _sapp_xi_t xi;
  2511. _sapp_xdnd_t xdnd;
  2512. // XLib manual says keycodes are in the range [8, 255] inclusive.
  2513. // https://tronche.com/gui/x/xlib/input/keyboard-encoding.html
  2514. bool key_repeat[_SAPP_X11_MAX_X11_KEYCODES];
  2515. } _sapp_x11_t;
  2516. #if defined(_SAPP_GLX)
  2517. typedef struct {
  2518. void* libgl;
  2519. int major;
  2520. int minor;
  2521. int event_base;
  2522. int error_base;
  2523. GLXContext ctx;
  2524. GLXWindow window;
  2525. // GLX 1.3 functions
  2526. PFNGLXGETFBCONFIGSPROC GetFBConfigs;
  2527. PFNGLXGETFBCONFIGATTRIBPROC GetFBConfigAttrib;
  2528. PFNGLXGETCLIENTSTRINGPROC GetClientString;
  2529. PFNGLXQUERYEXTENSIONPROC QueryExtension;
  2530. PFNGLXQUERYVERSIONPROC QueryVersion;
  2531. PFNGLXDESTROYCONTEXTPROC DestroyContext;
  2532. PFNGLXMAKECURRENTPROC MakeCurrent;
  2533. PFNGLXSWAPBUFFERSPROC SwapBuffers;
  2534. PFNGLXQUERYEXTENSIONSSTRINGPROC QueryExtensionsString;
  2535. PFNGLXGETVISUALFROMFBCONFIGPROC GetVisualFromFBConfig;
  2536. PFNGLXCREATEWINDOWPROC CreateWindow;
  2537. PFNGLXDESTROYWINDOWPROC DestroyWindow;
  2538. // GLX 1.4 and extension functions
  2539. PFNGLXGETPROCADDRESSPROC GetProcAddress;
  2540. PFNGLXGETPROCADDRESSPROC GetProcAddressARB;
  2541. PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT;
  2542. PFNGLXSWAPINTERVALMESAPROC SwapIntervalMESA;
  2543. PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
  2544. // special case glGetIntegerv
  2545. void (*GetIntegerv)(uint32_t pname, int32_t* data);
  2546. // extension availability
  2547. bool EXT_swap_control;
  2548. bool MESA_swap_control;
  2549. bool ARB_multisample;
  2550. bool ARB_create_context;
  2551. bool ARB_create_context_profile;
  2552. } _sapp_glx_t;
  2553. #else
  2554. typedef struct {
  2555. EGLDisplay display;
  2556. EGLContext context;
  2557. EGLSurface surface;
  2558. } _sapp_egl_t;
  2559. #endif // _SAPP_GLX
  2560. #endif // _SAPP_LINUX
  2561. #if defined(_SAPP_ANY_GL)
  2562. typedef struct {
  2563. uint32_t framebuffer;
  2564. } _sapp_gl_t;
  2565. #endif
  2566. typedef struct {
  2567. bool enabled;
  2568. int buf_size;
  2569. char* buffer;
  2570. } _sapp_clipboard_t;
  2571. typedef struct {
  2572. bool enabled;
  2573. int max_files;
  2574. int max_path_length;
  2575. int num_files;
  2576. int buf_size;
  2577. char* buffer;
  2578. } _sapp_drop_t;
  2579. typedef struct {
  2580. float x, y;
  2581. float dx, dy;
  2582. bool shown;
  2583. bool locked;
  2584. bool pos_valid;
  2585. sapp_mouse_cursor current_cursor;
  2586. } _sapp_mouse_t;
  2587. typedef struct {
  2588. sapp_desc desc;
  2589. bool valid;
  2590. bool fullscreen;
  2591. bool first_frame;
  2592. bool init_called;
  2593. bool cleanup_called;
  2594. bool quit_requested;
  2595. bool quit_ordered;
  2596. bool event_consumed;
  2597. bool html5_ask_leave_site;
  2598. bool onscreen_keyboard_shown;
  2599. int window_width;
  2600. int window_height;
  2601. int framebuffer_width;
  2602. int framebuffer_height;
  2603. int sample_count;
  2604. int swap_interval;
  2605. float dpi_scale;
  2606. uint64_t frame_count;
  2607. _sapp_timing_t timing;
  2608. sapp_event event;
  2609. _sapp_mouse_t mouse;
  2610. _sapp_clipboard_t clipboard;
  2611. _sapp_drop_t drop;
  2612. sapp_icon_desc default_icon_desc;
  2613. uint32_t* default_icon_pixels;
  2614. #if defined(SOKOL_WGPU)
  2615. _sapp_wgpu_t wgpu;
  2616. #endif
  2617. #if defined(_SAPP_MACOS)
  2618. _sapp_macos_t macos;
  2619. #elif defined(_SAPP_IOS)
  2620. _sapp_ios_t ios;
  2621. #elif defined(_SAPP_EMSCRIPTEN)
  2622. _sapp_emsc_t emsc;
  2623. #elif defined(_SAPP_WIN32)
  2624. _sapp_win32_t win32;
  2625. #if defined(SOKOL_D3D11)
  2626. _sapp_d3d11_t d3d11;
  2627. #elif defined(SOKOL_GLCORE)
  2628. _sapp_wgl_t wgl;
  2629. #endif
  2630. #elif defined(_SAPP_ANDROID)
  2631. _sapp_android_t android;
  2632. #elif defined(_SAPP_LINUX)
  2633. _sapp_x11_t x11;
  2634. #if defined(_SAPP_GLX)
  2635. _sapp_glx_t glx;
  2636. #else
  2637. _sapp_egl_t egl;
  2638. #endif
  2639. #endif
  2640. #if defined(_SAPP_ANY_GL)
  2641. _sapp_gl_t gl;
  2642. #endif
  2643. char html5_canvas_selector[_SAPP_MAX_TITLE_LENGTH];
  2644. char window_title[_SAPP_MAX_TITLE_LENGTH]; // UTF-8
  2645. wchar_t window_title_wide[_SAPP_MAX_TITLE_LENGTH]; // UTF-32 or UCS-2 */
  2646. sapp_keycode keycodes[SAPP_MAX_KEYCODES];
  2647. } _sapp_t;
  2648. static _sapp_t _sapp;
  2649. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  2650. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  2651. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  2652. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2653. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  2654. //
  2655. // >>logging
  2656. #if defined(SOKOL_DEBUG)
  2657. #define _SAPP_LOGITEM_XMACRO(item,msg) #item ": " msg,
  2658. static const char* _sapp_log_messages[] = {
  2659. _SAPP_LOG_ITEMS
  2660. };
  2661. #undef _SAPP_LOGITEM_XMACRO
  2662. #endif // SOKOL_DEBUG
  2663. #define _SAPP_PANIC(code) _sapp_log(SAPP_LOGITEM_ ##code, 0, 0, __LINE__)
  2664. #define _SAPP_ERROR(code) _sapp_log(SAPP_LOGITEM_ ##code, 1, 0, __LINE__)
  2665. #define _SAPP_WARN(code) _sapp_log(SAPP_LOGITEM_ ##code, 2, 0, __LINE__)
  2666. #define _SAPP_INFO(code) _sapp_log(SAPP_LOGITEM_ ##code, 3, 0, __LINE__)
  2667. static void _sapp_log(sapp_log_item log_item, uint32_t log_level, const char* msg, uint32_t line_nr) {
  2668. if (_sapp.desc.logger.func) {
  2669. const char* filename = 0;
  2670. #if defined(SOKOL_DEBUG)
  2671. filename = __FILE__;
  2672. if (0 == msg) {
  2673. msg = _sapp_log_messages[log_item];
  2674. }
  2675. #endif
  2676. _sapp.desc.logger.func("sapp", log_level, (uint32_t)log_item, msg, line_nr, filename, _sapp.desc.logger.user_data);
  2677. }
  2678. else {
  2679. // for log level PANIC it would be 'undefined behaviour' to continue
  2680. if (log_level == 0) {
  2681. abort();
  2682. }
  2683. }
  2684. }
  2685. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  2686. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  2687. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  2688. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2689. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  2690. //
  2691. // >>memory
  2692. _SOKOL_PRIVATE void _sapp_clear(void* ptr, size_t size) {
  2693. SOKOL_ASSERT(ptr && (size > 0));
  2694. memset(ptr, 0, size);
  2695. }
  2696. _SOKOL_PRIVATE void* _sapp_malloc(size_t size) {
  2697. SOKOL_ASSERT(size > 0);
  2698. void* ptr;
  2699. if (_sapp.desc.allocator.alloc_fn) {
  2700. ptr = _sapp.desc.allocator.alloc_fn(size, _sapp.desc.allocator.user_data);
  2701. } else {
  2702. ptr = malloc(size);
  2703. }
  2704. if (0 == ptr) {
  2705. _SAPP_PANIC(MALLOC_FAILED);
  2706. }
  2707. return ptr;
  2708. }
  2709. _SOKOL_PRIVATE void* _sapp_malloc_clear(size_t size) {
  2710. void* ptr = _sapp_malloc(size);
  2711. _sapp_clear(ptr, size);
  2712. return ptr;
  2713. }
  2714. _SOKOL_PRIVATE void _sapp_free(void* ptr) {
  2715. if (_sapp.desc.allocator.free_fn) {
  2716. _sapp.desc.allocator.free_fn(ptr, _sapp.desc.allocator.user_data);
  2717. }
  2718. else {
  2719. free(ptr);
  2720. }
  2721. }
  2722. // ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  2723. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2724. // ███████ █████ ██ ██████ █████ ██████ ███████
  2725. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2726. // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  2727. //
  2728. // >>helpers
  2729. _SOKOL_PRIVATE void _sapp_call_init(void) {
  2730. if (_sapp.desc.init_cb) {
  2731. _sapp.desc.init_cb();
  2732. }
  2733. else if (_sapp.desc.init_userdata_cb) {
  2734. _sapp.desc.init_userdata_cb(_sapp.desc.user_data);
  2735. }
  2736. _sapp.init_called = true;
  2737. }
  2738. _SOKOL_PRIVATE void _sapp_call_frame(void) {
  2739. if (_sapp.init_called && !_sapp.cleanup_called) {
  2740. if (_sapp.desc.frame_cb) {
  2741. _sapp.desc.frame_cb();
  2742. }
  2743. else if (_sapp.desc.frame_userdata_cb) {
  2744. _sapp.desc.frame_userdata_cb(_sapp.desc.user_data);
  2745. }
  2746. }
  2747. }
  2748. _SOKOL_PRIVATE void _sapp_call_cleanup(void) {
  2749. if (!_sapp.cleanup_called) {
  2750. if (_sapp.desc.cleanup_cb) {
  2751. _sapp.desc.cleanup_cb();
  2752. }
  2753. else if (_sapp.desc.cleanup_userdata_cb) {
  2754. _sapp.desc.cleanup_userdata_cb(_sapp.desc.user_data);
  2755. }
  2756. _sapp.cleanup_called = true;
  2757. }
  2758. }
  2759. _SOKOL_PRIVATE bool _sapp_call_event(const sapp_event* e) {
  2760. if (!_sapp.cleanup_called) {
  2761. if (_sapp.desc.event_cb) {
  2762. _sapp.desc.event_cb(e);
  2763. }
  2764. else if (_sapp.desc.event_userdata_cb) {
  2765. _sapp.desc.event_userdata_cb(e, _sapp.desc.user_data);
  2766. }
  2767. }
  2768. if (_sapp.event_consumed) {
  2769. _sapp.event_consumed = false;
  2770. return true;
  2771. }
  2772. else {
  2773. return false;
  2774. }
  2775. }
  2776. _SOKOL_PRIVATE char* _sapp_dropped_file_path_ptr(int index) {
  2777. SOKOL_ASSERT(_sapp.drop.buffer);
  2778. SOKOL_ASSERT((index >= 0) && (index <= _sapp.drop.max_files));
  2779. int offset = index * _sapp.drop.max_path_length;
  2780. SOKOL_ASSERT(offset < _sapp.drop.buf_size);
  2781. return &_sapp.drop.buffer[offset];
  2782. }
  2783. /* Copy a string into a fixed size buffer with guaranteed zero-
  2784. termination.
  2785. Return false if the string didn't fit into the buffer and had to be clamped.
  2786. FIXME: Currently UTF-8 strings might become invalid if the string
  2787. is clamped, because the last zero-byte might be written into
  2788. the middle of a multi-byte sequence.
  2789. */
  2790. _SOKOL_PRIVATE bool _sapp_strcpy(const char* src, char* dst, int max_len) {
  2791. SOKOL_ASSERT(src && dst && (max_len > 0));
  2792. char* const end = &(dst[max_len-1]);
  2793. char c = 0;
  2794. for (int i = 0; i < max_len; i++) {
  2795. c = *src;
  2796. if (c != 0) {
  2797. src++;
  2798. }
  2799. *dst++ = c;
  2800. }
  2801. /* truncated? */
  2802. if (c != 0) {
  2803. *end = 0;
  2804. return false;
  2805. }
  2806. else {
  2807. return true;
  2808. }
  2809. }
  2810. _SOKOL_PRIVATE sapp_desc _sapp_desc_defaults(const sapp_desc* desc) {
  2811. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  2812. sapp_desc res = *desc;
  2813. res.sample_count = _sapp_def(res.sample_count, 1);
  2814. res.swap_interval = _sapp_def(res.swap_interval, 1);
  2815. if (0 == res.gl_major_version) {
  2816. #if defined(SOKOL_GLCORE)
  2817. res.gl_major_version = 4;
  2818. #if defined(_SAPP_APPLE)
  2819. res.gl_minor_version = 1;
  2820. #else
  2821. res.gl_minor_version = 3;
  2822. #endif
  2823. #elif defined(SOKOL_GLES3)
  2824. res.gl_major_version = 3;
  2825. #if defined(_SAPP_ANDROID) || defined(_SAPP_LINUX)
  2826. res.gl_minor_version = 1;
  2827. #else
  2828. res.gl_minor_version = 0;
  2829. #endif
  2830. #endif
  2831. }
  2832. res.html5_canvas_selector = _sapp_def(res.html5_canvas_selector, "#canvas");
  2833. res.clipboard_size = _sapp_def(res.clipboard_size, 8192);
  2834. res.max_dropped_files = _sapp_def(res.max_dropped_files, 1);
  2835. res.max_dropped_file_path_length = _sapp_def(res.max_dropped_file_path_length, 2048);
  2836. res.window_title = _sapp_def(res.window_title, "sokol");
  2837. return res;
  2838. }
  2839. _SOKOL_PRIVATE void _sapp_init_state(const sapp_desc* desc) {
  2840. SOKOL_ASSERT(desc);
  2841. SOKOL_ASSERT(desc->width >= 0);
  2842. SOKOL_ASSERT(desc->height >= 0);
  2843. SOKOL_ASSERT(desc->sample_count >= 0);
  2844. SOKOL_ASSERT(desc->swap_interval >= 0);
  2845. SOKOL_ASSERT(desc->clipboard_size >= 0);
  2846. SOKOL_ASSERT(desc->max_dropped_files >= 0);
  2847. SOKOL_ASSERT(desc->max_dropped_file_path_length >= 0);
  2848. _SAPP_CLEAR_ARC_STRUCT(_sapp_t, _sapp);
  2849. _sapp.desc = _sapp_desc_defaults(desc);
  2850. _sapp.first_frame = true;
  2851. // NOTE: _sapp.desc.width/height may be 0! Platform backends need to deal with this
  2852. _sapp.window_width = _sapp.desc.width;
  2853. _sapp.window_height = _sapp.desc.height;
  2854. _sapp.framebuffer_width = _sapp.window_width;
  2855. _sapp.framebuffer_height = _sapp.window_height;
  2856. _sapp.sample_count = _sapp.desc.sample_count;
  2857. _sapp.swap_interval = _sapp.desc.swap_interval;
  2858. _sapp_strcpy(_sapp.desc.html5_canvas_selector, _sapp.html5_canvas_selector, sizeof(_sapp.html5_canvas_selector));
  2859. _sapp.desc.html5_canvas_selector = _sapp.html5_canvas_selector;
  2860. _sapp.html5_ask_leave_site = _sapp.desc.html5_ask_leave_site;
  2861. _sapp.clipboard.enabled = _sapp.desc.enable_clipboard;
  2862. if (_sapp.clipboard.enabled) {
  2863. _sapp.clipboard.buf_size = _sapp.desc.clipboard_size;
  2864. _sapp.clipboard.buffer = (char*) _sapp_malloc_clear((size_t)_sapp.clipboard.buf_size);
  2865. }
  2866. _sapp.drop.enabled = _sapp.desc.enable_dragndrop;
  2867. if (_sapp.drop.enabled) {
  2868. _sapp.drop.max_files = _sapp.desc.max_dropped_files;
  2869. _sapp.drop.max_path_length = _sapp.desc.max_dropped_file_path_length;
  2870. _sapp.drop.buf_size = _sapp.drop.max_files * _sapp.drop.max_path_length;
  2871. _sapp.drop.buffer = (char*) _sapp_malloc_clear((size_t)_sapp.drop.buf_size);
  2872. }
  2873. _sapp_strcpy(_sapp.desc.window_title, _sapp.window_title, sizeof(_sapp.window_title));
  2874. _sapp.desc.window_title = _sapp.window_title;
  2875. _sapp.dpi_scale = 1.0f;
  2876. _sapp.fullscreen = _sapp.desc.fullscreen;
  2877. _sapp.mouse.shown = true;
  2878. _sapp_timing_init(&_sapp.timing);
  2879. }
  2880. _SOKOL_PRIVATE void _sapp_discard_state(void) {
  2881. if (_sapp.clipboard.enabled) {
  2882. SOKOL_ASSERT(_sapp.clipboard.buffer);
  2883. _sapp_free((void*)_sapp.clipboard.buffer);
  2884. }
  2885. if (_sapp.drop.enabled) {
  2886. SOKOL_ASSERT(_sapp.drop.buffer);
  2887. _sapp_free((void*)_sapp.drop.buffer);
  2888. }
  2889. if (_sapp.default_icon_pixels) {
  2890. _sapp_free((void*)_sapp.default_icon_pixels);
  2891. }
  2892. _SAPP_CLEAR_ARC_STRUCT(_sapp_t, _sapp);
  2893. }
  2894. _SOKOL_PRIVATE void _sapp_init_event(sapp_event_type type) {
  2895. _sapp_clear(&_sapp.event, sizeof(_sapp.event));
  2896. _sapp.event.type = type;
  2897. _sapp.event.frame_count = _sapp.frame_count;
  2898. _sapp.event.mouse_button = SAPP_MOUSEBUTTON_INVALID;
  2899. _sapp.event.window_width = _sapp.window_width;
  2900. _sapp.event.window_height = _sapp.window_height;
  2901. _sapp.event.framebuffer_width = _sapp.framebuffer_width;
  2902. _sapp.event.framebuffer_height = _sapp.framebuffer_height;
  2903. _sapp.event.mouse_x = _sapp.mouse.x;
  2904. _sapp.event.mouse_y = _sapp.mouse.y;
  2905. _sapp.event.mouse_dx = _sapp.mouse.dx;
  2906. _sapp.event.mouse_dy = _sapp.mouse.dy;
  2907. }
  2908. _SOKOL_PRIVATE bool _sapp_events_enabled(void) {
  2909. /* only send events when an event callback is set, and the init function was called */
  2910. return (_sapp.desc.event_cb || _sapp.desc.event_userdata_cb) && _sapp.init_called;
  2911. }
  2912. _SOKOL_PRIVATE sapp_keycode _sapp_translate_key(int scan_code) {
  2913. if ((scan_code >= 0) && (scan_code < SAPP_MAX_KEYCODES)) {
  2914. return _sapp.keycodes[scan_code];
  2915. }
  2916. else {
  2917. return SAPP_KEYCODE_INVALID;
  2918. }
  2919. }
  2920. _SOKOL_PRIVATE void _sapp_clear_drop_buffer(void) {
  2921. if (_sapp.drop.enabled) {
  2922. SOKOL_ASSERT(_sapp.drop.buffer);
  2923. _sapp_clear(_sapp.drop.buffer, (size_t)_sapp.drop.buf_size);
  2924. }
  2925. }
  2926. _SOKOL_PRIVATE void _sapp_frame(void) {
  2927. if (_sapp.first_frame) {
  2928. _sapp.first_frame = false;
  2929. _sapp_call_init();
  2930. }
  2931. _sapp_call_frame();
  2932. _sapp.frame_count++;
  2933. }
  2934. _SOKOL_PRIVATE bool _sapp_image_validate(const sapp_image_desc* desc) {
  2935. SOKOL_ASSERT(desc->width > 0);
  2936. SOKOL_ASSERT(desc->height > 0);
  2937. SOKOL_ASSERT(desc->pixels.ptr != 0);
  2938. SOKOL_ASSERT(desc->pixels.size > 0);
  2939. const size_t wh_size = (size_t)(desc->width * desc->height) * sizeof(uint32_t);
  2940. if (wh_size != desc->pixels.size) {
  2941. _SAPP_ERROR(IMAGE_DATA_SIZE_MISMATCH);
  2942. return false;
  2943. }
  2944. return true;
  2945. }
  2946. _SOKOL_PRIVATE int _sapp_image_bestmatch(const sapp_image_desc image_descs[], int num_images, int width, int height) {
  2947. int least_diff = 0x7FFFFFFF;
  2948. int least_index = 0;
  2949. for (int i = 0; i < num_images; i++) {
  2950. int diff = (image_descs[i].width * image_descs[i].height) - (width * height);
  2951. if (diff < 0) {
  2952. diff = -diff;
  2953. }
  2954. if (diff < least_diff) {
  2955. least_diff = diff;
  2956. least_index = i;
  2957. }
  2958. }
  2959. return least_index;
  2960. }
  2961. _SOKOL_PRIVATE int _sapp_icon_num_images(const sapp_icon_desc* desc) {
  2962. int index = 0;
  2963. for (; index < SAPP_MAX_ICONIMAGES; index++) {
  2964. if (0 == desc->images[index].pixels.ptr) {
  2965. break;
  2966. }
  2967. }
  2968. return index;
  2969. }
  2970. _SOKOL_PRIVATE bool _sapp_validate_icon_desc(const sapp_icon_desc* desc, int num_images) {
  2971. SOKOL_ASSERT(num_images <= SAPP_MAX_ICONIMAGES);
  2972. for (int i = 0; i < num_images; i++) {
  2973. const sapp_image_desc* img_desc = &desc->images[i];
  2974. if (!_sapp_image_validate(img_desc)) {
  2975. return false;
  2976. }
  2977. }
  2978. return true;
  2979. }
  2980. _SOKOL_PRIVATE void _sapp_setup_default_icon(void) {
  2981. SOKOL_ASSERT(0 == _sapp.default_icon_pixels);
  2982. const int num_icons = 3;
  2983. const int icon_sizes[3] = { 16, 32, 64 }; // must be multiple of 8!
  2984. // allocate a pixel buffer for all icon pixels
  2985. int all_num_pixels = 0;
  2986. for (int i = 0; i < num_icons; i++) {
  2987. all_num_pixels += icon_sizes[i] * icon_sizes[i];
  2988. }
  2989. _sapp.default_icon_pixels = (uint32_t*) _sapp_malloc_clear((size_t)all_num_pixels * sizeof(uint32_t));
  2990. // initialize default_icon_desc struct
  2991. uint32_t* dst = _sapp.default_icon_pixels;
  2992. const uint32_t* dst_end = dst + all_num_pixels;
  2993. (void)dst_end; // silence unused warning in release mode
  2994. for (int i = 0; i < num_icons; i++) {
  2995. const int dim = (int) icon_sizes[i];
  2996. const int num_pixels = dim * dim;
  2997. sapp_image_desc* img_desc = &_sapp.default_icon_desc.images[i];
  2998. img_desc->width = dim;
  2999. img_desc->height = dim;
  3000. img_desc->pixels.ptr = dst;
  3001. img_desc->pixels.size = (size_t)num_pixels * sizeof(uint32_t);
  3002. dst += num_pixels;
  3003. }
  3004. SOKOL_ASSERT(dst == dst_end);
  3005. // Amstrad CPC font 'S'
  3006. const uint8_t tile[8] = {
  3007. 0x3C,
  3008. 0x66,
  3009. 0x60,
  3010. 0x3C,
  3011. 0x06,
  3012. 0x66,
  3013. 0x3C,
  3014. 0x00,
  3015. };
  3016. // rainbow colors
  3017. const uint32_t colors[8] = {
  3018. 0xFF4370FF,
  3019. 0xFF26A7FF,
  3020. 0xFF58EEFF,
  3021. 0xFF57E1D4,
  3022. 0xFF65CC9C,
  3023. 0xFF6ABB66,
  3024. 0xFFF5A542,
  3025. 0xFFC2577E,
  3026. };
  3027. dst = _sapp.default_icon_pixels;
  3028. const uint32_t blank = 0x00FFFFFF;
  3029. const uint32_t shadow = 0xFF000000;
  3030. for (int i = 0; i < num_icons; i++) {
  3031. const int dim = icon_sizes[i];
  3032. SOKOL_ASSERT((dim % 8) == 0);
  3033. const int scale = dim / 8;
  3034. for (int ty = 0, y = 0; ty < 8; ty++) {
  3035. const uint32_t color = colors[ty];
  3036. for (int sy = 0; sy < scale; sy++, y++) {
  3037. uint8_t bits = tile[ty];
  3038. for (int tx = 0, x = 0; tx < 8; tx++, bits<<=1) {
  3039. uint32_t pixel = (0 == (bits & 0x80)) ? blank : color;
  3040. for (int sx = 0; sx < scale; sx++, x++) {
  3041. SOKOL_ASSERT(dst < dst_end);
  3042. *dst++ = pixel;
  3043. }
  3044. }
  3045. }
  3046. }
  3047. }
  3048. SOKOL_ASSERT(dst == dst_end);
  3049. // right shadow
  3050. dst = _sapp.default_icon_pixels;
  3051. for (int i = 0; i < num_icons; i++) {
  3052. const int dim = icon_sizes[i];
  3053. for (int y = 0; y < dim; y++) {
  3054. uint32_t prev_color = blank;
  3055. for (int x = 0; x < dim; x++) {
  3056. const int dst_index = y * dim + x;
  3057. const uint32_t cur_color = dst[dst_index];
  3058. if ((cur_color == blank) && (prev_color != blank)) {
  3059. dst[dst_index] = shadow;
  3060. }
  3061. prev_color = cur_color;
  3062. }
  3063. }
  3064. dst += dim * dim;
  3065. }
  3066. SOKOL_ASSERT(dst == dst_end);
  3067. // bottom shadow
  3068. dst = _sapp.default_icon_pixels;
  3069. for (int i = 0; i < num_icons; i++) {
  3070. const int dim = icon_sizes[i];
  3071. for (int x = 0; x < dim; x++) {
  3072. uint32_t prev_color = blank;
  3073. for (int y = 0; y < dim; y++) {
  3074. const int dst_index = y * dim + x;
  3075. const uint32_t cur_color = dst[dst_index];
  3076. if ((cur_color == blank) && (prev_color != blank)) {
  3077. dst[dst_index] = shadow;
  3078. }
  3079. prev_color = cur_color;
  3080. }
  3081. }
  3082. dst += dim * dim;
  3083. }
  3084. SOKOL_ASSERT(dst == dst_end);
  3085. }
  3086. // ██ ██ ██████ ██████ ██ ██
  3087. // ██ ██ ██ ██ ██ ██ ██
  3088. // ██ █ ██ ██ ███ ██████ ██ ██
  3089. // ██ ███ ██ ██ ██ ██ ██ ██
  3090. // ███ ███ ██████ ██ ██████
  3091. //
  3092. // >>wgpu
  3093. #if defined(SOKOL_WGPU)
  3094. _SOKOL_PRIVATE WGPUStringView _sapp_wgpu_stringview(const char* str) {
  3095. WGPUStringView res;
  3096. if (str) {
  3097. res.data = str;
  3098. res.length = strlen(str);
  3099. } else {
  3100. res.data = 0;
  3101. res.length = 0;
  3102. }
  3103. return res;
  3104. }
  3105. _SOKOL_PRIVATE void _sapp_wgpu_create_swapchain(bool called_from_resize) {
  3106. SOKOL_ASSERT(_sapp.wgpu.instance);
  3107. SOKOL_ASSERT(_sapp.wgpu.device);
  3108. SOKOL_ASSERT(0 == _sapp.wgpu.msaa_tex);
  3109. SOKOL_ASSERT(0 == _sapp.wgpu.msaa_view);
  3110. SOKOL_ASSERT(0 == _sapp.wgpu.depth_stencil_tex);
  3111. SOKOL_ASSERT(0 == _sapp.wgpu.depth_stencil_view);
  3112. SOKOL_ASSERT(0 == _sapp.wgpu.swapchain_view);
  3113. if (!called_from_resize) {
  3114. SOKOL_ASSERT(0 == _sapp.wgpu.surface);
  3115. WGPUSurfaceDescriptor surf_desc;
  3116. _sapp_clear(&surf_desc, sizeof(surf_desc));
  3117. #if defined (_SAPP_EMSCRIPTEN)
  3118. WGPUEmscriptenSurfaceSourceCanvasHTMLSelector html_canvas_desc;
  3119. _sapp_clear(&html_canvas_desc, sizeof(html_canvas_desc));
  3120. html_canvas_desc.chain.sType = WGPUSType_EmscriptenSurfaceSourceCanvasHTMLSelector;
  3121. html_canvas_desc.selector = _sapp_wgpu_stringview(_sapp.html5_canvas_selector);
  3122. surf_desc.nextInChain = &html_canvas_desc.chain;
  3123. #else
  3124. #error "Unsupported platform for SOKOL_WGPU"
  3125. #endif
  3126. _sapp.wgpu.surface = wgpuInstanceCreateSurface(_sapp.wgpu.instance, &surf_desc);
  3127. if (0 == _sapp.wgpu.surface) {
  3128. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_SURFACE_FAILED);
  3129. }
  3130. WGPUSurfaceCapabilities surf_caps;
  3131. _sapp_clear(&surf_caps, sizeof(surf_caps));
  3132. WGPUStatus caps_status = wgpuSurfaceGetCapabilities(_sapp.wgpu.surface, _sapp.wgpu.adapter, &surf_caps);
  3133. if (caps_status != WGPUStatus_Success) {
  3134. _SAPP_PANIC(WGPU_SWAPCHAIN_SURFACE_GET_CAPABILITIES_FAILED);
  3135. }
  3136. _sapp.wgpu.render_format = surf_caps.formats[0];
  3137. }
  3138. SOKOL_ASSERT(_sapp.wgpu.surface);
  3139. WGPUSurfaceConfiguration surf_conf;
  3140. _sapp_clear(&surf_conf, sizeof(surf_conf));
  3141. surf_conf.device = _sapp.wgpu.device;
  3142. surf_conf.format = _sapp.wgpu.render_format;
  3143. surf_conf.usage = WGPUTextureUsage_RenderAttachment;
  3144. surf_conf.width = (uint32_t)_sapp.framebuffer_width;
  3145. surf_conf.height = (uint32_t)_sapp.framebuffer_height;
  3146. surf_conf.alphaMode = WGPUCompositeAlphaMode_Opaque;
  3147. #if defined(_SAPP_EMSCRIPTEN)
  3148. // FIXME: make this further configurable?
  3149. if (_sapp.desc.html5_premultiplied_alpha) {
  3150. surf_conf.alphaMode = WGPUCompositeAlphaMode_Premultiplied;
  3151. }
  3152. #endif
  3153. surf_conf.presentMode = WGPUPresentMode_Fifo;
  3154. wgpuSurfaceConfigure(_sapp.wgpu.surface, &surf_conf);
  3155. WGPUTextureDescriptor ds_desc;
  3156. _sapp_clear(&ds_desc, sizeof(ds_desc));
  3157. ds_desc.usage = WGPUTextureUsage_RenderAttachment;
  3158. ds_desc.dimension = WGPUTextureDimension_2D;
  3159. ds_desc.size.width = (uint32_t)_sapp.framebuffer_width;
  3160. ds_desc.size.height = (uint32_t)_sapp.framebuffer_height;
  3161. ds_desc.size.depthOrArrayLayers = 1;
  3162. ds_desc.format = WGPUTextureFormat_Depth32FloatStencil8;
  3163. ds_desc.mipLevelCount = 1;
  3164. ds_desc.sampleCount = (uint32_t)_sapp.sample_count;
  3165. _sapp.wgpu.depth_stencil_tex = wgpuDeviceCreateTexture(_sapp.wgpu.device, &ds_desc);
  3166. if (0 == _sapp.wgpu.depth_stencil_tex) {
  3167. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_TEXTURE_FAILED);
  3168. }
  3169. _sapp.wgpu.depth_stencil_view = wgpuTextureCreateView(_sapp.wgpu.depth_stencil_tex, 0);
  3170. if (0 == _sapp.wgpu.depth_stencil_view) {
  3171. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_VIEW_FAILED);
  3172. }
  3173. if (_sapp.sample_count > 1) {
  3174. WGPUTextureDescriptor msaa_desc;
  3175. _sapp_clear(&msaa_desc, sizeof(msaa_desc));
  3176. msaa_desc.usage = WGPUTextureUsage_RenderAttachment;
  3177. msaa_desc.dimension = WGPUTextureDimension_2D;
  3178. msaa_desc.size.width = (uint32_t)_sapp.framebuffer_width;
  3179. msaa_desc.size.height = (uint32_t)_sapp.framebuffer_height;
  3180. msaa_desc.size.depthOrArrayLayers = 1;
  3181. msaa_desc.format = _sapp.wgpu.render_format;
  3182. msaa_desc.mipLevelCount = 1;
  3183. msaa_desc.sampleCount = (uint32_t)_sapp.sample_count;
  3184. _sapp.wgpu.msaa_tex = wgpuDeviceCreateTexture(_sapp.wgpu.device, &msaa_desc);
  3185. if (0 == _sapp.wgpu.msaa_tex) {
  3186. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_MSAA_TEXTURE_FAILED);
  3187. }
  3188. _sapp.wgpu.msaa_view = wgpuTextureCreateView(_sapp.wgpu.msaa_tex, 0);
  3189. if (0 == _sapp.wgpu.msaa_view) {
  3190. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_MSAA_VIEW_FAILED);
  3191. }
  3192. }
  3193. }
  3194. _SOKOL_PRIVATE void _sapp_wgpu_discard_swapchain(bool called_from_resize) {
  3195. if (_sapp.wgpu.msaa_view) {
  3196. wgpuTextureViewRelease(_sapp.wgpu.msaa_view);
  3197. _sapp.wgpu.msaa_view = 0;
  3198. }
  3199. if (_sapp.wgpu.msaa_tex) {
  3200. wgpuTextureRelease(_sapp.wgpu.msaa_tex);
  3201. _sapp.wgpu.msaa_tex = 0;
  3202. }
  3203. if (_sapp.wgpu.depth_stencil_view) {
  3204. wgpuTextureViewRelease(_sapp.wgpu.depth_stencil_view);
  3205. _sapp.wgpu.depth_stencil_view = 0;
  3206. }
  3207. if (_sapp.wgpu.depth_stencil_tex) {
  3208. wgpuTextureRelease(_sapp.wgpu.depth_stencil_tex);
  3209. _sapp.wgpu.depth_stencil_tex = 0;
  3210. }
  3211. if (!called_from_resize) {
  3212. if (_sapp.wgpu.surface) {
  3213. wgpuSurfaceRelease(_sapp.wgpu.surface);
  3214. _sapp.wgpu.surface = 0;
  3215. }
  3216. }
  3217. }
  3218. _SOKOL_PRIVATE WGPUTextureView _sapp_wgpu_swapchain_next(void) {
  3219. WGPUSurfaceTexture surf_tex;
  3220. _sapp_clear(&surf_tex, sizeof(surf_tex));
  3221. wgpuSurfaceGetCurrentTexture(_sapp.wgpu.surface, &surf_tex);
  3222. switch (surf_tex.status) {
  3223. case WGPUSurfaceGetCurrentTextureStatus_SuccessOptimal:
  3224. case WGPUSurfaceGetCurrentTextureStatus_SuccessSuboptimal:
  3225. // all ok
  3226. break;
  3227. case WGPUSurfaceGetCurrentTextureStatus_Timeout:
  3228. case WGPUSurfaceGetCurrentTextureStatus_Outdated:
  3229. case WGPUSurfaceGetCurrentTextureStatus_Lost:
  3230. // skip this frame and reconfigure surface
  3231. if (surf_tex.texture) {
  3232. wgpuTextureRelease(surf_tex.texture);
  3233. }
  3234. _sapp_wgpu_discard_swapchain(false);
  3235. _sapp_wgpu_create_swapchain(false);
  3236. return 0;
  3237. case WGPUSurfaceGetCurrentTextureStatus_Error:
  3238. default:
  3239. _SAPP_PANIC(WGPU_SWAPCHAIN_GETCURRENTTEXTURE_FAILED);
  3240. break;
  3241. }
  3242. return wgpuTextureCreateView(surf_tex.texture, 0);
  3243. }
  3244. _SOKOL_PRIVATE void _sapp_wgpu_size_changed(void) {
  3245. if (_sapp.wgpu.surface) {
  3246. _sapp_wgpu_discard_swapchain(true);
  3247. _sapp_wgpu_create_swapchain(true);
  3248. }
  3249. }
  3250. _SOKOL_PRIVATE void _sapp_wgpu_request_device_cb(WGPURequestDeviceStatus status, WGPUDevice device, WGPUStringView msg, void* userdata1, void* userdata2) {
  3251. _SOKOL_UNUSED(msg);
  3252. _SOKOL_UNUSED(userdata1);
  3253. _SOKOL_UNUSED(userdata2);
  3254. SOKOL_ASSERT(!_sapp.wgpu.async_init_done);
  3255. if (status != WGPURequestDeviceStatus_Success) {
  3256. if (status == WGPURequestDeviceStatus_Error) {
  3257. _SAPP_PANIC(WGPU_REQUEST_DEVICE_STATUS_ERROR);
  3258. } else {
  3259. _SAPP_PANIC(WGPU_REQUEST_DEVICE_STATUS_UNKNOWN);
  3260. }
  3261. }
  3262. SOKOL_ASSERT(device);
  3263. _sapp.wgpu.device = device;
  3264. _sapp_wgpu_create_swapchain(false);
  3265. _sapp.wgpu.async_init_done = true;
  3266. }
  3267. _SOKOL_PRIVATE void _sapp_wgpu_request_adapter_cb(WGPURequestAdapterStatus status, WGPUAdapter adapter, WGPUStringView msg, void* userdata1, void* userdata2) {
  3268. _SOKOL_UNUSED(msg);
  3269. _SOKOL_UNUSED(userdata1);
  3270. _SOKOL_UNUSED(userdata2);
  3271. if (status != WGPURequestAdapterStatus_Success) {
  3272. switch (status) {
  3273. case WGPURequestAdapterStatus_Unavailable: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_UNAVAILABLE); break;
  3274. case WGPURequestAdapterStatus_Error: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_ERROR); break;
  3275. default: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_UNKNOWN); break;
  3276. }
  3277. }
  3278. SOKOL_ASSERT(adapter);
  3279. _sapp.wgpu.adapter = adapter;
  3280. size_t cur_feature_index = 1;
  3281. #define _SAPP_WGPU_MAX_REQUESTED_FEATURES (8)
  3282. WGPUFeatureName requiredFeatures[_SAPP_WGPU_MAX_REQUESTED_FEATURES] = {
  3283. WGPUFeatureName_Depth32FloatStencil8,
  3284. };
  3285. // check for optional features we're interested in
  3286. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionBC)) {
  3287. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  3288. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionBC;
  3289. }
  3290. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionETC2)) {
  3291. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  3292. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionETC2;
  3293. }
  3294. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionASTC)) {
  3295. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  3296. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionASTC;
  3297. }
  3298. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_Float32Filterable)) {
  3299. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  3300. requiredFeatures[cur_feature_index++] = WGPUFeatureName_Float32Filterable;
  3301. }
  3302. #undef _SAPP_WGPU_MAX_REQUESTED_FEATURES
  3303. WGPURequestDeviceCallbackInfo cb_info;
  3304. _sapp_clear(&cb_info, sizeof(cb_info));
  3305. cb_info.mode = WGPUCallbackMode_AllowProcessEvents;
  3306. cb_info.callback = _sapp_wgpu_request_device_cb;
  3307. WGPUDeviceDescriptor dev_desc;
  3308. _sapp_clear(&dev_desc, sizeof(dev_desc));
  3309. dev_desc.requiredFeatureCount = cur_feature_index;
  3310. dev_desc.requiredFeatures = requiredFeatures,
  3311. wgpuAdapterRequestDevice(adapter, &dev_desc, cb_info);
  3312. }
  3313. _SOKOL_PRIVATE void _sapp_wgpu_init(void) {
  3314. SOKOL_ASSERT(0 == _sapp.wgpu.instance);
  3315. SOKOL_ASSERT(!_sapp.wgpu.async_init_done);
  3316. _sapp.wgpu.instance = wgpuCreateInstance(0);
  3317. if (0 == _sapp.wgpu.instance) {
  3318. _SAPP_PANIC(WGPU_CREATE_INSTANCE_FAILED);
  3319. }
  3320. // FIXME: power preference?
  3321. WGPURequestAdapterCallbackInfo cb_info;
  3322. _sapp_clear(&cb_info, sizeof(cb_info));
  3323. cb_info.mode = WGPUCallbackMode_AllowProcessEvents;
  3324. cb_info.callback = _sapp_wgpu_request_adapter_cb;
  3325. wgpuInstanceRequestAdapter(_sapp.wgpu.instance, 0, cb_info);
  3326. }
  3327. _SOKOL_PRIVATE void _sapp_wgpu_frame(void) {
  3328. wgpuInstanceProcessEvents(_sapp.wgpu.instance);
  3329. if (_sapp.wgpu.async_init_done) {
  3330. _sapp.wgpu.swapchain_view = _sapp_wgpu_swapchain_next();
  3331. _sapp_frame();
  3332. wgpuTextureViewRelease(_sapp.wgpu.swapchain_view);
  3333. _sapp.wgpu.swapchain_view = 0;
  3334. }
  3335. }
  3336. #endif // SOKOL_WGPU
  3337. // █████ ██████ ██████ ██ ███████
  3338. // ██ ██ ██ ██ ██ ██ ██ ██
  3339. // ███████ ██████ ██████ ██ █████
  3340. // ██ ██ ██ ██ ██ ██
  3341. // ██ ██ ██ ██ ███████ ███████
  3342. //
  3343. // >>apple
  3344. #if defined(_SAPP_APPLE)
  3345. #if __has_feature(objc_arc)
  3346. #define _SAPP_OBJC_RELEASE(obj) { obj = nil; }
  3347. #else
  3348. #define _SAPP_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  3349. #endif
  3350. // ███ ███ █████ ██████ ██████ ███████
  3351. // ████ ████ ██ ██ ██ ██ ██ ██
  3352. // ██ ████ ██ ███████ ██ ██ ██ ███████
  3353. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  3354. // ██ ██ ██ ██ ██████ ██████ ███████
  3355. //
  3356. // >>macos
  3357. #if defined(_SAPP_MACOS)
  3358. _SOKOL_PRIVATE void _sapp_macos_init_keytable(void) {
  3359. _sapp.keycodes[0x1D] = SAPP_KEYCODE_0;
  3360. _sapp.keycodes[0x12] = SAPP_KEYCODE_1;
  3361. _sapp.keycodes[0x13] = SAPP_KEYCODE_2;
  3362. _sapp.keycodes[0x14] = SAPP_KEYCODE_3;
  3363. _sapp.keycodes[0x15] = SAPP_KEYCODE_4;
  3364. _sapp.keycodes[0x17] = SAPP_KEYCODE_5;
  3365. _sapp.keycodes[0x16] = SAPP_KEYCODE_6;
  3366. _sapp.keycodes[0x1A] = SAPP_KEYCODE_7;
  3367. _sapp.keycodes[0x1C] = SAPP_KEYCODE_8;
  3368. _sapp.keycodes[0x19] = SAPP_KEYCODE_9;
  3369. _sapp.keycodes[0x00] = SAPP_KEYCODE_A;
  3370. _sapp.keycodes[0x0B] = SAPP_KEYCODE_B;
  3371. _sapp.keycodes[0x08] = SAPP_KEYCODE_C;
  3372. _sapp.keycodes[0x02] = SAPP_KEYCODE_D;
  3373. _sapp.keycodes[0x0E] = SAPP_KEYCODE_E;
  3374. _sapp.keycodes[0x03] = SAPP_KEYCODE_F;
  3375. _sapp.keycodes[0x05] = SAPP_KEYCODE_G;
  3376. _sapp.keycodes[0x04] = SAPP_KEYCODE_H;
  3377. _sapp.keycodes[0x22] = SAPP_KEYCODE_I;
  3378. _sapp.keycodes[0x26] = SAPP_KEYCODE_J;
  3379. _sapp.keycodes[0x28] = SAPP_KEYCODE_K;
  3380. _sapp.keycodes[0x25] = SAPP_KEYCODE_L;
  3381. _sapp.keycodes[0x2E] = SAPP_KEYCODE_M;
  3382. _sapp.keycodes[0x2D] = SAPP_KEYCODE_N;
  3383. _sapp.keycodes[0x1F] = SAPP_KEYCODE_O;
  3384. _sapp.keycodes[0x23] = SAPP_KEYCODE_P;
  3385. _sapp.keycodes[0x0C] = SAPP_KEYCODE_Q;
  3386. _sapp.keycodes[0x0F] = SAPP_KEYCODE_R;
  3387. _sapp.keycodes[0x01] = SAPP_KEYCODE_S;
  3388. _sapp.keycodes[0x11] = SAPP_KEYCODE_T;
  3389. _sapp.keycodes[0x20] = SAPP_KEYCODE_U;
  3390. _sapp.keycodes[0x09] = SAPP_KEYCODE_V;
  3391. _sapp.keycodes[0x0D] = SAPP_KEYCODE_W;
  3392. _sapp.keycodes[0x07] = SAPP_KEYCODE_X;
  3393. _sapp.keycodes[0x10] = SAPP_KEYCODE_Y;
  3394. _sapp.keycodes[0x06] = SAPP_KEYCODE_Z;
  3395. _sapp.keycodes[0x27] = SAPP_KEYCODE_APOSTROPHE;
  3396. _sapp.keycodes[0x2A] = SAPP_KEYCODE_BACKSLASH;
  3397. _sapp.keycodes[0x2B] = SAPP_KEYCODE_COMMA;
  3398. _sapp.keycodes[0x18] = SAPP_KEYCODE_EQUAL;
  3399. _sapp.keycodes[0x32] = SAPP_KEYCODE_GRAVE_ACCENT;
  3400. _sapp.keycodes[0x21] = SAPP_KEYCODE_LEFT_BRACKET;
  3401. _sapp.keycodes[0x1B] = SAPP_KEYCODE_MINUS;
  3402. _sapp.keycodes[0x2F] = SAPP_KEYCODE_PERIOD;
  3403. _sapp.keycodes[0x1E] = SAPP_KEYCODE_RIGHT_BRACKET;
  3404. _sapp.keycodes[0x29] = SAPP_KEYCODE_SEMICOLON;
  3405. _sapp.keycodes[0x2C] = SAPP_KEYCODE_SLASH;
  3406. _sapp.keycodes[0x0A] = SAPP_KEYCODE_WORLD_1;
  3407. _sapp.keycodes[0x33] = SAPP_KEYCODE_BACKSPACE;
  3408. _sapp.keycodes[0x39] = SAPP_KEYCODE_CAPS_LOCK;
  3409. _sapp.keycodes[0x75] = SAPP_KEYCODE_DELETE;
  3410. _sapp.keycodes[0x7D] = SAPP_KEYCODE_DOWN;
  3411. _sapp.keycodes[0x77] = SAPP_KEYCODE_END;
  3412. _sapp.keycodes[0x24] = SAPP_KEYCODE_ENTER;
  3413. _sapp.keycodes[0x35] = SAPP_KEYCODE_ESCAPE;
  3414. _sapp.keycodes[0x7A] = SAPP_KEYCODE_F1;
  3415. _sapp.keycodes[0x78] = SAPP_KEYCODE_F2;
  3416. _sapp.keycodes[0x63] = SAPP_KEYCODE_F3;
  3417. _sapp.keycodes[0x76] = SAPP_KEYCODE_F4;
  3418. _sapp.keycodes[0x60] = SAPP_KEYCODE_F5;
  3419. _sapp.keycodes[0x61] = SAPP_KEYCODE_F6;
  3420. _sapp.keycodes[0x62] = SAPP_KEYCODE_F7;
  3421. _sapp.keycodes[0x64] = SAPP_KEYCODE_F8;
  3422. _sapp.keycodes[0x65] = SAPP_KEYCODE_F9;
  3423. _sapp.keycodes[0x6D] = SAPP_KEYCODE_F10;
  3424. _sapp.keycodes[0x67] = SAPP_KEYCODE_F11;
  3425. _sapp.keycodes[0x6F] = SAPP_KEYCODE_F12;
  3426. _sapp.keycodes[0x69] = SAPP_KEYCODE_F13;
  3427. _sapp.keycodes[0x6B] = SAPP_KEYCODE_F14;
  3428. _sapp.keycodes[0x71] = SAPP_KEYCODE_F15;
  3429. _sapp.keycodes[0x6A] = SAPP_KEYCODE_F16;
  3430. _sapp.keycodes[0x40] = SAPP_KEYCODE_F17;
  3431. _sapp.keycodes[0x4F] = SAPP_KEYCODE_F18;
  3432. _sapp.keycodes[0x50] = SAPP_KEYCODE_F19;
  3433. _sapp.keycodes[0x5A] = SAPP_KEYCODE_F20;
  3434. _sapp.keycodes[0x73] = SAPP_KEYCODE_HOME;
  3435. _sapp.keycodes[0x72] = SAPP_KEYCODE_INSERT;
  3436. _sapp.keycodes[0x7B] = SAPP_KEYCODE_LEFT;
  3437. _sapp.keycodes[0x3A] = SAPP_KEYCODE_LEFT_ALT;
  3438. _sapp.keycodes[0x3B] = SAPP_KEYCODE_LEFT_CONTROL;
  3439. _sapp.keycodes[0x38] = SAPP_KEYCODE_LEFT_SHIFT;
  3440. _sapp.keycodes[0x37] = SAPP_KEYCODE_LEFT_SUPER;
  3441. _sapp.keycodes[0x6E] = SAPP_KEYCODE_MENU;
  3442. _sapp.keycodes[0x47] = SAPP_KEYCODE_NUM_LOCK;
  3443. _sapp.keycodes[0x79] = SAPP_KEYCODE_PAGE_DOWN;
  3444. _sapp.keycodes[0x74] = SAPP_KEYCODE_PAGE_UP;
  3445. _sapp.keycodes[0x7C] = SAPP_KEYCODE_RIGHT;
  3446. _sapp.keycodes[0x3D] = SAPP_KEYCODE_RIGHT_ALT;
  3447. _sapp.keycodes[0x3E] = SAPP_KEYCODE_RIGHT_CONTROL;
  3448. _sapp.keycodes[0x3C] = SAPP_KEYCODE_RIGHT_SHIFT;
  3449. _sapp.keycodes[0x36] = SAPP_KEYCODE_RIGHT_SUPER;
  3450. _sapp.keycodes[0x31] = SAPP_KEYCODE_SPACE;
  3451. _sapp.keycodes[0x30] = SAPP_KEYCODE_TAB;
  3452. _sapp.keycodes[0x7E] = SAPP_KEYCODE_UP;
  3453. _sapp.keycodes[0x52] = SAPP_KEYCODE_KP_0;
  3454. _sapp.keycodes[0x53] = SAPP_KEYCODE_KP_1;
  3455. _sapp.keycodes[0x54] = SAPP_KEYCODE_KP_2;
  3456. _sapp.keycodes[0x55] = SAPP_KEYCODE_KP_3;
  3457. _sapp.keycodes[0x56] = SAPP_KEYCODE_KP_4;
  3458. _sapp.keycodes[0x57] = SAPP_KEYCODE_KP_5;
  3459. _sapp.keycodes[0x58] = SAPP_KEYCODE_KP_6;
  3460. _sapp.keycodes[0x59] = SAPP_KEYCODE_KP_7;
  3461. _sapp.keycodes[0x5B] = SAPP_KEYCODE_KP_8;
  3462. _sapp.keycodes[0x5C] = SAPP_KEYCODE_KP_9;
  3463. _sapp.keycodes[0x45] = SAPP_KEYCODE_KP_ADD;
  3464. _sapp.keycodes[0x41] = SAPP_KEYCODE_KP_DECIMAL;
  3465. _sapp.keycodes[0x4B] = SAPP_KEYCODE_KP_DIVIDE;
  3466. _sapp.keycodes[0x4C] = SAPP_KEYCODE_KP_ENTER;
  3467. _sapp.keycodes[0x51] = SAPP_KEYCODE_KP_EQUAL;
  3468. _sapp.keycodes[0x43] = SAPP_KEYCODE_KP_MULTIPLY;
  3469. _sapp.keycodes[0x4E] = SAPP_KEYCODE_KP_SUBTRACT;
  3470. }
  3471. _SOKOL_PRIVATE void _sapp_macos_discard_state(void) {
  3472. // NOTE: it's safe to call [release] on a nil object
  3473. if (_sapp.macos.keyup_monitor != nil) {
  3474. [NSEvent removeMonitor:_sapp.macos.keyup_monitor];
  3475. // NOTE: removeMonitor also releases the object
  3476. _sapp.macos.keyup_monitor = nil;
  3477. }
  3478. _SAPP_OBJC_RELEASE(_sapp.macos.tracking_area);
  3479. _SAPP_OBJC_RELEASE(_sapp.macos.app_dlg);
  3480. _SAPP_OBJC_RELEASE(_sapp.macos.win_dlg);
  3481. _SAPP_OBJC_RELEASE(_sapp.macos.view);
  3482. #if defined(SOKOL_METAL)
  3483. _SAPP_OBJC_RELEASE(_sapp.macos.mtl_device);
  3484. #endif
  3485. _SAPP_OBJC_RELEASE(_sapp.macos.window);
  3486. }
  3487. // undocumented methods for creating cursors (see GLFW 3.4 and imgui_impl_osx.mm)
  3488. @interface NSCursor()
  3489. + (id)_windowResizeNorthWestSouthEastCursor;
  3490. + (id)_windowResizeNorthEastSouthWestCursor;
  3491. + (id)_windowResizeNorthSouthCursor;
  3492. + (id)_windowResizeEastWestCursor;
  3493. @end
  3494. _SOKOL_PRIVATE void _sapp_macos_init_cursors(void) {
  3495. _sapp.macos.cursors[SAPP_MOUSECURSOR_DEFAULT] = nil; // not a bug
  3496. _sapp.macos.cursors[SAPP_MOUSECURSOR_ARROW] = [NSCursor arrowCursor];
  3497. _sapp.macos.cursors[SAPP_MOUSECURSOR_IBEAM] = [NSCursor IBeamCursor];
  3498. _sapp.macos.cursors[SAPP_MOUSECURSOR_CROSSHAIR] = [NSCursor crosshairCursor];
  3499. _sapp.macos.cursors[SAPP_MOUSECURSOR_POINTING_HAND] = [NSCursor pointingHandCursor];
  3500. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_EW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
  3501. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
  3502. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
  3503. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
  3504. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_ALL] = [NSCursor closedHandCursor];
  3505. _sapp.macos.cursors[SAPP_MOUSECURSOR_NOT_ALLOWED] = [NSCursor operationNotAllowedCursor];
  3506. }
  3507. _SOKOL_PRIVATE void _sapp_macos_run(const sapp_desc* desc) {
  3508. _sapp_init_state(desc);
  3509. _sapp_macos_init_keytable();
  3510. [NSApplication sharedApplication];
  3511. // set the application dock icon as early as possible, otherwise
  3512. // the dummy icon will be visible for a short time
  3513. sapp_set_icon(&_sapp.desc.icon);
  3514. _sapp.macos.app_dlg = [[_sapp_macos_app_delegate alloc] init];
  3515. NSApp.delegate = _sapp.macos.app_dlg;
  3516. // workaround for "no key-up sent while Cmd is pressed" taken from GLFW:
  3517. NSEvent* (^keyup_monitor)(NSEvent*) = ^NSEvent* (NSEvent* event) {
  3518. if ([event modifierFlags] & NSEventModifierFlagCommand) {
  3519. [[NSApp keyWindow] sendEvent:event];
  3520. }
  3521. return event;
  3522. };
  3523. _sapp.macos.keyup_monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyUp handler:keyup_monitor];
  3524. [NSApp run];
  3525. // NOTE: [NSApp run] never returns, instead cleanup code
  3526. // must be put into applicationWillTerminate
  3527. }
  3528. /* MacOS entry function */
  3529. #if !defined(SOKOL_NO_ENTRY)
  3530. int main(int argc, char* argv[]) {
  3531. sapp_desc desc = sokol_main(argc, argv);
  3532. _sapp_macos_run(&desc);
  3533. return 0;
  3534. }
  3535. #endif /* SOKOL_NO_ENTRY */
  3536. _SOKOL_PRIVATE uint32_t _sapp_macos_mods(NSEvent* ev) {
  3537. const NSEventModifierFlags f = (ev == nil) ? NSEvent.modifierFlags : ev.modifierFlags;
  3538. const NSUInteger b = NSEvent.pressedMouseButtons;
  3539. uint32_t m = 0;
  3540. if (f & NSEventModifierFlagShift) {
  3541. m |= SAPP_MODIFIER_SHIFT;
  3542. }
  3543. if (f & NSEventModifierFlagControl) {
  3544. m |= SAPP_MODIFIER_CTRL;
  3545. }
  3546. if (f & NSEventModifierFlagOption) {
  3547. m |= SAPP_MODIFIER_ALT;
  3548. }
  3549. if (f & NSEventModifierFlagCommand) {
  3550. m |= SAPP_MODIFIER_SUPER;
  3551. }
  3552. if (0 != (b & (1<<0))) {
  3553. m |= SAPP_MODIFIER_LMB;
  3554. }
  3555. if (0 != (b & (1<<1))) {
  3556. m |= SAPP_MODIFIER_RMB;
  3557. }
  3558. if (0 != (b & (1<<2))) {
  3559. m |= SAPP_MODIFIER_MMB;
  3560. }
  3561. return m;
  3562. }
  3563. _SOKOL_PRIVATE void _sapp_macos_mouse_event(sapp_event_type type, sapp_mousebutton btn, uint32_t mod) {
  3564. if (_sapp_events_enabled()) {
  3565. _sapp_init_event(type);
  3566. _sapp.event.mouse_button = btn;
  3567. _sapp.event.modifiers = mod;
  3568. _sapp_call_event(&_sapp.event);
  3569. }
  3570. }
  3571. _SOKOL_PRIVATE void _sapp_macos_key_event(sapp_event_type type, sapp_keycode key, bool repeat, uint32_t mod) {
  3572. if (_sapp_events_enabled()) {
  3573. _sapp_init_event(type);
  3574. _sapp.event.key_code = key;
  3575. _sapp.event.key_repeat = repeat;
  3576. _sapp.event.modifiers = mod;
  3577. _sapp_call_event(&_sapp.event);
  3578. }
  3579. }
  3580. _SOKOL_PRIVATE void _sapp_macos_app_event(sapp_event_type type) {
  3581. if (_sapp_events_enabled()) {
  3582. _sapp_init_event(type);
  3583. _sapp_call_event(&_sapp.event);
  3584. }
  3585. }
  3586. /* NOTE: unlike the iOS version of this function, the macOS version
  3587. can dynamically update the DPI scaling factor when a window is moved
  3588. between HighDPI / LowDPI screens.
  3589. */
  3590. _SOKOL_PRIVATE void _sapp_macos_update_dimensions(void) {
  3591. if (_sapp.desc.high_dpi) {
  3592. _sapp.dpi_scale = [_sapp.macos.window screen].backingScaleFactor;
  3593. }
  3594. else {
  3595. _sapp.dpi_scale = 1.0f;
  3596. }
  3597. _sapp.macos.view.layer.contentsScale = _sapp.dpi_scale; // NOTE: needed because we set layerContentsPlacement to a non-scaling value in windowWillStartLiveResize.
  3598. const NSRect bounds = [_sapp.macos.view bounds];
  3599. _sapp.window_width = (int)roundf(bounds.size.width);
  3600. _sapp.window_height = (int)roundf(bounds.size.height);
  3601. #if defined(SOKOL_METAL)
  3602. _sapp.framebuffer_width = (int)roundf(bounds.size.width * _sapp.dpi_scale);
  3603. _sapp.framebuffer_height = (int)roundf(bounds.size.height * _sapp.dpi_scale);
  3604. const CGSize fb_size = _sapp.macos.view.drawableSize;
  3605. const int cur_fb_width = (int)roundf(fb_size.width);
  3606. const int cur_fb_height = (int)roundf(fb_size.height);
  3607. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  3608. (_sapp.framebuffer_height != cur_fb_height);
  3609. #elif defined(SOKOL_GLCORE)
  3610. const int cur_fb_width = (int)roundf(bounds.size.width * _sapp.dpi_scale);
  3611. const int cur_fb_height = (int)roundf(bounds.size.height * _sapp.dpi_scale);
  3612. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  3613. (_sapp.framebuffer_height != cur_fb_height);
  3614. _sapp.framebuffer_width = cur_fb_width;
  3615. _sapp.framebuffer_height = cur_fb_height;
  3616. #endif
  3617. if (_sapp.framebuffer_width == 0) {
  3618. _sapp.framebuffer_width = 1;
  3619. }
  3620. if (_sapp.framebuffer_height == 0) {
  3621. _sapp.framebuffer_height = 1;
  3622. }
  3623. if (_sapp.window_width == 0) {
  3624. _sapp.window_width = 1;
  3625. }
  3626. if (_sapp.window_height == 0) {
  3627. _sapp.window_height = 1;
  3628. }
  3629. if (dim_changed) {
  3630. #if defined(SOKOL_METAL)
  3631. CGSize drawable_size = { (CGFloat) _sapp.framebuffer_width, (CGFloat) _sapp.framebuffer_height };
  3632. _sapp.macos.view.drawableSize = drawable_size;
  3633. #else
  3634. // nothing to do for GL?
  3635. #endif
  3636. if (!_sapp.first_frame) {
  3637. _sapp_macos_app_event(SAPP_EVENTTYPE_RESIZED);
  3638. }
  3639. }
  3640. }
  3641. _SOKOL_PRIVATE void _sapp_macos_toggle_fullscreen(void) {
  3642. /* NOTE: the _sapp.fullscreen flag is also notified by the
  3643. windowDidEnterFullscreen / windowDidExitFullscreen
  3644. event handlers
  3645. */
  3646. _sapp.fullscreen = !_sapp.fullscreen;
  3647. [_sapp.macos.window toggleFullScreen:nil];
  3648. }
  3649. _SOKOL_PRIVATE void _sapp_macos_set_clipboard_string(const char* str) {
  3650. @autoreleasepool {
  3651. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  3652. [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
  3653. [pasteboard setString:@(str) forType:NSPasteboardTypeString];
  3654. }
  3655. }
  3656. _SOKOL_PRIVATE const char* _sapp_macos_get_clipboard_string(void) {
  3657. SOKOL_ASSERT(_sapp.clipboard.buffer);
  3658. @autoreleasepool {
  3659. _sapp.clipboard.buffer[0] = 0;
  3660. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  3661. if (![[pasteboard types] containsObject:NSPasteboardTypeString]) {
  3662. return _sapp.clipboard.buffer;
  3663. }
  3664. NSString* str = [pasteboard stringForType:NSPasteboardTypeString];
  3665. if (!str) {
  3666. return _sapp.clipboard.buffer;
  3667. }
  3668. _sapp_strcpy([str UTF8String], _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  3669. }
  3670. return _sapp.clipboard.buffer;
  3671. }
  3672. _SOKOL_PRIVATE void _sapp_macos_update_window_title(void) {
  3673. [_sapp.macos.window setTitle: [NSString stringWithUTF8String:_sapp.window_title]];
  3674. }
  3675. _SOKOL_PRIVATE void _sapp_macos_mouse_update_from_nspoint(NSPoint mouse_pos, bool clear_dxdy) {
  3676. if (!_sapp.mouse.locked) {
  3677. float new_x = mouse_pos.x * _sapp.dpi_scale;
  3678. float new_y = _sapp.framebuffer_height - (mouse_pos.y * _sapp.dpi_scale) - 1;
  3679. if (clear_dxdy) {
  3680. _sapp.mouse.dx = 0.0f;
  3681. _sapp.mouse.dy = 0.0f;
  3682. }
  3683. else if (_sapp.mouse.pos_valid) {
  3684. // don't update dx/dy in the very first update
  3685. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  3686. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  3687. }
  3688. _sapp.mouse.x = new_x;
  3689. _sapp.mouse.y = new_y;
  3690. _sapp.mouse.pos_valid = true;
  3691. }
  3692. }
  3693. _SOKOL_PRIVATE void _sapp_macos_mouse_update_from_nsevent(NSEvent* event, bool clear_dxdy) {
  3694. _sapp_macos_mouse_update_from_nspoint(event.locationInWindow, clear_dxdy);
  3695. }
  3696. _SOKOL_PRIVATE void _sapp_macos_show_mouse(bool visible) {
  3697. /* NOTE: this function is only called when the mouse visibility actually changes */
  3698. if (visible) {
  3699. CGDisplayShowCursor(kCGDirectMainDisplay);
  3700. }
  3701. else {
  3702. CGDisplayHideCursor(kCGDirectMainDisplay);
  3703. }
  3704. }
  3705. _SOKOL_PRIVATE void _sapp_macos_lock_mouse(bool lock) {
  3706. if (lock == _sapp.mouse.locked) {
  3707. return;
  3708. }
  3709. _sapp.mouse.dx = 0.0f;
  3710. _sapp.mouse.dy = 0.0f;
  3711. _sapp.mouse.locked = lock;
  3712. /*
  3713. NOTE that this code doesn't warp the mouse cursor to the window
  3714. center as everybody else does it. This lead to a spike in the
  3715. *second* mouse-moved event after the warp happened. The
  3716. mouse centering doesn't seem to be required (mouse-moved events
  3717. are reported correctly even when the cursor is at an edge of the screen).
  3718. NOTE also that the hide/show of the mouse cursor should properly
  3719. stack with calls to sapp_show_mouse()
  3720. */
  3721. if (_sapp.mouse.locked) {
  3722. CGAssociateMouseAndMouseCursorPosition(NO);
  3723. [NSCursor hide];
  3724. }
  3725. else {
  3726. [NSCursor unhide];
  3727. CGAssociateMouseAndMouseCursorPosition(YES);
  3728. }
  3729. }
  3730. _SOKOL_PRIVATE void _sapp_macos_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  3731. // show/hide cursor only if visibility status has changed (required because show/hide stacks)
  3732. if (shown != _sapp.mouse.shown) {
  3733. if (shown) {
  3734. [NSCursor unhide];
  3735. }
  3736. else {
  3737. [NSCursor hide];
  3738. }
  3739. }
  3740. // update cursor type
  3741. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  3742. if (_sapp.macos.cursors[cursor]) {
  3743. [_sapp.macos.cursors[cursor] set];
  3744. }
  3745. else {
  3746. [[NSCursor arrowCursor] set];
  3747. }
  3748. }
  3749. _SOKOL_PRIVATE void _sapp_macos_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  3750. NSDockTile* dock_tile = NSApp.dockTile;
  3751. const int wanted_width = (int) dock_tile.size.width;
  3752. const int wanted_height = (int) dock_tile.size.height;
  3753. const int img_index = _sapp_image_bestmatch(icon_desc->images, num_images, wanted_width, wanted_height);
  3754. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  3755. CGColorSpaceRef cg_color_space = CGColorSpaceCreateDeviceRGB();
  3756. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)img_desc->pixels.ptr, (CFIndex)img_desc->pixels.size);
  3757. CGDataProviderRef cg_data_provider = CGDataProviderCreateWithCFData(cf_data);
  3758. CGImageRef cg_img = CGImageCreate(
  3759. (size_t)img_desc->width, // width
  3760. (size_t)img_desc->height, // height
  3761. 8, // bitsPerComponent
  3762. 32, // bitsPerPixel
  3763. (size_t)img_desc->width * 4,// bytesPerRow
  3764. cg_color_space, // space
  3765. kCGImageAlphaLast | kCGImageByteOrderDefault, // bitmapInfo
  3766. cg_data_provider, // provider
  3767. NULL, // decode
  3768. false, // shouldInterpolate
  3769. kCGRenderingIntentDefault);
  3770. CFRelease(cf_data);
  3771. CGDataProviderRelease(cg_data_provider);
  3772. CGColorSpaceRelease(cg_color_space);
  3773. NSImage* ns_image = [[NSImage alloc] initWithCGImage:cg_img size:dock_tile.size];
  3774. dock_tile.contentView = [NSImageView imageViewWithImage:ns_image];
  3775. [dock_tile display];
  3776. _SAPP_OBJC_RELEASE(ns_image);
  3777. CGImageRelease(cg_img);
  3778. }
  3779. _SOKOL_PRIVATE void _sapp_macos_frame(void) {
  3780. _sapp_frame();
  3781. if (_sapp.quit_requested || _sapp.quit_ordered) {
  3782. [_sapp.macos.window performClose:nil];
  3783. }
  3784. }
  3785. @implementation _sapp_macos_app_delegate
  3786. - (void)applicationDidFinishLaunching:(NSNotification*)aNotification {
  3787. _SOKOL_UNUSED(aNotification);
  3788. _sapp_macos_init_cursors();
  3789. if ((_sapp.window_width == 0) || (_sapp.window_height == 0)) {
  3790. // use 4/5 of screen size as default size
  3791. NSRect screen_rect = NSScreen.mainScreen.frame;
  3792. if (_sapp.window_width == 0) {
  3793. _sapp.window_width = (int)roundf((screen_rect.size.width * 4.0f) / 5.0f);
  3794. }
  3795. if (_sapp.window_height == 0) {
  3796. _sapp.window_height = (int)roundf((screen_rect.size.height * 4.0f) / 5.0f);
  3797. }
  3798. }
  3799. const NSUInteger style =
  3800. NSWindowStyleMaskTitled |
  3801. NSWindowStyleMaskClosable |
  3802. NSWindowStyleMaskMiniaturizable |
  3803. NSWindowStyleMaskResizable;
  3804. NSRect window_rect = NSMakeRect(0, 0, _sapp.window_width, _sapp.window_height);
  3805. _sapp.macos.window = [[_sapp_macos_window alloc]
  3806. initWithContentRect:window_rect
  3807. styleMask:style
  3808. backing:NSBackingStoreBuffered
  3809. defer:NO];
  3810. _sapp.macos.window.releasedWhenClosed = NO; // this is necessary for proper cleanup in applicationWillTerminate
  3811. _sapp.macos.window.title = [NSString stringWithUTF8String:_sapp.window_title];
  3812. _sapp.macos.window.acceptsMouseMovedEvents = YES;
  3813. _sapp.macos.window.restorable = YES;
  3814. _sapp.macos.win_dlg = [[_sapp_macos_window_delegate alloc] init];
  3815. _sapp.macos.window.delegate = _sapp.macos.win_dlg;
  3816. #if defined(SOKOL_METAL)
  3817. NSInteger max_fps = 60;
  3818. #if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 120000)
  3819. if (@available(macOS 12.0, *)) {
  3820. max_fps = [NSScreen.mainScreen maximumFramesPerSecond];
  3821. }
  3822. #endif
  3823. _sapp.macos.mtl_device = MTLCreateSystemDefaultDevice();
  3824. _sapp.macos.view = [[_sapp_macos_view alloc] init];
  3825. [_sapp.macos.view updateTrackingAreas];
  3826. _sapp.macos.view.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  3827. _sapp.macos.view.device = _sapp.macos.mtl_device;
  3828. _sapp.macos.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
  3829. _sapp.macos.view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  3830. _sapp.macos.view.sampleCount = (NSUInteger) _sapp.sample_count;
  3831. _sapp.macos.view.autoResizeDrawable = false;
  3832. _sapp.macos.window.contentView = _sapp.macos.view;
  3833. [_sapp.macos.window makeFirstResponder:_sapp.macos.view];
  3834. _sapp.macos.view.layer.magnificationFilter = kCAFilterNearest;
  3835. #elif defined(SOKOL_GLCORE)
  3836. NSOpenGLPixelFormatAttribute attrs[32];
  3837. int i = 0;
  3838. attrs[i++] = NSOpenGLPFAAccelerated;
  3839. attrs[i++] = NSOpenGLPFADoubleBuffer;
  3840. attrs[i++] = NSOpenGLPFAOpenGLProfile;
  3841. const int glVersion = _sapp.desc.gl_major_version * 10 + _sapp.desc.gl_minor_version;
  3842. switch(glVersion) {
  3843. case 10: attrs[i++] = NSOpenGLProfileVersionLegacy; break;
  3844. case 32: attrs[i++] = NSOpenGLProfileVersion3_2Core; break;
  3845. case 41: attrs[i++] = NSOpenGLProfileVersion4_1Core; break;
  3846. default:
  3847. _SAPP_PANIC(MACOS_INVALID_NSOPENGL_PROFILE);
  3848. }
  3849. attrs[i++] = NSOpenGLPFAColorSize; attrs[i++] = 24;
  3850. attrs[i++] = NSOpenGLPFAAlphaSize; attrs[i++] = 8;
  3851. attrs[i++] = NSOpenGLPFADepthSize; attrs[i++] = 24;
  3852. attrs[i++] = NSOpenGLPFAStencilSize; attrs[i++] = 8;
  3853. if (_sapp.sample_count > 1) {
  3854. attrs[i++] = NSOpenGLPFAMultisample;
  3855. attrs[i++] = NSOpenGLPFASampleBuffers; attrs[i++] = 1;
  3856. attrs[i++] = NSOpenGLPFASamples; attrs[i++] = (NSOpenGLPixelFormatAttribute)_sapp.sample_count;
  3857. }
  3858. else {
  3859. attrs[i++] = NSOpenGLPFASampleBuffers; attrs[i++] = 0;
  3860. }
  3861. attrs[i++] = 0;
  3862. NSOpenGLPixelFormat* glpixelformat_obj = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  3863. SOKOL_ASSERT(glpixelformat_obj != nil);
  3864. _sapp.macos.view = [[_sapp_macos_view alloc]
  3865. initWithFrame:window_rect
  3866. pixelFormat:glpixelformat_obj];
  3867. _SAPP_OBJC_RELEASE(glpixelformat_obj);
  3868. [_sapp.macos.view updateTrackingAreas];
  3869. if (_sapp.desc.high_dpi) {
  3870. [_sapp.macos.view setWantsBestResolutionOpenGLSurface:YES];
  3871. }
  3872. else {
  3873. [_sapp.macos.view setWantsBestResolutionOpenGLSurface:NO];
  3874. }
  3875. _sapp.macos.window.contentView = _sapp.macos.view;
  3876. [_sapp.macos.window makeFirstResponder:_sapp.macos.view];
  3877. NSTimer* timer_obj = [NSTimer timerWithTimeInterval:0.001
  3878. target:_sapp.macos.view
  3879. selector:@selector(timerFired:)
  3880. userInfo:nil
  3881. repeats:YES];
  3882. [[NSRunLoop currentRunLoop] addTimer:timer_obj forMode:NSDefaultRunLoopMode];
  3883. timer_obj = nil;
  3884. #endif
  3885. [_sapp.macos.window center];
  3886. _sapp.valid = true;
  3887. NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
  3888. if (_sapp.fullscreen) {
  3889. /* ^^^ on GL, this already toggles a rendered frame, so set the valid flag before */
  3890. [_sapp.macos.window toggleFullScreen:self];
  3891. }
  3892. [NSApp activateIgnoringOtherApps:YES];
  3893. [_sapp.macos.window makeKeyAndOrderFront:nil];
  3894. _sapp_macos_update_dimensions();
  3895. [NSEvent setMouseCoalescingEnabled:NO];
  3896. // workaround for window not being focused during a long init callback
  3897. // for details see: https://github.com/floooh/sokol/pull/982
  3898. // also see: https://gitlab.gnome.org/GNOME/gtk/-/issues/2342
  3899. NSEvent *focusevent = [NSEvent otherEventWithType:NSEventTypeAppKitDefined
  3900. location:NSZeroPoint
  3901. modifierFlags:0x40
  3902. timestamp:0
  3903. windowNumber:0
  3904. context:nil
  3905. subtype:NSEventSubtypeApplicationActivated
  3906. data1:0
  3907. data2:0];
  3908. [NSApp postEvent:focusevent atStart:YES];
  3909. }
  3910. - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender {
  3911. _SOKOL_UNUSED(sender);
  3912. return YES;
  3913. }
  3914. - (void)applicationWillTerminate:(NSNotification*)notification {
  3915. _SOKOL_UNUSED(notification);
  3916. _sapp_call_cleanup();
  3917. _sapp_macos_discard_state();
  3918. _sapp_discard_state();
  3919. }
  3920. @end
  3921. @implementation _sapp_macos_window_delegate
  3922. - (BOOL)windowShouldClose:(id)sender {
  3923. _SOKOL_UNUSED(sender);
  3924. /* only give user-code a chance to intervene when sapp_quit() wasn't already called */
  3925. if (!_sapp.quit_ordered) {
  3926. /* if window should be closed and event handling is enabled, give user code
  3927. a chance to intervene via sapp_cancel_quit()
  3928. */
  3929. _sapp.quit_requested = true;
  3930. _sapp_macos_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  3931. /* user code hasn't intervened, quit the app */
  3932. if (_sapp.quit_requested) {
  3933. _sapp.quit_ordered = true;
  3934. }
  3935. }
  3936. if (_sapp.quit_ordered) {
  3937. return YES;
  3938. }
  3939. else {
  3940. return NO;
  3941. }
  3942. }
  3943. #if defined(SOKOL_METAL)
  3944. - (void)windowWillStartLiveResize:(NSNotification *)notification {
  3945. // Work around the MTKView resizing glitch by "anchoring" the layer to the window corner opposite
  3946. // to the currently manipulated corner (or edge). This prevents the content stretching back and
  3947. // forth during resizing. This is a workaround for this issue: https://github.com/floooh/sokol/issues/700
  3948. // Can be removed if/when migrating to CAMetalLayer: https://github.com/floooh/sokol/issues/727
  3949. bool resizing_from_left = _sapp.mouse.x < _sapp.window_width/2;
  3950. bool resizing_from_top = _sapp.mouse.y < _sapp.window_height/2;
  3951. NSViewLayerContentsPlacement placement;
  3952. if (resizing_from_left) {
  3953. placement = resizing_from_top ? NSViewLayerContentsPlacementBottomRight : NSViewLayerContentsPlacementTopRight;
  3954. } else {
  3955. placement = resizing_from_top ? NSViewLayerContentsPlacementBottomLeft : NSViewLayerContentsPlacementTopLeft;
  3956. }
  3957. _sapp.macos.view.layerContentsPlacement = placement;
  3958. }
  3959. #endif
  3960. - (void)windowDidResize:(NSNotification*)notification {
  3961. _SOKOL_UNUSED(notification);
  3962. _sapp_macos_update_dimensions();
  3963. }
  3964. - (void)windowDidChangeScreen:(NSNotification*)notification {
  3965. _SOKOL_UNUSED(notification);
  3966. _sapp_timing_reset(&_sapp.timing);
  3967. _sapp_macos_update_dimensions();
  3968. }
  3969. - (void)windowDidMiniaturize:(NSNotification*)notification {
  3970. _SOKOL_UNUSED(notification);
  3971. _sapp_macos_app_event(SAPP_EVENTTYPE_ICONIFIED);
  3972. }
  3973. - (void)windowDidDeminiaturize:(NSNotification*)notification {
  3974. _SOKOL_UNUSED(notification);
  3975. _sapp_macos_app_event(SAPP_EVENTTYPE_RESTORED);
  3976. }
  3977. - (void)windowDidBecomeKey:(NSNotification*)notification {
  3978. _SOKOL_UNUSED(notification);
  3979. _sapp_macos_app_event(SAPP_EVENTTYPE_FOCUSED);
  3980. }
  3981. - (void)windowDidResignKey:(NSNotification*)notification {
  3982. _SOKOL_UNUSED(notification);
  3983. _sapp_macos_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  3984. }
  3985. - (void)windowDidEnterFullScreen:(NSNotification*)notification {
  3986. _SOKOL_UNUSED(notification);
  3987. _sapp.fullscreen = true;
  3988. }
  3989. - (void)windowDidExitFullScreen:(NSNotification*)notification {
  3990. _SOKOL_UNUSED(notification);
  3991. _sapp.fullscreen = false;
  3992. }
  3993. @end
  3994. @implementation _sapp_macos_window
  3995. - (instancetype)initWithContentRect:(NSRect)contentRect
  3996. styleMask:(NSWindowStyleMask)style
  3997. backing:(NSBackingStoreType)backingStoreType
  3998. defer:(BOOL)flag {
  3999. if (self = [super initWithContentRect:contentRect styleMask:style backing:backingStoreType defer:flag]) {
  4000. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  4001. [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
  4002. #endif
  4003. }
  4004. return self;
  4005. }
  4006. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  4007. return NSDragOperationCopy;
  4008. }
  4009. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  4010. return NSDragOperationCopy;
  4011. }
  4012. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  4013. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  4014. NSPasteboard *pboard = [sender draggingPasteboard];
  4015. if ([pboard.types containsObject:NSPasteboardTypeFileURL]) {
  4016. _sapp_clear_drop_buffer();
  4017. _sapp.drop.num_files = ((int)pboard.pasteboardItems.count > _sapp.drop.max_files) ? _sapp.drop.max_files : (int)pboard.pasteboardItems.count;
  4018. bool drop_failed = false;
  4019. for (int i = 0; i < _sapp.drop.num_files; i++) {
  4020. NSURL *fileUrl = [NSURL fileURLWithPath:[pboard.pasteboardItems[(NSUInteger)i] stringForType:NSPasteboardTypeFileURL]];
  4021. if (!_sapp_strcpy(fileUrl.standardizedURL.path.UTF8String, _sapp_dropped_file_path_ptr(i), _sapp.drop.max_path_length)) {
  4022. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  4023. drop_failed = true;
  4024. break;
  4025. }
  4026. }
  4027. if (!drop_failed) {
  4028. if (_sapp_events_enabled()) {
  4029. _sapp_macos_mouse_update_from_nspoint(sender.draggingLocation, true);
  4030. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  4031. _sapp.event.modifiers = _sapp_macos_mods(nil);
  4032. _sapp_call_event(&_sapp.event);
  4033. }
  4034. }
  4035. else {
  4036. _sapp_clear_drop_buffer();
  4037. _sapp.drop.num_files = 0;
  4038. }
  4039. return YES;
  4040. }
  4041. #endif
  4042. return NO;
  4043. }
  4044. @end
  4045. @implementation _sapp_macos_view
  4046. #if defined(SOKOL_GLCORE)
  4047. - (void)timerFired:(id)sender {
  4048. _SOKOL_UNUSED(sender);
  4049. [self setNeedsDisplay:YES];
  4050. }
  4051. - (void)prepareOpenGL {
  4052. [super prepareOpenGL];
  4053. GLint swapInt = 1;
  4054. NSOpenGLContext* ctx = [_sapp.macos.view openGLContext];
  4055. [ctx setValues:&swapInt forParameter:NSOpenGLContextParameterSwapInterval];
  4056. [ctx makeCurrentContext];
  4057. }
  4058. #endif
  4059. _SOKOL_PRIVATE void _sapp_macos_poll_input_events(void) {
  4060. /*
  4061. NOTE: late event polling temporarily out-commented to check if this
  4062. causes infrequent and almost impossible to reproduce problems with the
  4063. window close events, see:
  4064. https://github.com/floooh/sokol/pull/483#issuecomment-805148815
  4065. const NSEventMask mask = NSEventMaskLeftMouseDown |
  4066. NSEventMaskLeftMouseUp|
  4067. NSEventMaskRightMouseDown |
  4068. NSEventMaskRightMouseUp |
  4069. NSEventMaskMouseMoved |
  4070. NSEventMaskLeftMouseDragged |
  4071. NSEventMaskRightMouseDragged |
  4072. NSEventMaskMouseEntered |
  4073. NSEventMaskMouseExited |
  4074. NSEventMaskKeyDown |
  4075. NSEventMaskKeyUp |
  4076. NSEventMaskCursorUpdate |
  4077. NSEventMaskScrollWheel |
  4078. NSEventMaskTabletPoint |
  4079. NSEventMaskTabletProximity |
  4080. NSEventMaskOtherMouseDown |
  4081. NSEventMaskOtherMouseUp |
  4082. NSEventMaskOtherMouseDragged |
  4083. NSEventMaskPressure |
  4084. NSEventMaskDirectTouch;
  4085. @autoreleasepool {
  4086. for (;;) {
  4087. // NOTE: using NSDefaultRunLoopMode here causes stuttering in the GL backend,
  4088. // see: https://github.com/floooh/sokol/issues/486
  4089. NSEvent* event = [NSApp nextEventMatchingMask:mask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES];
  4090. if (event == nil) {
  4091. break;
  4092. }
  4093. [NSApp sendEvent:event];
  4094. }
  4095. }
  4096. */
  4097. }
  4098. - (void)drawRect:(NSRect)rect {
  4099. _SOKOL_UNUSED(rect);
  4100. #if defined(_SAPP_ANY_GL)
  4101. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  4102. #endif
  4103. _sapp_timing_measure(&_sapp.timing);
  4104. /* Catch any last-moment input events */
  4105. _sapp_macos_poll_input_events();
  4106. @autoreleasepool {
  4107. _sapp_macos_frame();
  4108. }
  4109. #if defined(_SAPP_ANY_GL)
  4110. [[_sapp.macos.view openGLContext] flushBuffer];
  4111. #endif
  4112. }
  4113. - (BOOL)isOpaque {
  4114. return YES;
  4115. }
  4116. - (BOOL)canBecomeKeyView {
  4117. return YES;
  4118. }
  4119. - (BOOL)acceptsFirstResponder {
  4120. return YES;
  4121. }
  4122. - (void)updateTrackingAreas {
  4123. if (_sapp.macos.tracking_area != nil) {
  4124. [self removeTrackingArea:_sapp.macos.tracking_area];
  4125. _SAPP_OBJC_RELEASE(_sapp.macos.tracking_area);
  4126. }
  4127. const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
  4128. NSTrackingActiveInKeyWindow |
  4129. NSTrackingEnabledDuringMouseDrag |
  4130. NSTrackingCursorUpdate |
  4131. NSTrackingInVisibleRect |
  4132. NSTrackingAssumeInside;
  4133. _sapp.macos.tracking_area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
  4134. [self addTrackingArea:_sapp.macos.tracking_area];
  4135. [super updateTrackingAreas];
  4136. }
  4137. // helper function to make GL context active
  4138. static void _sapp_gl_make_current(void) {
  4139. #if defined(SOKOL_GLCORE)
  4140. [[_sapp.macos.view openGLContext] makeCurrentContext];
  4141. #endif
  4142. }
  4143. - (void)mouseEntered:(NSEvent*)event {
  4144. _sapp_gl_make_current();
  4145. _sapp_macos_mouse_update_from_nsevent(event, true);
  4146. /* don't send mouse enter/leave while dragging (so that it behaves the same as
  4147. on Windows while SetCapture is active
  4148. */
  4149. if (0 == _sapp.macos.mouse_buttons) {
  4150. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  4151. }
  4152. }
  4153. - (void)mouseExited:(NSEvent*)event {
  4154. _sapp_gl_make_current();
  4155. _sapp_macos_mouse_update_from_nsevent(event, true);
  4156. if (0 == _sapp.macos.mouse_buttons) {
  4157. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  4158. }
  4159. }
  4160. - (void)mouseDown:(NSEvent*)event {
  4161. _sapp_gl_make_current();
  4162. _sapp_macos_mouse_update_from_nsevent(event, false);
  4163. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_LEFT, _sapp_macos_mods(event));
  4164. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_LEFT);
  4165. }
  4166. - (void)mouseUp:(NSEvent*)event {
  4167. _sapp_gl_make_current();
  4168. _sapp_macos_mouse_update_from_nsevent(event, false);
  4169. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_LEFT, _sapp_macos_mods(event));
  4170. _sapp.macos.mouse_buttons &= ~(1<<SAPP_MOUSEBUTTON_LEFT);
  4171. }
  4172. - (void)rightMouseDown:(NSEvent*)event {
  4173. _sapp_gl_make_current();
  4174. _sapp_macos_mouse_update_from_nsevent(event, false);
  4175. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_RIGHT, _sapp_macos_mods(event));
  4176. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_RIGHT);
  4177. }
  4178. - (void)rightMouseUp:(NSEvent*)event {
  4179. _sapp_gl_make_current();
  4180. _sapp_macos_mouse_update_from_nsevent(event, false);
  4181. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_RIGHT, _sapp_macos_mods(event));
  4182. _sapp.macos.mouse_buttons &= ~(1<<SAPP_MOUSEBUTTON_RIGHT);
  4183. }
  4184. - (void)otherMouseDown:(NSEvent*)event {
  4185. _sapp_gl_make_current();
  4186. _sapp_macos_mouse_update_from_nsevent(event, false);
  4187. if (2 == event.buttonNumber) {
  4188. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_MIDDLE, _sapp_macos_mods(event));
  4189. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_MIDDLE);
  4190. }
  4191. }
  4192. - (void)otherMouseUp:(NSEvent*)event {
  4193. _sapp_gl_make_current();
  4194. _sapp_macos_mouse_update_from_nsevent(event, false);
  4195. if (2 == event.buttonNumber) {
  4196. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_MIDDLE, _sapp_macos_mods(event));
  4197. _sapp.macos.mouse_buttons &= (1<<SAPP_MOUSEBUTTON_MIDDLE);
  4198. }
  4199. }
  4200. - (void)otherMouseDragged:(NSEvent*)event {
  4201. _sapp_gl_make_current();
  4202. _sapp_macos_mouse_update_from_nsevent(event, false);
  4203. if (2 == event.buttonNumber) {
  4204. if (_sapp.mouse.locked) {
  4205. _sapp.mouse.dx = [event deltaX];
  4206. _sapp.mouse.dy = [event deltaY];
  4207. }
  4208. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  4209. }
  4210. }
  4211. - (void)mouseMoved:(NSEvent*)event {
  4212. _sapp_gl_make_current();
  4213. _sapp_macos_mouse_update_from_nsevent(event, false);
  4214. if (_sapp.mouse.locked) {
  4215. _sapp.mouse.dx = [event deltaX];
  4216. _sapp.mouse.dy = [event deltaY];
  4217. }
  4218. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID , _sapp_macos_mods(event));
  4219. }
  4220. - (void)mouseDragged:(NSEvent*)event {
  4221. _sapp_gl_make_current();
  4222. _sapp_macos_mouse_update_from_nsevent(event, false);
  4223. if (_sapp.mouse.locked) {
  4224. _sapp.mouse.dx = [event deltaX];
  4225. _sapp.mouse.dy = [event deltaY];
  4226. }
  4227. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID , _sapp_macos_mods(event));
  4228. }
  4229. - (void)rightMouseDragged:(NSEvent*)event {
  4230. _sapp_gl_make_current();
  4231. _sapp_macos_mouse_update_from_nsevent(event, false);
  4232. if (_sapp.mouse.locked) {
  4233. _sapp.mouse.dx = [event deltaX];
  4234. _sapp.mouse.dy = [event deltaY];
  4235. }
  4236. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  4237. }
  4238. - (void)scrollWheel:(NSEvent*)event {
  4239. _sapp_gl_make_current();
  4240. _sapp_macos_mouse_update_from_nsevent(event, true);
  4241. if (_sapp_events_enabled()) {
  4242. float dx = (float) event.scrollingDeltaX;
  4243. float dy = (float) event.scrollingDeltaY;
  4244. if (event.hasPreciseScrollingDeltas) {
  4245. dx *= 0.1;
  4246. dy *= 0.1;
  4247. }
  4248. if ((_sapp_absf(dx) > 0.0f) || (_sapp_absf(dy) > 0.0f)) {
  4249. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  4250. _sapp.event.modifiers = _sapp_macos_mods(event);
  4251. _sapp.event.scroll_x = dx;
  4252. _sapp.event.scroll_y = dy;
  4253. _sapp_call_event(&_sapp.event);
  4254. }
  4255. }
  4256. }
  4257. - (void)keyDown:(NSEvent*)event {
  4258. if (_sapp_events_enabled()) {
  4259. _sapp_gl_make_current();
  4260. const uint32_t mods = _sapp_macos_mods(event);
  4261. const sapp_keycode key_code = _sapp_translate_key(event.keyCode);
  4262. _sapp_macos_key_event(SAPP_EVENTTYPE_KEY_DOWN, key_code, event.isARepeat, mods);
  4263. const NSString* chars = event.characters;
  4264. const NSUInteger len = chars.length;
  4265. if (len > 0) {
  4266. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  4267. _sapp.event.modifiers = mods;
  4268. for (NSUInteger i = 0; i < len; i++) {
  4269. const unichar codepoint = [chars characterAtIndex:i];
  4270. if ((codepoint & 0xFF00) == 0xF700) {
  4271. continue;
  4272. }
  4273. _sapp.event.char_code = codepoint;
  4274. _sapp.event.key_repeat = event.isARepeat;
  4275. _sapp_call_event(&_sapp.event);
  4276. }
  4277. }
  4278. /* if this is a Cmd+V (paste), also send a CLIPBOARD_PASTE event */
  4279. if (_sapp.clipboard.enabled && (mods == SAPP_MODIFIER_SUPER) && (key_code == SAPP_KEYCODE_V)) {
  4280. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  4281. _sapp_call_event(&_sapp.event);
  4282. }
  4283. }
  4284. }
  4285. - (BOOL)performKeyEquivalent:(NSEvent*)event {
  4286. // fixes Ctrl-Tab keydown not triggering a keyDown event
  4287. //
  4288. // NOTE: it seems that Ctrl-F1 cannot be intercepted the same way, but since
  4289. // this enabled critical accessibility features that's probably a good thing.
  4290. switch (_sapp_translate_key(event.keyCode)) {
  4291. case SAPP_KEYCODE_TAB:
  4292. [_sapp.macos.view keyDown:event];
  4293. return YES;
  4294. default:
  4295. return NO;
  4296. }
  4297. }
  4298. - (void)keyUp:(NSEvent*)event {
  4299. _sapp_gl_make_current();
  4300. _sapp_macos_key_event(SAPP_EVENTTYPE_KEY_UP,
  4301. _sapp_translate_key(event.keyCode),
  4302. event.isARepeat,
  4303. _sapp_macos_mods(event));
  4304. }
  4305. - (void)flagsChanged:(NSEvent*)event {
  4306. const uint32_t old_f = _sapp.macos.flags_changed_store;
  4307. const uint32_t new_f = (uint32_t)event.modifierFlags;
  4308. _sapp.macos.flags_changed_store = new_f;
  4309. sapp_keycode key_code = SAPP_KEYCODE_INVALID;
  4310. bool down = false;
  4311. if ((new_f ^ old_f) & NSEventModifierFlagShift) {
  4312. key_code = SAPP_KEYCODE_LEFT_SHIFT;
  4313. down = 0 != (new_f & NSEventModifierFlagShift);
  4314. }
  4315. if ((new_f ^ old_f) & NSEventModifierFlagControl) {
  4316. key_code = SAPP_KEYCODE_LEFT_CONTROL;
  4317. down = 0 != (new_f & NSEventModifierFlagControl);
  4318. }
  4319. if ((new_f ^ old_f) & NSEventModifierFlagOption) {
  4320. key_code = SAPP_KEYCODE_LEFT_ALT;
  4321. down = 0 != (new_f & NSEventModifierFlagOption);
  4322. }
  4323. if ((new_f ^ old_f) & NSEventModifierFlagCommand) {
  4324. key_code = SAPP_KEYCODE_LEFT_SUPER;
  4325. down = 0 != (new_f & NSEventModifierFlagCommand);
  4326. }
  4327. if (key_code != SAPP_KEYCODE_INVALID) {
  4328. _sapp_macos_key_event(down ? SAPP_EVENTTYPE_KEY_DOWN : SAPP_EVENTTYPE_KEY_UP,
  4329. key_code,
  4330. false,
  4331. _sapp_macos_mods(event));
  4332. }
  4333. }
  4334. @end
  4335. #endif // macOS
  4336. // ██ ██████ ███████
  4337. // ██ ██ ██ ██
  4338. // ██ ██ ██ ███████
  4339. // ██ ██ ██ ██
  4340. // ██ ██████ ███████
  4341. //
  4342. // >>ios
  4343. #if defined(_SAPP_IOS)
  4344. _SOKOL_PRIVATE void _sapp_ios_discard_state(void) {
  4345. // NOTE: it's safe to call [release] on a nil object
  4346. _SAPP_OBJC_RELEASE(_sapp.ios.textfield_dlg);
  4347. _SAPP_OBJC_RELEASE(_sapp.ios.textfield);
  4348. #if defined(SOKOL_METAL)
  4349. _SAPP_OBJC_RELEASE(_sapp.ios.view_ctrl);
  4350. _SAPP_OBJC_RELEASE(_sapp.ios.mtl_device);
  4351. #else
  4352. _SAPP_OBJC_RELEASE(_sapp.ios.view_ctrl);
  4353. _SAPP_OBJC_RELEASE(_sapp.ios.eagl_ctx);
  4354. #endif
  4355. _SAPP_OBJC_RELEASE(_sapp.ios.view);
  4356. _SAPP_OBJC_RELEASE(_sapp.ios.window);
  4357. }
  4358. _SOKOL_PRIVATE void _sapp_ios_run(const sapp_desc* desc) {
  4359. _sapp_init_state(desc);
  4360. static int argc = 1;
  4361. static char* argv[] = { (char*)"sokol_app" };
  4362. UIApplicationMain(argc, argv, nil, NSStringFromClass([_sapp_app_delegate class]));
  4363. }
  4364. /* iOS entry function */
  4365. #if !defined(SOKOL_NO_ENTRY)
  4366. int main(int argc, char* argv[]) {
  4367. sapp_desc desc = sokol_main(argc, argv);
  4368. _sapp_ios_run(&desc);
  4369. return 0;
  4370. }
  4371. #endif /* SOKOL_NO_ENTRY */
  4372. _SOKOL_PRIVATE void _sapp_ios_app_event(sapp_event_type type) {
  4373. if (_sapp_events_enabled()) {
  4374. _sapp_init_event(type);
  4375. _sapp_call_event(&_sapp.event);
  4376. }
  4377. }
  4378. _SOKOL_PRIVATE void _sapp_ios_touch_event(sapp_event_type type, NSSet<UITouch *>* touches, UIEvent* event) {
  4379. if (_sapp_events_enabled()) {
  4380. _sapp_init_event(type);
  4381. NSEnumerator* enumerator = event.allTouches.objectEnumerator;
  4382. UITouch* ios_touch;
  4383. while ((ios_touch = [enumerator nextObject])) {
  4384. if ((_sapp.event.num_touches + 1) < SAPP_MAX_TOUCHPOINTS) {
  4385. CGPoint ios_pos = [ios_touch locationInView:_sapp.ios.view];
  4386. sapp_touchpoint* cur_point = &_sapp.event.touches[_sapp.event.num_touches++];
  4387. cur_point->identifier = (uintptr_t) ios_touch;
  4388. cur_point->pos_x = ios_pos.x * _sapp.dpi_scale;
  4389. cur_point->pos_y = ios_pos.y * _sapp.dpi_scale;
  4390. cur_point->changed = [touches containsObject:ios_touch];
  4391. }
  4392. }
  4393. if (_sapp.event.num_touches > 0) {
  4394. _sapp_call_event(&_sapp.event);
  4395. }
  4396. }
  4397. }
  4398. _SOKOL_PRIVATE void _sapp_ios_update_dimensions(void) {
  4399. CGRect screen_rect = UIScreen.mainScreen.bounds;
  4400. _sapp.framebuffer_width = (int)roundf(screen_rect.size.width * _sapp.dpi_scale);
  4401. _sapp.framebuffer_height = (int)roundf(screen_rect.size.height * _sapp.dpi_scale);
  4402. _sapp.window_width = (int)roundf(screen_rect.size.width);
  4403. _sapp.window_height = (int)roundf(screen_rect.size.height);
  4404. int cur_fb_width, cur_fb_height;
  4405. #if defined(SOKOL_METAL)
  4406. const CGSize fb_size = _sapp.ios.view.drawableSize;
  4407. cur_fb_width = (int)roundf(fb_size.width);
  4408. cur_fb_height = (int)roundf(fb_size.height);
  4409. #else
  4410. cur_fb_width = (int)roundf(_sapp.ios.view.drawableWidth);
  4411. cur_fb_height = (int)roundf(_sapp.ios.view.drawableHeight);
  4412. #endif
  4413. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  4414. (_sapp.framebuffer_height != cur_fb_height);
  4415. if (dim_changed) {
  4416. #if defined(SOKOL_METAL)
  4417. const CGSize drawable_size = { (CGFloat) _sapp.framebuffer_width, (CGFloat) _sapp.framebuffer_height };
  4418. _sapp.ios.view.drawableSize = drawable_size;
  4419. #else
  4420. // nothing to do here, GLKView correctly respects the view's contentScaleFactor
  4421. #endif
  4422. if (!_sapp.first_frame) {
  4423. _sapp_ios_app_event(SAPP_EVENTTYPE_RESIZED);
  4424. }
  4425. }
  4426. }
  4427. _SOKOL_PRIVATE void _sapp_ios_frame(void) {
  4428. _sapp_ios_update_dimensions();
  4429. _sapp_frame();
  4430. }
  4431. _SOKOL_PRIVATE void _sapp_ios_show_keyboard(bool shown) {
  4432. /* if not happened yet, create an invisible text field */
  4433. if (nil == _sapp.ios.textfield) {
  4434. _sapp.ios.textfield_dlg = [[_sapp_textfield_dlg alloc] init];
  4435. _sapp.ios.textfield = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];
  4436. _sapp.ios.textfield.keyboardType = UIKeyboardTypeDefault;
  4437. _sapp.ios.textfield.returnKeyType = UIReturnKeyDefault;
  4438. _sapp.ios.textfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
  4439. _sapp.ios.textfield.autocorrectionType = UITextAutocorrectionTypeNo;
  4440. _sapp.ios.textfield.spellCheckingType = UITextSpellCheckingTypeNo;
  4441. _sapp.ios.textfield.hidden = YES;
  4442. _sapp.ios.textfield.text = @"x";
  4443. _sapp.ios.textfield.delegate = _sapp.ios.textfield_dlg;
  4444. [_sapp.ios.view_ctrl.view addSubview:_sapp.ios.textfield];
  4445. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4446. selector:@selector(keyboardWasShown:)
  4447. name:UIKeyboardDidShowNotification object:nil];
  4448. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4449. selector:@selector(keyboardWillBeHidden:)
  4450. name:UIKeyboardWillHideNotification object:nil];
  4451. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4452. selector:@selector(keyboardDidChangeFrame:)
  4453. name:UIKeyboardDidChangeFrameNotification object:nil];
  4454. }
  4455. if (shown) {
  4456. /* setting the text field as first responder brings up the onscreen keyboard */
  4457. [_sapp.ios.textfield becomeFirstResponder];
  4458. }
  4459. else {
  4460. [_sapp.ios.textfield resignFirstResponder];
  4461. }
  4462. }
  4463. @implementation _sapp_app_delegate
  4464. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  4465. CGRect screen_rect = UIScreen.mainScreen.bounds;
  4466. _sapp.ios.window = [[UIWindow alloc] initWithFrame:screen_rect];
  4467. _sapp.window_width = (int)roundf(screen_rect.size.width);
  4468. _sapp.window_height = (int)roundf(screen_rect.size.height);
  4469. if (_sapp.desc.high_dpi) {
  4470. _sapp.dpi_scale = (float) UIScreen.mainScreen.nativeScale;
  4471. }
  4472. else {
  4473. _sapp.dpi_scale = 1.0f;
  4474. }
  4475. _sapp.framebuffer_width = (int)roundf(_sapp.window_width * _sapp.dpi_scale);
  4476. _sapp.framebuffer_height = (int)roundf(_sapp.window_height * _sapp.dpi_scale);
  4477. NSInteger max_fps = UIScreen.mainScreen.maximumFramesPerSecond;
  4478. #if defined(SOKOL_METAL)
  4479. _sapp.ios.mtl_device = MTLCreateSystemDefaultDevice();
  4480. _sapp.ios.view = [[_sapp_ios_view alloc] init];
  4481. _sapp.ios.view.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  4482. _sapp.ios.view.device = _sapp.ios.mtl_device;
  4483. _sapp.ios.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
  4484. _sapp.ios.view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  4485. _sapp.ios.view.sampleCount = (NSUInteger)_sapp.sample_count;
  4486. /* NOTE: iOS MTKView seems to ignore thew view's contentScaleFactor
  4487. and automatically renders at Retina resolution. We'll disable
  4488. autoResize and instead do the resizing in _sapp_ios_update_dimensions()
  4489. */
  4490. _sapp.ios.view.autoResizeDrawable = false;
  4491. _sapp.ios.view.userInteractionEnabled = YES;
  4492. _sapp.ios.view.multipleTouchEnabled = YES;
  4493. _sapp.ios.view_ctrl = [[UIViewController alloc] init];
  4494. _sapp.ios.view_ctrl.modalPresentationStyle = UIModalPresentationFullScreen;
  4495. _sapp.ios.view_ctrl.view = _sapp.ios.view;
  4496. _sapp.ios.window.rootViewController = _sapp.ios.view_ctrl;
  4497. #else
  4498. _sapp.ios.eagl_ctx = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
  4499. _sapp.ios.view = [[_sapp_ios_view alloc] initWithFrame:screen_rect];
  4500. _sapp.ios.view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
  4501. _sapp.ios.view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
  4502. _sapp.ios.view.drawableStencilFormat = GLKViewDrawableStencilFormatNone;
  4503. GLKViewDrawableMultisample msaa = _sapp.sample_count > 1 ? GLKViewDrawableMultisample4X : GLKViewDrawableMultisampleNone;
  4504. _sapp.ios.view.drawableMultisample = msaa;
  4505. _sapp.ios.view.context = _sapp.ios.eagl_ctx;
  4506. _sapp.ios.view.enableSetNeedsDisplay = NO;
  4507. _sapp.ios.view.userInteractionEnabled = YES;
  4508. _sapp.ios.view.multipleTouchEnabled = YES;
  4509. // on GLKView, contentScaleFactor appears to work just fine!
  4510. if (_sapp.desc.high_dpi) {
  4511. _sapp.ios.view.contentScaleFactor = _sapp.dpi_scale;
  4512. }
  4513. else {
  4514. _sapp.ios.view.contentScaleFactor = 1.0;
  4515. }
  4516. _sapp.ios.view_ctrl = [[GLKViewController alloc] init];
  4517. _sapp.ios.view_ctrl.view = _sapp.ios.view;
  4518. _sapp.ios.view_ctrl.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  4519. _sapp.ios.window.rootViewController = _sapp.ios.view_ctrl;
  4520. #endif
  4521. [_sapp.ios.window makeKeyAndVisible];
  4522. _sapp.valid = true;
  4523. return YES;
  4524. }
  4525. - (void)applicationWillResignActive:(UIApplication *)application {
  4526. if (!_sapp.ios.suspended) {
  4527. _sapp.ios.suspended = true;
  4528. _sapp_ios_app_event(SAPP_EVENTTYPE_SUSPENDED);
  4529. }
  4530. }
  4531. - (void)applicationDidBecomeActive:(UIApplication *)application {
  4532. if (_sapp.ios.suspended) {
  4533. _sapp.ios.suspended = false;
  4534. _sapp_ios_app_event(SAPP_EVENTTYPE_RESUMED);
  4535. }
  4536. }
  4537. /* NOTE: this method will rarely ever be called, iOS application
  4538. which are terminated by the user are usually killed via signal 9
  4539. by the operating system.
  4540. */
  4541. - (void)applicationWillTerminate:(UIApplication *)application {
  4542. _SOKOL_UNUSED(application);
  4543. _sapp_call_cleanup();
  4544. _sapp_ios_discard_state();
  4545. _sapp_discard_state();
  4546. }
  4547. @end
  4548. @implementation _sapp_textfield_dlg
  4549. - (void)keyboardWasShown:(NSNotification*)notif {
  4550. _sapp.onscreen_keyboard_shown = true;
  4551. /* query the keyboard's size, and modify the content view's size */
  4552. if (_sapp.desc.ios_keyboard_resizes_canvas) {
  4553. NSDictionary* info = notif.userInfo;
  4554. CGFloat kbd_h = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
  4555. CGRect view_frame = UIScreen.mainScreen.bounds;
  4556. view_frame.size.height -= kbd_h;
  4557. _sapp.ios.view.frame = view_frame;
  4558. }
  4559. }
  4560. - (void)keyboardWillBeHidden:(NSNotification*)notif {
  4561. _sapp.onscreen_keyboard_shown = false;
  4562. if (_sapp.desc.ios_keyboard_resizes_canvas) {
  4563. _sapp.ios.view.frame = UIScreen.mainScreen.bounds;
  4564. }
  4565. }
  4566. - (void)keyboardDidChangeFrame:(NSNotification*)notif {
  4567. /* this is for the case when the screen rotation changes while the keyboard is open */
  4568. if (_sapp.onscreen_keyboard_shown && _sapp.desc.ios_keyboard_resizes_canvas) {
  4569. NSDictionary* info = notif.userInfo;
  4570. CGFloat kbd_h = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
  4571. CGRect view_frame = UIScreen.mainScreen.bounds;
  4572. view_frame.size.height -= kbd_h;
  4573. _sapp.ios.view.frame = view_frame;
  4574. }
  4575. }
  4576. - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
  4577. if (_sapp_events_enabled()) {
  4578. const NSUInteger len = string.length;
  4579. if (len > 0) {
  4580. for (NSUInteger i = 0; i < len; i++) {
  4581. unichar c = [string characterAtIndex:i];
  4582. if (c >= 32) {
  4583. /* ignore surrogates for now */
  4584. if ((c < 0xD800) || (c > 0xDFFF)) {
  4585. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  4586. _sapp.event.char_code = c;
  4587. _sapp_call_event(&_sapp.event);
  4588. }
  4589. }
  4590. if (c <= 32) {
  4591. sapp_keycode k = SAPP_KEYCODE_INVALID;
  4592. switch (c) {
  4593. case 10: k = SAPP_KEYCODE_ENTER; break;
  4594. case 32: k = SAPP_KEYCODE_SPACE; break;
  4595. default: break;
  4596. }
  4597. if (k != SAPP_KEYCODE_INVALID) {
  4598. _sapp_init_event(SAPP_EVENTTYPE_KEY_DOWN);
  4599. _sapp.event.key_code = k;
  4600. _sapp_call_event(&_sapp.event);
  4601. _sapp_init_event(SAPP_EVENTTYPE_KEY_UP);
  4602. _sapp.event.key_code = k;
  4603. _sapp_call_event(&_sapp.event);
  4604. }
  4605. }
  4606. }
  4607. }
  4608. else {
  4609. /* this was a backspace */
  4610. _sapp_init_event(SAPP_EVENTTYPE_KEY_DOWN);
  4611. _sapp.event.key_code = SAPP_KEYCODE_BACKSPACE;
  4612. _sapp_call_event(&_sapp.event);
  4613. _sapp_init_event(SAPP_EVENTTYPE_KEY_UP);
  4614. _sapp.event.key_code = SAPP_KEYCODE_BACKSPACE;
  4615. _sapp_call_event(&_sapp.event);
  4616. }
  4617. }
  4618. return NO;
  4619. }
  4620. @end
  4621. @implementation _sapp_ios_view
  4622. - (void)drawRect:(CGRect)rect {
  4623. _SOKOL_UNUSED(rect);
  4624. #if defined(_SAPP_ANY_GL)
  4625. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  4626. #endif
  4627. _sapp_timing_measure(&_sapp.timing);
  4628. @autoreleasepool {
  4629. _sapp_ios_frame();
  4630. }
  4631. }
  4632. - (BOOL)isOpaque {
  4633. return YES;
  4634. }
  4635. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4636. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_BEGAN, touches, event);
  4637. }
  4638. - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4639. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_MOVED, touches, event);
  4640. }
  4641. - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4642. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_ENDED, touches, event);
  4643. }
  4644. - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4645. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_CANCELLED, touches, event);
  4646. }
  4647. @end
  4648. #endif /* TARGET_OS_IPHONE */
  4649. #endif /* _SAPP_APPLE */
  4650. // ███████ ███ ███ ███████ ██████ ██████ ██ ██████ ████████ ███████ ███ ██
  4651. // ██ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  4652. // █████ ██ ████ ██ ███████ ██ ██████ ██ ██████ ██ █████ ██ ██ ██
  4653. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  4654. // ███████ ██ ██ ███████ ██████ ██ ██ ██ ██ ██ ███████ ██ ████
  4655. //
  4656. // >>emscripten
  4657. #if defined(_SAPP_EMSCRIPTEN)
  4658. #if defined(EM_JS_DEPS)
  4659. EM_JS_DEPS(sokol_app, "$withStackSave,$stringToUTF8OnStack,$findCanvasEventTarget")
  4660. #endif
  4661. #ifdef __cplusplus
  4662. extern "C" {
  4663. #endif
  4664. typedef void (*_sapp_html5_fetch_callback) (const sapp_html5_fetch_response*);
  4665. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_onpaste(const char* str) {
  4666. if (_sapp.clipboard.enabled) {
  4667. _sapp_strcpy(str, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  4668. if (_sapp_events_enabled()) {
  4669. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  4670. _sapp_call_event(&_sapp.event);
  4671. }
  4672. }
  4673. }
  4674. /* https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload */
  4675. EMSCRIPTEN_KEEPALIVE int _sapp_html5_get_ask_leave_site(void) {
  4676. return _sapp.html5_ask_leave_site ? 1 : 0;
  4677. }
  4678. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_begin_drop(int num) {
  4679. if (!_sapp.drop.enabled) {
  4680. return;
  4681. }
  4682. if (num < 0) {
  4683. num = 0;
  4684. }
  4685. if (num > _sapp.drop.max_files) {
  4686. num = _sapp.drop.max_files;
  4687. }
  4688. _sapp.drop.num_files = num;
  4689. _sapp_clear_drop_buffer();
  4690. }
  4691. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_drop(int i, const char* name) {
  4692. /* NOTE: name is only the filename part, not a path */
  4693. if (!_sapp.drop.enabled) {
  4694. return;
  4695. }
  4696. if (0 == name) {
  4697. return;
  4698. }
  4699. SOKOL_ASSERT(_sapp.drop.num_files <= _sapp.drop.max_files);
  4700. if ((i < 0) || (i >= _sapp.drop.num_files)) {
  4701. return;
  4702. }
  4703. if (!_sapp_strcpy(name, _sapp_dropped_file_path_ptr(i), _sapp.drop.max_path_length)) {
  4704. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  4705. _sapp.drop.num_files = 0;
  4706. }
  4707. }
  4708. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_end_drop(int x, int y, int mods) {
  4709. if (!_sapp.drop.enabled) {
  4710. return;
  4711. }
  4712. if (0 == _sapp.drop.num_files) {
  4713. /* there was an error copying the filenames */
  4714. _sapp_clear_drop_buffer();
  4715. return;
  4716. }
  4717. if (_sapp_events_enabled()) {
  4718. _sapp.mouse.x = (float)x * _sapp.dpi_scale;
  4719. _sapp.mouse.y = (float)y * _sapp.dpi_scale;
  4720. _sapp.mouse.dx = 0.0f;
  4721. _sapp.mouse.dy = 0.0f;
  4722. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  4723. // see sapp_js_add_dragndrop_listeners for mods constants
  4724. if (mods & 1) { _sapp.event.modifiers |= SAPP_MODIFIER_SHIFT; }
  4725. if (mods & 2) { _sapp.event.modifiers |= SAPP_MODIFIER_CTRL; }
  4726. if (mods & 4) { _sapp.event.modifiers |= SAPP_MODIFIER_ALT; }
  4727. if (mods & 8) { _sapp.event.modifiers |= SAPP_MODIFIER_SUPER; }
  4728. _sapp_call_event(&_sapp.event);
  4729. }
  4730. }
  4731. 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) {
  4732. sapp_html5_fetch_response response;
  4733. _sapp_clear(&response, sizeof(response));
  4734. response.succeeded = (0 != success);
  4735. response.error_code = (sapp_html5_fetch_error) error_code;
  4736. response.file_index = index;
  4737. response.data.ptr = buf_ptr;
  4738. response.data.size = fetched_size;
  4739. response.buffer.ptr = buf_ptr;
  4740. response.buffer.size = buf_size;
  4741. response.user_data = user_data;
  4742. callback(&response);
  4743. }
  4744. #ifdef __cplusplus
  4745. } /* extern "C" */
  4746. #endif
  4747. EM_JS(void, sapp_js_add_beforeunload_listener, (void), {
  4748. Module.sokol_beforeunload = (event) => {
  4749. if (__sapp_html5_get_ask_leave_site() != 0) {
  4750. event.preventDefault();
  4751. event.returnValue = ' ';
  4752. }
  4753. };
  4754. window.addEventListener('beforeunload', Module.sokol_beforeunload);
  4755. })
  4756. EM_JS(void, sapp_js_remove_beforeunload_listener, (void), {
  4757. window.removeEventListener('beforeunload', Module.sokol_beforeunload);
  4758. })
  4759. EM_JS(void, sapp_js_add_clipboard_listener, (void), {
  4760. Module.sokol_paste = (event) => {
  4761. const pasted_str = event.clipboardData.getData('text');
  4762. withStackSave(() => {
  4763. const cstr = stringToUTF8OnStack(pasted_str);
  4764. __sapp_emsc_onpaste(cstr);
  4765. });
  4766. };
  4767. window.addEventListener('paste', Module.sokol_paste);
  4768. })
  4769. EM_JS(void, sapp_js_remove_clipboard_listener, (void), {
  4770. window.removeEventListener('paste', Module.sokol_paste);
  4771. })
  4772. EM_JS(void, sapp_js_write_clipboard, (const char* c_str), {
  4773. const str = UTF8ToString(c_str);
  4774. const ta = document.createElement('textarea');
  4775. ta.setAttribute('autocomplete', 'off');
  4776. ta.setAttribute('autocorrect', 'off');
  4777. ta.setAttribute('autocapitalize', 'off');
  4778. ta.setAttribute('spellcheck', 'false');
  4779. ta.style.left = -100 + 'px';
  4780. ta.style.top = -100 + 'px';
  4781. ta.style.height = 1;
  4782. ta.style.width = 1;
  4783. ta.value = str;
  4784. document.body.appendChild(ta);
  4785. ta.select();
  4786. document.execCommand('copy');
  4787. document.body.removeChild(ta);
  4788. })
  4789. _SOKOL_PRIVATE void _sapp_emsc_set_clipboard_string(const char* str) {
  4790. sapp_js_write_clipboard(str);
  4791. }
  4792. EM_JS(void, sapp_js_add_dragndrop_listeners, (void), {
  4793. Module.sokol_drop_files = [];
  4794. Module.sokol_dragenter = (event) => {
  4795. event.stopPropagation();
  4796. event.preventDefault();
  4797. };
  4798. Module.sokol_dragleave = (event) => {
  4799. event.stopPropagation();
  4800. event.preventDefault();
  4801. };
  4802. Module.sokol_dragover = (event) => {
  4803. event.stopPropagation();
  4804. event.preventDefault();
  4805. };
  4806. Module.sokol_drop = (event) => {
  4807. event.stopPropagation();
  4808. event.preventDefault();
  4809. const files = event.dataTransfer.files;
  4810. Module.sokol_dropped_files = files;
  4811. __sapp_emsc_begin_drop(files.length);
  4812. for (let i = 0; i < files.length; i++) {
  4813. withStackSave(() => {
  4814. const cstr = stringToUTF8OnStack(files[i].name);
  4815. __sapp_emsc_drop(i, cstr);
  4816. });
  4817. }
  4818. let mods = 0;
  4819. if (event.shiftKey) { mods |= 1; }
  4820. if (event.ctrlKey) { mods |= 2; }
  4821. if (event.altKey) { mods |= 4; }
  4822. if (event.metaKey) { mods |= 8; }
  4823. // FIXME? see computation of targetX/targetY in emscripten via getClientBoundingRect
  4824. __sapp_emsc_end_drop(event.clientX, event.clientY, mods);
  4825. };
  4826. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4827. const canvas = Module.sapp_emsc_target;
  4828. canvas.addEventListener('dragenter', Module.sokol_dragenter, false);
  4829. canvas.addEventListener('dragleave', Module.sokol_dragleave, false);
  4830. canvas.addEventListener('dragover', Module.sokol_dragover, false);
  4831. canvas.addEventListener('drop', Module.sokol_drop, false);
  4832. })
  4833. EM_JS(uint32_t, sapp_js_dropped_file_size, (int index), {
  4834. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4835. const files = Module.sokol_dropped_files;
  4836. if ((index < 0) || (index >= files.length)) {
  4837. return 0;
  4838. }
  4839. else {
  4840. return files[index].size;
  4841. }
  4842. })
  4843. 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), {
  4844. const reader = new FileReader();
  4845. reader.onload = (loadEvent) => {
  4846. const content = loadEvent.target.result;
  4847. if (content.byteLength > buf_size) {
  4848. // SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL
  4849. __sapp_emsc_invoke_fetch_cb(index, 0, 1, callback, 0, buf_ptr, buf_size, user_data);
  4850. }
  4851. else {
  4852. HEAPU8.set(new Uint8Array(content), buf_ptr);
  4853. __sapp_emsc_invoke_fetch_cb(index, 1, 0, callback, content.byteLength, buf_ptr, buf_size, user_data);
  4854. }
  4855. };
  4856. reader.onerror = () => {
  4857. // SAPP_HTML5_FETCH_ERROR_OTHER
  4858. __sapp_emsc_invoke_fetch_cb(index, 0, 2, callback, 0, buf_ptr, buf_size, user_data);
  4859. };
  4860. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4861. const files = Module.sokol_dropped_files;
  4862. reader.readAsArrayBuffer(files[index]);
  4863. })
  4864. EM_JS(void, sapp_js_remove_dragndrop_listeners, (void), {
  4865. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4866. const canvas = Module.sapp_emsc_target;
  4867. canvas.removeEventListener('dragenter', Module.sokol_dragenter);
  4868. canvas.removeEventListener('dragleave', Module.sokol_dragleave);
  4869. canvas.removeEventListener('dragover', Module.sokol_dragover);
  4870. canvas.removeEventListener('drop', Module.sokol_drop);
  4871. })
  4872. EM_JS(void, sapp_js_init, (const char* c_str_target_selector, const char* c_str_document_title), {
  4873. if (c_str_document_title !== 0) {
  4874. document.title = UTF8ToString(c_str_document_title);
  4875. }
  4876. const target_selector_str = UTF8ToString(c_str_target_selector);
  4877. if (Module['canvas'] !== undefined) {
  4878. if (typeof Module['canvas'] === 'object') {
  4879. specialHTMLTargets[target_selector_str] = Module['canvas'];
  4880. } else {
  4881. console.warn("sokol_app.h: Module['canvas'] is set but is not an object");
  4882. }
  4883. }
  4884. Module.sapp_emsc_target = findCanvasEventTarget(target_selector_str);
  4885. if (!Module.sapp_emsc_target) {
  4886. console.warn("sokol_app.h: can't find html5_canvas_selector ", target_selector_str);
  4887. }
  4888. if (!Module.sapp_emsc_target.requestPointerLock) {
  4889. console.warn("sokol_app.h: target doesn't support requestPointerLock: ", target_selector_str);
  4890. }
  4891. })
  4892. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_pointerlockchange_cb(int emsc_type, const EmscriptenPointerlockChangeEvent* emsc_event, void* user_data) {
  4893. _SOKOL_UNUSED(emsc_type);
  4894. _SOKOL_UNUSED(user_data);
  4895. _sapp.mouse.locked = emsc_event->isActive;
  4896. return EM_TRUE;
  4897. }
  4898. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_pointerlockerror_cb(int emsc_type, const void* reserved, void* user_data) {
  4899. _SOKOL_UNUSED(emsc_type);
  4900. _SOKOL_UNUSED(reserved);
  4901. _SOKOL_UNUSED(user_data);
  4902. _sapp.mouse.locked = false;
  4903. _sapp.emsc.mouse_lock_requested = false;
  4904. return true;
  4905. }
  4906. EM_JS(void, sapp_js_request_pointerlock, (void), {
  4907. if (Module.sapp_emsc_target) {
  4908. if (Module.sapp_emsc_target.requestPointerLock) {
  4909. Module.sapp_emsc_target.requestPointerLock();
  4910. }
  4911. }
  4912. })
  4913. EM_JS(void, sapp_js_exit_pointerlock, (void), {
  4914. if (document.exitPointerLock) {
  4915. document.exitPointerLock();
  4916. }
  4917. })
  4918. _SOKOL_PRIVATE void _sapp_emsc_lock_mouse(bool lock) {
  4919. if (lock) {
  4920. /* request mouse-lock during event handler invocation (see _sapp_emsc_update_mouse_lock_state) */
  4921. _sapp.emsc.mouse_lock_requested = true;
  4922. }
  4923. else {
  4924. /* NOTE: the _sapp.mouse_locked state will be set in the pointerlockchange callback */
  4925. _sapp.emsc.mouse_lock_requested = false;
  4926. sapp_js_exit_pointerlock();
  4927. }
  4928. }
  4929. /* called from inside event handlers to check if mouse lock had been requested,
  4930. and if yes, actually enter mouse lock.
  4931. */
  4932. _SOKOL_PRIVATE void _sapp_emsc_update_mouse_lock_state(void) {
  4933. if (_sapp.emsc.mouse_lock_requested) {
  4934. _sapp.emsc.mouse_lock_requested = false;
  4935. sapp_js_request_pointerlock();
  4936. }
  4937. }
  4938. // set mouse cursor type
  4939. EM_JS(void, sapp_js_set_cursor, (int cursor_type, int shown), {
  4940. if (Module.sapp_emsc_target) {
  4941. let cursor;
  4942. if (shown === 0) {
  4943. cursor = "none";
  4944. }
  4945. else switch (cursor_type) {
  4946. case 0: cursor = "auto"; break; // SAPP_MOUSECURSOR_DEFAULT
  4947. case 1: cursor = "default"; break; // SAPP_MOUSECURSOR_ARROW
  4948. case 2: cursor = "text"; break; // SAPP_MOUSECURSOR_IBEAM
  4949. case 3: cursor = "crosshair"; break; // SAPP_MOUSECURSOR_CROSSHAIR
  4950. case 4: cursor = "pointer"; break; // SAPP_MOUSECURSOR_POINTING_HAND
  4951. case 5: cursor = "ew-resize"; break; // SAPP_MOUSECURSOR_RESIZE_EW
  4952. case 6: cursor = "ns-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NS
  4953. case 7: cursor = "nwse-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NWSE
  4954. case 8: cursor = "nesw-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NESW
  4955. case 9: cursor = "all-scroll"; break; // SAPP_MOUSECURSOR_RESIZE_ALL
  4956. case 10: cursor = "not-allowed"; break; // SAPP_MOUSECURSOR_NOT_ALLOWED
  4957. default: cursor = "auto"; break;
  4958. }
  4959. Module.sapp_emsc_target.style.cursor = cursor;
  4960. }
  4961. })
  4962. _SOKOL_PRIVATE void _sapp_emsc_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  4963. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  4964. sapp_js_set_cursor((int)cursor, shown ? 1 : 0);
  4965. }
  4966. /* JS helper functions to update browser tab favicon */
  4967. EM_JS(void, sapp_js_clear_favicon, (void), {
  4968. const link = document.getElementById('sokol-app-favicon');
  4969. if (link) {
  4970. document.head.removeChild(link);
  4971. }
  4972. })
  4973. EM_JS(void, sapp_js_set_favicon, (int w, int h, const uint8_t* pixels), {
  4974. const canvas = document.createElement('canvas');
  4975. canvas.width = w;
  4976. canvas.height = h;
  4977. const ctx = canvas.getContext('2d');
  4978. const img_data = ctx.createImageData(w, h);
  4979. img_data.data.set(HEAPU8.subarray(pixels, pixels + w*h*4));
  4980. ctx.putImageData(img_data, 0, 0);
  4981. const new_link = document.createElement('link');
  4982. new_link.id = 'sokol-app-favicon';
  4983. new_link.rel = 'shortcut icon';
  4984. new_link.href = canvas.toDataURL();
  4985. document.head.appendChild(new_link);
  4986. })
  4987. _SOKOL_PRIVATE void _sapp_emsc_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  4988. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  4989. sapp_js_clear_favicon();
  4990. // find the best matching image candidate for 16x16 pixels
  4991. int img_index = _sapp_image_bestmatch(icon_desc->images, num_images, 16, 16);
  4992. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  4993. sapp_js_set_favicon(img_desc->width, img_desc->height, (const uint8_t*) img_desc->pixels.ptr);
  4994. }
  4995. _SOKOL_PRIVATE uint32_t _sapp_emsc_mouse_button_mods(uint16_t buttons) {
  4996. uint32_t m = 0;
  4997. if (0 != (buttons & (1<<0))) { m |= SAPP_MODIFIER_LMB; }
  4998. if (0 != (buttons & (1<<1))) { m |= SAPP_MODIFIER_RMB; } // not a bug
  4999. if (0 != (buttons & (1<<2))) { m |= SAPP_MODIFIER_MMB; } // not a bug
  5000. return m;
  5001. }
  5002. _SOKOL_PRIVATE uint32_t _sapp_emsc_mouse_event_mods(const EmscriptenMouseEvent* ev) {
  5003. uint32_t m = 0;
  5004. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  5005. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  5006. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  5007. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  5008. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  5009. return m;
  5010. }
  5011. _SOKOL_PRIVATE uint32_t _sapp_emsc_key_event_mods(const EmscriptenKeyboardEvent* ev) {
  5012. uint32_t m = 0;
  5013. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  5014. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  5015. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  5016. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  5017. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  5018. return m;
  5019. }
  5020. _SOKOL_PRIVATE uint32_t _sapp_emsc_touch_event_mods(const EmscriptenTouchEvent* ev) {
  5021. uint32_t m = 0;
  5022. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  5023. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  5024. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  5025. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  5026. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  5027. return m;
  5028. }
  5029. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_size_changed(int event_type, const EmscriptenUiEvent* ui_event, void* user_data) {
  5030. _SOKOL_UNUSED(event_type);
  5031. _SOKOL_UNUSED(user_data);
  5032. double w, h;
  5033. emscripten_get_element_css_size(_sapp.html5_canvas_selector, &w, &h);
  5034. /* The above method might report zero when toggling HTML5 fullscreen,
  5035. in that case use the window's inner width reported by the
  5036. emscripten event. This works ok when toggling *into* fullscreen
  5037. but doesn't properly restore the previous canvas size when switching
  5038. back from fullscreen.
  5039. In general, due to the HTML5's fullscreen API's flaky nature it is
  5040. recommended to use 'soft fullscreen' (stretching the WebGL canvas
  5041. over the browser windows client rect) with a CSS definition like this:
  5042. position: absolute;
  5043. top: 0px;
  5044. left: 0px;
  5045. margin: 0px;
  5046. border: 0;
  5047. width: 100%;
  5048. height: 100%;
  5049. overflow: hidden;
  5050. display: block;
  5051. */
  5052. if (w < 1.0) {
  5053. w = ui_event->windowInnerWidth;
  5054. }
  5055. else {
  5056. _sapp.window_width = (int)roundf(w);
  5057. }
  5058. if (h < 1.0) {
  5059. h = ui_event->windowInnerHeight;
  5060. }
  5061. else {
  5062. _sapp.window_height = (int)roundf(h);
  5063. }
  5064. if (_sapp.desc.high_dpi) {
  5065. _sapp.dpi_scale = emscripten_get_device_pixel_ratio();
  5066. }
  5067. _sapp.framebuffer_width = (int)roundf(w * _sapp.dpi_scale);
  5068. _sapp.framebuffer_height = (int)roundf(h * _sapp.dpi_scale);
  5069. SOKOL_ASSERT((_sapp.framebuffer_width > 0) && (_sapp.framebuffer_height > 0));
  5070. emscripten_set_canvas_element_size(_sapp.html5_canvas_selector, _sapp.framebuffer_width, _sapp.framebuffer_height);
  5071. #if defined(SOKOL_WGPU)
  5072. // on WebGPU: recreate size-dependent rendering surfaces
  5073. _sapp_wgpu_size_changed();
  5074. #endif
  5075. if (_sapp_events_enabled()) {
  5076. _sapp_init_event(SAPP_EVENTTYPE_RESIZED);
  5077. _sapp_call_event(&_sapp.event);
  5078. }
  5079. return true;
  5080. }
  5081. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_mouse_cb(int emsc_type, const EmscriptenMouseEvent* emsc_event, void* user_data) {
  5082. _SOKOL_UNUSED(user_data);
  5083. bool consume_event = !_sapp.desc.html5_bubble_mouse_events;
  5084. _sapp.emsc.mouse_buttons = emsc_event->buttons;
  5085. if (_sapp.mouse.locked) {
  5086. _sapp.mouse.dx = (float) emsc_event->movementX;
  5087. _sapp.mouse.dy = (float) emsc_event->movementY;
  5088. } else {
  5089. float new_x = emsc_event->targetX * _sapp.dpi_scale;
  5090. float new_y = emsc_event->targetY * _sapp.dpi_scale;
  5091. if (_sapp.mouse.pos_valid) {
  5092. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  5093. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  5094. }
  5095. _sapp.mouse.x = new_x;
  5096. _sapp.mouse.y = new_y;
  5097. _sapp.mouse.pos_valid = true;
  5098. }
  5099. if (_sapp_events_enabled() && (emsc_event->button >= 0) && (emsc_event->button < SAPP_MAX_MOUSEBUTTONS)) {
  5100. sapp_event_type type;
  5101. bool is_button_event = false;
  5102. bool clear_dxdy = false;
  5103. switch (emsc_type) {
  5104. case EMSCRIPTEN_EVENT_MOUSEDOWN:
  5105. type = SAPP_EVENTTYPE_MOUSE_DOWN;
  5106. is_button_event = true;
  5107. break;
  5108. case EMSCRIPTEN_EVENT_MOUSEUP:
  5109. type = SAPP_EVENTTYPE_MOUSE_UP;
  5110. is_button_event = true;
  5111. break;
  5112. case EMSCRIPTEN_EVENT_MOUSEMOVE:
  5113. type = SAPP_EVENTTYPE_MOUSE_MOVE;
  5114. break;
  5115. case EMSCRIPTEN_EVENT_MOUSEENTER:
  5116. type = SAPP_EVENTTYPE_MOUSE_ENTER;
  5117. clear_dxdy = true;
  5118. break;
  5119. case EMSCRIPTEN_EVENT_MOUSELEAVE:
  5120. type = SAPP_EVENTTYPE_MOUSE_LEAVE;
  5121. clear_dxdy = true;
  5122. break;
  5123. default:
  5124. type = SAPP_EVENTTYPE_INVALID;
  5125. break;
  5126. }
  5127. if (clear_dxdy) {
  5128. _sapp.mouse.dx = 0.0f;
  5129. _sapp.mouse.dy = 0.0f;
  5130. }
  5131. if (type != SAPP_EVENTTYPE_INVALID) {
  5132. _sapp_init_event(type);
  5133. _sapp.event.modifiers = _sapp_emsc_mouse_event_mods(emsc_event);
  5134. if (is_button_event) {
  5135. switch (emsc_event->button) {
  5136. case 0: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_LEFT; break;
  5137. case 1: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_MIDDLE; break;
  5138. case 2: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_RIGHT; break;
  5139. default: _sapp.event.mouse_button = (sapp_mousebutton)emsc_event->button; break;
  5140. }
  5141. } else {
  5142. _sapp.event.mouse_button = SAPP_MOUSEBUTTON_INVALID;
  5143. }
  5144. consume_event |= _sapp_call_event(&_sapp.event);
  5145. }
  5146. // mouse lock can only be activated in mouse button events (not in move, enter or leave)
  5147. if (is_button_event) {
  5148. _sapp_emsc_update_mouse_lock_state();
  5149. }
  5150. }
  5151. return consume_event;
  5152. }
  5153. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_wheel_cb(int emsc_type, const EmscriptenWheelEvent* emsc_event, void* user_data) {
  5154. _SOKOL_UNUSED(emsc_type);
  5155. _SOKOL_UNUSED(user_data);
  5156. bool consume_event = !_sapp.desc.html5_bubble_wheel_events;
  5157. _sapp.emsc.mouse_buttons = emsc_event->mouse.buttons;
  5158. if (_sapp_events_enabled()) {
  5159. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  5160. _sapp.event.modifiers = _sapp_emsc_mouse_event_mods(&emsc_event->mouse);
  5161. /* see https://github.com/floooh/sokol/issues/339 */
  5162. float scale;
  5163. switch (emsc_event->deltaMode) {
  5164. case DOM_DELTA_PIXEL: scale = -0.04f; break;
  5165. case DOM_DELTA_LINE: scale = -1.33f; break;
  5166. case DOM_DELTA_PAGE: scale = -10.0f; break; // FIXME: this is a guess
  5167. default: scale = -0.1f; break; // shouldn't happen
  5168. }
  5169. _sapp.event.scroll_x = scale * (float)emsc_event->deltaX;
  5170. _sapp.event.scroll_y = scale * (float)emsc_event->deltaY;
  5171. consume_event |= _sapp_call_event(&_sapp.event);
  5172. }
  5173. _sapp_emsc_update_mouse_lock_state();
  5174. return consume_event;
  5175. }
  5176. static struct {
  5177. const char* str;
  5178. sapp_keycode code;
  5179. } _sapp_emsc_keymap[] = {
  5180. { "Backspace", SAPP_KEYCODE_BACKSPACE },
  5181. { "Tab", SAPP_KEYCODE_TAB },
  5182. { "Enter", SAPP_KEYCODE_ENTER },
  5183. { "ShiftLeft", SAPP_KEYCODE_LEFT_SHIFT },
  5184. { "ShiftRight", SAPP_KEYCODE_RIGHT_SHIFT },
  5185. { "ControlLeft", SAPP_KEYCODE_LEFT_CONTROL },
  5186. { "ControlRight", SAPP_KEYCODE_RIGHT_CONTROL },
  5187. { "AltLeft", SAPP_KEYCODE_LEFT_ALT },
  5188. { "AltRight", SAPP_KEYCODE_RIGHT_ALT },
  5189. { "Pause", SAPP_KEYCODE_PAUSE },
  5190. { "CapsLock", SAPP_KEYCODE_CAPS_LOCK },
  5191. { "Escape", SAPP_KEYCODE_ESCAPE },
  5192. { "Space", SAPP_KEYCODE_SPACE },
  5193. { "PageUp", SAPP_KEYCODE_PAGE_UP },
  5194. { "PageDown", SAPP_KEYCODE_PAGE_DOWN },
  5195. { "End", SAPP_KEYCODE_END },
  5196. { "Home", SAPP_KEYCODE_HOME },
  5197. { "ArrowLeft", SAPP_KEYCODE_LEFT },
  5198. { "ArrowUp", SAPP_KEYCODE_UP },
  5199. { "ArrowRight", SAPP_KEYCODE_RIGHT },
  5200. { "ArrowDown", SAPP_KEYCODE_DOWN },
  5201. { "PrintScreen", SAPP_KEYCODE_PRINT_SCREEN },
  5202. { "Insert", SAPP_KEYCODE_INSERT },
  5203. { "Delete", SAPP_KEYCODE_DELETE },
  5204. { "Digit0", SAPP_KEYCODE_0 },
  5205. { "Digit1", SAPP_KEYCODE_1 },
  5206. { "Digit2", SAPP_KEYCODE_2 },
  5207. { "Digit3", SAPP_KEYCODE_3 },
  5208. { "Digit4", SAPP_KEYCODE_4 },
  5209. { "Digit5", SAPP_KEYCODE_5 },
  5210. { "Digit6", SAPP_KEYCODE_6 },
  5211. { "Digit7", SAPP_KEYCODE_7 },
  5212. { "Digit8", SAPP_KEYCODE_8 },
  5213. { "Digit9", SAPP_KEYCODE_9 },
  5214. { "KeyA", SAPP_KEYCODE_A },
  5215. { "KeyB", SAPP_KEYCODE_B },
  5216. { "KeyC", SAPP_KEYCODE_C },
  5217. { "KeyD", SAPP_KEYCODE_D },
  5218. { "KeyE", SAPP_KEYCODE_E },
  5219. { "KeyF", SAPP_KEYCODE_F },
  5220. { "KeyG", SAPP_KEYCODE_G },
  5221. { "KeyH", SAPP_KEYCODE_H },
  5222. { "KeyI", SAPP_KEYCODE_I },
  5223. { "KeyJ", SAPP_KEYCODE_J },
  5224. { "KeyK", SAPP_KEYCODE_K },
  5225. { "KeyL", SAPP_KEYCODE_L },
  5226. { "KeyM", SAPP_KEYCODE_M },
  5227. { "KeyN", SAPP_KEYCODE_N },
  5228. { "KeyO", SAPP_KEYCODE_O },
  5229. { "KeyP", SAPP_KEYCODE_P },
  5230. { "KeyQ", SAPP_KEYCODE_Q },
  5231. { "KeyR", SAPP_KEYCODE_R },
  5232. { "KeyS", SAPP_KEYCODE_S },
  5233. { "KeyT", SAPP_KEYCODE_T },
  5234. { "KeyU", SAPP_KEYCODE_U },
  5235. { "KeyV", SAPP_KEYCODE_V },
  5236. { "KeyW", SAPP_KEYCODE_W },
  5237. { "KeyX", SAPP_KEYCODE_X },
  5238. { "KeyY", SAPP_KEYCODE_Y },
  5239. { "KeyZ", SAPP_KEYCODE_Z },
  5240. { "MetaLeft", SAPP_KEYCODE_LEFT_SUPER },
  5241. { "MetaRight", SAPP_KEYCODE_RIGHT_SUPER },
  5242. { "Numpad0", SAPP_KEYCODE_KP_0 },
  5243. { "Numpad1", SAPP_KEYCODE_KP_1 },
  5244. { "Numpad2", SAPP_KEYCODE_KP_2 },
  5245. { "Numpad3", SAPP_KEYCODE_KP_3 },
  5246. { "Numpad4", SAPP_KEYCODE_KP_4 },
  5247. { "Numpad5", SAPP_KEYCODE_KP_5 },
  5248. { "Numpad6", SAPP_KEYCODE_KP_6 },
  5249. { "Numpad7", SAPP_KEYCODE_KP_7 },
  5250. { "Numpad8", SAPP_KEYCODE_KP_8 },
  5251. { "Numpad9", SAPP_KEYCODE_KP_9 },
  5252. { "NumpadMultiply", SAPP_KEYCODE_KP_MULTIPLY },
  5253. { "NumpadAdd", SAPP_KEYCODE_KP_ADD },
  5254. { "NumpadSubtract", SAPP_KEYCODE_KP_SUBTRACT },
  5255. { "NumpadDecimal", SAPP_KEYCODE_KP_DECIMAL },
  5256. { "NumpadDivide", SAPP_KEYCODE_KP_DIVIDE },
  5257. { "F1", SAPP_KEYCODE_F1 },
  5258. { "F2", SAPP_KEYCODE_F2 },
  5259. { "F3", SAPP_KEYCODE_F3 },
  5260. { "F4", SAPP_KEYCODE_F4 },
  5261. { "F5", SAPP_KEYCODE_F5 },
  5262. { "F6", SAPP_KEYCODE_F6 },
  5263. { "F7", SAPP_KEYCODE_F7 },
  5264. { "F8", SAPP_KEYCODE_F8 },
  5265. { "F9", SAPP_KEYCODE_F9 },
  5266. { "F10", SAPP_KEYCODE_F10 },
  5267. { "F11", SAPP_KEYCODE_F11 },
  5268. { "F12", SAPP_KEYCODE_F12 },
  5269. { "NumLock", SAPP_KEYCODE_NUM_LOCK },
  5270. { "ScrollLock", SAPP_KEYCODE_SCROLL_LOCK },
  5271. { "Semicolon", SAPP_KEYCODE_SEMICOLON },
  5272. { "Equal", SAPP_KEYCODE_EQUAL },
  5273. { "Comma", SAPP_KEYCODE_COMMA },
  5274. { "Minus", SAPP_KEYCODE_MINUS },
  5275. { "Period", SAPP_KEYCODE_PERIOD },
  5276. { "Slash", SAPP_KEYCODE_SLASH },
  5277. { "Backquote", SAPP_KEYCODE_GRAVE_ACCENT },
  5278. { "BracketLeft", SAPP_KEYCODE_LEFT_BRACKET },
  5279. { "Backslash", SAPP_KEYCODE_BACKSLASH },
  5280. { "BracketRight", SAPP_KEYCODE_RIGHT_BRACKET },
  5281. { "Quote", SAPP_KEYCODE_GRAVE_ACCENT }, // FIXME: ???
  5282. { 0, SAPP_KEYCODE_INVALID },
  5283. };
  5284. _SOKOL_PRIVATE sapp_keycode _sapp_emsc_translate_key(const char* str) {
  5285. int i = 0;
  5286. const char* keystr;
  5287. while (( keystr = _sapp_emsc_keymap[i].str )) {
  5288. if (0 == strcmp(str, keystr)) {
  5289. return _sapp_emsc_keymap[i].code;
  5290. }
  5291. i += 1;
  5292. }
  5293. return SAPP_KEYCODE_INVALID;
  5294. }
  5295. // returns true if the key code is a 'character key', this is used to decide
  5296. // if a key event needs to bubble up to create a char event
  5297. _SOKOL_PRIVATE bool _sapp_emsc_is_char_key(sapp_keycode key_code) {
  5298. return key_code < SAPP_KEYCODE_WORLD_1;
  5299. }
  5300. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_key_cb(int emsc_type, const EmscriptenKeyboardEvent* emsc_event, void* user_data) {
  5301. _SOKOL_UNUSED(user_data);
  5302. bool consume_event = false;
  5303. if (_sapp_events_enabled()) {
  5304. sapp_event_type type;
  5305. switch (emsc_type) {
  5306. case EMSCRIPTEN_EVENT_KEYDOWN:
  5307. type = SAPP_EVENTTYPE_KEY_DOWN;
  5308. break;
  5309. case EMSCRIPTEN_EVENT_KEYUP:
  5310. type = SAPP_EVENTTYPE_KEY_UP;
  5311. break;
  5312. case EMSCRIPTEN_EVENT_KEYPRESS:
  5313. type = SAPP_EVENTTYPE_CHAR;
  5314. break;
  5315. default:
  5316. type = SAPP_EVENTTYPE_INVALID;
  5317. break;
  5318. }
  5319. if (type != SAPP_EVENTTYPE_INVALID) {
  5320. bool send_keyup_followup = false;
  5321. _sapp_init_event(type);
  5322. _sapp.event.key_repeat = emsc_event->repeat;
  5323. _sapp.event.modifiers = _sapp_emsc_key_event_mods(emsc_event);
  5324. if (type == SAPP_EVENTTYPE_CHAR) {
  5325. // NOTE: charCode doesn't appear to be supported on Android Chrome
  5326. _sapp.event.char_code = emsc_event->charCode;
  5327. consume_event |= !_sapp.desc.html5_bubble_char_events;
  5328. } else {
  5329. if (0 != emsc_event->code[0]) {
  5330. // This code path is for desktop browsers which send untranslated 'physical' key code strings
  5331. // (which is what we actually want for key events)
  5332. _sapp.event.key_code = _sapp_emsc_translate_key(emsc_event->code);
  5333. } else {
  5334. // This code path is for mobile browsers which only send localized key code
  5335. // strings. Note that the translation will only work for a small subset
  5336. // of localization-agnostic keys (like Enter, arrow keys, etc...), but
  5337. // regular alpha-numeric keys will all result in an SAPP_KEYCODE_INVALID)
  5338. _sapp.event.key_code = _sapp_emsc_translate_key(emsc_event->key);
  5339. }
  5340. // Special hack for macOS: if the Super key is pressed, macOS doesn't
  5341. // send keyUp events. As a workaround, to prevent keys from
  5342. // "sticking", we'll send a keyup event following a keydown
  5343. // when the SUPER key is pressed
  5344. if ((type == SAPP_EVENTTYPE_KEY_DOWN) &&
  5345. (_sapp.event.key_code != SAPP_KEYCODE_LEFT_SUPER) &&
  5346. (_sapp.event.key_code != SAPP_KEYCODE_RIGHT_SUPER) &&
  5347. (_sapp.event.modifiers & SAPP_MODIFIER_SUPER))
  5348. {
  5349. send_keyup_followup = true;
  5350. }
  5351. // 'character key events' will always need to bubble up, otherwise the browser
  5352. // wouldn't be able to generate character events.
  5353. if (!_sapp_emsc_is_char_key(_sapp.event.key_code)) {
  5354. consume_event |= !_sapp.desc.html5_bubble_key_events;
  5355. }
  5356. }
  5357. consume_event |= _sapp_call_event(&_sapp.event);
  5358. if (send_keyup_followup) {
  5359. _sapp.event.type = SAPP_EVENTTYPE_KEY_UP;
  5360. consume_event |= _sapp_call_event(&_sapp.event);
  5361. }
  5362. }
  5363. }
  5364. _sapp_emsc_update_mouse_lock_state();
  5365. return consume_event;
  5366. }
  5367. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_touch_cb(int emsc_type, const EmscriptenTouchEvent* emsc_event, void* user_data) {
  5368. _SOKOL_UNUSED(user_data);
  5369. bool consume_event = !_sapp.desc.html5_bubble_touch_events;
  5370. if (_sapp_events_enabled()) {
  5371. sapp_event_type type;
  5372. switch (emsc_type) {
  5373. case EMSCRIPTEN_EVENT_TOUCHSTART:
  5374. type = SAPP_EVENTTYPE_TOUCHES_BEGAN;
  5375. break;
  5376. case EMSCRIPTEN_EVENT_TOUCHMOVE:
  5377. type = SAPP_EVENTTYPE_TOUCHES_MOVED;
  5378. break;
  5379. case EMSCRIPTEN_EVENT_TOUCHEND:
  5380. type = SAPP_EVENTTYPE_TOUCHES_ENDED;
  5381. break;
  5382. case EMSCRIPTEN_EVENT_TOUCHCANCEL:
  5383. type = SAPP_EVENTTYPE_TOUCHES_CANCELLED;
  5384. break;
  5385. default:
  5386. type = SAPP_EVENTTYPE_INVALID;
  5387. break;
  5388. }
  5389. if (type != SAPP_EVENTTYPE_INVALID) {
  5390. _sapp_init_event(type);
  5391. _sapp.event.modifiers = _sapp_emsc_touch_event_mods(emsc_event);
  5392. _sapp.event.num_touches = emsc_event->numTouches;
  5393. if (_sapp.event.num_touches > SAPP_MAX_TOUCHPOINTS) {
  5394. _sapp.event.num_touches = SAPP_MAX_TOUCHPOINTS;
  5395. }
  5396. for (int i = 0; i < _sapp.event.num_touches; i++) {
  5397. const EmscriptenTouchPoint* src = &emsc_event->touches[i];
  5398. sapp_touchpoint* dst = &_sapp.event.touches[i];
  5399. dst->identifier = (uintptr_t)src->identifier;
  5400. dst->pos_x = src->targetX * _sapp.dpi_scale;
  5401. dst->pos_y = src->targetY * _sapp.dpi_scale;
  5402. dst->changed = src->isChanged;
  5403. }
  5404. consume_event |= _sapp_call_event(&_sapp.event);
  5405. }
  5406. }
  5407. return consume_event;
  5408. }
  5409. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_focus_cb(int emsc_type, const EmscriptenFocusEvent* emsc_event, void* user_data) {
  5410. _SOKOL_UNUSED(emsc_type);
  5411. _SOKOL_UNUSED(emsc_event);
  5412. _SOKOL_UNUSED(user_data);
  5413. if (_sapp_events_enabled()) {
  5414. _sapp_init_event(SAPP_EVENTTYPE_FOCUSED);
  5415. _sapp_call_event(&_sapp.event);
  5416. }
  5417. return true;
  5418. }
  5419. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_blur_cb(int emsc_type, const EmscriptenFocusEvent* emsc_event, void* user_data) {
  5420. _SOKOL_UNUSED(emsc_type);
  5421. _SOKOL_UNUSED(emsc_event);
  5422. _SOKOL_UNUSED(user_data);
  5423. if (_sapp_events_enabled()) {
  5424. _sapp_init_event(SAPP_EVENTTYPE_UNFOCUSED);
  5425. _sapp_call_event(&_sapp.event);
  5426. }
  5427. return true;
  5428. }
  5429. #if defined(SOKOL_GLES3)
  5430. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_webgl_context_cb(int emsc_type, const void* reserved, void* user_data) {
  5431. _SOKOL_UNUSED(reserved);
  5432. _SOKOL_UNUSED(user_data);
  5433. sapp_event_type type;
  5434. switch (emsc_type) {
  5435. case EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: type = SAPP_EVENTTYPE_SUSPENDED; break;
  5436. case EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: type = SAPP_EVENTTYPE_RESUMED; break;
  5437. default: type = SAPP_EVENTTYPE_INVALID; break;
  5438. }
  5439. if (_sapp_events_enabled() && (SAPP_EVENTTYPE_INVALID != type)) {
  5440. _sapp_init_event(type);
  5441. _sapp_call_event(&_sapp.event);
  5442. }
  5443. return true;
  5444. }
  5445. _SOKOL_PRIVATE void _sapp_emsc_webgl_init(void) {
  5446. EmscriptenWebGLContextAttributes attrs;
  5447. emscripten_webgl_init_context_attributes(&attrs);
  5448. attrs.alpha = _sapp.desc.alpha;
  5449. attrs.depth = true;
  5450. attrs.stencil = true;
  5451. attrs.antialias = _sapp.sample_count > 1;
  5452. attrs.premultipliedAlpha = _sapp.desc.html5_premultiplied_alpha;
  5453. attrs.preserveDrawingBuffer = _sapp.desc.html5_preserve_drawing_buffer;
  5454. attrs.enableExtensionsByDefault = true;
  5455. attrs.majorVersion = 2;
  5456. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(_sapp.html5_canvas_selector, &attrs);
  5457. // FIXME: error message?
  5458. emscripten_webgl_make_context_current(ctx);
  5459. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  5460. }
  5461. #endif
  5462. _SOKOL_PRIVATE void _sapp_emsc_register_eventhandlers(void) {
  5463. // NOTE: HTML canvas doesn't receive input focus, this is why key event handlers are added
  5464. // to the window object (this could be worked around by adding a "tab index" to the
  5465. // canvas)
  5466. emscripten_set_mousedown_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5467. emscripten_set_mouseup_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5468. emscripten_set_mousemove_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5469. emscripten_set_mouseenter_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5470. emscripten_set_mouseleave_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5471. emscripten_set_wheel_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_wheel_cb);
  5472. emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5473. emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5474. emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5475. emscripten_set_touchstart_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5476. emscripten_set_touchmove_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5477. emscripten_set_touchend_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5478. emscripten_set_touchcancel_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5479. emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, _sapp_emsc_pointerlockchange_cb);
  5480. emscripten_set_pointerlockerror_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, _sapp_emsc_pointerlockerror_cb);
  5481. emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_focus_cb);
  5482. emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_blur_cb);
  5483. sapp_js_add_beforeunload_listener();
  5484. if (_sapp.clipboard.enabled) {
  5485. sapp_js_add_clipboard_listener();
  5486. }
  5487. if (_sapp.drop.enabled) {
  5488. sapp_js_add_dragndrop_listeners();
  5489. }
  5490. #if defined(SOKOL_GLES3)
  5491. emscripten_set_webglcontextlost_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_webgl_context_cb);
  5492. emscripten_set_webglcontextrestored_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_webgl_context_cb);
  5493. #endif
  5494. }
  5495. _SOKOL_PRIVATE void _sapp_emsc_unregister_eventhandlers(void) {
  5496. emscripten_set_mousedown_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5497. emscripten_set_mouseup_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5498. emscripten_set_mousemove_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5499. emscripten_set_mouseenter_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5500. emscripten_set_mouseleave_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5501. emscripten_set_wheel_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5502. emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5503. emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5504. emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5505. emscripten_set_touchstart_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5506. emscripten_set_touchmove_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5507. emscripten_set_touchend_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5508. emscripten_set_touchcancel_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5509. emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, 0);
  5510. emscripten_set_pointerlockerror_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, 0);
  5511. emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5512. emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5513. if (!_sapp.desc.html5_canvas_resize) {
  5514. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5515. }
  5516. sapp_js_remove_beforeunload_listener();
  5517. if (_sapp.clipboard.enabled) {
  5518. sapp_js_remove_clipboard_listener();
  5519. }
  5520. if (_sapp.drop.enabled) {
  5521. sapp_js_remove_dragndrop_listeners();
  5522. }
  5523. #if defined(SOKOL_GLES3)
  5524. emscripten_set_webglcontextlost_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5525. emscripten_set_webglcontextrestored_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5526. #endif
  5527. }
  5528. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_frame_animation_loop(double time, void* userData) {
  5529. _SOKOL_UNUSED(userData);
  5530. _sapp_timing_external(&_sapp.timing, time / 1000.0);
  5531. #if defined(SOKOL_WGPU)
  5532. _sapp_wgpu_frame();
  5533. #else
  5534. _sapp_frame();
  5535. #endif
  5536. // quit-handling
  5537. if (_sapp.quit_requested) {
  5538. _sapp_init_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  5539. _sapp_call_event(&_sapp.event);
  5540. if (_sapp.quit_requested) {
  5541. _sapp.quit_ordered = true;
  5542. }
  5543. }
  5544. if (_sapp.quit_ordered) {
  5545. _sapp_emsc_unregister_eventhandlers();
  5546. #if defined(SOKOL_WGPU)
  5547. _sapp_wgpu_discard_swapchain(false);
  5548. #endif
  5549. _sapp_call_cleanup();
  5550. _sapp_discard_state();
  5551. return EM_FALSE;
  5552. }
  5553. return EM_TRUE;
  5554. }
  5555. _SOKOL_PRIVATE void _sapp_emsc_frame_main_loop(void) {
  5556. const double time = emscripten_performance_now();
  5557. if (!_sapp_emsc_frame_animation_loop(time, 0)) {
  5558. emscripten_cancel_main_loop();
  5559. }
  5560. }
  5561. _SOKOL_PRIVATE void _sapp_emsc_run(const sapp_desc* desc) {
  5562. _sapp_init_state(desc);
  5563. const char* document_title = desc->html5_update_document_title ? _sapp.window_title : 0;
  5564. sapp_js_init(_sapp.html5_canvas_selector, document_title);
  5565. double w, h;
  5566. if (_sapp.desc.html5_canvas_resize) {
  5567. w = (double) _sapp_def(_sapp.desc.width, _SAPP_FALLBACK_DEFAULT_WINDOW_WIDTH);
  5568. h = (double) _sapp_def(_sapp.desc.height, _SAPP_FALLBACK_DEFAULT_WINDOW_HEIGHT);
  5569. }
  5570. else {
  5571. emscripten_get_element_css_size(_sapp.html5_canvas_selector, &w, &h);
  5572. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, false, _sapp_emsc_size_changed);
  5573. }
  5574. if (_sapp.desc.high_dpi) {
  5575. _sapp.dpi_scale = emscripten_get_device_pixel_ratio();
  5576. }
  5577. _sapp.window_width = (int)roundf(w);
  5578. _sapp.window_height = (int)roundf(h);
  5579. _sapp.framebuffer_width = (int)roundf(w * _sapp.dpi_scale);
  5580. _sapp.framebuffer_height = (int)roundf(h * _sapp.dpi_scale);
  5581. emscripten_set_canvas_element_size(_sapp.html5_canvas_selector, _sapp.framebuffer_width, _sapp.framebuffer_height);
  5582. #if defined(SOKOL_GLES3)
  5583. _sapp_emsc_webgl_init();
  5584. #elif defined(SOKOL_WGPU)
  5585. _sapp_wgpu_init();
  5586. #endif
  5587. _sapp.valid = true;
  5588. _sapp_emsc_register_eventhandlers();
  5589. sapp_set_icon(&desc->icon);
  5590. // start the frame loop
  5591. if (_sapp.desc.html5_use_emsc_set_main_loop) {
  5592. emscripten_set_main_loop(_sapp_emsc_frame_main_loop, 0, _sapp.desc.html5_emsc_set_main_loop_simulate_infinite_loop);
  5593. } else {
  5594. emscripten_request_animation_frame_loop(_sapp_emsc_frame_animation_loop, 0);
  5595. }
  5596. // NOT A BUG: do not call _sapp_discard_state() here, instead this is
  5597. // called in _sapp_emsc_frame() when the application is ordered to quit
  5598. }
  5599. #if !defined(SOKOL_NO_ENTRY)
  5600. int main(int argc, char* argv[]) {
  5601. sapp_desc desc = sokol_main(argc, argv);
  5602. _sapp_emsc_run(&desc);
  5603. return 0;
  5604. }
  5605. #endif /* SOKOL_NO_ENTRY */
  5606. #endif /* _SAPP_EMSCRIPTEN */
  5607. // ██████ ██ ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  5608. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5609. // ██ ███ ██ ███████ █████ ██ ██████ █████ ██████ ███████
  5610. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5611. // ██████ ███████ ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  5612. //
  5613. // >>gl helpers
  5614. #if defined(SOKOL_GLCORE)
  5615. typedef struct {
  5616. int red_bits;
  5617. int green_bits;
  5618. int blue_bits;
  5619. int alpha_bits;
  5620. int depth_bits;
  5621. int stencil_bits;
  5622. int samples;
  5623. bool doublebuffer;
  5624. uintptr_t handle;
  5625. } _sapp_gl_fbconfig;
  5626. _SOKOL_PRIVATE void _sapp_gl_init_fbconfig(_sapp_gl_fbconfig* fbconfig) {
  5627. _sapp_clear(fbconfig, sizeof(_sapp_gl_fbconfig));
  5628. /* -1 means "don't care" */
  5629. fbconfig->red_bits = -1;
  5630. fbconfig->green_bits = -1;
  5631. fbconfig->blue_bits = -1;
  5632. fbconfig->alpha_bits = -1;
  5633. fbconfig->depth_bits = -1;
  5634. fbconfig->stencil_bits = -1;
  5635. fbconfig->samples = -1;
  5636. }
  5637. typedef struct {
  5638. int least_missing;
  5639. int least_color_diff;
  5640. int least_extra_diff;
  5641. bool best_match;
  5642. } _sapp_gl_fbselect;
  5643. _SOKOL_PRIVATE void _sapp_gl_init_fbselect(_sapp_gl_fbselect* fbselect) {
  5644. _sapp_clear(fbselect, sizeof(_sapp_gl_fbselect));
  5645. fbselect->least_missing = 1000000;
  5646. fbselect->least_color_diff = 10000000;
  5647. fbselect->least_extra_diff = 10000000;
  5648. fbselect->best_match = false;
  5649. }
  5650. // NOTE: this is used only in the WGL code path
  5651. _SOKOL_PRIVATE bool _sapp_gl_select_fbconfig(_sapp_gl_fbselect* fbselect, const _sapp_gl_fbconfig* desired, const _sapp_gl_fbconfig* current) {
  5652. int missing = 0;
  5653. if (desired->doublebuffer != current->doublebuffer) {
  5654. return false;
  5655. }
  5656. if ((desired->alpha_bits > 0) && (current->alpha_bits == 0)) {
  5657. missing++;
  5658. }
  5659. if ((desired->depth_bits > 0) && (current->depth_bits == 0)) {
  5660. missing++;
  5661. }
  5662. if ((desired->stencil_bits > 0) && (current->stencil_bits == 0)) {
  5663. missing++;
  5664. }
  5665. if ((desired->samples > 0) && (current->samples == 0)) {
  5666. /* Technically, several multisampling buffers could be
  5667. involved, but that's a lower level implementation detail and
  5668. not important to us here, so we count them as one
  5669. */
  5670. missing++;
  5671. }
  5672. /* These polynomials make many small channel size differences matter
  5673. less than one large channel size difference
  5674. Calculate color channel size difference value
  5675. */
  5676. int color_diff = 0;
  5677. if (desired->red_bits != -1) {
  5678. color_diff += (desired->red_bits - current->red_bits) * (desired->red_bits - current->red_bits);
  5679. }
  5680. if (desired->green_bits != -1) {
  5681. color_diff += (desired->green_bits - current->green_bits) * (desired->green_bits - current->green_bits);
  5682. }
  5683. if (desired->blue_bits != -1) {
  5684. color_diff += (desired->blue_bits - current->blue_bits) * (desired->blue_bits - current->blue_bits);
  5685. }
  5686. /* Calculate non-color channel size difference value */
  5687. int extra_diff = 0;
  5688. if (desired->alpha_bits != -1) {
  5689. extra_diff += (desired->alpha_bits - current->alpha_bits) * (desired->alpha_bits - current->alpha_bits);
  5690. }
  5691. if (desired->depth_bits != -1) {
  5692. extra_diff += (desired->depth_bits - current->depth_bits) * (desired->depth_bits - current->depth_bits);
  5693. }
  5694. if (desired->stencil_bits != -1) {
  5695. extra_diff += (desired->stencil_bits - current->stencil_bits) * (desired->stencil_bits - current->stencil_bits);
  5696. }
  5697. if (desired->samples != -1) {
  5698. extra_diff += (desired->samples - current->samples) * (desired->samples - current->samples);
  5699. }
  5700. /* Figure out if the current one is better than the best one found so far
  5701. Least number of missing buffers is the most important heuristic,
  5702. then color buffer size match and lastly size match for other buffers
  5703. */
  5704. bool new_closest = false;
  5705. if (missing < fbselect->least_missing) {
  5706. new_closest = true;
  5707. } else if (missing == fbselect->least_missing) {
  5708. if ((color_diff < fbselect->least_color_diff) ||
  5709. ((color_diff == fbselect->least_color_diff) && (extra_diff < fbselect->least_extra_diff)))
  5710. {
  5711. new_closest = true;
  5712. }
  5713. }
  5714. if (new_closest) {
  5715. fbselect->least_missing = missing;
  5716. fbselect->least_color_diff = color_diff;
  5717. fbselect->least_extra_diff = extra_diff;
  5718. fbselect->best_match = (missing | color_diff | extra_diff) == 0;
  5719. }
  5720. return new_closest;
  5721. }
  5722. // NOTE: this is used only in the GLX code path
  5723. _SOKOL_PRIVATE const _sapp_gl_fbconfig* _sapp_gl_choose_fbconfig(const _sapp_gl_fbconfig* desired, const _sapp_gl_fbconfig* alternatives, int count) {
  5724. int missing, least_missing = 1000000;
  5725. int color_diff, least_color_diff = 10000000;
  5726. int extra_diff, least_extra_diff = 10000000;
  5727. const _sapp_gl_fbconfig* current;
  5728. const _sapp_gl_fbconfig* closest = 0;
  5729. for (int i = 0; i < count; i++) {
  5730. current = alternatives + i;
  5731. if (desired->doublebuffer != current->doublebuffer) {
  5732. continue;
  5733. }
  5734. missing = 0;
  5735. if (desired->alpha_bits > 0 && current->alpha_bits == 0) {
  5736. missing++;
  5737. }
  5738. if (desired->depth_bits > 0 && current->depth_bits == 0) {
  5739. missing++;
  5740. }
  5741. if (desired->stencil_bits > 0 && current->stencil_bits == 0) {
  5742. missing++;
  5743. }
  5744. if (desired->samples > 0 && current->samples == 0) {
  5745. /* Technically, several multisampling buffers could be
  5746. involved, but that's a lower level implementation detail and
  5747. not important to us here, so we count them as one
  5748. */
  5749. missing++;
  5750. }
  5751. /* These polynomials make many small channel size differences matter
  5752. less than one large channel size difference
  5753. Calculate color channel size difference value
  5754. */
  5755. color_diff = 0;
  5756. if (desired->red_bits != -1) {
  5757. color_diff += (desired->red_bits - current->red_bits) * (desired->red_bits - current->red_bits);
  5758. }
  5759. if (desired->green_bits != -1) {
  5760. color_diff += (desired->green_bits - current->green_bits) * (desired->green_bits - current->green_bits);
  5761. }
  5762. if (desired->blue_bits != -1) {
  5763. color_diff += (desired->blue_bits - current->blue_bits) * (desired->blue_bits - current->blue_bits);
  5764. }
  5765. /* Calculate non-color channel size difference value */
  5766. extra_diff = 0;
  5767. if (desired->alpha_bits != -1) {
  5768. extra_diff += (desired->alpha_bits - current->alpha_bits) * (desired->alpha_bits - current->alpha_bits);
  5769. }
  5770. if (desired->depth_bits != -1) {
  5771. extra_diff += (desired->depth_bits - current->depth_bits) * (desired->depth_bits - current->depth_bits);
  5772. }
  5773. if (desired->stencil_bits != -1) {
  5774. extra_diff += (desired->stencil_bits - current->stencil_bits) * (desired->stencil_bits - current->stencil_bits);
  5775. }
  5776. if (desired->samples != -1) {
  5777. extra_diff += (desired->samples - current->samples) * (desired->samples - current->samples);
  5778. }
  5779. /* Figure out if the current one is better than the best one found so far
  5780. Least number of missing buffers is the most important heuristic,
  5781. then color buffer size match and lastly size match for other buffers
  5782. */
  5783. if (missing < least_missing) {
  5784. closest = current;
  5785. }
  5786. else if (missing == least_missing) {
  5787. if ((color_diff < least_color_diff) ||
  5788. (color_diff == least_color_diff && extra_diff < least_extra_diff))
  5789. {
  5790. closest = current;
  5791. }
  5792. }
  5793. if (current == closest) {
  5794. least_missing = missing;
  5795. least_color_diff = color_diff;
  5796. least_extra_diff = extra_diff;
  5797. }
  5798. }
  5799. return closest;
  5800. }
  5801. #endif
  5802. // ██ ██ ██ ███ ██ ██████ ██████ ██ ██ ███████
  5803. // ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██
  5804. // ██ █ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █ ██ ███████
  5805. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██ ██
  5806. // ███ ███ ██ ██ ████ ██████ ██████ ███ ███ ███████
  5807. //
  5808. // >>windows
  5809. #if defined(_SAPP_WIN32)
  5810. _SOKOL_PRIVATE bool _sapp_win32_utf8_to_wide(const char* src, wchar_t* dst, int dst_num_bytes) {
  5811. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  5812. _sapp_clear(dst, (size_t)dst_num_bytes);
  5813. const int dst_chars = dst_num_bytes / (int)sizeof(wchar_t);
  5814. const int dst_needed = MultiByteToWideChar(CP_UTF8, 0, src, -1, 0, 0);
  5815. if ((dst_needed > 0) && (dst_needed < dst_chars)) {
  5816. MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, dst_chars);
  5817. return true;
  5818. }
  5819. else {
  5820. /* input string doesn't fit into destination buffer */
  5821. return false;
  5822. }
  5823. }
  5824. _SOKOL_PRIVATE void _sapp_win32_app_event(sapp_event_type type) {
  5825. if (_sapp_events_enabled()) {
  5826. _sapp_init_event(type);
  5827. _sapp_call_event(&_sapp.event);
  5828. }
  5829. }
  5830. _SOKOL_PRIVATE void _sapp_win32_init_keytable(void) {
  5831. /* same as GLFW */
  5832. _sapp.keycodes[0x00B] = SAPP_KEYCODE_0;
  5833. _sapp.keycodes[0x002] = SAPP_KEYCODE_1;
  5834. _sapp.keycodes[0x003] = SAPP_KEYCODE_2;
  5835. _sapp.keycodes[0x004] = SAPP_KEYCODE_3;
  5836. _sapp.keycodes[0x005] = SAPP_KEYCODE_4;
  5837. _sapp.keycodes[0x006] = SAPP_KEYCODE_5;
  5838. _sapp.keycodes[0x007] = SAPP_KEYCODE_6;
  5839. _sapp.keycodes[0x008] = SAPP_KEYCODE_7;
  5840. _sapp.keycodes[0x009] = SAPP_KEYCODE_8;
  5841. _sapp.keycodes[0x00A] = SAPP_KEYCODE_9;
  5842. _sapp.keycodes[0x01E] = SAPP_KEYCODE_A;
  5843. _sapp.keycodes[0x030] = SAPP_KEYCODE_B;
  5844. _sapp.keycodes[0x02E] = SAPP_KEYCODE_C;
  5845. _sapp.keycodes[0x020] = SAPP_KEYCODE_D;
  5846. _sapp.keycodes[0x012] = SAPP_KEYCODE_E;
  5847. _sapp.keycodes[0x021] = SAPP_KEYCODE_F;
  5848. _sapp.keycodes[0x022] = SAPP_KEYCODE_G;
  5849. _sapp.keycodes[0x023] = SAPP_KEYCODE_H;
  5850. _sapp.keycodes[0x017] = SAPP_KEYCODE_I;
  5851. _sapp.keycodes[0x024] = SAPP_KEYCODE_J;
  5852. _sapp.keycodes[0x025] = SAPP_KEYCODE_K;
  5853. _sapp.keycodes[0x026] = SAPP_KEYCODE_L;
  5854. _sapp.keycodes[0x032] = SAPP_KEYCODE_M;
  5855. _sapp.keycodes[0x031] = SAPP_KEYCODE_N;
  5856. _sapp.keycodes[0x018] = SAPP_KEYCODE_O;
  5857. _sapp.keycodes[0x019] = SAPP_KEYCODE_P;
  5858. _sapp.keycodes[0x010] = SAPP_KEYCODE_Q;
  5859. _sapp.keycodes[0x013] = SAPP_KEYCODE_R;
  5860. _sapp.keycodes[0x01F] = SAPP_KEYCODE_S;
  5861. _sapp.keycodes[0x014] = SAPP_KEYCODE_T;
  5862. _sapp.keycodes[0x016] = SAPP_KEYCODE_U;
  5863. _sapp.keycodes[0x02F] = SAPP_KEYCODE_V;
  5864. _sapp.keycodes[0x011] = SAPP_KEYCODE_W;
  5865. _sapp.keycodes[0x02D] = SAPP_KEYCODE_X;
  5866. _sapp.keycodes[0x015] = SAPP_KEYCODE_Y;
  5867. _sapp.keycodes[0x02C] = SAPP_KEYCODE_Z;
  5868. _sapp.keycodes[0x028] = SAPP_KEYCODE_APOSTROPHE;
  5869. _sapp.keycodes[0x02B] = SAPP_KEYCODE_BACKSLASH;
  5870. _sapp.keycodes[0x033] = SAPP_KEYCODE_COMMA;
  5871. _sapp.keycodes[0x00D] = SAPP_KEYCODE_EQUAL;
  5872. _sapp.keycodes[0x029] = SAPP_KEYCODE_GRAVE_ACCENT;
  5873. _sapp.keycodes[0x01A] = SAPP_KEYCODE_LEFT_BRACKET;
  5874. _sapp.keycodes[0x00C] = SAPP_KEYCODE_MINUS;
  5875. _sapp.keycodes[0x034] = SAPP_KEYCODE_PERIOD;
  5876. _sapp.keycodes[0x01B] = SAPP_KEYCODE_RIGHT_BRACKET;
  5877. _sapp.keycodes[0x027] = SAPP_KEYCODE_SEMICOLON;
  5878. _sapp.keycodes[0x035] = SAPP_KEYCODE_SLASH;
  5879. _sapp.keycodes[0x056] = SAPP_KEYCODE_WORLD_2;
  5880. _sapp.keycodes[0x00E] = SAPP_KEYCODE_BACKSPACE;
  5881. _sapp.keycodes[0x153] = SAPP_KEYCODE_DELETE;
  5882. _sapp.keycodes[0x14F] = SAPP_KEYCODE_END;
  5883. _sapp.keycodes[0x01C] = SAPP_KEYCODE_ENTER;
  5884. _sapp.keycodes[0x001] = SAPP_KEYCODE_ESCAPE;
  5885. _sapp.keycodes[0x147] = SAPP_KEYCODE_HOME;
  5886. _sapp.keycodes[0x152] = SAPP_KEYCODE_INSERT;
  5887. _sapp.keycodes[0x15D] = SAPP_KEYCODE_MENU;
  5888. _sapp.keycodes[0x151] = SAPP_KEYCODE_PAGE_DOWN;
  5889. _sapp.keycodes[0x149] = SAPP_KEYCODE_PAGE_UP;
  5890. _sapp.keycodes[0x045] = SAPP_KEYCODE_PAUSE;
  5891. _sapp.keycodes[0x146] = SAPP_KEYCODE_PAUSE;
  5892. _sapp.keycodes[0x039] = SAPP_KEYCODE_SPACE;
  5893. _sapp.keycodes[0x00F] = SAPP_KEYCODE_TAB;
  5894. _sapp.keycodes[0x03A] = SAPP_KEYCODE_CAPS_LOCK;
  5895. _sapp.keycodes[0x145] = SAPP_KEYCODE_NUM_LOCK;
  5896. _sapp.keycodes[0x046] = SAPP_KEYCODE_SCROLL_LOCK;
  5897. _sapp.keycodes[0x03B] = SAPP_KEYCODE_F1;
  5898. _sapp.keycodes[0x03C] = SAPP_KEYCODE_F2;
  5899. _sapp.keycodes[0x03D] = SAPP_KEYCODE_F3;
  5900. _sapp.keycodes[0x03E] = SAPP_KEYCODE_F4;
  5901. _sapp.keycodes[0x03F] = SAPP_KEYCODE_F5;
  5902. _sapp.keycodes[0x040] = SAPP_KEYCODE_F6;
  5903. _sapp.keycodes[0x041] = SAPP_KEYCODE_F7;
  5904. _sapp.keycodes[0x042] = SAPP_KEYCODE_F8;
  5905. _sapp.keycodes[0x043] = SAPP_KEYCODE_F9;
  5906. _sapp.keycodes[0x044] = SAPP_KEYCODE_F10;
  5907. _sapp.keycodes[0x057] = SAPP_KEYCODE_F11;
  5908. _sapp.keycodes[0x058] = SAPP_KEYCODE_F12;
  5909. _sapp.keycodes[0x064] = SAPP_KEYCODE_F13;
  5910. _sapp.keycodes[0x065] = SAPP_KEYCODE_F14;
  5911. _sapp.keycodes[0x066] = SAPP_KEYCODE_F15;
  5912. _sapp.keycodes[0x067] = SAPP_KEYCODE_F16;
  5913. _sapp.keycodes[0x068] = SAPP_KEYCODE_F17;
  5914. _sapp.keycodes[0x069] = SAPP_KEYCODE_F18;
  5915. _sapp.keycodes[0x06A] = SAPP_KEYCODE_F19;
  5916. _sapp.keycodes[0x06B] = SAPP_KEYCODE_F20;
  5917. _sapp.keycodes[0x06C] = SAPP_KEYCODE_F21;
  5918. _sapp.keycodes[0x06D] = SAPP_KEYCODE_F22;
  5919. _sapp.keycodes[0x06E] = SAPP_KEYCODE_F23;
  5920. _sapp.keycodes[0x076] = SAPP_KEYCODE_F24;
  5921. _sapp.keycodes[0x038] = SAPP_KEYCODE_LEFT_ALT;
  5922. _sapp.keycodes[0x01D] = SAPP_KEYCODE_LEFT_CONTROL;
  5923. _sapp.keycodes[0x02A] = SAPP_KEYCODE_LEFT_SHIFT;
  5924. _sapp.keycodes[0x15B] = SAPP_KEYCODE_LEFT_SUPER;
  5925. _sapp.keycodes[0x137] = SAPP_KEYCODE_PRINT_SCREEN;
  5926. _sapp.keycodes[0x138] = SAPP_KEYCODE_RIGHT_ALT;
  5927. _sapp.keycodes[0x11D] = SAPP_KEYCODE_RIGHT_CONTROL;
  5928. _sapp.keycodes[0x036] = SAPP_KEYCODE_RIGHT_SHIFT;
  5929. _sapp.keycodes[0x136] = SAPP_KEYCODE_RIGHT_SHIFT;
  5930. _sapp.keycodes[0x15C] = SAPP_KEYCODE_RIGHT_SUPER;
  5931. _sapp.keycodes[0x150] = SAPP_KEYCODE_DOWN;
  5932. _sapp.keycodes[0x14B] = SAPP_KEYCODE_LEFT;
  5933. _sapp.keycodes[0x14D] = SAPP_KEYCODE_RIGHT;
  5934. _sapp.keycodes[0x148] = SAPP_KEYCODE_UP;
  5935. _sapp.keycodes[0x052] = SAPP_KEYCODE_KP_0;
  5936. _sapp.keycodes[0x04F] = SAPP_KEYCODE_KP_1;
  5937. _sapp.keycodes[0x050] = SAPP_KEYCODE_KP_2;
  5938. _sapp.keycodes[0x051] = SAPP_KEYCODE_KP_3;
  5939. _sapp.keycodes[0x04B] = SAPP_KEYCODE_KP_4;
  5940. _sapp.keycodes[0x04C] = SAPP_KEYCODE_KP_5;
  5941. _sapp.keycodes[0x04D] = SAPP_KEYCODE_KP_6;
  5942. _sapp.keycodes[0x047] = SAPP_KEYCODE_KP_7;
  5943. _sapp.keycodes[0x048] = SAPP_KEYCODE_KP_8;
  5944. _sapp.keycodes[0x049] = SAPP_KEYCODE_KP_9;
  5945. _sapp.keycodes[0x04E] = SAPP_KEYCODE_KP_ADD;
  5946. _sapp.keycodes[0x053] = SAPP_KEYCODE_KP_DECIMAL;
  5947. _sapp.keycodes[0x135] = SAPP_KEYCODE_KP_DIVIDE;
  5948. _sapp.keycodes[0x11C] = SAPP_KEYCODE_KP_ENTER;
  5949. _sapp.keycodes[0x037] = SAPP_KEYCODE_KP_MULTIPLY;
  5950. _sapp.keycodes[0x04A] = SAPP_KEYCODE_KP_SUBTRACT;
  5951. }
  5952. #endif // _SAPP_WIN32
  5953. #if defined(_SAPP_WIN32)
  5954. #if defined(SOKOL_D3D11)
  5955. #if defined(__cplusplus)
  5956. #define _sapp_d3d11_Release(self) (self)->Release()
  5957. #define _sapp_win32_refiid(iid) iid
  5958. #else
  5959. #define _sapp_d3d11_Release(self) (self)->lpVtbl->Release(self)
  5960. #define _sapp_win32_refiid(iid) &iid
  5961. #endif
  5962. #define _SAPP_SAFE_RELEASE(obj) if (obj) { _sapp_d3d11_Release(obj); obj=0; }
  5963. static const IID _sapp_IID_ID3D11Texture2D = { 0x6f15aaf2,0xd208,0x4e89, {0x9a,0xb4,0x48,0x95,0x35,0xd3,0x4f,0x9c} };
  5964. static const IID _sapp_IID_IDXGIDevice1 = { 0x77db970f,0x6276,0x48ba, {0xba,0x28,0x07,0x01,0x43,0xb4,0x39,0x2c} };
  5965. static const IID _sapp_IID_IDXGIFactory = { 0x7b7166ec,0x21c7,0x44ae, {0xb2,0x1a,0xc9,0xae,0x32,0x1a,0xe3,0x69} };
  5966. static inline HRESULT _sapp_dxgi_GetBuffer(IDXGISwapChain* self, UINT Buffer, REFIID riid, void** ppSurface) {
  5967. #if defined(__cplusplus)
  5968. return self->GetBuffer(Buffer, riid, ppSurface);
  5969. #else
  5970. return self->lpVtbl->GetBuffer(self, Buffer, riid, ppSurface);
  5971. #endif
  5972. }
  5973. static inline HRESULT _sapp_d3d11_QueryInterface(ID3D11Device* self, REFIID riid, void** ppvObject) {
  5974. #if defined(__cplusplus)
  5975. return self->QueryInterface(riid, ppvObject);
  5976. #else
  5977. return self->lpVtbl->QueryInterface(self, riid, ppvObject);
  5978. #endif
  5979. }
  5980. static inline HRESULT _sapp_d3d11_CreateRenderTargetView(ID3D11Device* self, ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView) {
  5981. #if defined(__cplusplus)
  5982. return self->CreateRenderTargetView(pResource, pDesc, ppRTView);
  5983. #else
  5984. return self->lpVtbl->CreateRenderTargetView(self, pResource, pDesc, ppRTView);
  5985. #endif
  5986. }
  5987. static inline HRESULT _sapp_d3d11_CreateTexture2D(ID3D11Device* self, const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D) {
  5988. #if defined(__cplusplus)
  5989. return self->CreateTexture2D(pDesc, pInitialData, ppTexture2D);
  5990. #else
  5991. return self->lpVtbl->CreateTexture2D(self, pDesc, pInitialData, ppTexture2D);
  5992. #endif
  5993. }
  5994. static inline HRESULT _sapp_d3d11_CreateDepthStencilView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView) {
  5995. #if defined(__cplusplus)
  5996. return self->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView);
  5997. #else
  5998. return self->lpVtbl->CreateDepthStencilView(self, pResource, pDesc, ppDepthStencilView);
  5999. #endif
  6000. }
  6001. static inline HRESULT _sapp_dxgi_ResizeBuffers(IDXGISwapChain* self, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags) {
  6002. #if defined(__cplusplus)
  6003. return self->ResizeBuffers(BufferCount, Width, Height, NewFormat, SwapChainFlags);
  6004. #else
  6005. return self->lpVtbl->ResizeBuffers(self, BufferCount, Width, Height, NewFormat, SwapChainFlags);
  6006. #endif
  6007. }
  6008. static inline HRESULT _sapp_dxgi_Present(IDXGISwapChain* self, UINT SyncInterval, UINT Flags) {
  6009. #if defined(__cplusplus)
  6010. return self->Present(SyncInterval, Flags);
  6011. #else
  6012. return self->lpVtbl->Present(self, SyncInterval, Flags);
  6013. #endif
  6014. }
  6015. static inline HRESULT _sapp_dxgi_GetFrameStatistics(IDXGISwapChain* self, DXGI_FRAME_STATISTICS* pStats) {
  6016. #if defined(__cplusplus)
  6017. return self->GetFrameStatistics(pStats);
  6018. #else
  6019. return self->lpVtbl->GetFrameStatistics(self, pStats);
  6020. #endif
  6021. }
  6022. static inline HRESULT _sapp_dxgi_SetMaximumFrameLatency(IDXGIDevice1* self, UINT MaxLatency) {
  6023. #if defined(__cplusplus)
  6024. return self->SetMaximumFrameLatency(MaxLatency);
  6025. #else
  6026. return self->lpVtbl->SetMaximumFrameLatency(self, MaxLatency);
  6027. #endif
  6028. }
  6029. static inline HRESULT _sapp_dxgi_GetAdapter(IDXGIDevice1* self, IDXGIAdapter** pAdapter) {
  6030. #if defined(__cplusplus)
  6031. return self->GetAdapter(pAdapter);
  6032. #else
  6033. return self->lpVtbl->GetAdapter(self, pAdapter);
  6034. #endif
  6035. }
  6036. static inline HRESULT _sapp_dxgi_GetParent(IDXGIObject* self, REFIID riid, void** ppParent) {
  6037. #if defined(__cplusplus)
  6038. return self->GetParent(riid, ppParent);
  6039. #else
  6040. return self->lpVtbl->GetParent(self, riid, ppParent);
  6041. #endif
  6042. }
  6043. static inline HRESULT _sapp_dxgi_MakeWindowAssociation(IDXGIFactory* self, HWND WindowHandle, UINT Flags) {
  6044. #if defined(__cplusplus)
  6045. return self->MakeWindowAssociation(WindowHandle, Flags);
  6046. #else
  6047. return self->lpVtbl->MakeWindowAssociation(self, WindowHandle, Flags);
  6048. #endif
  6049. }
  6050. _SOKOL_PRIVATE void _sapp_d3d11_create_device_and_swapchain(void) {
  6051. DXGI_SWAP_CHAIN_DESC* sc_desc = &_sapp.d3d11.swap_chain_desc;
  6052. sc_desc->BufferDesc.Width = (UINT)_sapp.framebuffer_width;
  6053. sc_desc->BufferDesc.Height = (UINT)_sapp.framebuffer_height;
  6054. sc_desc->BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  6055. sc_desc->BufferDesc.RefreshRate.Numerator = 60;
  6056. sc_desc->BufferDesc.RefreshRate.Denominator = 1;
  6057. sc_desc->OutputWindow = _sapp.win32.hwnd;
  6058. sc_desc->Windowed = true;
  6059. if (_sapp.win32.is_win10_or_greater) {
  6060. sc_desc->BufferCount = 2;
  6061. sc_desc->SwapEffect = (DXGI_SWAP_EFFECT) _SAPP_DXGI_SWAP_EFFECT_FLIP_DISCARD;
  6062. _sapp.d3d11.use_dxgi_frame_stats = true;
  6063. }
  6064. else {
  6065. sc_desc->BufferCount = 1;
  6066. sc_desc->SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  6067. _sapp.d3d11.use_dxgi_frame_stats = false;
  6068. }
  6069. sc_desc->SampleDesc.Count = 1;
  6070. sc_desc->SampleDesc.Quality = 0;
  6071. sc_desc->BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  6072. UINT create_flags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  6073. #if defined(SOKOL_DEBUG)
  6074. create_flags |= D3D11_CREATE_DEVICE_DEBUG;
  6075. #endif
  6076. D3D_FEATURE_LEVEL requested_feature_levels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0 };
  6077. D3D_FEATURE_LEVEL result_feature_level;
  6078. HRESULT hr = D3D11CreateDeviceAndSwapChain(
  6079. NULL, /* pAdapter (use default) */
  6080. D3D_DRIVER_TYPE_HARDWARE, /* DriverType */
  6081. NULL, /* Software */
  6082. create_flags, /* Flags */
  6083. requested_feature_levels, /* pFeatureLevels */
  6084. 2, /* FeatureLevels */
  6085. D3D11_SDK_VERSION, /* SDKVersion */
  6086. sc_desc, /* pSwapChainDesc */
  6087. &_sapp.d3d11.swap_chain, /* ppSwapChain */
  6088. &_sapp.d3d11.device, /* ppDevice */
  6089. &result_feature_level, /* pFeatureLevel */
  6090. &_sapp.d3d11.device_context); /* ppImmediateContext */
  6091. _SOKOL_UNUSED(hr);
  6092. #if defined(SOKOL_DEBUG)
  6093. if (!SUCCEEDED(hr)) {
  6094. // if initialization with D3D11_CREATE_DEVICE_DEBUG fails, this could be because the
  6095. // 'D3D11 debug layer' stopped working, indicated by the error message:
  6096. // ===
  6097. // D3D11CreateDevice: Flags (0x2) were specified which require the D3D11 SDK Layers for Windows 10, but they are not present on the system.
  6098. // These flags must be removed, or the Windows 10 SDK must be installed.
  6099. // Flags include: D3D11_CREATE_DEVICE_DEBUG
  6100. // ===
  6101. //
  6102. // ...just retry with the DEBUG flag switched off
  6103. _SAPP_ERROR(WIN32_D3D11_CREATE_DEVICE_AND_SWAPCHAIN_WITH_DEBUG_FAILED);
  6104. create_flags &= ~(UINT)D3D11_CREATE_DEVICE_DEBUG;
  6105. hr = D3D11CreateDeviceAndSwapChain(
  6106. NULL, /* pAdapter (use default) */
  6107. D3D_DRIVER_TYPE_HARDWARE, /* DriverType */
  6108. NULL, /* Software */
  6109. create_flags, /* Flags */
  6110. requested_feature_levels, /* pFeatureLevels */
  6111. 2, /* FeatureLevels */
  6112. D3D11_SDK_VERSION, /* SDKVersion */
  6113. sc_desc, /* pSwapChainDesc */
  6114. &_sapp.d3d11.swap_chain, /* ppSwapChain */
  6115. &_sapp.d3d11.device, /* ppDevice */
  6116. &result_feature_level, /* pFeatureLevel */
  6117. &_sapp.d3d11.device_context); /* ppImmediateContext */
  6118. }
  6119. #endif
  6120. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.swap_chain && _sapp.d3d11.device && _sapp.d3d11.device_context);
  6121. // minimize frame latency, disable Alt-Enter
  6122. hr = _sapp_d3d11_QueryInterface(_sapp.d3d11.device, _sapp_win32_refiid(_sapp_IID_IDXGIDevice1), (void**)&_sapp.d3d11.dxgi_device);
  6123. if (SUCCEEDED(hr) && _sapp.d3d11.dxgi_device) {
  6124. _sapp_dxgi_SetMaximumFrameLatency(_sapp.d3d11.dxgi_device, 1);
  6125. IDXGIAdapter* dxgi_adapter = 0;
  6126. hr = _sapp_dxgi_GetAdapter(_sapp.d3d11.dxgi_device, &dxgi_adapter);
  6127. if (SUCCEEDED(hr) && dxgi_adapter) {
  6128. IDXGIFactory* dxgi_factory = 0;
  6129. hr = _sapp_dxgi_GetParent((IDXGIObject*)dxgi_adapter, _sapp_win32_refiid(_sapp_IID_IDXGIFactory), (void**)&dxgi_factory);
  6130. if (SUCCEEDED(hr)) {
  6131. _sapp_dxgi_MakeWindowAssociation(dxgi_factory, _sapp.win32.hwnd, DXGI_MWA_NO_ALT_ENTER|DXGI_MWA_NO_PRINT_SCREEN);
  6132. _SAPP_SAFE_RELEASE(dxgi_factory);
  6133. }
  6134. else {
  6135. _SAPP_ERROR(WIN32_D3D11_GET_IDXGIFACTORY_FAILED);
  6136. }
  6137. _SAPP_SAFE_RELEASE(dxgi_adapter);
  6138. }
  6139. else {
  6140. _SAPP_ERROR(WIN32_D3D11_GET_IDXGIADAPTER_FAILED);
  6141. }
  6142. }
  6143. else {
  6144. _SAPP_PANIC(WIN32_D3D11_QUERY_INTERFACE_IDXGIDEVICE1_FAILED);
  6145. }
  6146. }
  6147. _SOKOL_PRIVATE void _sapp_d3d11_destroy_device_and_swapchain(void) {
  6148. _SAPP_SAFE_RELEASE(_sapp.d3d11.swap_chain);
  6149. _SAPP_SAFE_RELEASE(_sapp.d3d11.dxgi_device);
  6150. _SAPP_SAFE_RELEASE(_sapp.d3d11.device_context);
  6151. _SAPP_SAFE_RELEASE(_sapp.d3d11.device);
  6152. }
  6153. _SOKOL_PRIVATE void _sapp_d3d11_create_default_render_target(void) {
  6154. SOKOL_ASSERT(0 == _sapp.d3d11.rt);
  6155. SOKOL_ASSERT(0 == _sapp.d3d11.rtv);
  6156. SOKOL_ASSERT(0 == _sapp.d3d11.msaa_rt);
  6157. SOKOL_ASSERT(0 == _sapp.d3d11.msaa_rtv);
  6158. SOKOL_ASSERT(0 == _sapp.d3d11.ds);
  6159. SOKOL_ASSERT(0 == _sapp.d3d11.dsv);
  6160. HRESULT hr; _SOKOL_UNUSED(hr);
  6161. /* view for the swapchain-created framebuffer */
  6162. hr = _sapp_dxgi_GetBuffer(_sapp.d3d11.swap_chain, 0, _sapp_win32_refiid(_sapp_IID_ID3D11Texture2D), (void**)&_sapp.d3d11.rt);
  6163. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.rt);
  6164. hr = _sapp_d3d11_CreateRenderTargetView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.rt, NULL, &_sapp.d3d11.rtv);
  6165. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.rtv);
  6166. /* common desc for MSAA and depth-stencil texture */
  6167. D3D11_TEXTURE2D_DESC tex_desc;
  6168. _sapp_clear(&tex_desc, sizeof(tex_desc));
  6169. tex_desc.Width = (UINT)_sapp.framebuffer_width;
  6170. tex_desc.Height = (UINT)_sapp.framebuffer_height;
  6171. tex_desc.MipLevels = 1;
  6172. tex_desc.ArraySize = 1;
  6173. tex_desc.Usage = D3D11_USAGE_DEFAULT;
  6174. tex_desc.BindFlags = D3D11_BIND_RENDER_TARGET;
  6175. tex_desc.SampleDesc.Count = (UINT) _sapp.sample_count;
  6176. tex_desc.SampleDesc.Quality = (UINT) (_sapp.sample_count > 1 ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0);
  6177. /* create MSAA texture and view if antialiasing requested */
  6178. if (_sapp.sample_count > 1) {
  6179. tex_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  6180. hr = _sapp_d3d11_CreateTexture2D(_sapp.d3d11.device, &tex_desc, NULL, &_sapp.d3d11.msaa_rt);
  6181. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.msaa_rt);
  6182. hr = _sapp_d3d11_CreateRenderTargetView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.msaa_rt, NULL, &_sapp.d3d11.msaa_rtv);
  6183. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.msaa_rtv);
  6184. }
  6185. /* texture and view for the depth-stencil-surface */
  6186. tex_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  6187. tex_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  6188. hr = _sapp_d3d11_CreateTexture2D(_sapp.d3d11.device, &tex_desc, NULL, &_sapp.d3d11.ds);
  6189. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.ds);
  6190. hr = _sapp_d3d11_CreateDepthStencilView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.ds, NULL, &_sapp.d3d11.dsv);
  6191. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.dsv);
  6192. }
  6193. _SOKOL_PRIVATE void _sapp_d3d11_destroy_default_render_target(void) {
  6194. _SAPP_SAFE_RELEASE(_sapp.d3d11.rt);
  6195. _SAPP_SAFE_RELEASE(_sapp.d3d11.rtv);
  6196. _SAPP_SAFE_RELEASE(_sapp.d3d11.msaa_rt);
  6197. _SAPP_SAFE_RELEASE(_sapp.d3d11.msaa_rtv);
  6198. _SAPP_SAFE_RELEASE(_sapp.d3d11.ds);
  6199. _SAPP_SAFE_RELEASE(_sapp.d3d11.dsv);
  6200. }
  6201. _SOKOL_PRIVATE void _sapp_d3d11_resize_default_render_target(void) {
  6202. if (_sapp.d3d11.swap_chain) {
  6203. _sapp_d3d11_destroy_default_render_target();
  6204. _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);
  6205. _sapp_d3d11_create_default_render_target();
  6206. }
  6207. }
  6208. _SOKOL_PRIVATE void _sapp_d3d11_present(bool do_not_wait) {
  6209. UINT flags = 0;
  6210. if (_sapp.win32.is_win10_or_greater && do_not_wait) {
  6211. /* this hack/workaround somewhat improves window-movement and -sizing
  6212. responsiveness when rendering is controlled via WM_TIMER during window
  6213. move and resize on NVIDIA cards on Win10 with recent drivers.
  6214. */
  6215. flags = DXGI_PRESENT_DO_NOT_WAIT;
  6216. }
  6217. _sapp_dxgi_Present(_sapp.d3d11.swap_chain, (UINT)_sapp.swap_interval, flags);
  6218. }
  6219. #endif /* SOKOL_D3D11 */
  6220. #if defined(SOKOL_GLCORE)
  6221. _SOKOL_PRIVATE void _sapp_wgl_init(void) {
  6222. _sapp.wgl.opengl32 = LoadLibraryA("opengl32.dll");
  6223. if (!_sapp.wgl.opengl32) {
  6224. _SAPP_PANIC(WIN32_LOAD_OPENGL32_DLL_FAILED);
  6225. }
  6226. SOKOL_ASSERT(_sapp.wgl.opengl32);
  6227. _sapp.wgl.CreateContext = (PFN_wglCreateContext)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglCreateContext");
  6228. SOKOL_ASSERT(_sapp.wgl.CreateContext);
  6229. _sapp.wgl.DeleteContext = (PFN_wglDeleteContext)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglDeleteContext");
  6230. SOKOL_ASSERT(_sapp.wgl.DeleteContext);
  6231. _sapp.wgl.GetProcAddress = (PFN_wglGetProcAddress)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglGetProcAddress");
  6232. SOKOL_ASSERT(_sapp.wgl.GetProcAddress);
  6233. _sapp.wgl.GetCurrentDC = (PFN_wglGetCurrentDC)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglGetCurrentDC");
  6234. SOKOL_ASSERT(_sapp.wgl.GetCurrentDC);
  6235. _sapp.wgl.MakeCurrent = (PFN_wglMakeCurrent)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglMakeCurrent");
  6236. SOKOL_ASSERT(_sapp.wgl.MakeCurrent);
  6237. _sapp.wgl.GetIntegerv = (void(WINAPI*)(uint32_t, int32_t*)) GetProcAddress(_sapp.wgl.opengl32, "glGetIntegerv");
  6238. SOKOL_ASSERT(_sapp.wgl.GetIntegerv);
  6239. _sapp.wgl.msg_hwnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW,
  6240. L"SOKOLAPP",
  6241. L"sokol-app message window",
  6242. WS_CLIPSIBLINGS|WS_CLIPCHILDREN,
  6243. 0, 0, 1, 1,
  6244. NULL, NULL,
  6245. GetModuleHandleW(NULL),
  6246. NULL);
  6247. if (!_sapp.wgl.msg_hwnd) {
  6248. _SAPP_PANIC(WIN32_CREATE_HELPER_WINDOW_FAILED);
  6249. }
  6250. SOKOL_ASSERT(_sapp.wgl.msg_hwnd);
  6251. ShowWindow(_sapp.wgl.msg_hwnd, SW_HIDE);
  6252. MSG msg;
  6253. while (PeekMessageW(&msg, _sapp.wgl.msg_hwnd, 0, 0, PM_REMOVE)) {
  6254. TranslateMessage(&msg);
  6255. DispatchMessageW(&msg);
  6256. }
  6257. _sapp.wgl.msg_dc = GetDC(_sapp.wgl.msg_hwnd);
  6258. if (!_sapp.wgl.msg_dc) {
  6259. _SAPP_PANIC(WIN32_HELPER_WINDOW_GETDC_FAILED);
  6260. }
  6261. }
  6262. _SOKOL_PRIVATE void _sapp_wgl_shutdown(void) {
  6263. SOKOL_ASSERT(_sapp.wgl.opengl32 && _sapp.wgl.msg_hwnd);
  6264. DestroyWindow(_sapp.wgl.msg_hwnd); _sapp.wgl.msg_hwnd = 0;
  6265. FreeLibrary(_sapp.wgl.opengl32); _sapp.wgl.opengl32 = 0;
  6266. }
  6267. _SOKOL_PRIVATE bool _sapp_wgl_has_ext(const char* ext, const char* extensions) {
  6268. SOKOL_ASSERT(ext && extensions);
  6269. const char* start = extensions;
  6270. while (true) {
  6271. const char* where = strstr(start, ext);
  6272. if (!where) {
  6273. return false;
  6274. }
  6275. const char* terminator = where + strlen(ext);
  6276. if ((where == start) || (*(where - 1) == ' ')) {
  6277. if (*terminator == ' ' || *terminator == '\0') {
  6278. break;
  6279. }
  6280. }
  6281. start = terminator;
  6282. }
  6283. return true;
  6284. }
  6285. _SOKOL_PRIVATE bool _sapp_wgl_ext_supported(const char* ext) {
  6286. SOKOL_ASSERT(ext);
  6287. if (_sapp.wgl.GetExtensionsStringEXT) {
  6288. const char* extensions = _sapp.wgl.GetExtensionsStringEXT();
  6289. if (extensions) {
  6290. if (_sapp_wgl_has_ext(ext, extensions)) {
  6291. return true;
  6292. }
  6293. }
  6294. }
  6295. if (_sapp.wgl.GetExtensionsStringARB) {
  6296. const char* extensions = _sapp.wgl.GetExtensionsStringARB(_sapp.wgl.GetCurrentDC());
  6297. if (extensions) {
  6298. if (_sapp_wgl_has_ext(ext, extensions)) {
  6299. return true;
  6300. }
  6301. }
  6302. }
  6303. return false;
  6304. }
  6305. _SOKOL_PRIVATE void _sapp_wgl_load_extensions(void) {
  6306. SOKOL_ASSERT(_sapp.wgl.msg_dc);
  6307. PIXELFORMATDESCRIPTOR pfd;
  6308. _sapp_clear(&pfd, sizeof(pfd));
  6309. pfd.nSize = sizeof(pfd);
  6310. pfd.nVersion = 1;
  6311. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  6312. pfd.iPixelType = PFD_TYPE_RGBA;
  6313. pfd.cColorBits = 24;
  6314. if (!SetPixelFormat(_sapp.wgl.msg_dc, ChoosePixelFormat(_sapp.wgl.msg_dc, &pfd), &pfd)) {
  6315. _SAPP_PANIC(WIN32_DUMMY_CONTEXT_SET_PIXELFORMAT_FAILED);
  6316. }
  6317. HGLRC rc = _sapp.wgl.CreateContext(_sapp.wgl.msg_dc);
  6318. if (!rc) {
  6319. _SAPP_PANIC(WIN32_CREATE_DUMMY_CONTEXT_FAILED);
  6320. }
  6321. if (!_sapp.wgl.MakeCurrent(_sapp.wgl.msg_dc, rc)) {
  6322. _SAPP_PANIC(WIN32_DUMMY_CONTEXT_MAKE_CURRENT_FAILED);
  6323. }
  6324. _sapp.wgl.GetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void*) _sapp.wgl.GetProcAddress("wglGetExtensionsStringEXT");
  6325. _sapp.wgl.GetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)(void*) _sapp.wgl.GetProcAddress("wglGetExtensionsStringARB");
  6326. _sapp.wgl.CreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)(void*) _sapp.wgl.GetProcAddress("wglCreateContextAttribsARB");
  6327. _sapp.wgl.SwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)(void*) _sapp.wgl.GetProcAddress("wglSwapIntervalEXT");
  6328. _sapp.wgl.GetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)(void*) _sapp.wgl.GetProcAddress("wglGetPixelFormatAttribivARB");
  6329. _sapp.wgl.arb_multisample = _sapp_wgl_ext_supported("WGL_ARB_multisample");
  6330. _sapp.wgl.arb_create_context = _sapp_wgl_ext_supported("WGL_ARB_create_context");
  6331. _sapp.wgl.arb_create_context_profile = _sapp_wgl_ext_supported("WGL_ARB_create_context_profile");
  6332. _sapp.wgl.ext_swap_control = _sapp_wgl_ext_supported("WGL_EXT_swap_control");
  6333. _sapp.wgl.arb_pixel_format = _sapp_wgl_ext_supported("WGL_ARB_pixel_format");
  6334. _sapp.wgl.MakeCurrent(_sapp.wgl.msg_dc, 0);
  6335. _sapp.wgl.DeleteContext(rc);
  6336. }
  6337. _SOKOL_PRIVATE int _sapp_wgl_attrib(int pixel_format, int attrib) {
  6338. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6339. int value = 0;
  6340. if (!_sapp.wgl.GetPixelFormatAttribivARB(_sapp.win32.dc, pixel_format, 0, 1, &attrib, &value)) {
  6341. _SAPP_PANIC(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED);
  6342. }
  6343. return value;
  6344. }
  6345. _SOKOL_PRIVATE void _sapp_wgl_attribiv(int pixel_format, int num_attribs, const int* attribs, int* results) {
  6346. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6347. if (!_sapp.wgl.GetPixelFormatAttribivARB(_sapp.win32.dc, pixel_format, 0, num_attribs, attribs, results)) {
  6348. _SAPP_PANIC(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED);
  6349. }
  6350. }
  6351. _SOKOL_PRIVATE int _sapp_wgl_find_pixel_format(void) {
  6352. SOKOL_ASSERT(_sapp.win32.dc);
  6353. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6354. #define _sapp_wgl_num_query_tags (12)
  6355. const int query_tags[_sapp_wgl_num_query_tags] = {
  6356. WGL_SUPPORT_OPENGL_ARB,
  6357. WGL_DRAW_TO_WINDOW_ARB,
  6358. WGL_PIXEL_TYPE_ARB,
  6359. WGL_ACCELERATION_ARB,
  6360. WGL_DOUBLE_BUFFER_ARB,
  6361. WGL_RED_BITS_ARB,
  6362. WGL_GREEN_BITS_ARB,
  6363. WGL_BLUE_BITS_ARB,
  6364. WGL_ALPHA_BITS_ARB,
  6365. WGL_DEPTH_BITS_ARB,
  6366. WGL_STENCIL_BITS_ARB,
  6367. WGL_SAMPLES_ARB,
  6368. };
  6369. const int result_support_opengl_index = 0;
  6370. const int result_draw_to_window_index = 1;
  6371. const int result_pixel_type_index = 2;
  6372. const int result_acceleration_index = 3;
  6373. const int result_double_buffer_index = 4;
  6374. const int result_red_bits_index = 5;
  6375. const int result_green_bits_index = 6;
  6376. const int result_blue_bits_index = 7;
  6377. const int result_alpha_bits_index = 8;
  6378. const int result_depth_bits_index = 9;
  6379. const int result_stencil_bits_index = 10;
  6380. const int result_samples_index = 11;
  6381. int query_results[_sapp_wgl_num_query_tags] = {0};
  6382. // Drop the last item if multisample extension is not supported.
  6383. // If in future querying with multiple extensions, will have to shuffle index values to have active extensions on the end.
  6384. int query_count = _sapp_wgl_num_query_tags;
  6385. if (!_sapp.wgl.arb_multisample) {
  6386. query_count = _sapp_wgl_num_query_tags - 1;
  6387. }
  6388. int native_count = _sapp_wgl_attrib(1, WGL_NUMBER_PIXEL_FORMATS_ARB);
  6389. _sapp_gl_fbconfig desired;
  6390. _sapp_gl_init_fbconfig(&desired);
  6391. desired.red_bits = 8;
  6392. desired.green_bits = 8;
  6393. desired.blue_bits = 8;
  6394. desired.alpha_bits = 8;
  6395. desired.depth_bits = 24;
  6396. desired.stencil_bits = 8;
  6397. desired.doublebuffer = true;
  6398. desired.samples = (_sapp.sample_count > 1) ? _sapp.sample_count : 0;
  6399. int pixel_format = 0;
  6400. _sapp_gl_fbselect fbselect;
  6401. _sapp_gl_init_fbselect(&fbselect);
  6402. for (int i = 0; i < native_count; i++) {
  6403. const int n = i + 1;
  6404. _sapp_wgl_attribiv(n, query_count, query_tags, query_results);
  6405. if (query_results[result_support_opengl_index] == 0
  6406. || query_results[result_draw_to_window_index] == 0
  6407. || query_results[result_pixel_type_index] != WGL_TYPE_RGBA_ARB
  6408. || query_results[result_acceleration_index] == WGL_NO_ACCELERATION_ARB)
  6409. {
  6410. continue;
  6411. }
  6412. _sapp_gl_fbconfig u;
  6413. _sapp_clear(&u, sizeof(u));
  6414. u.red_bits = query_results[result_red_bits_index];
  6415. u.green_bits = query_results[result_green_bits_index];
  6416. u.blue_bits = query_results[result_blue_bits_index];
  6417. u.alpha_bits = query_results[result_alpha_bits_index];
  6418. u.depth_bits = query_results[result_depth_bits_index];
  6419. u.stencil_bits = query_results[result_stencil_bits_index];
  6420. u.doublebuffer = 0 != query_results[result_double_buffer_index];
  6421. u.samples = query_results[result_samples_index]; // NOTE: If arb_multisample is not supported - just takes the default 0
  6422. // Test if this pixel format is better than the previous one
  6423. if (_sapp_gl_select_fbconfig(&fbselect, &desired, &u)) {
  6424. pixel_format = (uintptr_t)n;
  6425. // Early exit if matching as good as possible
  6426. if (fbselect.best_match) {
  6427. break;
  6428. }
  6429. }
  6430. }
  6431. return pixel_format;
  6432. }
  6433. _SOKOL_PRIVATE void _sapp_wgl_create_context(void) {
  6434. int pixel_format = _sapp_wgl_find_pixel_format();
  6435. if (0 == pixel_format) {
  6436. _SAPP_PANIC(WIN32_WGL_FIND_PIXELFORMAT_FAILED);
  6437. }
  6438. PIXELFORMATDESCRIPTOR pfd;
  6439. if (!DescribePixelFormat(_sapp.win32.dc, pixel_format, sizeof(pfd), &pfd)) {
  6440. _SAPP_PANIC(WIN32_WGL_DESCRIBE_PIXELFORMAT_FAILED);
  6441. }
  6442. if (!SetPixelFormat(_sapp.win32.dc, pixel_format, &pfd)) {
  6443. _SAPP_PANIC(WIN32_WGL_SET_PIXELFORMAT_FAILED);
  6444. }
  6445. if (!_sapp.wgl.arb_create_context) {
  6446. _SAPP_PANIC(WIN32_WGL_ARB_CREATE_CONTEXT_REQUIRED);
  6447. }
  6448. if (!_sapp.wgl.arb_create_context_profile) {
  6449. _SAPP_PANIC(WIN32_WGL_ARB_CREATE_CONTEXT_PROFILE_REQUIRED);
  6450. }
  6451. const int attrs[] = {
  6452. WGL_CONTEXT_MAJOR_VERSION_ARB, _sapp.desc.gl_major_version,
  6453. WGL_CONTEXT_MINOR_VERSION_ARB, _sapp.desc.gl_minor_version,
  6454. #if defined(SOKOL_DEBUG)
  6455. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,
  6456. #else
  6457. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
  6458. #endif
  6459. WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
  6460. 0, 0
  6461. };
  6462. _sapp.wgl.gl_ctx = _sapp.wgl.CreateContextAttribsARB(_sapp.win32.dc, 0, attrs);
  6463. if (!_sapp.wgl.gl_ctx) {
  6464. const DWORD err = GetLastError();
  6465. if (err == (0xc0070000 | ERROR_INVALID_VERSION_ARB)) {
  6466. _SAPP_PANIC(WIN32_WGL_OPENGL_VERSION_NOT_SUPPORTED);
  6467. }
  6468. else if (err == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) {
  6469. _SAPP_PANIC(WIN32_WGL_OPENGL_PROFILE_NOT_SUPPORTED);
  6470. }
  6471. else if (err == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) {
  6472. _SAPP_PANIC(WIN32_WGL_INCOMPATIBLE_DEVICE_CONTEXT);
  6473. }
  6474. else {
  6475. _SAPP_PANIC(WIN32_WGL_CREATE_CONTEXT_ATTRIBS_FAILED_OTHER);
  6476. }
  6477. }
  6478. _sapp.wgl.MakeCurrent(_sapp.win32.dc, _sapp.wgl.gl_ctx);
  6479. if (_sapp.wgl.ext_swap_control) {
  6480. /* FIXME: DwmIsCompositionEnabled() (see GLFW) */
  6481. _sapp.wgl.SwapIntervalEXT(_sapp.swap_interval);
  6482. }
  6483. const uint32_t gl_framebuffer_binding = 0x8CA6;
  6484. _sapp.wgl.GetIntegerv(gl_framebuffer_binding, (int32_t*)&_sapp.gl.framebuffer);
  6485. }
  6486. _SOKOL_PRIVATE void _sapp_wgl_destroy_context(void) {
  6487. SOKOL_ASSERT(_sapp.wgl.gl_ctx);
  6488. _sapp.wgl.DeleteContext(_sapp.wgl.gl_ctx);
  6489. _sapp.wgl.gl_ctx = 0;
  6490. }
  6491. _SOKOL_PRIVATE void _sapp_wgl_swap_buffers(void) {
  6492. SOKOL_ASSERT(_sapp.win32.dc);
  6493. /* FIXME: DwmIsCompositionEnabled? (see GLFW) */
  6494. SwapBuffers(_sapp.win32.dc);
  6495. }
  6496. #endif /* SOKOL_GLCORE */
  6497. _SOKOL_PRIVATE bool _sapp_win32_wide_to_utf8(const wchar_t* src, char* dst, int dst_num_bytes) {
  6498. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  6499. _sapp_clear(dst, (size_t)dst_num_bytes);
  6500. const int bytes_needed = WideCharToMultiByte(CP_UTF8, 0, src, -1, NULL, 0, NULL, NULL);
  6501. if (bytes_needed <= dst_num_bytes) {
  6502. WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, dst_num_bytes, NULL, NULL);
  6503. return true;
  6504. }
  6505. else {
  6506. return false;
  6507. }
  6508. }
  6509. /* updates current window and framebuffer size from the window's client rect, returns true if size has changed */
  6510. _SOKOL_PRIVATE bool _sapp_win32_update_dimensions(void) {
  6511. RECT rect;
  6512. if (GetClientRect(_sapp.win32.hwnd, &rect)) {
  6513. float window_width = (float)(rect.right - rect.left) / _sapp.win32.dpi.window_scale;
  6514. float window_height = (float)(rect.bottom - rect.top) / _sapp.win32.dpi.window_scale;
  6515. _sapp.window_width = (int)roundf(window_width);
  6516. _sapp.window_height = (int)roundf(window_height);
  6517. int fb_width = (int)roundf(window_width * _sapp.win32.dpi.content_scale);
  6518. int fb_height = (int)roundf(window_height * _sapp.win32.dpi.content_scale);
  6519. /* prevent a framebuffer size of 0 when window is minimized */
  6520. if (0 == fb_width) {
  6521. fb_width = 1;
  6522. }
  6523. if (0 == fb_height) {
  6524. fb_height = 1;
  6525. }
  6526. if ((fb_width != _sapp.framebuffer_width) || (fb_height != _sapp.framebuffer_height)) {
  6527. _sapp.framebuffer_width = fb_width;
  6528. _sapp.framebuffer_height = fb_height;
  6529. return true;
  6530. }
  6531. }
  6532. else {
  6533. _sapp.window_width = _sapp.window_height = 1;
  6534. _sapp.framebuffer_width = _sapp.framebuffer_height = 1;
  6535. }
  6536. return false;
  6537. }
  6538. _SOKOL_PRIVATE void _sapp_win32_set_fullscreen(bool fullscreen, UINT swp_flags) {
  6539. HMONITOR monitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONEAREST);
  6540. MONITORINFO minfo;
  6541. _sapp_clear(&minfo, sizeof(minfo));
  6542. minfo.cbSize = sizeof(MONITORINFO);
  6543. GetMonitorInfo(monitor, &minfo);
  6544. const RECT mr = minfo.rcMonitor;
  6545. const int monitor_w = mr.right - mr.left;
  6546. const int monitor_h = mr.bottom - mr.top;
  6547. const DWORD win_ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  6548. DWORD win_style;
  6549. RECT rect = { 0, 0, 0, 0 };
  6550. _sapp.fullscreen = fullscreen;
  6551. if (!_sapp.fullscreen) {
  6552. win_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
  6553. rect = _sapp.win32.stored_window_rect;
  6554. }
  6555. else {
  6556. GetWindowRect(_sapp.win32.hwnd, &_sapp.win32.stored_window_rect);
  6557. win_style = WS_POPUP | WS_SYSMENU | WS_VISIBLE;
  6558. rect.left = mr.left;
  6559. rect.top = mr.top;
  6560. rect.right = rect.left + monitor_w;
  6561. rect.bottom = rect.top + monitor_h;
  6562. AdjustWindowRectEx(&rect, win_style, FALSE, win_ex_style);
  6563. }
  6564. const int win_w = rect.right - rect.left;
  6565. const int win_h = rect.bottom - rect.top;
  6566. const int win_x = rect.left;
  6567. const int win_y = rect.top;
  6568. SetWindowLongPtr(_sapp.win32.hwnd, GWL_STYLE, win_style);
  6569. SetWindowPos(_sapp.win32.hwnd, HWND_TOP, win_x, win_y, win_w, win_h, swp_flags | SWP_FRAMECHANGED);
  6570. }
  6571. _SOKOL_PRIVATE void _sapp_win32_toggle_fullscreen(void) {
  6572. _sapp_win32_set_fullscreen(!_sapp.fullscreen, SWP_SHOWWINDOW);
  6573. }
  6574. _SOKOL_PRIVATE void _sapp_win32_init_cursor(sapp_mouse_cursor cursor) {
  6575. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  6576. // NOTE: the OCR_* constants are only defined if OEMRESOURCE is defined
  6577. // before windows.h is included, but we can't guarantee that because
  6578. // the sokol_app.h implementation may be included with other implementations
  6579. // in the same compilation unit
  6580. int id = 0;
  6581. switch (cursor) {
  6582. case SAPP_MOUSECURSOR_ARROW: id = 32512; break; // OCR_NORMAL
  6583. case SAPP_MOUSECURSOR_IBEAM: id = 32513; break; // OCR_IBEAM
  6584. case SAPP_MOUSECURSOR_CROSSHAIR: id = 32515; break; // OCR_CROSS
  6585. case SAPP_MOUSECURSOR_POINTING_HAND: id = 32649; break; // OCR_HAND
  6586. case SAPP_MOUSECURSOR_RESIZE_EW: id = 32644; break; // OCR_SIZEWE
  6587. case SAPP_MOUSECURSOR_RESIZE_NS: id = 32645; break; // OCR_SIZENS
  6588. case SAPP_MOUSECURSOR_RESIZE_NWSE: id = 32642; break; // OCR_SIZENWSE
  6589. case SAPP_MOUSECURSOR_RESIZE_NESW: id = 32643; break; // OCR_SIZENESW
  6590. case SAPP_MOUSECURSOR_RESIZE_ALL: id = 32646; break; // OCR_SIZEALL
  6591. case SAPP_MOUSECURSOR_NOT_ALLOWED: id = 32648; break; // OCR_NO
  6592. default: break;
  6593. }
  6594. if (id != 0) {
  6595. _sapp.win32.cursors[cursor] = (HCURSOR)LoadImageW(NULL, MAKEINTRESOURCEW(id), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE|LR_SHARED);
  6596. }
  6597. // fallback: default cursor
  6598. if (0 == _sapp.win32.cursors[cursor]) {
  6599. // 32512 => IDC_ARROW
  6600. _sapp.win32.cursors[cursor] = LoadCursorW(NULL, MAKEINTRESOURCEW(32512));
  6601. }
  6602. SOKOL_ASSERT(0 != _sapp.win32.cursors[cursor]);
  6603. }
  6604. _SOKOL_PRIVATE void _sapp_win32_init_cursors(void) {
  6605. for (int i = 0; i < _SAPP_MOUSECURSOR_NUM; i++) {
  6606. _sapp_win32_init_cursor((sapp_mouse_cursor)i);
  6607. }
  6608. }
  6609. _SOKOL_PRIVATE bool _sapp_win32_cursor_in_content_area(void) {
  6610. POINT pos;
  6611. if (!GetCursorPos(&pos)) {
  6612. return false;
  6613. }
  6614. if (WindowFromPoint(pos) != _sapp.win32.hwnd) {
  6615. return false;
  6616. }
  6617. RECT area;
  6618. GetClientRect(_sapp.win32.hwnd, &area);
  6619. ClientToScreen(_sapp.win32.hwnd, (POINT*)&area.left);
  6620. ClientToScreen(_sapp.win32.hwnd, (POINT*)&area.right);
  6621. return PtInRect(&area, pos) == TRUE;
  6622. }
  6623. _SOKOL_PRIVATE void _sapp_win32_update_cursor(sapp_mouse_cursor cursor, bool shown, bool skip_area_test) {
  6624. // NOTE: when called from WM_SETCURSOR, the area test would be redundant
  6625. if (!skip_area_test) {
  6626. if (!_sapp_win32_cursor_in_content_area()) {
  6627. return;
  6628. }
  6629. }
  6630. if (!shown) {
  6631. SetCursor(NULL);
  6632. }
  6633. else {
  6634. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  6635. SOKOL_ASSERT(0 != _sapp.win32.cursors[cursor]);
  6636. SetCursor(_sapp.win32.cursors[cursor]);
  6637. }
  6638. }
  6639. _SOKOL_PRIVATE void _sapp_win32_capture_mouse(uint8_t btn_mask) {
  6640. if (0 == _sapp.win32.mouse.capture_mask) {
  6641. SetCapture(_sapp.win32.hwnd);
  6642. }
  6643. _sapp.win32.mouse.capture_mask |= btn_mask;
  6644. }
  6645. _SOKOL_PRIVATE void _sapp_win32_release_mouse(uint8_t btn_mask) {
  6646. if (0 != _sapp.win32.mouse.capture_mask) {
  6647. _sapp.win32.mouse.capture_mask &= ~btn_mask;
  6648. if (0 == _sapp.win32.mouse.capture_mask) {
  6649. ReleaseCapture();
  6650. }
  6651. }
  6652. }
  6653. _SOKOL_PRIVATE bool _sapp_win32_is_foreground_window(void) {
  6654. return _sapp.win32.hwnd == GetForegroundWindow();
  6655. }
  6656. _SOKOL_PRIVATE void _sapp_win32_lock_mouse(bool lock) {
  6657. _sapp.win32.mouse.requested_lock = lock;
  6658. }
  6659. _SOKOL_PRIVATE void _sapp_win32_free_raw_input_data(void) {
  6660. if (_sapp.win32.raw_input_data.ptr) {
  6661. _sapp_free(_sapp.win32.raw_input_data.ptr);
  6662. _sapp.win32.raw_input_data.ptr = 0;
  6663. _sapp.win32.raw_input_data.size = 0;
  6664. }
  6665. }
  6666. _SOKOL_PRIVATE void _sapp_win32_alloc_raw_input_data(size_t size) {
  6667. SOKOL_ASSERT(!_sapp.win32.raw_input_data.ptr);
  6668. SOKOL_ASSERT(size > 0);
  6669. _sapp.win32.raw_input_data.ptr = _sapp_malloc(size);
  6670. _sapp.win32.raw_input_data.size = size;
  6671. SOKOL_ASSERT(_sapp.win32.raw_input_data.ptr);
  6672. }
  6673. _SOKOL_PRIVATE void* _sapp_win32_ensure_raw_input_data(size_t required_size) {
  6674. if (required_size > _sapp.win32.raw_input_data.size) {
  6675. _sapp_win32_free_raw_input_data();
  6676. _sapp_win32_alloc_raw_input_data(required_size);
  6677. }
  6678. // we expect that malloc() returns at least 8-byte aligned memory
  6679. SOKOL_ASSERT((((uintptr_t)_sapp.win32.raw_input_data.ptr) & 7) == 0);
  6680. return _sapp.win32.raw_input_data.ptr;
  6681. }
  6682. _SOKOL_PRIVATE void _sapp_win32_do_lock_mouse(void) {
  6683. _sapp.mouse.locked = true;
  6684. // hide mouse cursor (NOTE: this maintains a hidden counter, but since
  6685. // only mouse-lock uses ShowCursor this doesn't matter)
  6686. ShowCursor(FALSE);
  6687. // reset dx/dy and release any active mouse capture
  6688. _sapp.mouse.dx = 0.0f;
  6689. _sapp.mouse.dy = 0.0f;
  6690. _sapp_win32_release_mouse(0xFF);
  6691. // store current mouse position so that it can be restored when unlocked
  6692. POINT pos;
  6693. if (GetCursorPos(&pos)) {
  6694. _sapp.win32.mouse.lock.pos_valid = true;
  6695. _sapp.win32.mouse.lock.pos_x = pos.x;
  6696. _sapp.win32.mouse.lock.pos_y = pos.y;
  6697. } else {
  6698. _sapp.win32.mouse.lock.pos_valid = false;
  6699. }
  6700. // while mouse is locked, restrict cursor movement to the client
  6701. // rectangle so that we don't loose any mouse movement events
  6702. RECT client_rect;
  6703. GetClientRect(_sapp.win32.hwnd, &client_rect);
  6704. POINT mid_point;
  6705. mid_point.x = (client_rect.right - client_rect.left) / 2;
  6706. mid_point.y = (client_rect.bottom - client_rect.top) / 2;
  6707. ClientToScreen(_sapp.win32.hwnd, &mid_point);
  6708. RECT clip_rect;
  6709. clip_rect.left = clip_rect.right = mid_point.x;
  6710. clip_rect.top = clip_rect.bottom = mid_point.y;
  6711. ClipCursor(&clip_rect);
  6712. // enable raw input for mouse, starts sending WM_INPUT messages to WinProc (see GLFW)
  6713. const RAWINPUTDEVICE rid = {
  6714. 0x01, // usUsagePage: HID_USAGE_PAGE_GENERIC
  6715. 0x02, // usUsage: HID_USAGE_GENERIC_MOUSE
  6716. 0, // dwFlags
  6717. _sapp.win32.hwnd // hwndTarget
  6718. };
  6719. if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
  6720. _SAPP_ERROR(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_LOCK);
  6721. }
  6722. // in case the raw mouse device only supports absolute position reporting,
  6723. // we need to skip the dx/dy compution for the first WM_INPUT event
  6724. _sapp.win32.mouse.raw_input.pos_valid = false;
  6725. }
  6726. _SOKOL_PRIVATE void _sapp_win32_do_unlock_mouse(void) {
  6727. _sapp.mouse.locked = false;
  6728. // make mouse cursor visible
  6729. ShowCursor(TRUE);
  6730. // reset dx/dy and release any active mouse capture
  6731. _sapp.mouse.dx = 0.0f;
  6732. _sapp.mouse.dy = 0.0f;
  6733. _sapp_win32_release_mouse(0xFF);
  6734. // disable raw input for mouse
  6735. const RAWINPUTDEVICE rid = { 0x01, 0x02, RIDEV_REMOVE, NULL };
  6736. if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
  6737. _SAPP_ERROR(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_UNLOCK);
  6738. }
  6739. // unrestrict mouse movement
  6740. ClipCursor(NULL);
  6741. // restore the 'pre-locked' mouse position
  6742. if (_sapp.win32.mouse.lock.pos_valid) {
  6743. SetCursorPos(_sapp.win32.mouse.lock.pos_x, _sapp.win32.mouse.lock.pos_y);
  6744. _sapp.win32.mouse.lock.pos_valid = false;
  6745. }
  6746. }
  6747. _SOKOL_PRIVATE void _sapp_win32_update_mouse_lock(void) {
  6748. // mouse lock can only be active when we're the active window
  6749. if (!_sapp_win32_is_foreground_window()) {
  6750. // unlock mouse if currently locked
  6751. if (_sapp.mouse.locked) {
  6752. _sapp_win32_do_unlock_mouse();
  6753. }
  6754. return;
  6755. }
  6756. // nothing to do if requested lock state matches current lock state
  6757. const bool lock = _sapp.win32.mouse.requested_lock;
  6758. if (lock == _sapp.mouse.locked) {
  6759. return;
  6760. }
  6761. // otherwise change into desired state
  6762. if (lock) {
  6763. _sapp_win32_do_lock_mouse();
  6764. } else {
  6765. _sapp_win32_do_unlock_mouse();
  6766. }
  6767. }
  6768. _SOKOL_PRIVATE bool _sapp_win32_update_monitor(void) {
  6769. const HMONITOR cur_monitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONULL);
  6770. if (cur_monitor != _sapp.win32.hmonitor) {
  6771. _sapp.win32.hmonitor = cur_monitor;
  6772. return true;
  6773. }
  6774. else {
  6775. return false;
  6776. }
  6777. }
  6778. _SOKOL_PRIVATE uint32_t _sapp_win32_mods(void) {
  6779. uint32_t mods = 0;
  6780. if (GetKeyState(VK_SHIFT) & (1<<15)) {
  6781. mods |= SAPP_MODIFIER_SHIFT;
  6782. }
  6783. if (GetKeyState(VK_CONTROL) & (1<<15)) {
  6784. mods |= SAPP_MODIFIER_CTRL;
  6785. }
  6786. if (GetKeyState(VK_MENU) & (1<<15)) {
  6787. mods |= SAPP_MODIFIER_ALT;
  6788. }
  6789. if ((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & (1<<15)) {
  6790. mods |= SAPP_MODIFIER_SUPER;
  6791. }
  6792. const bool swapped = (TRUE == GetSystemMetrics(SM_SWAPBUTTON));
  6793. if (GetAsyncKeyState(VK_LBUTTON)) {
  6794. mods |= swapped ? SAPP_MODIFIER_RMB : SAPP_MODIFIER_LMB;
  6795. }
  6796. if (GetAsyncKeyState(VK_RBUTTON)) {
  6797. mods |= swapped ? SAPP_MODIFIER_LMB : SAPP_MODIFIER_RMB;
  6798. }
  6799. if (GetAsyncKeyState(VK_MBUTTON)) {
  6800. mods |= SAPP_MODIFIER_MMB;
  6801. }
  6802. return mods;
  6803. }
  6804. _SOKOL_PRIVATE void _sapp_win32_mouse_update(LPARAM lParam) {
  6805. if (!_sapp.mouse.locked) {
  6806. const float new_x = (float)GET_X_LPARAM(lParam) * _sapp.win32.dpi.mouse_scale;
  6807. const float new_y = (float)GET_Y_LPARAM(lParam) * _sapp.win32.dpi.mouse_scale;
  6808. if (_sapp.mouse.pos_valid) {
  6809. // don't update dx/dy in the very first event
  6810. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  6811. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  6812. }
  6813. _sapp.mouse.x = new_x;
  6814. _sapp.mouse.y = new_y;
  6815. _sapp.mouse.pos_valid = true;
  6816. }
  6817. }
  6818. _SOKOL_PRIVATE void _sapp_win32_mouse_event(sapp_event_type type, sapp_mousebutton btn) {
  6819. if (_sapp_events_enabled()) {
  6820. _sapp_init_event(type);
  6821. _sapp.event.modifiers = _sapp_win32_mods();
  6822. _sapp.event.mouse_button = btn;
  6823. _sapp_call_event(&_sapp.event);
  6824. }
  6825. }
  6826. _SOKOL_PRIVATE void _sapp_win32_scroll_event(float x, float y) {
  6827. if (_sapp_events_enabled()) {
  6828. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  6829. _sapp.event.modifiers = _sapp_win32_mods();
  6830. _sapp.event.scroll_x = -x / 30.0f;
  6831. _sapp.event.scroll_y = y / 30.0f;
  6832. _sapp_call_event(&_sapp.event);
  6833. }
  6834. }
  6835. _SOKOL_PRIVATE void _sapp_win32_key_event(sapp_event_type type, int vk, bool repeat) {
  6836. if (_sapp_events_enabled() && (vk < SAPP_MAX_KEYCODES)) {
  6837. _sapp_init_event(type);
  6838. _sapp.event.modifiers = _sapp_win32_mods();
  6839. _sapp.event.key_code = _sapp.keycodes[vk];
  6840. _sapp.event.key_repeat = repeat;
  6841. _sapp_call_event(&_sapp.event);
  6842. /* check if a CLIPBOARD_PASTED event must be sent too */
  6843. if (_sapp.clipboard.enabled &&
  6844. (type == SAPP_EVENTTYPE_KEY_DOWN) &&
  6845. (_sapp.event.modifiers == SAPP_MODIFIER_CTRL) &&
  6846. (_sapp.event.key_code == SAPP_KEYCODE_V))
  6847. {
  6848. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  6849. _sapp_call_event(&_sapp.event);
  6850. }
  6851. }
  6852. }
  6853. _SOKOL_PRIVATE void _sapp_win32_char_event(uint32_t c, bool repeat) {
  6854. if (_sapp_events_enabled() && (c >= 32)) {
  6855. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  6856. _sapp.event.modifiers = _sapp_win32_mods();
  6857. _sapp.event.char_code = c;
  6858. _sapp.event.key_repeat = repeat;
  6859. _sapp_call_event(&_sapp.event);
  6860. }
  6861. }
  6862. _SOKOL_PRIVATE void _sapp_win32_dpi_changed(HWND hWnd, LPRECT proposed_win_rect) {
  6863. /* called on WM_DPICHANGED, which will only be sent to the application
  6864. if sapp_desc.high_dpi is true and the Windows version is recent enough
  6865. to support DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  6866. */
  6867. SOKOL_ASSERT(_sapp.desc.high_dpi);
  6868. HINSTANCE user32 = LoadLibraryA("user32.dll");
  6869. if (!user32) {
  6870. return;
  6871. }
  6872. typedef UINT(WINAPI * GETDPIFORWINDOW_T)(HWND hwnd);
  6873. GETDPIFORWINDOW_T fn_getdpiforwindow = (GETDPIFORWINDOW_T)(void*)GetProcAddress(user32, "GetDpiForWindow");
  6874. if (fn_getdpiforwindow) {
  6875. UINT dpix = fn_getdpiforwindow(_sapp.win32.hwnd);
  6876. // NOTE: for high-dpi apps, mouse_scale remains one
  6877. _sapp.win32.dpi.window_scale = (float)dpix / 96.0f;
  6878. _sapp.win32.dpi.content_scale = _sapp.win32.dpi.window_scale;
  6879. _sapp.dpi_scale = _sapp.win32.dpi.window_scale;
  6880. SetWindowPos(hWnd, 0,
  6881. proposed_win_rect->left,
  6882. proposed_win_rect->top,
  6883. proposed_win_rect->right - proposed_win_rect->left,
  6884. proposed_win_rect->bottom - proposed_win_rect->top,
  6885. SWP_NOZORDER | SWP_NOACTIVATE);
  6886. }
  6887. FreeLibrary(user32);
  6888. }
  6889. _SOKOL_PRIVATE void _sapp_win32_files_dropped(HDROP hdrop) {
  6890. if (!_sapp.drop.enabled) {
  6891. return;
  6892. }
  6893. _sapp_clear_drop_buffer();
  6894. bool drop_failed = false;
  6895. const int count = (int) DragQueryFileW(hdrop, 0xffffffff, NULL, 0);
  6896. _sapp.drop.num_files = (count > _sapp.drop.max_files) ? _sapp.drop.max_files : count;
  6897. for (UINT i = 0; i < (UINT)_sapp.drop.num_files; i++) {
  6898. const UINT num_chars = DragQueryFileW(hdrop, i, NULL, 0) + 1;
  6899. WCHAR* buffer = (WCHAR*) _sapp_malloc_clear(num_chars * sizeof(WCHAR));
  6900. DragQueryFileW(hdrop, i, buffer, num_chars);
  6901. if (!_sapp_win32_wide_to_utf8(buffer, _sapp_dropped_file_path_ptr((int)i), _sapp.drop.max_path_length)) {
  6902. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  6903. drop_failed = true;
  6904. }
  6905. _sapp_free(buffer);
  6906. }
  6907. DragFinish(hdrop);
  6908. if (!drop_failed) {
  6909. if (_sapp_events_enabled()) {
  6910. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  6911. _sapp.event.modifiers = _sapp_win32_mods();
  6912. _sapp_call_event(&_sapp.event);
  6913. }
  6914. }
  6915. else {
  6916. _sapp_clear_drop_buffer();
  6917. _sapp.drop.num_files = 0;
  6918. }
  6919. }
  6920. _SOKOL_PRIVATE void _sapp_win32_timing_measure(void) {
  6921. #if defined(SOKOL_D3D11)
  6922. // on D3D11, use the more precise DXGI timestamp
  6923. if (_sapp.d3d11.use_dxgi_frame_stats) {
  6924. DXGI_FRAME_STATISTICS dxgi_stats;
  6925. _sapp_clear(&dxgi_stats, sizeof(dxgi_stats));
  6926. HRESULT hr = _sapp_dxgi_GetFrameStatistics(_sapp.d3d11.swap_chain, &dxgi_stats);
  6927. if (SUCCEEDED(hr)) {
  6928. if (dxgi_stats.SyncRefreshCount != _sapp.d3d11.sync_refresh_count) {
  6929. if ((_sapp.d3d11.sync_refresh_count + 1) != dxgi_stats.SyncRefreshCount) {
  6930. _sapp_timing_discontinuity(&_sapp.timing);
  6931. }
  6932. _sapp.d3d11.sync_refresh_count = dxgi_stats.SyncRefreshCount;
  6933. LARGE_INTEGER qpc = dxgi_stats.SyncQPCTime;
  6934. const uint64_t now = (uint64_t)_sapp_int64_muldiv(qpc.QuadPart - _sapp.timing.timestamp.win.start.QuadPart, 1000000000, _sapp.timing.timestamp.win.freq.QuadPart);
  6935. _sapp_timing_external(&_sapp.timing, (double)now / 1000000000.0);
  6936. }
  6937. return;
  6938. }
  6939. }
  6940. // fallback if swap model isn't "flip-discard" or GetFrameStatistics failed for another reason
  6941. _sapp_timing_measure(&_sapp.timing);
  6942. #endif
  6943. #if defined(SOKOL_GLCORE)
  6944. _sapp_timing_measure(&_sapp.timing);
  6945. #endif
  6946. #if defined(SOKOL_NOAPI)
  6947. _sapp_timing_measure(&_sapp.timing);
  6948. #endif
  6949. }
  6950. _SOKOL_PRIVATE LRESULT CALLBACK _sapp_win32_wndproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  6951. if (!_sapp.win32.in_create_window) {
  6952. switch (uMsg) {
  6953. case WM_CLOSE:
  6954. /* only give user a chance to intervene when sapp_quit() wasn't already called */
  6955. if (!_sapp.quit_ordered) {
  6956. /* if window should be closed and event handling is enabled, give user code
  6957. a change to intervene via sapp_cancel_quit()
  6958. */
  6959. _sapp.quit_requested = true;
  6960. _sapp_win32_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  6961. /* if user code hasn't intervened, quit the app */
  6962. if (_sapp.quit_requested) {
  6963. _sapp.quit_ordered = true;
  6964. }
  6965. }
  6966. if (_sapp.quit_ordered) {
  6967. PostQuitMessage(0);
  6968. }
  6969. return 0;
  6970. case WM_SYSCOMMAND:
  6971. switch (wParam & 0xFFF0) {
  6972. case SC_SCREENSAVE:
  6973. case SC_MONITORPOWER:
  6974. if (_sapp.fullscreen) {
  6975. /* disable screen saver and blanking in fullscreen mode */
  6976. return 0;
  6977. }
  6978. break;
  6979. case SC_KEYMENU:
  6980. /* user trying to access menu via ALT */
  6981. return 0;
  6982. }
  6983. break;
  6984. case WM_ERASEBKGND:
  6985. return 1;
  6986. case WM_SIZE:
  6987. {
  6988. const bool iconified = wParam == SIZE_MINIMIZED;
  6989. if (iconified != _sapp.win32.iconified) {
  6990. _sapp.win32.iconified = iconified;
  6991. if (iconified) {
  6992. _sapp_win32_app_event(SAPP_EVENTTYPE_ICONIFIED);
  6993. }
  6994. else {
  6995. _sapp_win32_app_event(SAPP_EVENTTYPE_RESTORED);
  6996. }
  6997. }
  6998. }
  6999. break;
  7000. case WM_SETFOCUS:
  7001. _sapp_win32_app_event(SAPP_EVENTTYPE_FOCUSED);
  7002. break;
  7003. case WM_KILLFOCUS:
  7004. _sapp_win32_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  7005. break;
  7006. case WM_SETCURSOR:
  7007. if (LOWORD(lParam) == HTCLIENT) {
  7008. _sapp_win32_update_cursor(_sapp.mouse.current_cursor, _sapp.mouse.shown, true);
  7009. return TRUE;
  7010. }
  7011. break;
  7012. case WM_DPICHANGED:
  7013. {
  7014. /* Update window's DPI and size if its moved to another monitor with a different DPI
  7015. Only sent if DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is used.
  7016. */
  7017. _sapp_win32_dpi_changed(hWnd, (LPRECT)lParam);
  7018. break;
  7019. }
  7020. case WM_LBUTTONDOWN:
  7021. _sapp_win32_mouse_update(lParam);
  7022. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_LEFT);
  7023. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_LEFT);
  7024. break;
  7025. case WM_RBUTTONDOWN:
  7026. _sapp_win32_mouse_update(lParam);
  7027. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_RIGHT);
  7028. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_RIGHT);
  7029. break;
  7030. case WM_MBUTTONDOWN:
  7031. _sapp_win32_mouse_update(lParam);
  7032. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_MIDDLE);
  7033. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_MIDDLE);
  7034. break;
  7035. case WM_LBUTTONUP:
  7036. _sapp_win32_mouse_update(lParam);
  7037. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_LEFT);
  7038. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_LEFT);
  7039. break;
  7040. case WM_RBUTTONUP:
  7041. _sapp_win32_mouse_update(lParam);
  7042. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_RIGHT);
  7043. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_RIGHT);
  7044. break;
  7045. case WM_MBUTTONUP:
  7046. _sapp_win32_mouse_update(lParam);
  7047. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_MIDDLE);
  7048. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_MIDDLE);
  7049. break;
  7050. case WM_MOUSEMOVE:
  7051. if (!_sapp.mouse.locked) {
  7052. _sapp_win32_mouse_update(lParam);
  7053. if (!_sapp.win32.mouse.tracked) {
  7054. _sapp.win32.mouse.tracked = true;
  7055. TRACKMOUSEEVENT tme;
  7056. _sapp_clear(&tme, sizeof(tme));
  7057. tme.cbSize = sizeof(tme);
  7058. tme.dwFlags = TME_LEAVE;
  7059. tme.hwndTrack = _sapp.win32.hwnd;
  7060. TrackMouseEvent(&tme);
  7061. _sapp.mouse.dx = 0.0f;
  7062. _sapp.mouse.dy = 0.0f;
  7063. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID);
  7064. }
  7065. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID);
  7066. }
  7067. break;
  7068. case WM_INPUT:
  7069. /* raw mouse input during mouse-lock */
  7070. if (_sapp.mouse.locked) {
  7071. HRAWINPUT ri = (HRAWINPUT) lParam;
  7072. // see: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getrawinputdata
  7073. // also see: https://github.com/glfw/glfw/blob/e7ea71be039836da3a98cea55ae5569cb5eb885c/src/win32_window.c#L912-L924
  7074. // first poll for required size to alloc/grow input buffer, then get the actual data
  7075. UINT size = 0;
  7076. GetRawInputData(ri, RID_INPUT, NULL, &size, sizeof(RAWINPUTHEADER));
  7077. void* raw_input_data_ptr = _sapp_win32_ensure_raw_input_data(size);
  7078. if ((UINT)-1 == GetRawInputData(ri, RID_INPUT, raw_input_data_ptr, &size, sizeof(RAWINPUTHEADER))) {
  7079. _SAPP_ERROR(WIN32_GET_RAW_INPUT_DATA_FAILED);
  7080. break;
  7081. }
  7082. const RAWINPUT* raw_mouse_data = (const RAWINPUT*) raw_input_data_ptr;
  7083. if (raw_mouse_data->data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE) {
  7084. /* mouse only reports absolute position
  7085. NOTE: This code is untested and will most likely behave wrong in Remote Desktop sessions.
  7086. (such remote desktop sessions are setting the MOUSE_MOVE_ABSOLUTE flag).
  7087. See: https://github.com/floooh/sokol/issues/806 and
  7088. https://github.com/microsoft/DirectXTK/commit/ef56b63f3739381e451f7a5a5bd2c9779d2a7555)
  7089. */
  7090. LONG new_x = raw_mouse_data->data.mouse.lLastX;
  7091. LONG new_y = raw_mouse_data->data.mouse.lLastY;
  7092. if (_sapp.win32.mouse.raw_input.pos_valid) {
  7093. _sapp.mouse.dx = (float) (new_x - _sapp.win32.mouse.raw_input.pos_x);
  7094. _sapp.mouse.dy = (float) (new_y - _sapp.win32.mouse.raw_input.pos_y);
  7095. }
  7096. _sapp.win32.mouse.raw_input.pos_x = new_x;
  7097. _sapp.win32.mouse.raw_input.pos_y = new_y;
  7098. _sapp.win32.mouse.raw_input.pos_valid = true;
  7099. }
  7100. else {
  7101. /* mouse reports movement delta (this seems to be the common case) */
  7102. _sapp.mouse.dx = (float) raw_mouse_data->data.mouse.lLastX;
  7103. _sapp.mouse.dy = (float) raw_mouse_data->data.mouse.lLastY;
  7104. }
  7105. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID);
  7106. }
  7107. break;
  7108. case WM_MOUSELEAVE:
  7109. if (!_sapp.mouse.locked) {
  7110. _sapp.mouse.dx = 0.0f;
  7111. _sapp.mouse.dy = 0.0f;
  7112. _sapp.win32.mouse.tracked = false;
  7113. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID);
  7114. }
  7115. break;
  7116. case WM_MOUSEWHEEL:
  7117. _sapp_win32_scroll_event(0.0f, (float)((SHORT)HIWORD(wParam)));
  7118. break;
  7119. case WM_MOUSEHWHEEL:
  7120. _sapp_win32_scroll_event((float)((SHORT)HIWORD(wParam)), 0.0f);
  7121. break;
  7122. case WM_CHAR:
  7123. _sapp_win32_char_event((uint32_t)wParam, !!(lParam&0x40000000));
  7124. break;
  7125. case WM_KEYDOWN:
  7126. case WM_SYSKEYDOWN:
  7127. _sapp_win32_key_event(SAPP_EVENTTYPE_KEY_DOWN, (int)(HIWORD(lParam)&0x1FF), !!(lParam&0x40000000));
  7128. break;
  7129. case WM_KEYUP:
  7130. case WM_SYSKEYUP:
  7131. _sapp_win32_key_event(SAPP_EVENTTYPE_KEY_UP, (int)(HIWORD(lParam)&0x1FF), false);
  7132. break;
  7133. case WM_ENTERSIZEMOVE:
  7134. SetTimer(_sapp.win32.hwnd, 1, USER_TIMER_MINIMUM, NULL);
  7135. break;
  7136. case WM_EXITSIZEMOVE:
  7137. KillTimer(_sapp.win32.hwnd, 1);
  7138. break;
  7139. case WM_TIMER:
  7140. _sapp_win32_timing_measure();
  7141. _sapp_frame();
  7142. #if defined(SOKOL_D3D11)
  7143. // present with DXGI_PRESENT_DO_NOT_WAIT
  7144. _sapp_d3d11_present(true);
  7145. #endif
  7146. #if defined(SOKOL_GLCORE)
  7147. _sapp_wgl_swap_buffers();
  7148. #endif
  7149. /* NOTE: resizing the swap-chain during resize leads to a substantial
  7150. memory spike (hundreds of megabytes for a few seconds).
  7151. if (_sapp_win32_update_dimensions()) {
  7152. #if defined(SOKOL_D3D11)
  7153. _sapp_d3d11_resize_default_render_target();
  7154. #endif
  7155. _sapp_win32_app_event(SAPP_EVENTTYPE_RESIZED);
  7156. }
  7157. */
  7158. break;
  7159. case WM_NCLBUTTONDOWN:
  7160. /* workaround for half-second pause when starting to move window
  7161. see: https://gamedev.net/forums/topic/672094-keeping-things-moving-during-win32-moveresize-events/5254386/
  7162. */
  7163. if (SendMessage(_sapp.win32.hwnd, WM_NCHITTEST, wParam, lParam) == HTCAPTION) {
  7164. POINT point = { 0, 0 };
  7165. if (GetCursorPos(&point)) {
  7166. ScreenToClient(_sapp.win32.hwnd, &point);
  7167. PostMessage(_sapp.win32.hwnd, WM_MOUSEMOVE, 0, ((uint32_t)point.x)|(((uint32_t)point.y) << 16));
  7168. }
  7169. }
  7170. break;
  7171. case WM_DROPFILES:
  7172. _sapp_win32_files_dropped((HDROP)wParam);
  7173. break;
  7174. case WM_DISPLAYCHANGE:
  7175. // refresh rate might have changed
  7176. _sapp_timing_reset(&_sapp.timing);
  7177. break;
  7178. default:
  7179. break;
  7180. }
  7181. }
  7182. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  7183. }
  7184. _SOKOL_PRIVATE void _sapp_win32_create_window(void) {
  7185. WNDCLASSW wndclassw;
  7186. _sapp_clear(&wndclassw, sizeof(wndclassw));
  7187. wndclassw.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  7188. wndclassw.lpfnWndProc = (WNDPROC) _sapp_win32_wndproc;
  7189. wndclassw.hInstance = GetModuleHandleW(NULL);
  7190. wndclassw.hCursor = LoadCursor(NULL, IDC_ARROW);
  7191. wndclassw.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  7192. wndclassw.lpszClassName = L"SOKOLAPP";
  7193. RegisterClassW(&wndclassw);
  7194. /* NOTE: regardless whether fullscreen is requested or not, a regular
  7195. windowed-mode window will always be created first (however in hidden
  7196. mode, so that no windowed-mode window pops up before the fullscreen window)
  7197. */
  7198. const DWORD win_ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  7199. RECT rect = { 0, 0, 0, 0 };
  7200. DWORD win_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
  7201. rect.right = (int) ((float)_sapp.window_width * _sapp.win32.dpi.window_scale);
  7202. rect.bottom = (int) ((float)_sapp.window_height * _sapp.win32.dpi.window_scale);
  7203. const bool use_default_width = 0 == _sapp.window_width;
  7204. const bool use_default_height = 0 == _sapp.window_height;
  7205. AdjustWindowRectEx(&rect, win_style, FALSE, win_ex_style);
  7206. const int win_width = rect.right - rect.left;
  7207. const int win_height = rect.bottom - rect.top;
  7208. _sapp.win32.in_create_window = true;
  7209. _sapp.win32.hwnd = CreateWindowExW(
  7210. win_ex_style, // dwExStyle
  7211. L"SOKOLAPP", // lpClassName
  7212. _sapp.window_title_wide, // lpWindowName
  7213. win_style, // dwStyle
  7214. CW_USEDEFAULT, // X
  7215. SW_HIDE, // Y (NOTE: CW_USEDEFAULT is not used for position here, but internally calls ShowWindow!
  7216. use_default_width ? CW_USEDEFAULT : win_width, // nWidth
  7217. use_default_height ? CW_USEDEFAULT : win_height, // nHeight (NOTE: if width is CW_USEDEFAULT, height is actually ignored)
  7218. NULL, // hWndParent
  7219. NULL, // hMenu
  7220. GetModuleHandle(NULL), // hInstance
  7221. NULL); // lParam
  7222. _sapp.win32.in_create_window = false;
  7223. _sapp.win32.dc = GetDC(_sapp.win32.hwnd);
  7224. _sapp.win32.hmonitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONULL);
  7225. SOKOL_ASSERT(_sapp.win32.dc);
  7226. /* this will get the actual windowed-mode window size, if fullscreen
  7227. is requested, the set_fullscreen function will then capture the
  7228. current window rectangle, which then might be used later to
  7229. restore the window position when switching back to windowed
  7230. */
  7231. _sapp_win32_update_dimensions();
  7232. if (_sapp.fullscreen) {
  7233. _sapp_win32_set_fullscreen(_sapp.fullscreen, SWP_HIDEWINDOW);
  7234. _sapp_win32_update_dimensions();
  7235. }
  7236. ShowWindow(_sapp.win32.hwnd, SW_SHOW);
  7237. DragAcceptFiles(_sapp.win32.hwnd, 1);
  7238. }
  7239. _SOKOL_PRIVATE void _sapp_win32_destroy_window(void) {
  7240. DestroyWindow(_sapp.win32.hwnd); _sapp.win32.hwnd = 0;
  7241. UnregisterClassW(L"SOKOLAPP", GetModuleHandleW(NULL));
  7242. }
  7243. _SOKOL_PRIVATE void _sapp_win32_destroy_icons(void) {
  7244. if (_sapp.win32.big_icon) {
  7245. DestroyIcon(_sapp.win32.big_icon);
  7246. _sapp.win32.big_icon = 0;
  7247. }
  7248. if (_sapp.win32.small_icon) {
  7249. DestroyIcon(_sapp.win32.small_icon);
  7250. _sapp.win32.small_icon = 0;
  7251. }
  7252. }
  7253. _SOKOL_PRIVATE void _sapp_win32_init_console(void) {
  7254. if (_sapp.desc.win32_console_create || _sapp.desc.win32_console_attach) {
  7255. BOOL con_valid = FALSE;
  7256. if (_sapp.desc.win32_console_create) {
  7257. con_valid = AllocConsole();
  7258. }
  7259. else if (_sapp.desc.win32_console_attach) {
  7260. con_valid = AttachConsole(ATTACH_PARENT_PROCESS);
  7261. }
  7262. if (con_valid) {
  7263. FILE* res_fp = 0;
  7264. errno_t err;
  7265. err = freopen_s(&res_fp, "CON", "w", stdout);
  7266. (void)err;
  7267. err = freopen_s(&res_fp, "CON", "w", stderr);
  7268. (void)err;
  7269. }
  7270. }
  7271. if (_sapp.desc.win32_console_utf8) {
  7272. _sapp.win32.orig_codepage = GetConsoleOutputCP();
  7273. SetConsoleOutputCP(CP_UTF8);
  7274. }
  7275. }
  7276. _SOKOL_PRIVATE void _sapp_win32_restore_console(void) {
  7277. if (_sapp.desc.win32_console_utf8) {
  7278. SetConsoleOutputCP(_sapp.win32.orig_codepage);
  7279. }
  7280. }
  7281. _SOKOL_PRIVATE void _sapp_win32_init_dpi(void) {
  7282. DECLARE_HANDLE(DPI_AWARENESS_CONTEXT_T);
  7283. typedef BOOL(WINAPI * SETPROCESSDPIAWARE_T)(void);
  7284. typedef bool (WINAPI * SETPROCESSDPIAWARENESSCONTEXT_T)(DPI_AWARENESS_CONTEXT_T); // since Windows 10, version 1703
  7285. typedef HRESULT(WINAPI * SETPROCESSDPIAWARENESS_T)(PROCESS_DPI_AWARENESS);
  7286. typedef HRESULT(WINAPI * GETDPIFORMONITOR_T)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*);
  7287. SETPROCESSDPIAWARE_T fn_setprocessdpiaware = 0;
  7288. SETPROCESSDPIAWARENESS_T fn_setprocessdpiawareness = 0;
  7289. GETDPIFORMONITOR_T fn_getdpiformonitor = 0;
  7290. SETPROCESSDPIAWARENESSCONTEXT_T fn_setprocessdpiawarenesscontext =0;
  7291. HINSTANCE user32 = LoadLibraryA("user32.dll");
  7292. if (user32) {
  7293. fn_setprocessdpiaware = (SETPROCESSDPIAWARE_T)(void*) GetProcAddress(user32, "SetProcessDPIAware");
  7294. fn_setprocessdpiawarenesscontext = (SETPROCESSDPIAWARENESSCONTEXT_T)(void*) GetProcAddress(user32, "SetProcessDpiAwarenessContext");
  7295. }
  7296. HINSTANCE shcore = LoadLibraryA("shcore.dll");
  7297. if (shcore) {
  7298. fn_setprocessdpiawareness = (SETPROCESSDPIAWARENESS_T)(void*) GetProcAddress(shcore, "SetProcessDpiAwareness");
  7299. fn_getdpiformonitor = (GETDPIFORMONITOR_T)(void*) GetProcAddress(shcore, "GetDpiForMonitor");
  7300. }
  7301. /*
  7302. NOTE on SetProcessDpiAware() vs SetProcessDpiAwareness() vs SetProcessDpiAwarenessContext():
  7303. These are different attempts to get DPI handling on Windows right, from oldest
  7304. to newest. SetProcessDpiAwarenessContext() is required for the new
  7305. DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 method.
  7306. */
  7307. if (fn_setprocessdpiawareness) {
  7308. if (_sapp.desc.high_dpi) {
  7309. /* app requests HighDPI rendering, first try the Win10 Creator Update per-monitor-dpi awareness,
  7310. if that fails, fall back to system-dpi-awareness
  7311. */
  7312. _sapp.win32.dpi.aware = true;
  7313. DPI_AWARENESS_CONTEXT_T per_monitor_aware_v2 = (DPI_AWARENESS_CONTEXT_T)-4;
  7314. if (!(fn_setprocessdpiawarenesscontext && fn_setprocessdpiawarenesscontext(per_monitor_aware_v2))) {
  7315. // fallback to system-dpi-aware
  7316. fn_setprocessdpiawareness(PROCESS_SYSTEM_DPI_AWARE);
  7317. }
  7318. }
  7319. else {
  7320. /* if the app didn't request HighDPI rendering, let Windows do the upscaling */
  7321. _sapp.win32.dpi.aware = false;
  7322. fn_setprocessdpiawareness(PROCESS_DPI_UNAWARE);
  7323. }
  7324. }
  7325. else if (fn_setprocessdpiaware) {
  7326. // fallback for Windows 7
  7327. _sapp.win32.dpi.aware = true;
  7328. fn_setprocessdpiaware();
  7329. }
  7330. /* get dpi scale factor for main monitor */
  7331. if (fn_getdpiformonitor && _sapp.win32.dpi.aware) {
  7332. POINT pt = { 1, 1 };
  7333. HMONITOR hm = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
  7334. UINT dpix, dpiy;
  7335. HRESULT hr = fn_getdpiformonitor(hm, MDT_EFFECTIVE_DPI, &dpix, &dpiy);
  7336. _SOKOL_UNUSED(hr);
  7337. SOKOL_ASSERT(SUCCEEDED(hr));
  7338. /* clamp window scale to an integer factor */
  7339. _sapp.win32.dpi.window_scale = (float)dpix / 96.0f;
  7340. }
  7341. else {
  7342. _sapp.win32.dpi.window_scale = 1.0f;
  7343. }
  7344. if (_sapp.desc.high_dpi) {
  7345. _sapp.win32.dpi.content_scale = _sapp.win32.dpi.window_scale;
  7346. _sapp.win32.dpi.mouse_scale = 1.0f;
  7347. }
  7348. else {
  7349. _sapp.win32.dpi.content_scale = 1.0f;
  7350. _sapp.win32.dpi.mouse_scale = 1.0f / _sapp.win32.dpi.window_scale;
  7351. }
  7352. _sapp.dpi_scale = _sapp.win32.dpi.content_scale;
  7353. if (user32) {
  7354. FreeLibrary(user32);
  7355. }
  7356. if (shcore) {
  7357. FreeLibrary(shcore);
  7358. }
  7359. }
  7360. _SOKOL_PRIVATE bool _sapp_win32_set_clipboard_string(const char* str) {
  7361. SOKOL_ASSERT(str);
  7362. SOKOL_ASSERT(_sapp.win32.hwnd);
  7363. SOKOL_ASSERT(_sapp.clipboard.enabled && (_sapp.clipboard.buf_size > 0));
  7364. if (!OpenClipboard(_sapp.win32.hwnd)) {
  7365. return false;
  7366. }
  7367. HANDLE object = 0;
  7368. wchar_t* wchar_buf = 0;
  7369. const SIZE_T wchar_buf_size = (SIZE_T)_sapp.clipboard.buf_size * sizeof(wchar_t);
  7370. object = GlobalAlloc(GMEM_MOVEABLE, wchar_buf_size);
  7371. if (NULL == object) {
  7372. goto error;
  7373. }
  7374. wchar_buf = (wchar_t*) GlobalLock(object);
  7375. if (NULL == wchar_buf) {
  7376. goto error;
  7377. }
  7378. if (!_sapp_win32_utf8_to_wide(str, wchar_buf, (int)wchar_buf_size)) {
  7379. goto error;
  7380. }
  7381. GlobalUnlock(object);
  7382. wchar_buf = 0;
  7383. EmptyClipboard();
  7384. // NOTE: when successful, SetClipboardData() takes ownership of memory object!
  7385. if (NULL == SetClipboardData(CF_UNICODETEXT, object)) {
  7386. goto error;
  7387. }
  7388. CloseClipboard();
  7389. return true;
  7390. error:
  7391. if (wchar_buf) {
  7392. GlobalUnlock(object);
  7393. }
  7394. if (object) {
  7395. GlobalFree(object);
  7396. }
  7397. CloseClipboard();
  7398. return false;
  7399. }
  7400. _SOKOL_PRIVATE const char* _sapp_win32_get_clipboard_string(void) {
  7401. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  7402. SOKOL_ASSERT(_sapp.win32.hwnd);
  7403. if (!OpenClipboard(_sapp.win32.hwnd)) {
  7404. /* silently ignore any errors and just return the current
  7405. content of the local clipboard buffer
  7406. */
  7407. return _sapp.clipboard.buffer;
  7408. }
  7409. HANDLE object = GetClipboardData(CF_UNICODETEXT);
  7410. if (!object) {
  7411. CloseClipboard();
  7412. return _sapp.clipboard.buffer;
  7413. }
  7414. const wchar_t* wchar_buf = (const wchar_t*) GlobalLock(object);
  7415. if (!wchar_buf) {
  7416. CloseClipboard();
  7417. return _sapp.clipboard.buffer;
  7418. }
  7419. if (!_sapp_win32_wide_to_utf8(wchar_buf, _sapp.clipboard.buffer, _sapp.clipboard.buf_size)) {
  7420. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  7421. }
  7422. GlobalUnlock(object);
  7423. CloseClipboard();
  7424. return _sapp.clipboard.buffer;
  7425. }
  7426. _SOKOL_PRIVATE void _sapp_win32_update_window_title(void) {
  7427. _sapp_win32_utf8_to_wide(_sapp.window_title, _sapp.window_title_wide, sizeof(_sapp.window_title_wide));
  7428. SetWindowTextW(_sapp.win32.hwnd, _sapp.window_title_wide);
  7429. }
  7430. _SOKOL_PRIVATE HICON _sapp_win32_create_icon_from_image(const sapp_image_desc* desc) {
  7431. BITMAPV5HEADER bi;
  7432. _sapp_clear(&bi, sizeof(bi));
  7433. bi.bV5Size = sizeof(bi);
  7434. bi.bV5Width = desc->width;
  7435. bi.bV5Height = -desc->height; // NOTE the '-' here to indicate that origin is top-left
  7436. bi.bV5Planes = 1;
  7437. bi.bV5BitCount = 32;
  7438. bi.bV5Compression = BI_BITFIELDS;
  7439. bi.bV5RedMask = 0x00FF0000;
  7440. bi.bV5GreenMask = 0x0000FF00;
  7441. bi.bV5BlueMask = 0x000000FF;
  7442. bi.bV5AlphaMask = 0xFF000000;
  7443. uint8_t* target = 0;
  7444. const uint8_t* source = (const uint8_t*)desc->pixels.ptr;
  7445. HDC dc = GetDC(NULL);
  7446. HBITMAP color = CreateDIBSection(dc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (void**)&target, NULL, (DWORD)0);
  7447. ReleaseDC(NULL, dc);
  7448. if (0 == color) {
  7449. return NULL;
  7450. }
  7451. SOKOL_ASSERT(target);
  7452. HBITMAP mask = CreateBitmap(desc->width, desc->height, 1, 1, NULL);
  7453. if (0 == mask) {
  7454. DeleteObject(color);
  7455. return NULL;
  7456. }
  7457. for (int i = 0; i < (desc->width*desc->height); i++) {
  7458. target[0] = source[2];
  7459. target[1] = source[1];
  7460. target[2] = source[0];
  7461. target[3] = source[3];
  7462. target += 4;
  7463. source += 4;
  7464. }
  7465. ICONINFO icon_info;
  7466. _sapp_clear(&icon_info, sizeof(icon_info));
  7467. icon_info.fIcon = true;
  7468. icon_info.xHotspot = 0;
  7469. icon_info.yHotspot = 0;
  7470. icon_info.hbmMask = mask;
  7471. icon_info.hbmColor = color;
  7472. HICON icon_handle = CreateIconIndirect(&icon_info);
  7473. DeleteObject(color);
  7474. DeleteObject(mask);
  7475. return icon_handle;
  7476. }
  7477. _SOKOL_PRIVATE void _sapp_win32_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  7478. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  7479. int big_img_index = _sapp_image_bestmatch(icon_desc->images, num_images, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
  7480. int sml_img_index = _sapp_image_bestmatch(icon_desc->images, num_images, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
  7481. HICON big_icon = _sapp_win32_create_icon_from_image(&icon_desc->images[big_img_index]);
  7482. HICON sml_icon = _sapp_win32_create_icon_from_image(&icon_desc->images[sml_img_index]);
  7483. // if icon creation or lookup has failed for some reason, leave the currently set icon untouched
  7484. if (0 != big_icon) {
  7485. SendMessage(_sapp.win32.hwnd, WM_SETICON, ICON_BIG, (LPARAM) big_icon);
  7486. if (0 != _sapp.win32.big_icon) {
  7487. DestroyIcon(_sapp.win32.big_icon);
  7488. }
  7489. _sapp.win32.big_icon = big_icon;
  7490. }
  7491. if (0 != sml_icon) {
  7492. SendMessage(_sapp.win32.hwnd, WM_SETICON, ICON_SMALL, (LPARAM) sml_icon);
  7493. if (0 != _sapp.win32.small_icon) {
  7494. DestroyIcon(_sapp.win32.small_icon);
  7495. }
  7496. _sapp.win32.small_icon = sml_icon;
  7497. }
  7498. }
  7499. /* don't laugh, but this seems to be the easiest and most robust
  7500. way to check if we're running on Win10
  7501. From: https://github.com/videolan/vlc/blob/232fb13b0d6110c4d1b683cde24cf9a7f2c5c2ea/modules/video_output/win32/d3d11_swapchain.c#L263
  7502. */
  7503. _SOKOL_PRIVATE bool _sapp_win32_is_win10_or_greater(void) {
  7504. HMODULE h = GetModuleHandleW(L"kernel32.dll");
  7505. if (NULL != h) {
  7506. return (NULL != GetProcAddress(h, "GetSystemCpuSetInformation"));
  7507. }
  7508. else {
  7509. return false;
  7510. }
  7511. }
  7512. _SOKOL_PRIVATE void _sapp_win32_run(const sapp_desc* desc) {
  7513. _sapp_init_state(desc);
  7514. _sapp_win32_init_console();
  7515. _sapp.win32.is_win10_or_greater = _sapp_win32_is_win10_or_greater();
  7516. _sapp_win32_init_keytable();
  7517. _sapp_win32_utf8_to_wide(_sapp.window_title, _sapp.window_title_wide, sizeof(_sapp.window_title_wide));
  7518. _sapp_win32_init_dpi();
  7519. _sapp_win32_init_cursors();
  7520. _sapp_win32_create_window();
  7521. sapp_set_icon(&desc->icon);
  7522. #if defined(SOKOL_D3D11)
  7523. _sapp_d3d11_create_device_and_swapchain();
  7524. _sapp_d3d11_create_default_render_target();
  7525. #endif
  7526. #if defined(SOKOL_GLCORE)
  7527. _sapp_wgl_init();
  7528. _sapp_wgl_load_extensions();
  7529. _sapp_wgl_create_context();
  7530. #endif
  7531. _sapp.valid = true;
  7532. bool done = false;
  7533. while (!(done || _sapp.quit_ordered)) {
  7534. _sapp_win32_timing_measure();
  7535. MSG msg;
  7536. while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
  7537. if (WM_QUIT == msg.message) {
  7538. done = true;
  7539. continue;
  7540. }
  7541. else {
  7542. TranslateMessage(&msg);
  7543. DispatchMessageW(&msg);
  7544. }
  7545. }
  7546. _sapp_frame();
  7547. #if defined(SOKOL_D3D11)
  7548. _sapp_d3d11_present(false);
  7549. if (IsIconic(_sapp.win32.hwnd)) {
  7550. Sleep((DWORD)(16 * _sapp.swap_interval));
  7551. }
  7552. #endif
  7553. #if defined(SOKOL_GLCORE)
  7554. _sapp_wgl_swap_buffers();
  7555. #endif
  7556. /* check for window resized, this cannot happen in WM_SIZE as it explodes memory usage */
  7557. if (_sapp_win32_update_dimensions()) {
  7558. #if defined(SOKOL_D3D11)
  7559. _sapp_d3d11_resize_default_render_target();
  7560. #endif
  7561. _sapp_win32_app_event(SAPP_EVENTTYPE_RESIZED);
  7562. }
  7563. /* check if the window monitor has changed, need to reset timing because
  7564. the new monitor might have a different refresh rate
  7565. */
  7566. if (_sapp_win32_update_monitor()) {
  7567. _sapp_timing_reset(&_sapp.timing);
  7568. }
  7569. if (_sapp.quit_requested) {
  7570. PostMessage(_sapp.win32.hwnd, WM_CLOSE, 0, 0);
  7571. }
  7572. // update mouse-lock state
  7573. _sapp_win32_update_mouse_lock();
  7574. }
  7575. _sapp_call_cleanup();
  7576. #if defined(SOKOL_D3D11)
  7577. _sapp_d3d11_destroy_default_render_target();
  7578. _sapp_d3d11_destroy_device_and_swapchain();
  7579. #elif defined(SOKOL_GLCORE)
  7580. _sapp_wgl_destroy_context();
  7581. _sapp_wgl_shutdown();
  7582. #endif
  7583. _sapp_win32_destroy_window();
  7584. _sapp_win32_destroy_icons();
  7585. _sapp_win32_restore_console();
  7586. _sapp_win32_free_raw_input_data();
  7587. _sapp_discard_state();
  7588. }
  7589. _SOKOL_PRIVATE char** _sapp_win32_command_line_to_utf8_argv(LPWSTR w_command_line, int* o_argc) {
  7590. int argc = 0;
  7591. char** argv = 0;
  7592. char* args;
  7593. LPWSTR* w_argv = CommandLineToArgvW(w_command_line, &argc);
  7594. if (w_argv == NULL) {
  7595. // FIXME: chicken egg problem, can't report errors before sokol_main() is called!
  7596. } else {
  7597. size_t size = wcslen(w_command_line) * 4;
  7598. argv = (char**) _sapp_malloc_clear(((size_t)argc + 1) * sizeof(char*) + size);
  7599. SOKOL_ASSERT(argv);
  7600. args = (char*) &argv[argc + 1];
  7601. int n;
  7602. for (int i = 0; i < argc; ++i) {
  7603. n = WideCharToMultiByte(CP_UTF8, 0, w_argv[i], -1, args, (int)size, NULL, NULL);
  7604. if (n == 0) {
  7605. // FIXME: chicken egg problem, can't report errors before sokol_main() is called!
  7606. break;
  7607. }
  7608. argv[i] = args;
  7609. size -= (size_t)n;
  7610. args += n;
  7611. }
  7612. LocalFree(w_argv);
  7613. }
  7614. *o_argc = argc;
  7615. return argv;
  7616. }
  7617. #if !defined(SOKOL_NO_ENTRY)
  7618. #if defined(SOKOL_WIN32_FORCE_MAIN)
  7619. int main(int argc, char* argv[]) {
  7620. sapp_desc desc = sokol_main(argc, argv);
  7621. _sapp_win32_run(&desc);
  7622. return 0;
  7623. }
  7624. #endif /* SOKOL_WIN32_FORCE_MAIN */
  7625. #if defined(SOKOL_WIN32_FORCE_WINMAIN) || !defined(SOKOL_WIN32_FORCE_MAIN)
  7626. int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) {
  7627. _SOKOL_UNUSED(hInstance);
  7628. _SOKOL_UNUSED(hPrevInstance);
  7629. _SOKOL_UNUSED(lpCmdLine);
  7630. _SOKOL_UNUSED(nCmdShow);
  7631. int argc_utf8 = 0;
  7632. char** argv_utf8 = _sapp_win32_command_line_to_utf8_argv(GetCommandLineW(), &argc_utf8);
  7633. sapp_desc desc = sokol_main(argc_utf8, argv_utf8);
  7634. _sapp_win32_run(&desc);
  7635. _sapp_free(argv_utf8);
  7636. return 0;
  7637. }
  7638. #endif /* SOKOL_WIN32_FORCE_WINMAIN */
  7639. #endif /* SOKOL_NO_ENTRY */
  7640. #ifdef _MSC_VER
  7641. #pragma warning(pop)
  7642. #endif
  7643. #endif /* _SAPP_WIN32 */
  7644. // █████ ███ ██ ██████ ██████ ██████ ██ ██████
  7645. // ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7646. // ███████ ██ ██ ██ ██ ██ ██████ ██ ██ ██ ██ ██
  7647. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7648. // ██ ██ ██ ████ ██████ ██ ██ ██████ ██ ██████
  7649. //
  7650. // >>android
  7651. #if defined(_SAPP_ANDROID)
  7652. /* android loop thread */
  7653. _SOKOL_PRIVATE bool _sapp_android_init_egl(void) {
  7654. SOKOL_ASSERT(_sapp.android.display == EGL_NO_DISPLAY);
  7655. SOKOL_ASSERT(_sapp.android.context == EGL_NO_CONTEXT);
  7656. EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  7657. if (display == EGL_NO_DISPLAY) {
  7658. return false;
  7659. }
  7660. if (eglInitialize(display, NULL, NULL) == EGL_FALSE) {
  7661. return false;
  7662. }
  7663. EGLint alpha_size = _sapp.desc.alpha ? 8 : 0;
  7664. const EGLint cfg_attributes[] = {
  7665. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  7666. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  7667. EGL_RED_SIZE, 8,
  7668. EGL_GREEN_SIZE, 8,
  7669. EGL_BLUE_SIZE, 8,
  7670. EGL_ALPHA_SIZE, alpha_size,
  7671. EGL_DEPTH_SIZE, 16,
  7672. EGL_STENCIL_SIZE, 0,
  7673. EGL_NONE,
  7674. };
  7675. EGLConfig available_cfgs[32];
  7676. EGLint cfg_count;
  7677. eglChooseConfig(display, cfg_attributes, available_cfgs, 32, &cfg_count);
  7678. SOKOL_ASSERT(cfg_count > 0);
  7679. SOKOL_ASSERT(cfg_count <= 32);
  7680. /* find config with 8-bit rgb buffer if available, ndk sample does not trust egl spec */
  7681. EGLConfig config;
  7682. bool exact_cfg_found = false;
  7683. for (int i = 0; i < cfg_count; ++i) {
  7684. EGLConfig c = available_cfgs[i];
  7685. EGLint r, g, b, a, d;
  7686. if (eglGetConfigAttrib(display, c, EGL_RED_SIZE, &r) == EGL_TRUE &&
  7687. eglGetConfigAttrib(display, c, EGL_GREEN_SIZE, &g) == EGL_TRUE &&
  7688. eglGetConfigAttrib(display, c, EGL_BLUE_SIZE, &b) == EGL_TRUE &&
  7689. eglGetConfigAttrib(display, c, EGL_ALPHA_SIZE, &a) == EGL_TRUE &&
  7690. eglGetConfigAttrib(display, c, EGL_DEPTH_SIZE, &d) == EGL_TRUE &&
  7691. r == 8 && g == 8 && b == 8 && (alpha_size == 0 || a == alpha_size) && d == 16) {
  7692. exact_cfg_found = true;
  7693. config = c;
  7694. break;
  7695. }
  7696. }
  7697. if (!exact_cfg_found) {
  7698. config = available_cfgs[0];
  7699. }
  7700. EGLint ctx_attributes[] = {
  7701. EGL_CONTEXT_MAJOR_VERSION, _sapp.desc.gl_major_version,
  7702. EGL_CONTEXT_MINOR_VERSION, _sapp.desc.gl_minor_version,
  7703. EGL_NONE,
  7704. };
  7705. EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, ctx_attributes);
  7706. if (context == EGL_NO_CONTEXT) {
  7707. return false;
  7708. }
  7709. _sapp.android.config = config;
  7710. _sapp.android.display = display;
  7711. _sapp.android.context = context;
  7712. return true;
  7713. }
  7714. _SOKOL_PRIVATE void _sapp_android_cleanup_egl(void) {
  7715. if (_sapp.android.display != EGL_NO_DISPLAY) {
  7716. eglMakeCurrent(_sapp.android.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  7717. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7718. eglDestroySurface(_sapp.android.display, _sapp.android.surface);
  7719. _sapp.android.surface = EGL_NO_SURFACE;
  7720. }
  7721. if (_sapp.android.context != EGL_NO_CONTEXT) {
  7722. eglDestroyContext(_sapp.android.display, _sapp.android.context);
  7723. _sapp.android.context = EGL_NO_CONTEXT;
  7724. }
  7725. eglTerminate(_sapp.android.display);
  7726. _sapp.android.display = EGL_NO_DISPLAY;
  7727. }
  7728. }
  7729. _SOKOL_PRIVATE bool _sapp_android_init_egl_surface(ANativeWindow* window) {
  7730. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7731. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7732. SOKOL_ASSERT(_sapp.android.surface == EGL_NO_SURFACE);
  7733. SOKOL_ASSERT(window);
  7734. /* TODO: set window flags */
  7735. /* ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0); */
  7736. /* create egl surface and make it current */
  7737. EGLSurface surface = eglCreateWindowSurface(_sapp.android.display, _sapp.android.config, window, NULL);
  7738. if (surface == EGL_NO_SURFACE) {
  7739. return false;
  7740. }
  7741. if (eglMakeCurrent(_sapp.android.display, surface, surface, _sapp.android.context) == EGL_FALSE) {
  7742. return false;
  7743. }
  7744. _sapp.android.surface = surface;
  7745. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  7746. return true;
  7747. }
  7748. _SOKOL_PRIVATE void _sapp_android_cleanup_egl_surface(void) {
  7749. if (_sapp.android.display == EGL_NO_DISPLAY) {
  7750. return;
  7751. }
  7752. eglMakeCurrent(_sapp.android.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  7753. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7754. eglDestroySurface(_sapp.android.display, _sapp.android.surface);
  7755. _sapp.android.surface = EGL_NO_SURFACE;
  7756. }
  7757. }
  7758. _SOKOL_PRIVATE void _sapp_android_app_event(sapp_event_type type) {
  7759. if (_sapp_events_enabled()) {
  7760. _sapp_init_event(type);
  7761. _sapp_call_event(&_sapp.event);
  7762. }
  7763. }
  7764. _SOKOL_PRIVATE void _sapp_android_update_dimensions(ANativeWindow* window, bool force_update) {
  7765. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7766. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7767. SOKOL_ASSERT(_sapp.android.surface != EGL_NO_SURFACE);
  7768. SOKOL_ASSERT(window);
  7769. const int32_t win_w = ANativeWindow_getWidth(window);
  7770. const int32_t win_h = ANativeWindow_getHeight(window);
  7771. SOKOL_ASSERT(win_w >= 0 && win_h >= 0);
  7772. const bool win_changed = (win_w != _sapp.window_width) || (win_h != _sapp.window_height);
  7773. _sapp.window_width = win_w;
  7774. _sapp.window_height = win_h;
  7775. if (win_changed || force_update) {
  7776. if (!_sapp.desc.high_dpi) {
  7777. const int32_t buf_w = win_w / 2;
  7778. const int32_t buf_h = win_h / 2;
  7779. EGLint format;
  7780. EGLBoolean egl_result = eglGetConfigAttrib(_sapp.android.display, _sapp.android.config, EGL_NATIVE_VISUAL_ID, &format);
  7781. SOKOL_ASSERT(egl_result == EGL_TRUE); _SOKOL_UNUSED(egl_result);
  7782. /* NOTE: calling ANativeWindow_setBuffersGeometry() with the same dimensions
  7783. as the ANativeWindow size results in weird display artefacts, that's
  7784. why it's only called when the buffer geometry is different from
  7785. the window size
  7786. */
  7787. int32_t result = ANativeWindow_setBuffersGeometry(window, buf_w, buf_h, format);
  7788. SOKOL_ASSERT(result == 0); _SOKOL_UNUSED(result);
  7789. }
  7790. }
  7791. /* query surface size */
  7792. EGLint fb_w, fb_h;
  7793. EGLBoolean egl_result_w = eglQuerySurface(_sapp.android.display, _sapp.android.surface, EGL_WIDTH, &fb_w);
  7794. EGLBoolean egl_result_h = eglQuerySurface(_sapp.android.display, _sapp.android.surface, EGL_HEIGHT, &fb_h);
  7795. SOKOL_ASSERT(egl_result_w == EGL_TRUE); _SOKOL_UNUSED(egl_result_w);
  7796. SOKOL_ASSERT(egl_result_h == EGL_TRUE); _SOKOL_UNUSED(egl_result_h);
  7797. const bool fb_changed = (fb_w != _sapp.framebuffer_width) || (fb_h != _sapp.framebuffer_height);
  7798. _sapp.framebuffer_width = fb_w;
  7799. _sapp.framebuffer_height = fb_h;
  7800. _sapp.dpi_scale = (float)_sapp.framebuffer_width / (float)_sapp.window_width;
  7801. if (win_changed || fb_changed || force_update) {
  7802. if (!_sapp.first_frame) {
  7803. _sapp_android_app_event(SAPP_EVENTTYPE_RESIZED);
  7804. }
  7805. }
  7806. }
  7807. _SOKOL_PRIVATE void _sapp_android_cleanup(void) {
  7808. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7809. /* egl context is bound, cleanup gracefully */
  7810. if (_sapp.init_called && !_sapp.cleanup_called) {
  7811. _sapp_call_cleanup();
  7812. }
  7813. }
  7814. /* always try to cleanup by destroying egl context */
  7815. _sapp_android_cleanup_egl();
  7816. }
  7817. _SOKOL_PRIVATE void _sapp_android_shutdown(void) {
  7818. /* try to cleanup while we still have a surface and can call cleanup_cb() */
  7819. _sapp_android_cleanup();
  7820. /* request exit */
  7821. ANativeActivity_finish(_sapp.android.activity);
  7822. }
  7823. _SOKOL_PRIVATE void _sapp_android_frame(void) {
  7824. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7825. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7826. SOKOL_ASSERT(_sapp.android.surface != EGL_NO_SURFACE);
  7827. _sapp_timing_measure(&_sapp.timing);
  7828. _sapp_android_update_dimensions(_sapp.android.current.window, false);
  7829. _sapp_frame();
  7830. eglSwapBuffers(_sapp.android.display, _sapp.android.surface);
  7831. }
  7832. _SOKOL_PRIVATE bool _sapp_android_touch_event(const AInputEvent* e) {
  7833. if (AInputEvent_getType(e) != AINPUT_EVENT_TYPE_MOTION) {
  7834. return false;
  7835. }
  7836. if (!_sapp_events_enabled()) {
  7837. return false;
  7838. }
  7839. int32_t action_idx = AMotionEvent_getAction(e);
  7840. int32_t action = action_idx & AMOTION_EVENT_ACTION_MASK;
  7841. sapp_event_type type = SAPP_EVENTTYPE_INVALID;
  7842. switch (action) {
  7843. case AMOTION_EVENT_ACTION_DOWN:
  7844. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  7845. type = SAPP_EVENTTYPE_TOUCHES_BEGAN;
  7846. break;
  7847. case AMOTION_EVENT_ACTION_MOVE:
  7848. type = SAPP_EVENTTYPE_TOUCHES_MOVED;
  7849. break;
  7850. case AMOTION_EVENT_ACTION_UP:
  7851. case AMOTION_EVENT_ACTION_POINTER_UP:
  7852. type = SAPP_EVENTTYPE_TOUCHES_ENDED;
  7853. break;
  7854. case AMOTION_EVENT_ACTION_CANCEL:
  7855. type = SAPP_EVENTTYPE_TOUCHES_CANCELLED;
  7856. break;
  7857. default:
  7858. break;
  7859. }
  7860. if (type == SAPP_EVENTTYPE_INVALID) {
  7861. return false;
  7862. }
  7863. int32_t idx = action_idx >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  7864. _sapp_init_event(type);
  7865. _sapp.event.num_touches = (int)AMotionEvent_getPointerCount(e);
  7866. if (_sapp.event.num_touches > SAPP_MAX_TOUCHPOINTS) {
  7867. _sapp.event.num_touches = SAPP_MAX_TOUCHPOINTS;
  7868. }
  7869. for (int32_t i = 0; i < _sapp.event.num_touches; i++) {
  7870. sapp_touchpoint* dst = &_sapp.event.touches[i];
  7871. dst->identifier = (uintptr_t)AMotionEvent_getPointerId(e, (size_t)i);
  7872. dst->pos_x = (AMotionEvent_getX(e, (size_t)i) / _sapp.window_width) * _sapp.framebuffer_width;
  7873. dst->pos_y = (AMotionEvent_getY(e, (size_t)i) / _sapp.window_height) * _sapp.framebuffer_height;
  7874. dst->android_tooltype = (sapp_android_tooltype) AMotionEvent_getToolType(e, (size_t)i);
  7875. if (action == AMOTION_EVENT_ACTION_POINTER_DOWN ||
  7876. action == AMOTION_EVENT_ACTION_POINTER_UP) {
  7877. dst->changed = (i == idx);
  7878. } else {
  7879. dst->changed = true;
  7880. }
  7881. }
  7882. _sapp_call_event(&_sapp.event);
  7883. return true;
  7884. }
  7885. _SOKOL_PRIVATE bool _sapp_android_key_event(const AInputEvent* e) {
  7886. if (AInputEvent_getType(e) != AINPUT_EVENT_TYPE_KEY) {
  7887. return false;
  7888. }
  7889. if (AKeyEvent_getKeyCode(e) == AKEYCODE_BACK) {
  7890. /* FIXME: this should be hooked into a "really quit?" mechanism
  7891. so the app can ask the user for confirmation, this is currently
  7892. generally missing in sokol_app.h
  7893. */
  7894. _sapp_android_shutdown();
  7895. return true;
  7896. }
  7897. return false;
  7898. }
  7899. _SOKOL_PRIVATE int _sapp_android_input_cb(int fd, int events, void* data) {
  7900. _SOKOL_UNUSED(fd);
  7901. _SOKOL_UNUSED(data);
  7902. if ((events & ALOOPER_EVENT_INPUT) == 0) {
  7903. _SAPP_ERROR(ANDROID_UNSUPPORTED_INPUT_EVENT_INPUT_CB);
  7904. return 1;
  7905. }
  7906. SOKOL_ASSERT(_sapp.android.current.input);
  7907. AInputEvent* event = NULL;
  7908. while (AInputQueue_getEvent(_sapp.android.current.input, &event) >= 0) {
  7909. if (AInputQueue_preDispatchEvent(_sapp.android.current.input, event) != 0) {
  7910. continue;
  7911. }
  7912. int32_t handled = 0;
  7913. if (_sapp_android_touch_event(event) || _sapp_android_key_event(event)) {
  7914. handled = 1;
  7915. }
  7916. AInputQueue_finishEvent(_sapp.android.current.input, event, handled);
  7917. }
  7918. return 1;
  7919. }
  7920. _SOKOL_PRIVATE int _sapp_android_main_cb(int fd, int events, void* data) {
  7921. _SOKOL_UNUSED(data);
  7922. if ((events & ALOOPER_EVENT_INPUT) == 0) {
  7923. _SAPP_ERROR(ANDROID_UNSUPPORTED_INPUT_EVENT_MAIN_CB);
  7924. return 1;
  7925. }
  7926. _sapp_android_msg_t msg;
  7927. if (read(fd, &msg, sizeof(msg)) != sizeof(msg)) {
  7928. _SAPP_ERROR(ANDROID_READ_MSG_FAILED);
  7929. return 1;
  7930. }
  7931. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7932. switch (msg) {
  7933. case _SOKOL_ANDROID_MSG_CREATE:
  7934. {
  7935. _SAPP_INFO(ANDROID_MSG_CREATE);
  7936. SOKOL_ASSERT(!_sapp.valid);
  7937. bool result = _sapp_android_init_egl();
  7938. SOKOL_ASSERT(result); _SOKOL_UNUSED(result);
  7939. _sapp.valid = true;
  7940. _sapp.android.has_created = true;
  7941. }
  7942. break;
  7943. case _SOKOL_ANDROID_MSG_RESUME:
  7944. _SAPP_INFO(ANDROID_MSG_RESUME);
  7945. _sapp.android.has_resumed = true;
  7946. _sapp_android_app_event(SAPP_EVENTTYPE_RESUMED);
  7947. break;
  7948. case _SOKOL_ANDROID_MSG_PAUSE:
  7949. _SAPP_INFO(ANDROID_MSG_PAUSE);
  7950. _sapp.android.has_resumed = false;
  7951. _sapp_android_app_event(SAPP_EVENTTYPE_SUSPENDED);
  7952. break;
  7953. case _SOKOL_ANDROID_MSG_FOCUS:
  7954. _SAPP_INFO(ANDROID_MSG_FOCUS);
  7955. _sapp.android.has_focus = true;
  7956. break;
  7957. case _SOKOL_ANDROID_MSG_NO_FOCUS:
  7958. _SAPP_INFO(ANDROID_MSG_NO_FOCUS);
  7959. _sapp.android.has_focus = false;
  7960. break;
  7961. case _SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW:
  7962. _SAPP_INFO(ANDROID_MSG_SET_NATIVE_WINDOW);
  7963. if (_sapp.android.current.window != _sapp.android.pending.window) {
  7964. if (_sapp.android.current.window != NULL) {
  7965. _sapp_android_cleanup_egl_surface();
  7966. }
  7967. if (_sapp.android.pending.window != NULL) {
  7968. if (_sapp_android_init_egl_surface(_sapp.android.pending.window)) {
  7969. _sapp_android_update_dimensions(_sapp.android.pending.window, true);
  7970. } else {
  7971. _sapp_android_shutdown();
  7972. }
  7973. }
  7974. }
  7975. _sapp.android.current.window = _sapp.android.pending.window;
  7976. break;
  7977. case _SOKOL_ANDROID_MSG_SET_INPUT_QUEUE:
  7978. _SAPP_INFO(ANDROID_MSG_SET_INPUT_QUEUE);
  7979. if (_sapp.android.current.input != _sapp.android.pending.input) {
  7980. if (_sapp.android.current.input != NULL) {
  7981. AInputQueue_detachLooper(_sapp.android.current.input);
  7982. }
  7983. if (_sapp.android.pending.input != NULL) {
  7984. AInputQueue_attachLooper(
  7985. _sapp.android.pending.input,
  7986. _sapp.android.looper,
  7987. ALOOPER_POLL_CALLBACK,
  7988. _sapp_android_input_cb,
  7989. NULL); /* data */
  7990. }
  7991. }
  7992. _sapp.android.current.input = _sapp.android.pending.input;
  7993. break;
  7994. case _SOKOL_ANDROID_MSG_DESTROY:
  7995. _SAPP_INFO(ANDROID_MSG_DESTROY);
  7996. _sapp_android_cleanup();
  7997. _sapp.valid = false;
  7998. _sapp.android.is_thread_stopping = true;
  7999. break;
  8000. default:
  8001. _SAPP_WARN(ANDROID_UNKNOWN_MSG);
  8002. break;
  8003. }
  8004. pthread_cond_broadcast(&_sapp.android.pt.cond); /* signal "received" */
  8005. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8006. return 1;
  8007. }
  8008. _SOKOL_PRIVATE bool _sapp_android_should_update(void) {
  8009. bool is_in_front = _sapp.android.has_resumed && _sapp.android.has_focus;
  8010. bool has_surface = _sapp.android.surface != EGL_NO_SURFACE;
  8011. return is_in_front && has_surface;
  8012. }
  8013. _SOKOL_PRIVATE void _sapp_android_show_keyboard(bool shown) {
  8014. SOKOL_ASSERT(_sapp.valid);
  8015. /* This seems to be broken in the NDK, but there is (a very cumbersome) workaround... */
  8016. if (shown) {
  8017. ANativeActivity_showSoftInput(_sapp.android.activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED);
  8018. } else {
  8019. ANativeActivity_hideSoftInput(_sapp.android.activity, ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS);
  8020. }
  8021. }
  8022. _SOKOL_PRIVATE void* _sapp_android_loop(void* arg) {
  8023. _SOKOL_UNUSED(arg);
  8024. _SAPP_INFO(ANDROID_LOOP_THREAD_STARTED);
  8025. _sapp.android.looper = ALooper_prepare(0 /* or ALOOPER_PREPARE_ALLOW_NON_CALLBACKS*/);
  8026. ALooper_addFd(_sapp.android.looper,
  8027. _sapp.android.pt.read_from_main_fd,
  8028. ALOOPER_POLL_CALLBACK,
  8029. ALOOPER_EVENT_INPUT,
  8030. _sapp_android_main_cb,
  8031. NULL); /* data */
  8032. /* signal start to main thread */
  8033. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8034. _sapp.android.is_thread_started = true;
  8035. pthread_cond_broadcast(&_sapp.android.pt.cond);
  8036. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8037. /* main loop */
  8038. while (!_sapp.android.is_thread_stopping) {
  8039. /* sokol frame */
  8040. if (_sapp_android_should_update()) {
  8041. _sapp_android_frame();
  8042. }
  8043. /* process all events (or stop early if app is requested to quit) */
  8044. bool process_events = true;
  8045. while (process_events && !_sapp.android.is_thread_stopping) {
  8046. bool block_until_event = !_sapp.android.is_thread_stopping && !_sapp_android_should_update();
  8047. process_events = ALooper_pollOnce(block_until_event ? -1 : 0, NULL, NULL, NULL) == ALOOPER_POLL_CALLBACK;
  8048. }
  8049. }
  8050. /* cleanup thread */
  8051. if (_sapp.android.current.input != NULL) {
  8052. AInputQueue_detachLooper(_sapp.android.current.input);
  8053. }
  8054. /* the following causes heap corruption on exit, why??
  8055. ALooper_removeFd(_sapp.android.looper, _sapp.android.pt.read_from_main_fd);
  8056. ALooper_release(_sapp.android.looper);*/
  8057. /* signal "destroyed" */
  8058. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8059. _sapp.android.is_thread_stopped = true;
  8060. pthread_cond_broadcast(&_sapp.android.pt.cond);
  8061. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8062. _SAPP_INFO(ANDROID_LOOP_THREAD_DONE);
  8063. return NULL;
  8064. }
  8065. /* android main/ui thread */
  8066. _SOKOL_PRIVATE void _sapp_android_msg(_sapp_android_msg_t msg) {
  8067. if (write(_sapp.android.pt.write_from_main_fd, &msg, sizeof(msg)) != sizeof(msg)) {
  8068. _SAPP_ERROR(ANDROID_WRITE_MSG_FAILED);
  8069. }
  8070. }
  8071. _SOKOL_PRIVATE void _sapp_android_on_start(ANativeActivity* activity) {
  8072. _SOKOL_UNUSED(activity);
  8073. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSTART);
  8074. }
  8075. _SOKOL_PRIVATE void _sapp_android_on_resume(ANativeActivity* activity) {
  8076. _SOKOL_UNUSED(activity);
  8077. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONRESUME);
  8078. _sapp_android_msg(_SOKOL_ANDROID_MSG_RESUME);
  8079. }
  8080. _SOKOL_PRIVATE void* _sapp_android_on_save_instance_state(ANativeActivity* activity, size_t* out_size) {
  8081. _SOKOL_UNUSED(activity);
  8082. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSAVEINSTANCESTATE);
  8083. *out_size = 0;
  8084. return NULL;
  8085. }
  8086. _SOKOL_PRIVATE void _sapp_android_on_window_focus_changed(ANativeActivity* activity, int has_focus) {
  8087. _SOKOL_UNUSED(activity);
  8088. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONWINDOWFOCUSCHANGED);
  8089. if (has_focus) {
  8090. _sapp_android_msg(_SOKOL_ANDROID_MSG_FOCUS);
  8091. } else {
  8092. _sapp_android_msg(_SOKOL_ANDROID_MSG_NO_FOCUS);
  8093. }
  8094. }
  8095. _SOKOL_PRIVATE void _sapp_android_on_pause(ANativeActivity* activity) {
  8096. _SOKOL_UNUSED(activity);
  8097. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONPAUSE);
  8098. _sapp_android_msg(_SOKOL_ANDROID_MSG_PAUSE);
  8099. }
  8100. _SOKOL_PRIVATE void _sapp_android_on_stop(ANativeActivity* activity) {
  8101. _SOKOL_UNUSED(activity);
  8102. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSTOP);
  8103. }
  8104. _SOKOL_PRIVATE void _sapp_android_msg_set_native_window(ANativeWindow* window) {
  8105. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8106. _sapp.android.pending.window = window;
  8107. _sapp_android_msg(_SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW);
  8108. while (_sapp.android.current.window != window) {
  8109. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8110. }
  8111. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8112. }
  8113. _SOKOL_PRIVATE void _sapp_android_on_native_window_created(ANativeActivity* activity, ANativeWindow* window) {
  8114. _SOKOL_UNUSED(activity);
  8115. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWCREATED);
  8116. _sapp_android_msg_set_native_window(window);
  8117. }
  8118. _SOKOL_PRIVATE void _sapp_android_on_native_window_destroyed(ANativeActivity* activity, ANativeWindow* window) {
  8119. _SOKOL_UNUSED(activity);
  8120. _SOKOL_UNUSED(window);
  8121. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWDESTROYED);
  8122. _sapp_android_msg_set_native_window(NULL);
  8123. }
  8124. _SOKOL_PRIVATE void _sapp_android_msg_set_input_queue(AInputQueue* input) {
  8125. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8126. _sapp.android.pending.input = input;
  8127. _sapp_android_msg(_SOKOL_ANDROID_MSG_SET_INPUT_QUEUE);
  8128. while (_sapp.android.current.input != input) {
  8129. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8130. }
  8131. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8132. }
  8133. _SOKOL_PRIVATE void _sapp_android_on_input_queue_created(ANativeActivity* activity, AInputQueue* queue) {
  8134. _SOKOL_UNUSED(activity);
  8135. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUECREATED);
  8136. _sapp_android_msg_set_input_queue(queue);
  8137. }
  8138. _SOKOL_PRIVATE void _sapp_android_on_input_queue_destroyed(ANativeActivity* activity, AInputQueue* queue) {
  8139. _SOKOL_UNUSED(activity);
  8140. _SOKOL_UNUSED(queue);
  8141. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUEDESTROYED);
  8142. _sapp_android_msg_set_input_queue(NULL);
  8143. }
  8144. _SOKOL_PRIVATE void _sapp_android_on_config_changed(ANativeActivity* activity) {
  8145. _SOKOL_UNUSED(activity);
  8146. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONCONFIGURATIONCHANGED);
  8147. /* see android:configChanges in manifest */
  8148. }
  8149. _SOKOL_PRIVATE void _sapp_android_on_low_memory(ANativeActivity* activity) {
  8150. _SOKOL_UNUSED(activity);
  8151. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONLOWMEMORY);
  8152. }
  8153. _SOKOL_PRIVATE void _sapp_android_on_destroy(ANativeActivity* activity) {
  8154. /*
  8155. * For some reason even an empty app using nativeactivity.h will crash (WIN DEATH)
  8156. * on my device (Moto X 2nd gen) when the app is removed from the task view
  8157. * (TaskStackView: onTaskViewDismissed).
  8158. *
  8159. * However, if ANativeActivity_finish() is explicitly called from for example
  8160. * _sapp_android_on_stop(), the crash disappears. Is this a bug in NativeActivity?
  8161. */
  8162. _SOKOL_UNUSED(activity);
  8163. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONDESTROY);
  8164. /* send destroy msg */
  8165. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8166. _sapp_android_msg(_SOKOL_ANDROID_MSG_DESTROY);
  8167. while (!_sapp.android.is_thread_stopped) {
  8168. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8169. }
  8170. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8171. /* clean up main thread */
  8172. pthread_cond_destroy(&_sapp.android.pt.cond);
  8173. pthread_mutex_destroy(&_sapp.android.pt.mutex);
  8174. close(_sapp.android.pt.read_from_main_fd);
  8175. close(_sapp.android.pt.write_from_main_fd);
  8176. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_DONE);
  8177. /* this is a bit naughty, but causes a clean restart of the app (static globals are reset) */
  8178. exit(0);
  8179. }
  8180. JNIEXPORT
  8181. void ANativeActivity_onCreate(ANativeActivity* activity, void* saved_state, size_t saved_state_size) {
  8182. _SOKOL_UNUSED(saved_state);
  8183. _SOKOL_UNUSED(saved_state_size);
  8184. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONCREATE);
  8185. // the NativeActity pointer needs to be available inside sokol_main()
  8186. // (see https://github.com/floooh/sokol/issues/708), however _sapp_init_state()
  8187. // will clear the global _sapp_t struct, so we need to initialize the native
  8188. // activity pointer twice, once before sokol_main() and once after _sapp_init_state()
  8189. _sapp_clear(&_sapp, sizeof(_sapp));
  8190. _sapp.android.activity = activity;
  8191. sapp_desc desc = sokol_main(0, NULL);
  8192. _sapp_init_state(&desc);
  8193. _sapp.android.activity = activity;
  8194. int pipe_fd[2];
  8195. if (pipe(pipe_fd) != 0) {
  8196. _SAPP_ERROR(ANDROID_CREATE_THREAD_PIPE_FAILED);
  8197. return;
  8198. }
  8199. _sapp.android.pt.read_from_main_fd = pipe_fd[0];
  8200. _sapp.android.pt.write_from_main_fd = pipe_fd[1];
  8201. pthread_mutex_init(&_sapp.android.pt.mutex, NULL);
  8202. pthread_cond_init(&_sapp.android.pt.cond, NULL);
  8203. pthread_attr_t attr;
  8204. pthread_attr_init(&attr);
  8205. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  8206. pthread_create(&_sapp.android.pt.thread, &attr, _sapp_android_loop, 0);
  8207. pthread_attr_destroy(&attr);
  8208. /* wait until main loop has started */
  8209. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8210. while (!_sapp.android.is_thread_started) {
  8211. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8212. }
  8213. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8214. /* send create msg */
  8215. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8216. _sapp_android_msg(_SOKOL_ANDROID_MSG_CREATE);
  8217. while (!_sapp.android.has_created) {
  8218. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8219. }
  8220. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8221. /* register for callbacks */
  8222. activity->callbacks->onStart = _sapp_android_on_start;
  8223. activity->callbacks->onResume = _sapp_android_on_resume;
  8224. activity->callbacks->onSaveInstanceState = _sapp_android_on_save_instance_state;
  8225. activity->callbacks->onWindowFocusChanged = _sapp_android_on_window_focus_changed;
  8226. activity->callbacks->onPause = _sapp_android_on_pause;
  8227. activity->callbacks->onStop = _sapp_android_on_stop;
  8228. activity->callbacks->onDestroy = _sapp_android_on_destroy;
  8229. activity->callbacks->onNativeWindowCreated = _sapp_android_on_native_window_created;
  8230. /* activity->callbacks->onNativeWindowResized = _sapp_android_on_native_window_resized; */
  8231. /* activity->callbacks->onNativeWindowRedrawNeeded = _sapp_android_on_native_window_redraw_needed; */
  8232. activity->callbacks->onNativeWindowDestroyed = _sapp_android_on_native_window_destroyed;
  8233. activity->callbacks->onInputQueueCreated = _sapp_android_on_input_queue_created;
  8234. activity->callbacks->onInputQueueDestroyed = _sapp_android_on_input_queue_destroyed;
  8235. /* activity->callbacks->onContentRectChanged = _sapp_android_on_content_rect_changed; */
  8236. activity->callbacks->onConfigurationChanged = _sapp_android_on_config_changed;
  8237. activity->callbacks->onLowMemory = _sapp_android_on_low_memory;
  8238. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_CREATE_SUCCESS);
  8239. /* NOT A BUG: do NOT call sapp_discard_state() */
  8240. }
  8241. #endif /* _SAPP_ANDROID */
  8242. // ██ ██ ███ ██ ██ ██ ██ ██
  8243. // ██ ██ ████ ██ ██ ██ ██ ██
  8244. // ██ ██ ██ ██ ██ ██ ██ ███
  8245. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  8246. // ███████ ██ ██ ████ ██████ ██ ██
  8247. //
  8248. // >>linux
  8249. #if defined(_SAPP_LINUX)
  8250. /* see GLFW's xkb_unicode.c */
  8251. static const struct _sapp_x11_codepair {
  8252. uint16_t keysym;
  8253. uint16_t ucs;
  8254. } _sapp_x11_keysymtab[] = {
  8255. { 0x01a1, 0x0104 },
  8256. { 0x01a2, 0x02d8 },
  8257. { 0x01a3, 0x0141 },
  8258. { 0x01a5, 0x013d },
  8259. { 0x01a6, 0x015a },
  8260. { 0x01a9, 0x0160 },
  8261. { 0x01aa, 0x015e },
  8262. { 0x01ab, 0x0164 },
  8263. { 0x01ac, 0x0179 },
  8264. { 0x01ae, 0x017d },
  8265. { 0x01af, 0x017b },
  8266. { 0x01b1, 0x0105 },
  8267. { 0x01b2, 0x02db },
  8268. { 0x01b3, 0x0142 },
  8269. { 0x01b5, 0x013e },
  8270. { 0x01b6, 0x015b },
  8271. { 0x01b7, 0x02c7 },
  8272. { 0x01b9, 0x0161 },
  8273. { 0x01ba, 0x015f },
  8274. { 0x01bb, 0x0165 },
  8275. { 0x01bc, 0x017a },
  8276. { 0x01bd, 0x02dd },
  8277. { 0x01be, 0x017e },
  8278. { 0x01bf, 0x017c },
  8279. { 0x01c0, 0x0154 },
  8280. { 0x01c3, 0x0102 },
  8281. { 0x01c5, 0x0139 },
  8282. { 0x01c6, 0x0106 },
  8283. { 0x01c8, 0x010c },
  8284. { 0x01ca, 0x0118 },
  8285. { 0x01cc, 0x011a },
  8286. { 0x01cf, 0x010e },
  8287. { 0x01d0, 0x0110 },
  8288. { 0x01d1, 0x0143 },
  8289. { 0x01d2, 0x0147 },
  8290. { 0x01d5, 0x0150 },
  8291. { 0x01d8, 0x0158 },
  8292. { 0x01d9, 0x016e },
  8293. { 0x01db, 0x0170 },
  8294. { 0x01de, 0x0162 },
  8295. { 0x01e0, 0x0155 },
  8296. { 0x01e3, 0x0103 },
  8297. { 0x01e5, 0x013a },
  8298. { 0x01e6, 0x0107 },
  8299. { 0x01e8, 0x010d },
  8300. { 0x01ea, 0x0119 },
  8301. { 0x01ec, 0x011b },
  8302. { 0x01ef, 0x010f },
  8303. { 0x01f0, 0x0111 },
  8304. { 0x01f1, 0x0144 },
  8305. { 0x01f2, 0x0148 },
  8306. { 0x01f5, 0x0151 },
  8307. { 0x01f8, 0x0159 },
  8308. { 0x01f9, 0x016f },
  8309. { 0x01fb, 0x0171 },
  8310. { 0x01fe, 0x0163 },
  8311. { 0x01ff, 0x02d9 },
  8312. { 0x02a1, 0x0126 },
  8313. { 0x02a6, 0x0124 },
  8314. { 0x02a9, 0x0130 },
  8315. { 0x02ab, 0x011e },
  8316. { 0x02ac, 0x0134 },
  8317. { 0x02b1, 0x0127 },
  8318. { 0x02b6, 0x0125 },
  8319. { 0x02b9, 0x0131 },
  8320. { 0x02bb, 0x011f },
  8321. { 0x02bc, 0x0135 },
  8322. { 0x02c5, 0x010a },
  8323. { 0x02c6, 0x0108 },
  8324. { 0x02d5, 0x0120 },
  8325. { 0x02d8, 0x011c },
  8326. { 0x02dd, 0x016c },
  8327. { 0x02de, 0x015c },
  8328. { 0x02e5, 0x010b },
  8329. { 0x02e6, 0x0109 },
  8330. { 0x02f5, 0x0121 },
  8331. { 0x02f8, 0x011d },
  8332. { 0x02fd, 0x016d },
  8333. { 0x02fe, 0x015d },
  8334. { 0x03a2, 0x0138 },
  8335. { 0x03a3, 0x0156 },
  8336. { 0x03a5, 0x0128 },
  8337. { 0x03a6, 0x013b },
  8338. { 0x03aa, 0x0112 },
  8339. { 0x03ab, 0x0122 },
  8340. { 0x03ac, 0x0166 },
  8341. { 0x03b3, 0x0157 },
  8342. { 0x03b5, 0x0129 },
  8343. { 0x03b6, 0x013c },
  8344. { 0x03ba, 0x0113 },
  8345. { 0x03bb, 0x0123 },
  8346. { 0x03bc, 0x0167 },
  8347. { 0x03bd, 0x014a },
  8348. { 0x03bf, 0x014b },
  8349. { 0x03c0, 0x0100 },
  8350. { 0x03c7, 0x012e },
  8351. { 0x03cc, 0x0116 },
  8352. { 0x03cf, 0x012a },
  8353. { 0x03d1, 0x0145 },
  8354. { 0x03d2, 0x014c },
  8355. { 0x03d3, 0x0136 },
  8356. { 0x03d9, 0x0172 },
  8357. { 0x03dd, 0x0168 },
  8358. { 0x03de, 0x016a },
  8359. { 0x03e0, 0x0101 },
  8360. { 0x03e7, 0x012f },
  8361. { 0x03ec, 0x0117 },
  8362. { 0x03ef, 0x012b },
  8363. { 0x03f1, 0x0146 },
  8364. { 0x03f2, 0x014d },
  8365. { 0x03f3, 0x0137 },
  8366. { 0x03f9, 0x0173 },
  8367. { 0x03fd, 0x0169 },
  8368. { 0x03fe, 0x016b },
  8369. { 0x047e, 0x203e },
  8370. { 0x04a1, 0x3002 },
  8371. { 0x04a2, 0x300c },
  8372. { 0x04a3, 0x300d },
  8373. { 0x04a4, 0x3001 },
  8374. { 0x04a5, 0x30fb },
  8375. { 0x04a6, 0x30f2 },
  8376. { 0x04a7, 0x30a1 },
  8377. { 0x04a8, 0x30a3 },
  8378. { 0x04a9, 0x30a5 },
  8379. { 0x04aa, 0x30a7 },
  8380. { 0x04ab, 0x30a9 },
  8381. { 0x04ac, 0x30e3 },
  8382. { 0x04ad, 0x30e5 },
  8383. { 0x04ae, 0x30e7 },
  8384. { 0x04af, 0x30c3 },
  8385. { 0x04b0, 0x30fc },
  8386. { 0x04b1, 0x30a2 },
  8387. { 0x04b2, 0x30a4 },
  8388. { 0x04b3, 0x30a6 },
  8389. { 0x04b4, 0x30a8 },
  8390. { 0x04b5, 0x30aa },
  8391. { 0x04b6, 0x30ab },
  8392. { 0x04b7, 0x30ad },
  8393. { 0x04b8, 0x30af },
  8394. { 0x04b9, 0x30b1 },
  8395. { 0x04ba, 0x30b3 },
  8396. { 0x04bb, 0x30b5 },
  8397. { 0x04bc, 0x30b7 },
  8398. { 0x04bd, 0x30b9 },
  8399. { 0x04be, 0x30bb },
  8400. { 0x04bf, 0x30bd },
  8401. { 0x04c0, 0x30bf },
  8402. { 0x04c1, 0x30c1 },
  8403. { 0x04c2, 0x30c4 },
  8404. { 0x04c3, 0x30c6 },
  8405. { 0x04c4, 0x30c8 },
  8406. { 0x04c5, 0x30ca },
  8407. { 0x04c6, 0x30cb },
  8408. { 0x04c7, 0x30cc },
  8409. { 0x04c8, 0x30cd },
  8410. { 0x04c9, 0x30ce },
  8411. { 0x04ca, 0x30cf },
  8412. { 0x04cb, 0x30d2 },
  8413. { 0x04cc, 0x30d5 },
  8414. { 0x04cd, 0x30d8 },
  8415. { 0x04ce, 0x30db },
  8416. { 0x04cf, 0x30de },
  8417. { 0x04d0, 0x30df },
  8418. { 0x04d1, 0x30e0 },
  8419. { 0x04d2, 0x30e1 },
  8420. { 0x04d3, 0x30e2 },
  8421. { 0x04d4, 0x30e4 },
  8422. { 0x04d5, 0x30e6 },
  8423. { 0x04d6, 0x30e8 },
  8424. { 0x04d7, 0x30e9 },
  8425. { 0x04d8, 0x30ea },
  8426. { 0x04d9, 0x30eb },
  8427. { 0x04da, 0x30ec },
  8428. { 0x04db, 0x30ed },
  8429. { 0x04dc, 0x30ef },
  8430. { 0x04dd, 0x30f3 },
  8431. { 0x04de, 0x309b },
  8432. { 0x04df, 0x309c },
  8433. { 0x05ac, 0x060c },
  8434. { 0x05bb, 0x061b },
  8435. { 0x05bf, 0x061f },
  8436. { 0x05c1, 0x0621 },
  8437. { 0x05c2, 0x0622 },
  8438. { 0x05c3, 0x0623 },
  8439. { 0x05c4, 0x0624 },
  8440. { 0x05c5, 0x0625 },
  8441. { 0x05c6, 0x0626 },
  8442. { 0x05c7, 0x0627 },
  8443. { 0x05c8, 0x0628 },
  8444. { 0x05c9, 0x0629 },
  8445. { 0x05ca, 0x062a },
  8446. { 0x05cb, 0x062b },
  8447. { 0x05cc, 0x062c },
  8448. { 0x05cd, 0x062d },
  8449. { 0x05ce, 0x062e },
  8450. { 0x05cf, 0x062f },
  8451. { 0x05d0, 0x0630 },
  8452. { 0x05d1, 0x0631 },
  8453. { 0x05d2, 0x0632 },
  8454. { 0x05d3, 0x0633 },
  8455. { 0x05d4, 0x0634 },
  8456. { 0x05d5, 0x0635 },
  8457. { 0x05d6, 0x0636 },
  8458. { 0x05d7, 0x0637 },
  8459. { 0x05d8, 0x0638 },
  8460. { 0x05d9, 0x0639 },
  8461. { 0x05da, 0x063a },
  8462. { 0x05e0, 0x0640 },
  8463. { 0x05e1, 0x0641 },
  8464. { 0x05e2, 0x0642 },
  8465. { 0x05e3, 0x0643 },
  8466. { 0x05e4, 0x0644 },
  8467. { 0x05e5, 0x0645 },
  8468. { 0x05e6, 0x0646 },
  8469. { 0x05e7, 0x0647 },
  8470. { 0x05e8, 0x0648 },
  8471. { 0x05e9, 0x0649 },
  8472. { 0x05ea, 0x064a },
  8473. { 0x05eb, 0x064b },
  8474. { 0x05ec, 0x064c },
  8475. { 0x05ed, 0x064d },
  8476. { 0x05ee, 0x064e },
  8477. { 0x05ef, 0x064f },
  8478. { 0x05f0, 0x0650 },
  8479. { 0x05f1, 0x0651 },
  8480. { 0x05f2, 0x0652 },
  8481. { 0x06a1, 0x0452 },
  8482. { 0x06a2, 0x0453 },
  8483. { 0x06a3, 0x0451 },
  8484. { 0x06a4, 0x0454 },
  8485. { 0x06a5, 0x0455 },
  8486. { 0x06a6, 0x0456 },
  8487. { 0x06a7, 0x0457 },
  8488. { 0x06a8, 0x0458 },
  8489. { 0x06a9, 0x0459 },
  8490. { 0x06aa, 0x045a },
  8491. { 0x06ab, 0x045b },
  8492. { 0x06ac, 0x045c },
  8493. { 0x06ae, 0x045e },
  8494. { 0x06af, 0x045f },
  8495. { 0x06b0, 0x2116 },
  8496. { 0x06b1, 0x0402 },
  8497. { 0x06b2, 0x0403 },
  8498. { 0x06b3, 0x0401 },
  8499. { 0x06b4, 0x0404 },
  8500. { 0x06b5, 0x0405 },
  8501. { 0x06b6, 0x0406 },
  8502. { 0x06b7, 0x0407 },
  8503. { 0x06b8, 0x0408 },
  8504. { 0x06b9, 0x0409 },
  8505. { 0x06ba, 0x040a },
  8506. { 0x06bb, 0x040b },
  8507. { 0x06bc, 0x040c },
  8508. { 0x06be, 0x040e },
  8509. { 0x06bf, 0x040f },
  8510. { 0x06c0, 0x044e },
  8511. { 0x06c1, 0x0430 },
  8512. { 0x06c2, 0x0431 },
  8513. { 0x06c3, 0x0446 },
  8514. { 0x06c4, 0x0434 },
  8515. { 0x06c5, 0x0435 },
  8516. { 0x06c6, 0x0444 },
  8517. { 0x06c7, 0x0433 },
  8518. { 0x06c8, 0x0445 },
  8519. { 0x06c9, 0x0438 },
  8520. { 0x06ca, 0x0439 },
  8521. { 0x06cb, 0x043a },
  8522. { 0x06cc, 0x043b },
  8523. { 0x06cd, 0x043c },
  8524. { 0x06ce, 0x043d },
  8525. { 0x06cf, 0x043e },
  8526. { 0x06d0, 0x043f },
  8527. { 0x06d1, 0x044f },
  8528. { 0x06d2, 0x0440 },
  8529. { 0x06d3, 0x0441 },
  8530. { 0x06d4, 0x0442 },
  8531. { 0x06d5, 0x0443 },
  8532. { 0x06d6, 0x0436 },
  8533. { 0x06d7, 0x0432 },
  8534. { 0x06d8, 0x044c },
  8535. { 0x06d9, 0x044b },
  8536. { 0x06da, 0x0437 },
  8537. { 0x06db, 0x0448 },
  8538. { 0x06dc, 0x044d },
  8539. { 0x06dd, 0x0449 },
  8540. { 0x06de, 0x0447 },
  8541. { 0x06df, 0x044a },
  8542. { 0x06e0, 0x042e },
  8543. { 0x06e1, 0x0410 },
  8544. { 0x06e2, 0x0411 },
  8545. { 0x06e3, 0x0426 },
  8546. { 0x06e4, 0x0414 },
  8547. { 0x06e5, 0x0415 },
  8548. { 0x06e6, 0x0424 },
  8549. { 0x06e7, 0x0413 },
  8550. { 0x06e8, 0x0425 },
  8551. { 0x06e9, 0x0418 },
  8552. { 0x06ea, 0x0419 },
  8553. { 0x06eb, 0x041a },
  8554. { 0x06ec, 0x041b },
  8555. { 0x06ed, 0x041c },
  8556. { 0x06ee, 0x041d },
  8557. { 0x06ef, 0x041e },
  8558. { 0x06f0, 0x041f },
  8559. { 0x06f1, 0x042f },
  8560. { 0x06f2, 0x0420 },
  8561. { 0x06f3, 0x0421 },
  8562. { 0x06f4, 0x0422 },
  8563. { 0x06f5, 0x0423 },
  8564. { 0x06f6, 0x0416 },
  8565. { 0x06f7, 0x0412 },
  8566. { 0x06f8, 0x042c },
  8567. { 0x06f9, 0x042b },
  8568. { 0x06fa, 0x0417 },
  8569. { 0x06fb, 0x0428 },
  8570. { 0x06fc, 0x042d },
  8571. { 0x06fd, 0x0429 },
  8572. { 0x06fe, 0x0427 },
  8573. { 0x06ff, 0x042a },
  8574. { 0x07a1, 0x0386 },
  8575. { 0x07a2, 0x0388 },
  8576. { 0x07a3, 0x0389 },
  8577. { 0x07a4, 0x038a },
  8578. { 0x07a5, 0x03aa },
  8579. { 0x07a7, 0x038c },
  8580. { 0x07a8, 0x038e },
  8581. { 0x07a9, 0x03ab },
  8582. { 0x07ab, 0x038f },
  8583. { 0x07ae, 0x0385 },
  8584. { 0x07af, 0x2015 },
  8585. { 0x07b1, 0x03ac },
  8586. { 0x07b2, 0x03ad },
  8587. { 0x07b3, 0x03ae },
  8588. { 0x07b4, 0x03af },
  8589. { 0x07b5, 0x03ca },
  8590. { 0x07b6, 0x0390 },
  8591. { 0x07b7, 0x03cc },
  8592. { 0x07b8, 0x03cd },
  8593. { 0x07b9, 0x03cb },
  8594. { 0x07ba, 0x03b0 },
  8595. { 0x07bb, 0x03ce },
  8596. { 0x07c1, 0x0391 },
  8597. { 0x07c2, 0x0392 },
  8598. { 0x07c3, 0x0393 },
  8599. { 0x07c4, 0x0394 },
  8600. { 0x07c5, 0x0395 },
  8601. { 0x07c6, 0x0396 },
  8602. { 0x07c7, 0x0397 },
  8603. { 0x07c8, 0x0398 },
  8604. { 0x07c9, 0x0399 },
  8605. { 0x07ca, 0x039a },
  8606. { 0x07cb, 0x039b },
  8607. { 0x07cc, 0x039c },
  8608. { 0x07cd, 0x039d },
  8609. { 0x07ce, 0x039e },
  8610. { 0x07cf, 0x039f },
  8611. { 0x07d0, 0x03a0 },
  8612. { 0x07d1, 0x03a1 },
  8613. { 0x07d2, 0x03a3 },
  8614. { 0x07d4, 0x03a4 },
  8615. { 0x07d5, 0x03a5 },
  8616. { 0x07d6, 0x03a6 },
  8617. { 0x07d7, 0x03a7 },
  8618. { 0x07d8, 0x03a8 },
  8619. { 0x07d9, 0x03a9 },
  8620. { 0x07e1, 0x03b1 },
  8621. { 0x07e2, 0x03b2 },
  8622. { 0x07e3, 0x03b3 },
  8623. { 0x07e4, 0x03b4 },
  8624. { 0x07e5, 0x03b5 },
  8625. { 0x07e6, 0x03b6 },
  8626. { 0x07e7, 0x03b7 },
  8627. { 0x07e8, 0x03b8 },
  8628. { 0x07e9, 0x03b9 },
  8629. { 0x07ea, 0x03ba },
  8630. { 0x07eb, 0x03bb },
  8631. { 0x07ec, 0x03bc },
  8632. { 0x07ed, 0x03bd },
  8633. { 0x07ee, 0x03be },
  8634. { 0x07ef, 0x03bf },
  8635. { 0x07f0, 0x03c0 },
  8636. { 0x07f1, 0x03c1 },
  8637. { 0x07f2, 0x03c3 },
  8638. { 0x07f3, 0x03c2 },
  8639. { 0x07f4, 0x03c4 },
  8640. { 0x07f5, 0x03c5 },
  8641. { 0x07f6, 0x03c6 },
  8642. { 0x07f7, 0x03c7 },
  8643. { 0x07f8, 0x03c8 },
  8644. { 0x07f9, 0x03c9 },
  8645. { 0x08a1, 0x23b7 },
  8646. { 0x08a2, 0x250c },
  8647. { 0x08a3, 0x2500 },
  8648. { 0x08a4, 0x2320 },
  8649. { 0x08a5, 0x2321 },
  8650. { 0x08a6, 0x2502 },
  8651. { 0x08a7, 0x23a1 },
  8652. { 0x08a8, 0x23a3 },
  8653. { 0x08a9, 0x23a4 },
  8654. { 0x08aa, 0x23a6 },
  8655. { 0x08ab, 0x239b },
  8656. { 0x08ac, 0x239d },
  8657. { 0x08ad, 0x239e },
  8658. { 0x08ae, 0x23a0 },
  8659. { 0x08af, 0x23a8 },
  8660. { 0x08b0, 0x23ac },
  8661. { 0x08bc, 0x2264 },
  8662. { 0x08bd, 0x2260 },
  8663. { 0x08be, 0x2265 },
  8664. { 0x08bf, 0x222b },
  8665. { 0x08c0, 0x2234 },
  8666. { 0x08c1, 0x221d },
  8667. { 0x08c2, 0x221e },
  8668. { 0x08c5, 0x2207 },
  8669. { 0x08c8, 0x223c },
  8670. { 0x08c9, 0x2243 },
  8671. { 0x08cd, 0x21d4 },
  8672. { 0x08ce, 0x21d2 },
  8673. { 0x08cf, 0x2261 },
  8674. { 0x08d6, 0x221a },
  8675. { 0x08da, 0x2282 },
  8676. { 0x08db, 0x2283 },
  8677. { 0x08dc, 0x2229 },
  8678. { 0x08dd, 0x222a },
  8679. { 0x08de, 0x2227 },
  8680. { 0x08df, 0x2228 },
  8681. { 0x08ef, 0x2202 },
  8682. { 0x08f6, 0x0192 },
  8683. { 0x08fb, 0x2190 },
  8684. { 0x08fc, 0x2191 },
  8685. { 0x08fd, 0x2192 },
  8686. { 0x08fe, 0x2193 },
  8687. { 0x09e0, 0x25c6 },
  8688. { 0x09e1, 0x2592 },
  8689. { 0x09e2, 0x2409 },
  8690. { 0x09e3, 0x240c },
  8691. { 0x09e4, 0x240d },
  8692. { 0x09e5, 0x240a },
  8693. { 0x09e8, 0x2424 },
  8694. { 0x09e9, 0x240b },
  8695. { 0x09ea, 0x2518 },
  8696. { 0x09eb, 0x2510 },
  8697. { 0x09ec, 0x250c },
  8698. { 0x09ed, 0x2514 },
  8699. { 0x09ee, 0x253c },
  8700. { 0x09ef, 0x23ba },
  8701. { 0x09f0, 0x23bb },
  8702. { 0x09f1, 0x2500 },
  8703. { 0x09f2, 0x23bc },
  8704. { 0x09f3, 0x23bd },
  8705. { 0x09f4, 0x251c },
  8706. { 0x09f5, 0x2524 },
  8707. { 0x09f6, 0x2534 },
  8708. { 0x09f7, 0x252c },
  8709. { 0x09f8, 0x2502 },
  8710. { 0x0aa1, 0x2003 },
  8711. { 0x0aa2, 0x2002 },
  8712. { 0x0aa3, 0x2004 },
  8713. { 0x0aa4, 0x2005 },
  8714. { 0x0aa5, 0x2007 },
  8715. { 0x0aa6, 0x2008 },
  8716. { 0x0aa7, 0x2009 },
  8717. { 0x0aa8, 0x200a },
  8718. { 0x0aa9, 0x2014 },
  8719. { 0x0aaa, 0x2013 },
  8720. { 0x0aae, 0x2026 },
  8721. { 0x0aaf, 0x2025 },
  8722. { 0x0ab0, 0x2153 },
  8723. { 0x0ab1, 0x2154 },
  8724. { 0x0ab2, 0x2155 },
  8725. { 0x0ab3, 0x2156 },
  8726. { 0x0ab4, 0x2157 },
  8727. { 0x0ab5, 0x2158 },
  8728. { 0x0ab6, 0x2159 },
  8729. { 0x0ab7, 0x215a },
  8730. { 0x0ab8, 0x2105 },
  8731. { 0x0abb, 0x2012 },
  8732. { 0x0abc, 0x2329 },
  8733. { 0x0abe, 0x232a },
  8734. { 0x0ac3, 0x215b },
  8735. { 0x0ac4, 0x215c },
  8736. { 0x0ac5, 0x215d },
  8737. { 0x0ac6, 0x215e },
  8738. { 0x0ac9, 0x2122 },
  8739. { 0x0aca, 0x2613 },
  8740. { 0x0acc, 0x25c1 },
  8741. { 0x0acd, 0x25b7 },
  8742. { 0x0ace, 0x25cb },
  8743. { 0x0acf, 0x25af },
  8744. { 0x0ad0, 0x2018 },
  8745. { 0x0ad1, 0x2019 },
  8746. { 0x0ad2, 0x201c },
  8747. { 0x0ad3, 0x201d },
  8748. { 0x0ad4, 0x211e },
  8749. { 0x0ad6, 0x2032 },
  8750. { 0x0ad7, 0x2033 },
  8751. { 0x0ad9, 0x271d },
  8752. { 0x0adb, 0x25ac },
  8753. { 0x0adc, 0x25c0 },
  8754. { 0x0add, 0x25b6 },
  8755. { 0x0ade, 0x25cf },
  8756. { 0x0adf, 0x25ae },
  8757. { 0x0ae0, 0x25e6 },
  8758. { 0x0ae1, 0x25ab },
  8759. { 0x0ae2, 0x25ad },
  8760. { 0x0ae3, 0x25b3 },
  8761. { 0x0ae4, 0x25bd },
  8762. { 0x0ae5, 0x2606 },
  8763. { 0x0ae6, 0x2022 },
  8764. { 0x0ae7, 0x25aa },
  8765. { 0x0ae8, 0x25b2 },
  8766. { 0x0ae9, 0x25bc },
  8767. { 0x0aea, 0x261c },
  8768. { 0x0aeb, 0x261e },
  8769. { 0x0aec, 0x2663 },
  8770. { 0x0aed, 0x2666 },
  8771. { 0x0aee, 0x2665 },
  8772. { 0x0af0, 0x2720 },
  8773. { 0x0af1, 0x2020 },
  8774. { 0x0af2, 0x2021 },
  8775. { 0x0af3, 0x2713 },
  8776. { 0x0af4, 0x2717 },
  8777. { 0x0af5, 0x266f },
  8778. { 0x0af6, 0x266d },
  8779. { 0x0af7, 0x2642 },
  8780. { 0x0af8, 0x2640 },
  8781. { 0x0af9, 0x260e },
  8782. { 0x0afa, 0x2315 },
  8783. { 0x0afb, 0x2117 },
  8784. { 0x0afc, 0x2038 },
  8785. { 0x0afd, 0x201a },
  8786. { 0x0afe, 0x201e },
  8787. { 0x0ba3, 0x003c },
  8788. { 0x0ba6, 0x003e },
  8789. { 0x0ba8, 0x2228 },
  8790. { 0x0ba9, 0x2227 },
  8791. { 0x0bc0, 0x00af },
  8792. { 0x0bc2, 0x22a5 },
  8793. { 0x0bc3, 0x2229 },
  8794. { 0x0bc4, 0x230a },
  8795. { 0x0bc6, 0x005f },
  8796. { 0x0bca, 0x2218 },
  8797. { 0x0bcc, 0x2395 },
  8798. { 0x0bce, 0x22a4 },
  8799. { 0x0bcf, 0x25cb },
  8800. { 0x0bd3, 0x2308 },
  8801. { 0x0bd6, 0x222a },
  8802. { 0x0bd8, 0x2283 },
  8803. { 0x0bda, 0x2282 },
  8804. { 0x0bdc, 0x22a2 },
  8805. { 0x0bfc, 0x22a3 },
  8806. { 0x0cdf, 0x2017 },
  8807. { 0x0ce0, 0x05d0 },
  8808. { 0x0ce1, 0x05d1 },
  8809. { 0x0ce2, 0x05d2 },
  8810. { 0x0ce3, 0x05d3 },
  8811. { 0x0ce4, 0x05d4 },
  8812. { 0x0ce5, 0x05d5 },
  8813. { 0x0ce6, 0x05d6 },
  8814. { 0x0ce7, 0x05d7 },
  8815. { 0x0ce8, 0x05d8 },
  8816. { 0x0ce9, 0x05d9 },
  8817. { 0x0cea, 0x05da },
  8818. { 0x0ceb, 0x05db },
  8819. { 0x0cec, 0x05dc },
  8820. { 0x0ced, 0x05dd },
  8821. { 0x0cee, 0x05de },
  8822. { 0x0cef, 0x05df },
  8823. { 0x0cf0, 0x05e0 },
  8824. { 0x0cf1, 0x05e1 },
  8825. { 0x0cf2, 0x05e2 },
  8826. { 0x0cf3, 0x05e3 },
  8827. { 0x0cf4, 0x05e4 },
  8828. { 0x0cf5, 0x05e5 },
  8829. { 0x0cf6, 0x05e6 },
  8830. { 0x0cf7, 0x05e7 },
  8831. { 0x0cf8, 0x05e8 },
  8832. { 0x0cf9, 0x05e9 },
  8833. { 0x0cfa, 0x05ea },
  8834. { 0x0da1, 0x0e01 },
  8835. { 0x0da2, 0x0e02 },
  8836. { 0x0da3, 0x0e03 },
  8837. { 0x0da4, 0x0e04 },
  8838. { 0x0da5, 0x0e05 },
  8839. { 0x0da6, 0x0e06 },
  8840. { 0x0da7, 0x0e07 },
  8841. { 0x0da8, 0x0e08 },
  8842. { 0x0da9, 0x0e09 },
  8843. { 0x0daa, 0x0e0a },
  8844. { 0x0dab, 0x0e0b },
  8845. { 0x0dac, 0x0e0c },
  8846. { 0x0dad, 0x0e0d },
  8847. { 0x0dae, 0x0e0e },
  8848. { 0x0daf, 0x0e0f },
  8849. { 0x0db0, 0x0e10 },
  8850. { 0x0db1, 0x0e11 },
  8851. { 0x0db2, 0x0e12 },
  8852. { 0x0db3, 0x0e13 },
  8853. { 0x0db4, 0x0e14 },
  8854. { 0x0db5, 0x0e15 },
  8855. { 0x0db6, 0x0e16 },
  8856. { 0x0db7, 0x0e17 },
  8857. { 0x0db8, 0x0e18 },
  8858. { 0x0db9, 0x0e19 },
  8859. { 0x0dba, 0x0e1a },
  8860. { 0x0dbb, 0x0e1b },
  8861. { 0x0dbc, 0x0e1c },
  8862. { 0x0dbd, 0x0e1d },
  8863. { 0x0dbe, 0x0e1e },
  8864. { 0x0dbf, 0x0e1f },
  8865. { 0x0dc0, 0x0e20 },
  8866. { 0x0dc1, 0x0e21 },
  8867. { 0x0dc2, 0x0e22 },
  8868. { 0x0dc3, 0x0e23 },
  8869. { 0x0dc4, 0x0e24 },
  8870. { 0x0dc5, 0x0e25 },
  8871. { 0x0dc6, 0x0e26 },
  8872. { 0x0dc7, 0x0e27 },
  8873. { 0x0dc8, 0x0e28 },
  8874. { 0x0dc9, 0x0e29 },
  8875. { 0x0dca, 0x0e2a },
  8876. { 0x0dcb, 0x0e2b },
  8877. { 0x0dcc, 0x0e2c },
  8878. { 0x0dcd, 0x0e2d },
  8879. { 0x0dce, 0x0e2e },
  8880. { 0x0dcf, 0x0e2f },
  8881. { 0x0dd0, 0x0e30 },
  8882. { 0x0dd1, 0x0e31 },
  8883. { 0x0dd2, 0x0e32 },
  8884. { 0x0dd3, 0x0e33 },
  8885. { 0x0dd4, 0x0e34 },
  8886. { 0x0dd5, 0x0e35 },
  8887. { 0x0dd6, 0x0e36 },
  8888. { 0x0dd7, 0x0e37 },
  8889. { 0x0dd8, 0x0e38 },
  8890. { 0x0dd9, 0x0e39 },
  8891. { 0x0dda, 0x0e3a },
  8892. { 0x0ddf, 0x0e3f },
  8893. { 0x0de0, 0x0e40 },
  8894. { 0x0de1, 0x0e41 },
  8895. { 0x0de2, 0x0e42 },
  8896. { 0x0de3, 0x0e43 },
  8897. { 0x0de4, 0x0e44 },
  8898. { 0x0de5, 0x0e45 },
  8899. { 0x0de6, 0x0e46 },
  8900. { 0x0de7, 0x0e47 },
  8901. { 0x0de8, 0x0e48 },
  8902. { 0x0de9, 0x0e49 },
  8903. { 0x0dea, 0x0e4a },
  8904. { 0x0deb, 0x0e4b },
  8905. { 0x0dec, 0x0e4c },
  8906. { 0x0ded, 0x0e4d },
  8907. { 0x0df0, 0x0e50 },
  8908. { 0x0df1, 0x0e51 },
  8909. { 0x0df2, 0x0e52 },
  8910. { 0x0df3, 0x0e53 },
  8911. { 0x0df4, 0x0e54 },
  8912. { 0x0df5, 0x0e55 },
  8913. { 0x0df6, 0x0e56 },
  8914. { 0x0df7, 0x0e57 },
  8915. { 0x0df8, 0x0e58 },
  8916. { 0x0df9, 0x0e59 },
  8917. { 0x0ea1, 0x3131 },
  8918. { 0x0ea2, 0x3132 },
  8919. { 0x0ea3, 0x3133 },
  8920. { 0x0ea4, 0x3134 },
  8921. { 0x0ea5, 0x3135 },
  8922. { 0x0ea6, 0x3136 },
  8923. { 0x0ea7, 0x3137 },
  8924. { 0x0ea8, 0x3138 },
  8925. { 0x0ea9, 0x3139 },
  8926. { 0x0eaa, 0x313a },
  8927. { 0x0eab, 0x313b },
  8928. { 0x0eac, 0x313c },
  8929. { 0x0ead, 0x313d },
  8930. { 0x0eae, 0x313e },
  8931. { 0x0eaf, 0x313f },
  8932. { 0x0eb0, 0x3140 },
  8933. { 0x0eb1, 0x3141 },
  8934. { 0x0eb2, 0x3142 },
  8935. { 0x0eb3, 0x3143 },
  8936. { 0x0eb4, 0x3144 },
  8937. { 0x0eb5, 0x3145 },
  8938. { 0x0eb6, 0x3146 },
  8939. { 0x0eb7, 0x3147 },
  8940. { 0x0eb8, 0x3148 },
  8941. { 0x0eb9, 0x3149 },
  8942. { 0x0eba, 0x314a },
  8943. { 0x0ebb, 0x314b },
  8944. { 0x0ebc, 0x314c },
  8945. { 0x0ebd, 0x314d },
  8946. { 0x0ebe, 0x314e },
  8947. { 0x0ebf, 0x314f },
  8948. { 0x0ec0, 0x3150 },
  8949. { 0x0ec1, 0x3151 },
  8950. { 0x0ec2, 0x3152 },
  8951. { 0x0ec3, 0x3153 },
  8952. { 0x0ec4, 0x3154 },
  8953. { 0x0ec5, 0x3155 },
  8954. { 0x0ec6, 0x3156 },
  8955. { 0x0ec7, 0x3157 },
  8956. { 0x0ec8, 0x3158 },
  8957. { 0x0ec9, 0x3159 },
  8958. { 0x0eca, 0x315a },
  8959. { 0x0ecb, 0x315b },
  8960. { 0x0ecc, 0x315c },
  8961. { 0x0ecd, 0x315d },
  8962. { 0x0ece, 0x315e },
  8963. { 0x0ecf, 0x315f },
  8964. { 0x0ed0, 0x3160 },
  8965. { 0x0ed1, 0x3161 },
  8966. { 0x0ed2, 0x3162 },
  8967. { 0x0ed3, 0x3163 },
  8968. { 0x0ed4, 0x11a8 },
  8969. { 0x0ed5, 0x11a9 },
  8970. { 0x0ed6, 0x11aa },
  8971. { 0x0ed7, 0x11ab },
  8972. { 0x0ed8, 0x11ac },
  8973. { 0x0ed9, 0x11ad },
  8974. { 0x0eda, 0x11ae },
  8975. { 0x0edb, 0x11af },
  8976. { 0x0edc, 0x11b0 },
  8977. { 0x0edd, 0x11b1 },
  8978. { 0x0ede, 0x11b2 },
  8979. { 0x0edf, 0x11b3 },
  8980. { 0x0ee0, 0x11b4 },
  8981. { 0x0ee1, 0x11b5 },
  8982. { 0x0ee2, 0x11b6 },
  8983. { 0x0ee3, 0x11b7 },
  8984. { 0x0ee4, 0x11b8 },
  8985. { 0x0ee5, 0x11b9 },
  8986. { 0x0ee6, 0x11ba },
  8987. { 0x0ee7, 0x11bb },
  8988. { 0x0ee8, 0x11bc },
  8989. { 0x0ee9, 0x11bd },
  8990. { 0x0eea, 0x11be },
  8991. { 0x0eeb, 0x11bf },
  8992. { 0x0eec, 0x11c0 },
  8993. { 0x0eed, 0x11c1 },
  8994. { 0x0eee, 0x11c2 },
  8995. { 0x0eef, 0x316d },
  8996. { 0x0ef0, 0x3171 },
  8997. { 0x0ef1, 0x3178 },
  8998. { 0x0ef2, 0x317f },
  8999. { 0x0ef3, 0x3181 },
  9000. { 0x0ef4, 0x3184 },
  9001. { 0x0ef5, 0x3186 },
  9002. { 0x0ef6, 0x318d },
  9003. { 0x0ef7, 0x318e },
  9004. { 0x0ef8, 0x11eb },
  9005. { 0x0ef9, 0x11f0 },
  9006. { 0x0efa, 0x11f9 },
  9007. { 0x0eff, 0x20a9 },
  9008. { 0x13a4, 0x20ac },
  9009. { 0x13bc, 0x0152 },
  9010. { 0x13bd, 0x0153 },
  9011. { 0x13be, 0x0178 },
  9012. { 0x20ac, 0x20ac },
  9013. { 0xfe50, '`' },
  9014. { 0xfe51, 0x00b4 },
  9015. { 0xfe52, '^' },
  9016. { 0xfe53, '~' },
  9017. { 0xfe54, 0x00af },
  9018. { 0xfe55, 0x02d8 },
  9019. { 0xfe56, 0x02d9 },
  9020. { 0xfe57, 0x00a8 },
  9021. { 0xfe58, 0x02da },
  9022. { 0xfe59, 0x02dd },
  9023. { 0xfe5a, 0x02c7 },
  9024. { 0xfe5b, 0x00b8 },
  9025. { 0xfe5c, 0x02db },
  9026. { 0xfe5d, 0x037a },
  9027. { 0xfe5e, 0x309b },
  9028. { 0xfe5f, 0x309c },
  9029. { 0xfe63, '/' },
  9030. { 0xfe64, 0x02bc },
  9031. { 0xfe65, 0x02bd },
  9032. { 0xfe66, 0x02f5 },
  9033. { 0xfe67, 0x02f3 },
  9034. { 0xfe68, 0x02cd },
  9035. { 0xfe69, 0xa788 },
  9036. { 0xfe6a, 0x02f7 },
  9037. { 0xfe6e, ',' },
  9038. { 0xfe6f, 0x00a4 },
  9039. { 0xfe80, 'a' }, /* XK_dead_a */
  9040. { 0xfe81, 'A' }, /* XK_dead_A */
  9041. { 0xfe82, 'e' }, /* XK_dead_e */
  9042. { 0xfe83, 'E' }, /* XK_dead_E */
  9043. { 0xfe84, 'i' }, /* XK_dead_i */
  9044. { 0xfe85, 'I' }, /* XK_dead_I */
  9045. { 0xfe86, 'o' }, /* XK_dead_o */
  9046. { 0xfe87, 'O' }, /* XK_dead_O */
  9047. { 0xfe88, 'u' }, /* XK_dead_u */
  9048. { 0xfe89, 'U' }, /* XK_dead_U */
  9049. { 0xfe8a, 0x0259 },
  9050. { 0xfe8b, 0x018f },
  9051. { 0xfe8c, 0x00b5 },
  9052. { 0xfe90, '_' },
  9053. { 0xfe91, 0x02c8 },
  9054. { 0xfe92, 0x02cc },
  9055. { 0xff80 /*XKB_KEY_KP_Space*/, ' ' },
  9056. { 0xff95 /*XKB_KEY_KP_7*/, 0x0037 },
  9057. { 0xff96 /*XKB_KEY_KP_4*/, 0x0034 },
  9058. { 0xff97 /*XKB_KEY_KP_8*/, 0x0038 },
  9059. { 0xff98 /*XKB_KEY_KP_6*/, 0x0036 },
  9060. { 0xff99 /*XKB_KEY_KP_2*/, 0x0032 },
  9061. { 0xff9a /*XKB_KEY_KP_9*/, 0x0039 },
  9062. { 0xff9b /*XKB_KEY_KP_3*/, 0x0033 },
  9063. { 0xff9c /*XKB_KEY_KP_1*/, 0x0031 },
  9064. { 0xff9d /*XKB_KEY_KP_5*/, 0x0035 },
  9065. { 0xff9e /*XKB_KEY_KP_0*/, 0x0030 },
  9066. { 0xffaa /*XKB_KEY_KP_Multiply*/, '*' },
  9067. { 0xffab /*XKB_KEY_KP_Add*/, '+' },
  9068. { 0xffac /*XKB_KEY_KP_Separator*/, ',' },
  9069. { 0xffad /*XKB_KEY_KP_Subtract*/, '-' },
  9070. { 0xffae /*XKB_KEY_KP_Decimal*/, '.' },
  9071. { 0xffaf /*XKB_KEY_KP_Divide*/, '/' },
  9072. { 0xffb0 /*XKB_KEY_KP_0*/, 0x0030 },
  9073. { 0xffb1 /*XKB_KEY_KP_1*/, 0x0031 },
  9074. { 0xffb2 /*XKB_KEY_KP_2*/, 0x0032 },
  9075. { 0xffb3 /*XKB_KEY_KP_3*/, 0x0033 },
  9076. { 0xffb4 /*XKB_KEY_KP_4*/, 0x0034 },
  9077. { 0xffb5 /*XKB_KEY_KP_5*/, 0x0035 },
  9078. { 0xffb6 /*XKB_KEY_KP_6*/, 0x0036 },
  9079. { 0xffb7 /*XKB_KEY_KP_7*/, 0x0037 },
  9080. { 0xffb8 /*XKB_KEY_KP_8*/, 0x0038 },
  9081. { 0xffb9 /*XKB_KEY_KP_9*/, 0x0039 },
  9082. { 0xffbd /*XKB_KEY_KP_Equal*/, '=' }
  9083. };
  9084. _SOKOL_PRIVATE int _sapp_x11_error_handler(Display* display, XErrorEvent* event) {
  9085. _SOKOL_UNUSED(display);
  9086. _sapp.x11.error_code = event->error_code;
  9087. return 0;
  9088. }
  9089. _SOKOL_PRIVATE void _sapp_x11_grab_error_handler(void) {
  9090. _sapp.x11.error_code = Success;
  9091. XSetErrorHandler(_sapp_x11_error_handler);
  9092. }
  9093. _SOKOL_PRIVATE void _sapp_x11_release_error_handler(void) {
  9094. XSync(_sapp.x11.display, False);
  9095. XSetErrorHandler(NULL);
  9096. }
  9097. _SOKOL_PRIVATE void _sapp_x11_init_extensions(void) {
  9098. _sapp.x11.UTF8_STRING = XInternAtom(_sapp.x11.display, "UTF8_STRING", False);
  9099. _sapp.x11.WM_PROTOCOLS = XInternAtom(_sapp.x11.display, "WM_PROTOCOLS", False);
  9100. _sapp.x11.WM_DELETE_WINDOW = XInternAtom(_sapp.x11.display, "WM_DELETE_WINDOW", False);
  9101. _sapp.x11.WM_STATE = XInternAtom(_sapp.x11.display, "WM_STATE", False);
  9102. _sapp.x11.NET_WM_NAME = XInternAtom(_sapp.x11.display, "_NET_WM_NAME", False);
  9103. _sapp.x11.NET_WM_ICON_NAME = XInternAtom(_sapp.x11.display, "_NET_WM_ICON_NAME", False);
  9104. _sapp.x11.NET_WM_ICON = XInternAtom(_sapp.x11.display, "_NET_WM_ICON", False);
  9105. _sapp.x11.NET_WM_STATE = XInternAtom(_sapp.x11.display, "_NET_WM_STATE", False);
  9106. _sapp.x11.NET_WM_STATE_FULLSCREEN = XInternAtom(_sapp.x11.display, "_NET_WM_STATE_FULLSCREEN", False);
  9107. _sapp.x11.CLIPBOARD = XInternAtom(_sapp.x11.display, "CLIPBOARD", False);
  9108. _sapp.x11.TARGETS = XInternAtom(_sapp.x11.display, "TARGETS", False);
  9109. if (_sapp.drop.enabled) {
  9110. _sapp.x11.xdnd.XdndAware = XInternAtom(_sapp.x11.display, "XdndAware", False);
  9111. _sapp.x11.xdnd.XdndEnter = XInternAtom(_sapp.x11.display, "XdndEnter", False);
  9112. _sapp.x11.xdnd.XdndPosition = XInternAtom(_sapp.x11.display, "XdndPosition", False);
  9113. _sapp.x11.xdnd.XdndStatus = XInternAtom(_sapp.x11.display, "XdndStatus", False);
  9114. _sapp.x11.xdnd.XdndActionCopy = XInternAtom(_sapp.x11.display, "XdndActionCopy", False);
  9115. _sapp.x11.xdnd.XdndDrop = XInternAtom(_sapp.x11.display, "XdndDrop", False);
  9116. _sapp.x11.xdnd.XdndFinished = XInternAtom(_sapp.x11.display, "XdndFinished", False);
  9117. _sapp.x11.xdnd.XdndSelection = XInternAtom(_sapp.x11.display, "XdndSelection", False);
  9118. _sapp.x11.xdnd.XdndTypeList = XInternAtom(_sapp.x11.display, "XdndTypeList", False);
  9119. _sapp.x11.xdnd.text_uri_list = XInternAtom(_sapp.x11.display, "text/uri-list", False);
  9120. }
  9121. /* check Xi extension for raw mouse input */
  9122. if (XQueryExtension(_sapp.x11.display, "XInputExtension", &_sapp.x11.xi.major_opcode, &_sapp.x11.xi.event_base, &_sapp.x11.xi.error_base)) {
  9123. _sapp.x11.xi.major = 2;
  9124. _sapp.x11.xi.minor = 0;
  9125. if (XIQueryVersion(_sapp.x11.display, &_sapp.x11.xi.major, &_sapp.x11.xi.minor) == Success) {
  9126. _sapp.x11.xi.available = true;
  9127. }
  9128. }
  9129. }
  9130. // translate the X11 KeySyms for a key to sokol-app key code
  9131. // NOTE: this is only used as a fallback, in case the XBK method fails
  9132. // it is layout-dependent and will fail partially on most non-US layouts.
  9133. //
  9134. _SOKOL_PRIVATE sapp_keycode _sapp_x11_translate_keysyms(const KeySym* keysyms, int width) {
  9135. if (width > 1) {
  9136. switch (keysyms[1]) {
  9137. case XK_KP_0: return SAPP_KEYCODE_KP_0;
  9138. case XK_KP_1: return SAPP_KEYCODE_KP_1;
  9139. case XK_KP_2: return SAPP_KEYCODE_KP_2;
  9140. case XK_KP_3: return SAPP_KEYCODE_KP_3;
  9141. case XK_KP_4: return SAPP_KEYCODE_KP_4;
  9142. case XK_KP_5: return SAPP_KEYCODE_KP_5;
  9143. case XK_KP_6: return SAPP_KEYCODE_KP_6;
  9144. case XK_KP_7: return SAPP_KEYCODE_KP_7;
  9145. case XK_KP_8: return SAPP_KEYCODE_KP_8;
  9146. case XK_KP_9: return SAPP_KEYCODE_KP_9;
  9147. case XK_KP_Separator:
  9148. case XK_KP_Decimal: return SAPP_KEYCODE_KP_DECIMAL;
  9149. case XK_KP_Equal: return SAPP_KEYCODE_KP_EQUAL;
  9150. case XK_KP_Enter: return SAPP_KEYCODE_KP_ENTER;
  9151. default: break;
  9152. }
  9153. }
  9154. switch (keysyms[0]) {
  9155. case XK_Escape: return SAPP_KEYCODE_ESCAPE;
  9156. case XK_Tab: return SAPP_KEYCODE_TAB;
  9157. case XK_Shift_L: return SAPP_KEYCODE_LEFT_SHIFT;
  9158. case XK_Shift_R: return SAPP_KEYCODE_RIGHT_SHIFT;
  9159. case XK_Control_L: return SAPP_KEYCODE_LEFT_CONTROL;
  9160. case XK_Control_R: return SAPP_KEYCODE_RIGHT_CONTROL;
  9161. case XK_Meta_L:
  9162. case XK_Alt_L: return SAPP_KEYCODE_LEFT_ALT;
  9163. case XK_Mode_switch: // Mapped to Alt_R on many keyboards
  9164. case XK_ISO_Level3_Shift: // AltGr on at least some machines
  9165. case XK_Meta_R:
  9166. case XK_Alt_R: return SAPP_KEYCODE_RIGHT_ALT;
  9167. case XK_Super_L: return SAPP_KEYCODE_LEFT_SUPER;
  9168. case XK_Super_R: return SAPP_KEYCODE_RIGHT_SUPER;
  9169. case XK_Menu: return SAPP_KEYCODE_MENU;
  9170. case XK_Num_Lock: return SAPP_KEYCODE_NUM_LOCK;
  9171. case XK_Caps_Lock: return SAPP_KEYCODE_CAPS_LOCK;
  9172. case XK_Print: return SAPP_KEYCODE_PRINT_SCREEN;
  9173. case XK_Scroll_Lock: return SAPP_KEYCODE_SCROLL_LOCK;
  9174. case XK_Pause: return SAPP_KEYCODE_PAUSE;
  9175. case XK_Delete: return SAPP_KEYCODE_DELETE;
  9176. case XK_BackSpace: return SAPP_KEYCODE_BACKSPACE;
  9177. case XK_Return: return SAPP_KEYCODE_ENTER;
  9178. case XK_Home: return SAPP_KEYCODE_HOME;
  9179. case XK_End: return SAPP_KEYCODE_END;
  9180. case XK_Page_Up: return SAPP_KEYCODE_PAGE_UP;
  9181. case XK_Page_Down: return SAPP_KEYCODE_PAGE_DOWN;
  9182. case XK_Insert: return SAPP_KEYCODE_INSERT;
  9183. case XK_Left: return SAPP_KEYCODE_LEFT;
  9184. case XK_Right: return SAPP_KEYCODE_RIGHT;
  9185. case XK_Down: return SAPP_KEYCODE_DOWN;
  9186. case XK_Up: return SAPP_KEYCODE_UP;
  9187. case XK_F1: return SAPP_KEYCODE_F1;
  9188. case XK_F2: return SAPP_KEYCODE_F2;
  9189. case XK_F3: return SAPP_KEYCODE_F3;
  9190. case XK_F4: return SAPP_KEYCODE_F4;
  9191. case XK_F5: return SAPP_KEYCODE_F5;
  9192. case XK_F6: return SAPP_KEYCODE_F6;
  9193. case XK_F7: return SAPP_KEYCODE_F7;
  9194. case XK_F8: return SAPP_KEYCODE_F8;
  9195. case XK_F9: return SAPP_KEYCODE_F9;
  9196. case XK_F10: return SAPP_KEYCODE_F10;
  9197. case XK_F11: return SAPP_KEYCODE_F11;
  9198. case XK_F12: return SAPP_KEYCODE_F12;
  9199. case XK_F13: return SAPP_KEYCODE_F13;
  9200. case XK_F14: return SAPP_KEYCODE_F14;
  9201. case XK_F15: return SAPP_KEYCODE_F15;
  9202. case XK_F16: return SAPP_KEYCODE_F16;
  9203. case XK_F17: return SAPP_KEYCODE_F17;
  9204. case XK_F18: return SAPP_KEYCODE_F18;
  9205. case XK_F19: return SAPP_KEYCODE_F19;
  9206. case XK_F20: return SAPP_KEYCODE_F20;
  9207. case XK_F21: return SAPP_KEYCODE_F21;
  9208. case XK_F22: return SAPP_KEYCODE_F22;
  9209. case XK_F23: return SAPP_KEYCODE_F23;
  9210. case XK_F24: return SAPP_KEYCODE_F24;
  9211. case XK_F25: return SAPP_KEYCODE_F25;
  9212. // numeric keypad
  9213. case XK_KP_Divide: return SAPP_KEYCODE_KP_DIVIDE;
  9214. case XK_KP_Multiply: return SAPP_KEYCODE_KP_MULTIPLY;
  9215. case XK_KP_Subtract: return SAPP_KEYCODE_KP_SUBTRACT;
  9216. case XK_KP_Add: return SAPP_KEYCODE_KP_ADD;
  9217. // these should have been detected in secondary keysym test above!
  9218. case XK_KP_Insert: return SAPP_KEYCODE_KP_0;
  9219. case XK_KP_End: return SAPP_KEYCODE_KP_1;
  9220. case XK_KP_Down: return SAPP_KEYCODE_KP_2;
  9221. case XK_KP_Page_Down: return SAPP_KEYCODE_KP_3;
  9222. case XK_KP_Left: return SAPP_KEYCODE_KP_4;
  9223. case XK_KP_Right: return SAPP_KEYCODE_KP_6;
  9224. case XK_KP_Home: return SAPP_KEYCODE_KP_7;
  9225. case XK_KP_Up: return SAPP_KEYCODE_KP_8;
  9226. case XK_KP_Page_Up: return SAPP_KEYCODE_KP_9;
  9227. case XK_KP_Delete: return SAPP_KEYCODE_KP_DECIMAL;
  9228. case XK_KP_Equal: return SAPP_KEYCODE_KP_EQUAL;
  9229. case XK_KP_Enter: return SAPP_KEYCODE_KP_ENTER;
  9230. // last resort: Check for printable keys (should not happen if the XKB
  9231. // extension is available). This will give a layout dependent mapping
  9232. // (which is wrong, and we may miss some keys, especially on non-US
  9233. // keyboards), but it's better than nothing...
  9234. case XK_a: return SAPP_KEYCODE_A;
  9235. case XK_b: return SAPP_KEYCODE_B;
  9236. case XK_c: return SAPP_KEYCODE_C;
  9237. case XK_d: return SAPP_KEYCODE_D;
  9238. case XK_e: return SAPP_KEYCODE_E;
  9239. case XK_f: return SAPP_KEYCODE_F;
  9240. case XK_g: return SAPP_KEYCODE_G;
  9241. case XK_h: return SAPP_KEYCODE_H;
  9242. case XK_i: return SAPP_KEYCODE_I;
  9243. case XK_j: return SAPP_KEYCODE_J;
  9244. case XK_k: return SAPP_KEYCODE_K;
  9245. case XK_l: return SAPP_KEYCODE_L;
  9246. case XK_m: return SAPP_KEYCODE_M;
  9247. case XK_n: return SAPP_KEYCODE_N;
  9248. case XK_o: return SAPP_KEYCODE_O;
  9249. case XK_p: return SAPP_KEYCODE_P;
  9250. case XK_q: return SAPP_KEYCODE_Q;
  9251. case XK_r: return SAPP_KEYCODE_R;
  9252. case XK_s: return SAPP_KEYCODE_S;
  9253. case XK_t: return SAPP_KEYCODE_T;
  9254. case XK_u: return SAPP_KEYCODE_U;
  9255. case XK_v: return SAPP_KEYCODE_V;
  9256. case XK_w: return SAPP_KEYCODE_W;
  9257. case XK_x: return SAPP_KEYCODE_X;
  9258. case XK_y: return SAPP_KEYCODE_Y;
  9259. case XK_z: return SAPP_KEYCODE_Z;
  9260. case XK_1: return SAPP_KEYCODE_1;
  9261. case XK_2: return SAPP_KEYCODE_2;
  9262. case XK_3: return SAPP_KEYCODE_3;
  9263. case XK_4: return SAPP_KEYCODE_4;
  9264. case XK_5: return SAPP_KEYCODE_5;
  9265. case XK_6: return SAPP_KEYCODE_6;
  9266. case XK_7: return SAPP_KEYCODE_7;
  9267. case XK_8: return SAPP_KEYCODE_8;
  9268. case XK_9: return SAPP_KEYCODE_9;
  9269. case XK_0: return SAPP_KEYCODE_0;
  9270. case XK_space: return SAPP_KEYCODE_SPACE;
  9271. case XK_minus: return SAPP_KEYCODE_MINUS;
  9272. case XK_equal: return SAPP_KEYCODE_EQUAL;
  9273. case XK_bracketleft: return SAPP_KEYCODE_LEFT_BRACKET;
  9274. case XK_bracketright: return SAPP_KEYCODE_RIGHT_BRACKET;
  9275. case XK_backslash: return SAPP_KEYCODE_BACKSLASH;
  9276. case XK_semicolon: return SAPP_KEYCODE_SEMICOLON;
  9277. case XK_apostrophe: return SAPP_KEYCODE_APOSTROPHE;
  9278. case XK_grave: return SAPP_KEYCODE_GRAVE_ACCENT;
  9279. case XK_comma: return SAPP_KEYCODE_COMMA;
  9280. case XK_period: return SAPP_KEYCODE_PERIOD;
  9281. case XK_slash: return SAPP_KEYCODE_SLASH;
  9282. case XK_less: return SAPP_KEYCODE_WORLD_1; // At least in some layouts...
  9283. default: break;
  9284. }
  9285. // no matching translation was found
  9286. return SAPP_KEYCODE_INVALID;
  9287. }
  9288. // setup dynamic keycode/scancode mapping tables, this is required
  9289. // for getting layout-independent keycodes on X11.
  9290. //
  9291. // see GLFW x11_init.c/createKeyTables()
  9292. _SOKOL_PRIVATE void _sapp_x11_init_keytable(void) {
  9293. for (int i = 0; i < SAPP_MAX_KEYCODES; i++) {
  9294. _sapp.keycodes[i] = SAPP_KEYCODE_INVALID;
  9295. }
  9296. // use XKB to determine physical key locations independently of the current keyboard layout
  9297. XkbDescPtr desc = XkbGetMap(_sapp.x11.display, 0, XkbUseCoreKbd);
  9298. SOKOL_ASSERT(desc);
  9299. XkbGetNames(_sapp.x11.display, XkbKeyNamesMask | XkbKeyAliasesMask, desc);
  9300. const int scancode_min = desc->min_key_code;
  9301. const int scancode_max = desc->max_key_code;
  9302. const struct { sapp_keycode key; const char* name; } keymap[] = {
  9303. { SAPP_KEYCODE_GRAVE_ACCENT, "TLDE" },
  9304. { SAPP_KEYCODE_1, "AE01" },
  9305. { SAPP_KEYCODE_2, "AE02" },
  9306. { SAPP_KEYCODE_3, "AE03" },
  9307. { SAPP_KEYCODE_4, "AE04" },
  9308. { SAPP_KEYCODE_5, "AE05" },
  9309. { SAPP_KEYCODE_6, "AE06" },
  9310. { SAPP_KEYCODE_7, "AE07" },
  9311. { SAPP_KEYCODE_8, "AE08" },
  9312. { SAPP_KEYCODE_9, "AE09" },
  9313. { SAPP_KEYCODE_0, "AE10" },
  9314. { SAPP_KEYCODE_MINUS, "AE11" },
  9315. { SAPP_KEYCODE_EQUAL, "AE12" },
  9316. { SAPP_KEYCODE_Q, "AD01" },
  9317. { SAPP_KEYCODE_W, "AD02" },
  9318. { SAPP_KEYCODE_E, "AD03" },
  9319. { SAPP_KEYCODE_R, "AD04" },
  9320. { SAPP_KEYCODE_T, "AD05" },
  9321. { SAPP_KEYCODE_Y, "AD06" },
  9322. { SAPP_KEYCODE_U, "AD07" },
  9323. { SAPP_KEYCODE_I, "AD08" },
  9324. { SAPP_KEYCODE_O, "AD09" },
  9325. { SAPP_KEYCODE_P, "AD10" },
  9326. { SAPP_KEYCODE_LEFT_BRACKET, "AD11" },
  9327. { SAPP_KEYCODE_RIGHT_BRACKET, "AD12" },
  9328. { SAPP_KEYCODE_A, "AC01" },
  9329. { SAPP_KEYCODE_S, "AC02" },
  9330. { SAPP_KEYCODE_D, "AC03" },
  9331. { SAPP_KEYCODE_F, "AC04" },
  9332. { SAPP_KEYCODE_G, "AC05" },
  9333. { SAPP_KEYCODE_H, "AC06" },
  9334. { SAPP_KEYCODE_J, "AC07" },
  9335. { SAPP_KEYCODE_K, "AC08" },
  9336. { SAPP_KEYCODE_L, "AC09" },
  9337. { SAPP_KEYCODE_SEMICOLON, "AC10" },
  9338. { SAPP_KEYCODE_APOSTROPHE, "AC11" },
  9339. { SAPP_KEYCODE_Z, "AB01" },
  9340. { SAPP_KEYCODE_X, "AB02" },
  9341. { SAPP_KEYCODE_C, "AB03" },
  9342. { SAPP_KEYCODE_V, "AB04" },
  9343. { SAPP_KEYCODE_B, "AB05" },
  9344. { SAPP_KEYCODE_N, "AB06" },
  9345. { SAPP_KEYCODE_M, "AB07" },
  9346. { SAPP_KEYCODE_COMMA, "AB08" },
  9347. { SAPP_KEYCODE_PERIOD, "AB09" },
  9348. { SAPP_KEYCODE_SLASH, "AB10" },
  9349. { SAPP_KEYCODE_BACKSLASH, "BKSL" },
  9350. { SAPP_KEYCODE_WORLD_1, "LSGT" },
  9351. { SAPP_KEYCODE_SPACE, "SPCE" },
  9352. { SAPP_KEYCODE_ESCAPE, "ESC" },
  9353. { SAPP_KEYCODE_ENTER, "RTRN" },
  9354. { SAPP_KEYCODE_TAB, "TAB" },
  9355. { SAPP_KEYCODE_BACKSPACE, "BKSP" },
  9356. { SAPP_KEYCODE_INSERT, "INS" },
  9357. { SAPP_KEYCODE_DELETE, "DELE" },
  9358. { SAPP_KEYCODE_RIGHT, "RGHT" },
  9359. { SAPP_KEYCODE_LEFT, "LEFT" },
  9360. { SAPP_KEYCODE_DOWN, "DOWN" },
  9361. { SAPP_KEYCODE_UP, "UP" },
  9362. { SAPP_KEYCODE_PAGE_UP, "PGUP" },
  9363. { SAPP_KEYCODE_PAGE_DOWN, "PGDN" },
  9364. { SAPP_KEYCODE_HOME, "HOME" },
  9365. { SAPP_KEYCODE_END, "END" },
  9366. { SAPP_KEYCODE_CAPS_LOCK, "CAPS" },
  9367. { SAPP_KEYCODE_SCROLL_LOCK, "SCLK" },
  9368. { SAPP_KEYCODE_NUM_LOCK, "NMLK" },
  9369. { SAPP_KEYCODE_PRINT_SCREEN, "PRSC" },
  9370. { SAPP_KEYCODE_PAUSE, "PAUS" },
  9371. { SAPP_KEYCODE_F1, "FK01" },
  9372. { SAPP_KEYCODE_F2, "FK02" },
  9373. { SAPP_KEYCODE_F3, "FK03" },
  9374. { SAPP_KEYCODE_F4, "FK04" },
  9375. { SAPP_KEYCODE_F5, "FK05" },
  9376. { SAPP_KEYCODE_F6, "FK06" },
  9377. { SAPP_KEYCODE_F7, "FK07" },
  9378. { SAPP_KEYCODE_F8, "FK08" },
  9379. { SAPP_KEYCODE_F9, "FK09" },
  9380. { SAPP_KEYCODE_F10, "FK10" },
  9381. { SAPP_KEYCODE_F11, "FK11" },
  9382. { SAPP_KEYCODE_F12, "FK12" },
  9383. { SAPP_KEYCODE_F13, "FK13" },
  9384. { SAPP_KEYCODE_F14, "FK14" },
  9385. { SAPP_KEYCODE_F15, "FK15" },
  9386. { SAPP_KEYCODE_F16, "FK16" },
  9387. { SAPP_KEYCODE_F17, "FK17" },
  9388. { SAPP_KEYCODE_F18, "FK18" },
  9389. { SAPP_KEYCODE_F19, "FK19" },
  9390. { SAPP_KEYCODE_F20, "FK20" },
  9391. { SAPP_KEYCODE_F21, "FK21" },
  9392. { SAPP_KEYCODE_F22, "FK22" },
  9393. { SAPP_KEYCODE_F23, "FK23" },
  9394. { SAPP_KEYCODE_F24, "FK24" },
  9395. { SAPP_KEYCODE_F25, "FK25" },
  9396. { SAPP_KEYCODE_KP_0, "KP0" },
  9397. { SAPP_KEYCODE_KP_1, "KP1" },
  9398. { SAPP_KEYCODE_KP_2, "KP2" },
  9399. { SAPP_KEYCODE_KP_3, "KP3" },
  9400. { SAPP_KEYCODE_KP_4, "KP4" },
  9401. { SAPP_KEYCODE_KP_5, "KP5" },
  9402. { SAPP_KEYCODE_KP_6, "KP6" },
  9403. { SAPP_KEYCODE_KP_7, "KP7" },
  9404. { SAPP_KEYCODE_KP_8, "KP8" },
  9405. { SAPP_KEYCODE_KP_9, "KP9" },
  9406. { SAPP_KEYCODE_KP_DECIMAL, "KPDL" },
  9407. { SAPP_KEYCODE_KP_DIVIDE, "KPDV" },
  9408. { SAPP_KEYCODE_KP_MULTIPLY, "KPMU" },
  9409. { SAPP_KEYCODE_KP_SUBTRACT, "KPSU" },
  9410. { SAPP_KEYCODE_KP_ADD, "KPAD" },
  9411. { SAPP_KEYCODE_KP_ENTER, "KPEN" },
  9412. { SAPP_KEYCODE_KP_EQUAL, "KPEQ" },
  9413. { SAPP_KEYCODE_LEFT_SHIFT, "LFSH" },
  9414. { SAPP_KEYCODE_LEFT_CONTROL, "LCTL" },
  9415. { SAPP_KEYCODE_LEFT_ALT, "LALT" },
  9416. { SAPP_KEYCODE_LEFT_SUPER, "LWIN" },
  9417. { SAPP_KEYCODE_RIGHT_SHIFT, "RTSH" },
  9418. { SAPP_KEYCODE_RIGHT_CONTROL, "RCTL" },
  9419. { SAPP_KEYCODE_RIGHT_ALT, "RALT" },
  9420. { SAPP_KEYCODE_RIGHT_ALT, "LVL3" },
  9421. { SAPP_KEYCODE_RIGHT_ALT, "MDSW" },
  9422. { SAPP_KEYCODE_RIGHT_SUPER, "RWIN" },
  9423. { SAPP_KEYCODE_MENU, "MENU" }
  9424. };
  9425. const int num_keymap_items = (int)(sizeof(keymap) / sizeof(keymap[0]));
  9426. // find X11 keycode to sokol-app key code mapping
  9427. for (int scancode = scancode_min; scancode <= scancode_max; scancode++) {
  9428. sapp_keycode key = SAPP_KEYCODE_INVALID;
  9429. for (int i = 0; i < num_keymap_items; i++) {
  9430. if (strncmp(desc->names->keys[scancode].name, keymap[i].name, XkbKeyNameLength) == 0) {
  9431. key = keymap[i].key;
  9432. break;
  9433. }
  9434. }
  9435. // fall back to key aliases in case the key name did not match
  9436. for (int i = 0; i < desc->names->num_key_aliases; i++) {
  9437. if (key != SAPP_KEYCODE_INVALID) {
  9438. break;
  9439. }
  9440. if (strncmp(desc->names->key_aliases[i].real, desc->names->keys[scancode].name, XkbKeyNameLength) != 0) {
  9441. continue;
  9442. }
  9443. for (int j = 0; j < num_keymap_items; j++) {
  9444. if (strncmp(desc->names->key_aliases[i].alias, keymap[i].name, XkbKeyNameLength) == 0) {
  9445. key = keymap[i].key;
  9446. break;
  9447. }
  9448. }
  9449. }
  9450. _sapp.keycodes[scancode] = key;
  9451. }
  9452. XkbFreeNames(desc, XkbKeyNamesMask, True);
  9453. XkbFreeKeyboard(desc, 0, True);
  9454. int width = 0;
  9455. KeySym* keysyms = XGetKeyboardMapping(_sapp.x11.display, scancode_min, scancode_max - scancode_min + 1, &width);
  9456. for (int scancode = scancode_min; scancode <= scancode_max; scancode++) {
  9457. // translate untranslated key codes using the traditional X11 KeySym lookups
  9458. if (_sapp.keycodes[scancode] == SAPP_KEYCODE_INVALID) {
  9459. const size_t base = (size_t)((scancode - scancode_min) * width);
  9460. _sapp.keycodes[scancode] = _sapp_x11_translate_keysyms(&keysyms[base], width);
  9461. }
  9462. }
  9463. XFree(keysyms);
  9464. }
  9465. _SOKOL_PRIVATE void _sapp_x11_query_system_dpi(void) {
  9466. /* from GLFW:
  9467. NOTE: Default to the display-wide DPI as we don't currently have a policy
  9468. for which monitor a window is considered to be on
  9469. _sapp.x11.dpi = DisplayWidth(_sapp.x11.display, _sapp.x11.screen) *
  9470. 25.4f / DisplayWidthMM(_sapp.x11.display, _sapp.x11.screen);
  9471. NOTE: Basing the scale on Xft.dpi where available should provide the most
  9472. consistent user experience (matches Qt, Gtk, etc), although not
  9473. always the most accurate one
  9474. */
  9475. bool dpi_ok = false;
  9476. char* rms = XResourceManagerString(_sapp.x11.display);
  9477. if (rms) {
  9478. XrmDatabase db = XrmGetStringDatabase(rms);
  9479. if (db) {
  9480. XrmValue value;
  9481. char* type = NULL;
  9482. if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value)) {
  9483. if (type && strcmp(type, "String") == 0) {
  9484. _sapp.x11.dpi = atof(value.addr);
  9485. dpi_ok = true;
  9486. }
  9487. }
  9488. XrmDestroyDatabase(db);
  9489. }
  9490. }
  9491. // fallback if querying DPI had failed: assume the standard DPI 96.0f
  9492. if (!dpi_ok) {
  9493. _sapp.x11.dpi = 96.0f;
  9494. _SAPP_WARN(LINUX_X11_QUERY_SYSTEM_DPI_FAILED);
  9495. }
  9496. }
  9497. #if defined(_SAPP_GLX)
  9498. _SOKOL_PRIVATE bool _sapp_glx_has_ext(const char* ext, const char* extensions) {
  9499. SOKOL_ASSERT(ext);
  9500. const char* start = extensions;
  9501. while (true) {
  9502. const char* where = strstr(start, ext);
  9503. if (!where) {
  9504. return false;
  9505. }
  9506. const char* terminator = where + strlen(ext);
  9507. if ((where == start) || (*(where - 1) == ' ')) {
  9508. if (*terminator == ' ' || *terminator == '\0') {
  9509. break;
  9510. }
  9511. }
  9512. start = terminator;
  9513. }
  9514. return true;
  9515. }
  9516. _SOKOL_PRIVATE bool _sapp_glx_extsupported(const char* ext, const char* extensions) {
  9517. if (extensions) {
  9518. return _sapp_glx_has_ext(ext, extensions);
  9519. }
  9520. else {
  9521. return false;
  9522. }
  9523. }
  9524. _SOKOL_PRIVATE void* _sapp_glx_getprocaddr(const char* procname)
  9525. {
  9526. if (_sapp.glx.GetProcAddress) {
  9527. return (void*) _sapp.glx.GetProcAddress(procname);
  9528. }
  9529. else if (_sapp.glx.GetProcAddressARB) {
  9530. return (void*) _sapp.glx.GetProcAddressARB(procname);
  9531. }
  9532. else {
  9533. return dlsym(_sapp.glx.libgl, procname);
  9534. }
  9535. }
  9536. _SOKOL_PRIVATE void _sapp_glx_init(void) {
  9537. const char* sonames[] = { "libGL.so.1", "libGL.so", 0 };
  9538. for (int i = 0; sonames[i]; i++) {
  9539. _sapp.glx.libgl = dlopen(sonames[i], RTLD_LAZY|RTLD_GLOBAL);
  9540. if (_sapp.glx.libgl) {
  9541. break;
  9542. }
  9543. }
  9544. if (!_sapp.glx.libgl) {
  9545. _SAPP_PANIC(LINUX_GLX_LOAD_LIBGL_FAILED);
  9546. }
  9547. _sapp.glx.GetFBConfigs = (PFNGLXGETFBCONFIGSPROC) dlsym(_sapp.glx.libgl, "glXGetFBConfigs");
  9548. _sapp.glx.GetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) dlsym(_sapp.glx.libgl, "glXGetFBConfigAttrib");
  9549. _sapp.glx.GetClientString = (PFNGLXGETCLIENTSTRINGPROC) dlsym(_sapp.glx.libgl, "glXGetClientString");
  9550. _sapp.glx.QueryExtension = (PFNGLXQUERYEXTENSIONPROC) dlsym(_sapp.glx.libgl, "glXQueryExtension");
  9551. _sapp.glx.QueryVersion = (PFNGLXQUERYVERSIONPROC) dlsym(_sapp.glx.libgl, "glXQueryVersion");
  9552. _sapp.glx.DestroyContext = (PFNGLXDESTROYCONTEXTPROC) dlsym(_sapp.glx.libgl, "glXDestroyContext");
  9553. _sapp.glx.MakeCurrent = (PFNGLXMAKECURRENTPROC) dlsym(_sapp.glx.libgl, "glXMakeCurrent");
  9554. _sapp.glx.SwapBuffers = (PFNGLXSWAPBUFFERSPROC) dlsym(_sapp.glx.libgl, "glXSwapBuffers");
  9555. _sapp.glx.QueryExtensionsString = (PFNGLXQUERYEXTENSIONSSTRINGPROC) dlsym(_sapp.glx.libgl, "glXQueryExtensionsString");
  9556. _sapp.glx.CreateWindow = (PFNGLXCREATEWINDOWPROC) dlsym(_sapp.glx.libgl, "glXCreateWindow");
  9557. _sapp.glx.DestroyWindow = (PFNGLXDESTROYWINDOWPROC) dlsym(_sapp.glx.libgl, "glXDestroyWindow");
  9558. _sapp.glx.GetProcAddress = (PFNGLXGETPROCADDRESSPROC) dlsym(_sapp.glx.libgl, "glXGetProcAddress");
  9559. _sapp.glx.GetProcAddressARB = (PFNGLXGETPROCADDRESSPROC) dlsym(_sapp.glx.libgl, "glXGetProcAddressARB");
  9560. _sapp.glx.GetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) dlsym(_sapp.glx.libgl, "glXGetVisualFromFBConfig");
  9561. if (!_sapp.glx.GetFBConfigs ||
  9562. !_sapp.glx.GetFBConfigAttrib ||
  9563. !_sapp.glx.GetClientString ||
  9564. !_sapp.glx.QueryExtension ||
  9565. !_sapp.glx.QueryVersion ||
  9566. !_sapp.glx.DestroyContext ||
  9567. !_sapp.glx.MakeCurrent ||
  9568. !_sapp.glx.SwapBuffers ||
  9569. !_sapp.glx.QueryExtensionsString ||
  9570. !_sapp.glx.CreateWindow ||
  9571. !_sapp.glx.DestroyWindow ||
  9572. !_sapp.glx.GetProcAddress ||
  9573. !_sapp.glx.GetProcAddressARB ||
  9574. !_sapp.glx.GetVisualFromFBConfig)
  9575. {
  9576. _SAPP_PANIC(LINUX_GLX_LOAD_ENTRY_POINTS_FAILED);
  9577. }
  9578. if (!_sapp.glx.QueryExtension(_sapp.x11.display, &_sapp.glx.error_base, &_sapp.glx.event_base)) {
  9579. _SAPP_PANIC(LINUX_GLX_EXTENSION_NOT_FOUND);
  9580. }
  9581. if (!_sapp.glx.QueryVersion(_sapp.x11.display, &_sapp.glx.major, &_sapp.glx.minor)) {
  9582. _SAPP_PANIC(LINUX_GLX_QUERY_VERSION_FAILED);
  9583. }
  9584. if (_sapp.glx.major == 1 && _sapp.glx.minor < 3) {
  9585. _SAPP_PANIC(LINUX_GLX_VERSION_TOO_LOW);
  9586. }
  9587. const char* exts = _sapp.glx.QueryExtensionsString(_sapp.x11.display, _sapp.x11.screen);
  9588. if (_sapp_glx_extsupported("GLX_EXT_swap_control", exts)) {
  9589. _sapp.glx.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) _sapp_glx_getprocaddr("glXSwapIntervalEXT");
  9590. _sapp.glx.EXT_swap_control = 0 != _sapp.glx.SwapIntervalEXT;
  9591. }
  9592. if (_sapp_glx_extsupported("GLX_MESA_swap_control", exts)) {
  9593. _sapp.glx.SwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC) _sapp_glx_getprocaddr("glXSwapIntervalMESA");
  9594. _sapp.glx.MESA_swap_control = 0 != _sapp.glx.SwapIntervalMESA;
  9595. }
  9596. _sapp.glx.ARB_multisample = _sapp_glx_extsupported("GLX_ARB_multisample", exts);
  9597. if (_sapp_glx_extsupported("GLX_ARB_create_context", exts)) {
  9598. _sapp.glx.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) _sapp_glx_getprocaddr("glXCreateContextAttribsARB");
  9599. _sapp.glx.ARB_create_context = 0 != _sapp.glx.CreateContextAttribsARB;
  9600. }
  9601. _sapp.glx.ARB_create_context_profile = _sapp_glx_extsupported("GLX_ARB_create_context_profile", exts);
  9602. }
  9603. _SOKOL_PRIVATE int _sapp_glx_attrib(GLXFBConfig fbconfig, int attrib) {
  9604. int value;
  9605. _sapp.glx.GetFBConfigAttrib(_sapp.x11.display, fbconfig, attrib, &value);
  9606. return value;
  9607. }
  9608. _SOKOL_PRIVATE GLXFBConfig _sapp_glx_choosefbconfig(void) {
  9609. GLXFBConfig* native_configs;
  9610. _sapp_gl_fbconfig* usable_configs;
  9611. const _sapp_gl_fbconfig* closest;
  9612. int i, native_count, usable_count;
  9613. const char* vendor;
  9614. bool trust_window_bit = true;
  9615. /* HACK: This is a (hopefully temporary) workaround for Chromium
  9616. (VirtualBox GL) not setting the window bit on any GLXFBConfigs
  9617. */
  9618. vendor = _sapp.glx.GetClientString(_sapp.x11.display, GLX_VENDOR);
  9619. if (vendor && strcmp(vendor, "Chromium") == 0) {
  9620. trust_window_bit = false;
  9621. }
  9622. native_configs = _sapp.glx.GetFBConfigs(_sapp.x11.display, _sapp.x11.screen, &native_count);
  9623. if (!native_configs || !native_count) {
  9624. _SAPP_PANIC(LINUX_GLX_NO_GLXFBCONFIGS);
  9625. }
  9626. usable_configs = (_sapp_gl_fbconfig*) _sapp_malloc_clear((size_t)native_count * sizeof(_sapp_gl_fbconfig));
  9627. usable_count = 0;
  9628. for (i = 0; i < native_count; i++) {
  9629. const GLXFBConfig n = native_configs[i];
  9630. _sapp_gl_fbconfig* u = usable_configs + usable_count;
  9631. _sapp_gl_init_fbconfig(u);
  9632. /* Only consider RGBA GLXFBConfigs */
  9633. if (0 == (_sapp_glx_attrib(n, GLX_RENDER_TYPE) & GLX_RGBA_BIT)) {
  9634. continue;
  9635. }
  9636. /* Only consider window GLXFBConfigs */
  9637. if (0 == (_sapp_glx_attrib(n, GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT)) {
  9638. if (trust_window_bit) {
  9639. continue;
  9640. }
  9641. }
  9642. u->red_bits = _sapp_glx_attrib(n, GLX_RED_SIZE);
  9643. u->green_bits = _sapp_glx_attrib(n, GLX_GREEN_SIZE);
  9644. u->blue_bits = _sapp_glx_attrib(n, GLX_BLUE_SIZE);
  9645. u->alpha_bits = _sapp_glx_attrib(n, GLX_ALPHA_SIZE);
  9646. u->depth_bits = _sapp_glx_attrib(n, GLX_DEPTH_SIZE);
  9647. u->stencil_bits = _sapp_glx_attrib(n, GLX_STENCIL_SIZE);
  9648. if (_sapp_glx_attrib(n, GLX_DOUBLEBUFFER)) {
  9649. u->doublebuffer = true;
  9650. }
  9651. if (_sapp.glx.ARB_multisample) {
  9652. u->samples = _sapp_glx_attrib(n, GLX_SAMPLES);
  9653. }
  9654. u->handle = (uintptr_t) n;
  9655. usable_count++;
  9656. }
  9657. _sapp_gl_fbconfig desired;
  9658. _sapp_gl_init_fbconfig(&desired);
  9659. desired.red_bits = 8;
  9660. desired.green_bits = 8;
  9661. desired.blue_bits = 8;
  9662. desired.alpha_bits = 8;
  9663. desired.depth_bits = 24;
  9664. desired.stencil_bits = 8;
  9665. desired.doublebuffer = true;
  9666. desired.samples = _sapp.sample_count > 1 ? _sapp.sample_count : 0;
  9667. closest = _sapp_gl_choose_fbconfig(&desired, usable_configs, usable_count);
  9668. GLXFBConfig result = 0;
  9669. if (closest) {
  9670. result = (GLXFBConfig) closest->handle;
  9671. }
  9672. XFree(native_configs);
  9673. _sapp_free(usable_configs);
  9674. return result;
  9675. }
  9676. _SOKOL_PRIVATE void _sapp_glx_choose_visual(Visual** visual, int* depth) {
  9677. GLXFBConfig native = _sapp_glx_choosefbconfig();
  9678. if (0 == native) {
  9679. _SAPP_PANIC(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG);
  9680. }
  9681. XVisualInfo* result = _sapp.glx.GetVisualFromFBConfig(_sapp.x11.display, native);
  9682. if (!result) {
  9683. _SAPP_PANIC(LINUX_GLX_GET_VISUAL_FROM_FBCONFIG_FAILED);
  9684. }
  9685. *visual = result->visual;
  9686. *depth = result->depth;
  9687. XFree(result);
  9688. }
  9689. _SOKOL_PRIVATE void _sapp_glx_make_current(void) {
  9690. _sapp.glx.MakeCurrent(_sapp.x11.display, _sapp.glx.window, _sapp.glx.ctx);
  9691. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  9692. }
  9693. _SOKOL_PRIVATE void _sapp_glx_create_context(void) {
  9694. GLXFBConfig native = _sapp_glx_choosefbconfig();
  9695. if (0 == native){
  9696. _SAPP_PANIC(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG);
  9697. }
  9698. if (!(_sapp.glx.ARB_create_context && _sapp.glx.ARB_create_context_profile)) {
  9699. _SAPP_PANIC(LINUX_GLX_REQUIRED_EXTENSIONS_MISSING);
  9700. }
  9701. _sapp_x11_grab_error_handler();
  9702. const int attribs[] = {
  9703. GLX_CONTEXT_MAJOR_VERSION_ARB, _sapp.desc.gl_major_version,
  9704. GLX_CONTEXT_MINOR_VERSION_ARB, _sapp.desc.gl_minor_version,
  9705. GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
  9706. GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
  9707. 0, 0
  9708. };
  9709. _sapp.glx.ctx = _sapp.glx.CreateContextAttribsARB(_sapp.x11.display, native, NULL, True, attribs);
  9710. if (!_sapp.glx.ctx) {
  9711. _SAPP_PANIC(LINUX_GLX_CREATE_CONTEXT_FAILED);
  9712. }
  9713. _sapp_x11_release_error_handler();
  9714. _sapp.glx.window = _sapp.glx.CreateWindow(_sapp.x11.display, native, _sapp.x11.window, NULL);
  9715. if (!_sapp.glx.window) {
  9716. _SAPP_PANIC(LINUX_GLX_CREATE_WINDOW_FAILED);
  9717. }
  9718. _sapp_glx_make_current();
  9719. }
  9720. _SOKOL_PRIVATE void _sapp_glx_destroy_context(void) {
  9721. if (_sapp.glx.window) {
  9722. _sapp.glx.DestroyWindow(_sapp.x11.display, _sapp.glx.window);
  9723. _sapp.glx.window = 0;
  9724. }
  9725. if (_sapp.glx.ctx) {
  9726. _sapp.glx.DestroyContext(_sapp.x11.display, _sapp.glx.ctx);
  9727. _sapp.glx.ctx = 0;
  9728. }
  9729. }
  9730. _SOKOL_PRIVATE void _sapp_glx_swap_buffers(void) {
  9731. _sapp.glx.SwapBuffers(_sapp.x11.display, _sapp.glx.window);
  9732. }
  9733. _SOKOL_PRIVATE void _sapp_glx_swapinterval(int interval) {
  9734. if (_sapp.glx.EXT_swap_control) {
  9735. _sapp.glx.SwapIntervalEXT(_sapp.x11.display, _sapp.glx.window, interval);
  9736. }
  9737. else if (_sapp.glx.MESA_swap_control) {
  9738. _sapp.glx.SwapIntervalMESA(interval);
  9739. }
  9740. }
  9741. #endif /* _SAPP_GLX */
  9742. _SOKOL_PRIVATE void _sapp_x11_send_event(Atom type, int a, int b, int c, int d, int e) {
  9743. XEvent event;
  9744. _sapp_clear(&event, sizeof(event));
  9745. event.type = ClientMessage;
  9746. event.xclient.window = _sapp.x11.window;
  9747. event.xclient.format = 32;
  9748. event.xclient.message_type = type;
  9749. event.xclient.data.l[0] = a;
  9750. event.xclient.data.l[1] = b;
  9751. event.xclient.data.l[2] = c;
  9752. event.xclient.data.l[3] = d;
  9753. event.xclient.data.l[4] = e;
  9754. XSendEvent(_sapp.x11.display, _sapp.x11.root,
  9755. False,
  9756. SubstructureNotifyMask | SubstructureRedirectMask,
  9757. &event);
  9758. }
  9759. _SOKOL_PRIVATE void _sapp_x11_query_window_size(void) {
  9760. XWindowAttributes attribs;
  9761. XGetWindowAttributes(_sapp.x11.display, _sapp.x11.window, &attribs);
  9762. _sapp.window_width = attribs.width;
  9763. _sapp.window_height = attribs.height;
  9764. _sapp.framebuffer_width = _sapp.window_width;
  9765. _sapp.framebuffer_height = _sapp.window_height;
  9766. }
  9767. _SOKOL_PRIVATE void _sapp_x11_set_fullscreen(bool enable) {
  9768. /* NOTE: this function must be called after XMapWindow (which happens in _sapp_x11_show_window()) */
  9769. if (_sapp.x11.NET_WM_STATE && _sapp.x11.NET_WM_STATE_FULLSCREEN) {
  9770. if (enable) {
  9771. const int _NET_WM_STATE_ADD = 1;
  9772. _sapp_x11_send_event(_sapp.x11.NET_WM_STATE,
  9773. _NET_WM_STATE_ADD,
  9774. _sapp.x11.NET_WM_STATE_FULLSCREEN,
  9775. 0, 1, 0);
  9776. }
  9777. else {
  9778. const int _NET_WM_STATE_REMOVE = 0;
  9779. _sapp_x11_send_event(_sapp.x11.NET_WM_STATE,
  9780. _NET_WM_STATE_REMOVE,
  9781. _sapp.x11.NET_WM_STATE_FULLSCREEN,
  9782. 0, 1, 0);
  9783. }
  9784. }
  9785. XFlush(_sapp.x11.display);
  9786. }
  9787. _SOKOL_PRIVATE void _sapp_x11_create_hidden_cursor(void) {
  9788. SOKOL_ASSERT(0 == _sapp.x11.hidden_cursor);
  9789. const int w = 16;
  9790. const int h = 16;
  9791. XcursorImage* img = XcursorImageCreate(w, h);
  9792. SOKOL_ASSERT(img && (img->width == 16) && (img->height == 16) && img->pixels);
  9793. img->xhot = 0;
  9794. img->yhot = 0;
  9795. const size_t num_bytes = (size_t)(w * h) * sizeof(XcursorPixel);
  9796. _sapp_clear(img->pixels, num_bytes);
  9797. _sapp.x11.hidden_cursor = XcursorImageLoadCursor(_sapp.x11.display, img);
  9798. XcursorImageDestroy(img);
  9799. }
  9800. _SOKOL_PRIVATE void _sapp_x11_create_standard_cursor(sapp_mouse_cursor cursor, const char* name, const char* theme, int size, uint32_t fallback_native) {
  9801. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  9802. SOKOL_ASSERT(_sapp.x11.display);
  9803. if (theme) {
  9804. XcursorImage* img = XcursorLibraryLoadImage(name, theme, size);
  9805. if (img) {
  9806. _sapp.x11.cursors[cursor] = XcursorImageLoadCursor(_sapp.x11.display, img);
  9807. XcursorImageDestroy(img);
  9808. }
  9809. }
  9810. if (0 == _sapp.x11.cursors[cursor]) {
  9811. _sapp.x11.cursors[cursor] = XCreateFontCursor(_sapp.x11.display, fallback_native);
  9812. }
  9813. }
  9814. _SOKOL_PRIVATE void _sapp_x11_create_cursors(void) {
  9815. SOKOL_ASSERT(_sapp.x11.display);
  9816. const char* cursor_theme = XcursorGetTheme(_sapp.x11.display);
  9817. const int size = XcursorGetDefaultSize(_sapp.x11.display);
  9818. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_ARROW, "default", cursor_theme, size, XC_left_ptr);
  9819. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_IBEAM, "text", cursor_theme, size, XC_xterm);
  9820. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_CROSSHAIR, "crosshair", cursor_theme, size, XC_crosshair);
  9821. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_POINTING_HAND, "pointer", cursor_theme, size, XC_hand2);
  9822. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_EW, "ew-resize", cursor_theme, size, XC_sb_h_double_arrow);
  9823. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NS, "ns-resize", cursor_theme, size, XC_sb_v_double_arrow);
  9824. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NWSE, "nwse-resize", cursor_theme, size, 0);
  9825. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NESW, "nesw-resize", cursor_theme, size, 0);
  9826. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_ALL, "all-scroll", cursor_theme, size, XC_fleur);
  9827. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_NOT_ALLOWED, "no-allowed", cursor_theme, size, 0);
  9828. _sapp_x11_create_hidden_cursor();
  9829. }
  9830. _SOKOL_PRIVATE void _sapp_x11_destroy_cursors(void) {
  9831. SOKOL_ASSERT(_sapp.x11.display);
  9832. if (_sapp.x11.hidden_cursor) {
  9833. XFreeCursor(_sapp.x11.display, _sapp.x11.hidden_cursor);
  9834. _sapp.x11.hidden_cursor = 0;
  9835. }
  9836. for (int i = 0; i < _SAPP_MOUSECURSOR_NUM; i++) {
  9837. if (_sapp.x11.cursors[i]) {
  9838. XFreeCursor(_sapp.x11.display, _sapp.x11.cursors[i]);
  9839. _sapp.x11.cursors[i] = 0;
  9840. }
  9841. }
  9842. }
  9843. _SOKOL_PRIVATE void _sapp_x11_toggle_fullscreen(void) {
  9844. _sapp.fullscreen = !_sapp.fullscreen;
  9845. _sapp_x11_set_fullscreen(_sapp.fullscreen);
  9846. _sapp_x11_query_window_size();
  9847. }
  9848. _SOKOL_PRIVATE void _sapp_x11_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  9849. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  9850. if (shown) {
  9851. if (_sapp.x11.cursors[cursor]) {
  9852. XDefineCursor(_sapp.x11.display, _sapp.x11.window, _sapp.x11.cursors[cursor]);
  9853. }
  9854. else {
  9855. XUndefineCursor(_sapp.x11.display, _sapp.x11.window);
  9856. }
  9857. }
  9858. else {
  9859. XDefineCursor(_sapp.x11.display, _sapp.x11.window, _sapp.x11.hidden_cursor);
  9860. }
  9861. XFlush(_sapp.x11.display);
  9862. }
  9863. _SOKOL_PRIVATE void _sapp_x11_lock_mouse(bool lock) {
  9864. if (lock == _sapp.mouse.locked) {
  9865. return;
  9866. }
  9867. _sapp.mouse.dx = 0.0f;
  9868. _sapp.mouse.dy = 0.0f;
  9869. _sapp.mouse.locked = lock;
  9870. if (_sapp.mouse.locked) {
  9871. if (_sapp.x11.xi.available) {
  9872. XIEventMask em;
  9873. unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 }; // XIMaskLen is a macro
  9874. em.deviceid = XIAllMasterDevices;
  9875. em.mask_len = sizeof(mask);
  9876. em.mask = mask;
  9877. XISetMask(mask, XI_RawMotion);
  9878. XISelectEvents(_sapp.x11.display, _sapp.x11.root, &em, 1);
  9879. }
  9880. XGrabPointer(_sapp.x11.display, // display
  9881. _sapp.x11.window, // grab_window
  9882. True, // owner_events
  9883. ButtonPressMask | ButtonReleaseMask | PointerMotionMask, // event_mask
  9884. GrabModeAsync, // pointer_mode
  9885. GrabModeAsync, // keyboard_mode
  9886. _sapp.x11.window, // confine_to
  9887. _sapp.x11.hidden_cursor, // cursor
  9888. CurrentTime); // time
  9889. }
  9890. else {
  9891. if (_sapp.x11.xi.available) {
  9892. XIEventMask em;
  9893. unsigned char mask[] = { 0 };
  9894. em.deviceid = XIAllMasterDevices;
  9895. em.mask_len = sizeof(mask);
  9896. em.mask = mask;
  9897. XISelectEvents(_sapp.x11.display, _sapp.x11.root, &em, 1);
  9898. }
  9899. XWarpPointer(_sapp.x11.display, None, _sapp.x11.window, 0, 0, 0, 0, (int) _sapp.mouse.x, _sapp.mouse.y);
  9900. XUngrabPointer(_sapp.x11.display, CurrentTime);
  9901. }
  9902. XFlush(_sapp.x11.display);
  9903. }
  9904. _SOKOL_PRIVATE void _sapp_x11_set_clipboard_string(const char* str) {
  9905. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  9906. if (strlen(str) >= (size_t)_sapp.clipboard.buf_size) {
  9907. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  9908. }
  9909. XSetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD, _sapp.x11.window, CurrentTime);
  9910. if (XGetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD) != _sapp.x11.window) {
  9911. _SAPP_ERROR(LINUX_X11_FAILED_TO_BECOME_OWNER_OF_CLIPBOARD);
  9912. }
  9913. }
  9914. _SOKOL_PRIVATE const char* _sapp_x11_get_clipboard_string(void) {
  9915. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  9916. Atom none = XInternAtom(_sapp.x11.display, "SAPP_SELECTION", False);
  9917. Atom incremental = XInternAtom(_sapp.x11.display, "INCR", False);
  9918. if (XGetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD) == _sapp.x11.window) {
  9919. // Instead of doing a large number of X round-trips just to put this
  9920. // string into a window property and then read it back, just return it
  9921. return _sapp.clipboard.buffer;
  9922. }
  9923. XConvertSelection(_sapp.x11.display,
  9924. _sapp.x11.CLIPBOARD,
  9925. _sapp.x11.UTF8_STRING,
  9926. none,
  9927. _sapp.x11.window,
  9928. CurrentTime);
  9929. XEvent event;
  9930. while (!XCheckTypedWindowEvent(_sapp.x11.display, _sapp.x11.window, SelectionNotify, &event)) {
  9931. // Wait for event data to arrive on the X11 display socket
  9932. struct pollfd fd = { ConnectionNumber(_sapp.x11.display), POLLIN };
  9933. while (!XPending(_sapp.x11.display)) {
  9934. poll(&fd, 1, -1);
  9935. }
  9936. }
  9937. if (event.xselection.property == None) {
  9938. return NULL;
  9939. }
  9940. char* data = NULL;
  9941. Atom actualType;
  9942. int actualFormat;
  9943. unsigned long itemCount, bytesAfter;
  9944. const bool ret = XGetWindowProperty(_sapp.x11.display,
  9945. event.xselection.requestor,
  9946. event.xselection.property,
  9947. 0,
  9948. LONG_MAX,
  9949. True,
  9950. _sapp.x11.UTF8_STRING,
  9951. &actualType,
  9952. &actualFormat,
  9953. &itemCount,
  9954. &bytesAfter,
  9955. (unsigned char**) &data);
  9956. if (ret != Success || data == NULL) {
  9957. if (data != NULL) {
  9958. XFree(data);
  9959. }
  9960. return NULL;
  9961. }
  9962. if ((actualType == incremental) || (itemCount >= (size_t)_sapp.clipboard.buf_size)) {
  9963. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  9964. XFree(data);
  9965. return NULL;
  9966. }
  9967. _sapp_strcpy(data, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  9968. XFree(data);
  9969. return _sapp.clipboard.buffer;
  9970. }
  9971. _SOKOL_PRIVATE void _sapp_x11_update_window_title(void) {
  9972. Xutf8SetWMProperties(_sapp.x11.display,
  9973. _sapp.x11.window,
  9974. _sapp.window_title, _sapp.window_title,
  9975. NULL, 0, NULL, NULL, NULL);
  9976. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9977. _sapp.x11.NET_WM_NAME, _sapp.x11.UTF8_STRING, 8,
  9978. PropModeReplace,
  9979. (unsigned char*)_sapp.window_title,
  9980. strlen(_sapp.window_title));
  9981. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9982. _sapp.x11.NET_WM_ICON_NAME, _sapp.x11.UTF8_STRING, 8,
  9983. PropModeReplace,
  9984. (unsigned char*)_sapp.window_title,
  9985. strlen(_sapp.window_title));
  9986. XFlush(_sapp.x11.display);
  9987. }
  9988. _SOKOL_PRIVATE void _sapp_x11_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  9989. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  9990. int long_count = 0;
  9991. for (int i = 0; i < num_images; i++) {
  9992. const sapp_image_desc* img_desc = &icon_desc->images[i];
  9993. long_count += 2 + (img_desc->width * img_desc->height);
  9994. }
  9995. long* icon_data = (long*) _sapp_malloc_clear((size_t)long_count * sizeof(long));
  9996. SOKOL_ASSERT(icon_data);
  9997. long* dst = icon_data;
  9998. for (int img_index = 0; img_index < num_images; img_index++) {
  9999. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  10000. const uint8_t* src = (const uint8_t*) img_desc->pixels.ptr;
  10001. *dst++ = img_desc->width;
  10002. *dst++ = img_desc->height;
  10003. const int num_pixels = img_desc->width * img_desc->height;
  10004. for (int pixel_index = 0; pixel_index < num_pixels; pixel_index++) {
  10005. *dst++ = ((long)(src[pixel_index * 4 + 0]) << 16) |
  10006. ((long)(src[pixel_index * 4 + 1]) << 8) |
  10007. ((long)(src[pixel_index * 4 + 2]) << 0) |
  10008. ((long)(src[pixel_index * 4 + 3]) << 24);
  10009. }
  10010. }
  10011. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  10012. _sapp.x11.NET_WM_ICON,
  10013. XA_CARDINAL, 32,
  10014. PropModeReplace,
  10015. (unsigned char*)icon_data,
  10016. long_count);
  10017. _sapp_free(icon_data);
  10018. XFlush(_sapp.x11.display);
  10019. }
  10020. _SOKOL_PRIVATE void _sapp_x11_create_window(Visual* visual, int depth) {
  10021. _sapp.x11.colormap = XCreateColormap(_sapp.x11.display, _sapp.x11.root, visual, AllocNone);
  10022. XSetWindowAttributes wa;
  10023. _sapp_clear(&wa, sizeof(wa));
  10024. const uint32_t wamask = CWBorderPixel | CWColormap | CWEventMask;
  10025. wa.colormap = _sapp.x11.colormap;
  10026. wa.border_pixel = 0;
  10027. wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
  10028. PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
  10029. ExposureMask | FocusChangeMask | VisibilityChangeMask |
  10030. EnterWindowMask | LeaveWindowMask | PropertyChangeMask;
  10031. int display_width = DisplayWidth(_sapp.x11.display, _sapp.x11.screen);
  10032. int display_height = DisplayHeight(_sapp.x11.display, _sapp.x11.screen);
  10033. int window_width = (int)(_sapp.window_width * _sapp.dpi_scale);
  10034. int window_height = (int)(_sapp.window_height * _sapp.dpi_scale);
  10035. if (0 == window_width) {
  10036. window_width = (display_width * 4) / 5;
  10037. }
  10038. if (0 == window_height) {
  10039. window_height = (display_height * 4) / 5;
  10040. }
  10041. _sapp_x11_grab_error_handler();
  10042. _sapp.x11.window = XCreateWindow(_sapp.x11.display,
  10043. _sapp.x11.root,
  10044. 0, 0,
  10045. (uint32_t)window_width,
  10046. (uint32_t)window_height,
  10047. 0, /* border width */
  10048. depth, /* color depth */
  10049. InputOutput,
  10050. visual,
  10051. wamask,
  10052. &wa);
  10053. _sapp_x11_release_error_handler();
  10054. if (!_sapp.x11.window) {
  10055. _SAPP_PANIC(LINUX_X11_CREATE_WINDOW_FAILED);
  10056. }
  10057. Atom protocols[] = {
  10058. _sapp.x11.WM_DELETE_WINDOW
  10059. };
  10060. XSetWMProtocols(_sapp.x11.display, _sapp.x11.window, protocols, 1);
  10061. // NOTE: PPosition and PSize are obsolete and ignored
  10062. XSizeHints* hints = XAllocSizeHints();
  10063. hints->flags = PWinGravity;
  10064. hints->win_gravity = CenterGravity;
  10065. XSetWMNormalHints(_sapp.x11.display, _sapp.x11.window, hints);
  10066. XFree(hints);
  10067. // announce support for drag'n'drop
  10068. if (_sapp.drop.enabled) {
  10069. const Atom version = _SAPP_X11_XDND_VERSION;
  10070. XChangeProperty(_sapp.x11.display, _sapp.x11.window, _sapp.x11.xdnd.XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char*) &version, 1);
  10071. }
  10072. _sapp_x11_update_window_title();
  10073. _sapp_x11_query_window_size();
  10074. }
  10075. _SOKOL_PRIVATE void _sapp_x11_destroy_window(void) {
  10076. if (_sapp.x11.window) {
  10077. XUnmapWindow(_sapp.x11.display, _sapp.x11.window);
  10078. XDestroyWindow(_sapp.x11.display, _sapp.x11.window);
  10079. _sapp.x11.window = 0;
  10080. }
  10081. if (_sapp.x11.colormap) {
  10082. XFreeColormap(_sapp.x11.display, _sapp.x11.colormap);
  10083. _sapp.x11.colormap = 0;
  10084. }
  10085. XFlush(_sapp.x11.display);
  10086. }
  10087. _SOKOL_PRIVATE bool _sapp_x11_window_visible(void) {
  10088. XWindowAttributes wa;
  10089. XGetWindowAttributes(_sapp.x11.display, _sapp.x11.window, &wa);
  10090. return wa.map_state == IsViewable;
  10091. }
  10092. _SOKOL_PRIVATE void _sapp_x11_show_window(void) {
  10093. if (!_sapp_x11_window_visible()) {
  10094. XMapWindow(_sapp.x11.display, _sapp.x11.window);
  10095. XRaiseWindow(_sapp.x11.display, _sapp.x11.window);
  10096. XFlush(_sapp.x11.display);
  10097. }
  10098. }
  10099. _SOKOL_PRIVATE void _sapp_x11_hide_window(void) {
  10100. XUnmapWindow(_sapp.x11.display, _sapp.x11.window);
  10101. XFlush(_sapp.x11.display);
  10102. }
  10103. _SOKOL_PRIVATE unsigned long _sapp_x11_get_window_property(Window window, Atom property, Atom type, unsigned char** value) {
  10104. Atom actualType;
  10105. int actualFormat;
  10106. unsigned long itemCount, bytesAfter;
  10107. XGetWindowProperty(_sapp.x11.display,
  10108. window,
  10109. property,
  10110. 0,
  10111. LONG_MAX,
  10112. False,
  10113. type,
  10114. &actualType,
  10115. &actualFormat,
  10116. &itemCount,
  10117. &bytesAfter,
  10118. value);
  10119. return itemCount;
  10120. }
  10121. _SOKOL_PRIVATE int _sapp_x11_get_window_state(void) {
  10122. int result = WithdrawnState;
  10123. struct {
  10124. CARD32 state;
  10125. Window icon;
  10126. } *state = NULL;
  10127. if (_sapp_x11_get_window_property(_sapp.x11.window, _sapp.x11.WM_STATE, _sapp.x11.WM_STATE, (unsigned char**)&state) >= 2) {
  10128. result = (int)state->state;
  10129. }
  10130. if (state) {
  10131. XFree(state);
  10132. }
  10133. return result;
  10134. }
  10135. _SOKOL_PRIVATE uint32_t _sapp_x11_key_modifier_bit(sapp_keycode key) {
  10136. switch (key) {
  10137. case SAPP_KEYCODE_LEFT_SHIFT:
  10138. case SAPP_KEYCODE_RIGHT_SHIFT:
  10139. return SAPP_MODIFIER_SHIFT;
  10140. case SAPP_KEYCODE_LEFT_CONTROL:
  10141. case SAPP_KEYCODE_RIGHT_CONTROL:
  10142. return SAPP_MODIFIER_CTRL;
  10143. case SAPP_KEYCODE_LEFT_ALT:
  10144. case SAPP_KEYCODE_RIGHT_ALT:
  10145. return SAPP_MODIFIER_ALT;
  10146. case SAPP_KEYCODE_LEFT_SUPER:
  10147. case SAPP_KEYCODE_RIGHT_SUPER:
  10148. return SAPP_MODIFIER_SUPER;
  10149. default:
  10150. return 0;
  10151. }
  10152. }
  10153. _SOKOL_PRIVATE uint32_t _sapp_x11_button_modifier_bit(sapp_mousebutton btn) {
  10154. switch (btn) {
  10155. case SAPP_MOUSEBUTTON_LEFT: return SAPP_MODIFIER_LMB;
  10156. case SAPP_MOUSEBUTTON_RIGHT: return SAPP_MODIFIER_RMB;
  10157. case SAPP_MOUSEBUTTON_MIDDLE: return SAPP_MODIFIER_MMB;
  10158. default: return 0;
  10159. }
  10160. }
  10161. _SOKOL_PRIVATE uint32_t _sapp_x11_mods(uint32_t x11_mods) {
  10162. uint32_t mods = 0;
  10163. if (x11_mods & ShiftMask) {
  10164. mods |= SAPP_MODIFIER_SHIFT;
  10165. }
  10166. if (x11_mods & ControlMask) {
  10167. mods |= SAPP_MODIFIER_CTRL;
  10168. }
  10169. if (x11_mods & Mod1Mask) {
  10170. mods |= SAPP_MODIFIER_ALT;
  10171. }
  10172. if (x11_mods & Mod4Mask) {
  10173. mods |= SAPP_MODIFIER_SUPER;
  10174. }
  10175. if (x11_mods & Button1Mask) {
  10176. mods |= SAPP_MODIFIER_LMB;
  10177. }
  10178. if (x11_mods & Button2Mask) {
  10179. mods |= SAPP_MODIFIER_MMB;
  10180. }
  10181. if (x11_mods & Button3Mask) {
  10182. mods |= SAPP_MODIFIER_RMB;
  10183. }
  10184. return mods;
  10185. }
  10186. _SOKOL_PRIVATE void _sapp_x11_app_event(sapp_event_type type) {
  10187. if (_sapp_events_enabled()) {
  10188. _sapp_init_event(type);
  10189. _sapp_call_event(&_sapp.event);
  10190. }
  10191. }
  10192. _SOKOL_PRIVATE sapp_mousebutton _sapp_x11_translate_button(const XEvent* event) {
  10193. switch (event->xbutton.button) {
  10194. case Button1: return SAPP_MOUSEBUTTON_LEFT;
  10195. case Button2: return SAPP_MOUSEBUTTON_MIDDLE;
  10196. case Button3: return SAPP_MOUSEBUTTON_RIGHT;
  10197. default: return SAPP_MOUSEBUTTON_INVALID;
  10198. }
  10199. }
  10200. _SOKOL_PRIVATE void _sapp_x11_mouse_update(int x, int y, bool clear_dxdy) {
  10201. if (!_sapp.mouse.locked) {
  10202. const float new_x = (float) x;
  10203. const float new_y = (float) y;
  10204. if (clear_dxdy) {
  10205. _sapp.mouse.dx = 0.0f;
  10206. _sapp.mouse.dy = 0.0f;
  10207. } else if (_sapp.mouse.pos_valid) {
  10208. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  10209. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  10210. }
  10211. _sapp.mouse.x = new_x;
  10212. _sapp.mouse.y = new_y;
  10213. _sapp.mouse.pos_valid = true;
  10214. }
  10215. }
  10216. _SOKOL_PRIVATE void _sapp_x11_mouse_event(sapp_event_type type, sapp_mousebutton btn, uint32_t mods) {
  10217. if (_sapp_events_enabled()) {
  10218. _sapp_init_event(type);
  10219. _sapp.event.mouse_button = btn;
  10220. _sapp.event.modifiers = mods;
  10221. _sapp_call_event(&_sapp.event);
  10222. }
  10223. }
  10224. _SOKOL_PRIVATE void _sapp_x11_scroll_event(float x, float y, uint32_t mods) {
  10225. if (_sapp_events_enabled()) {
  10226. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  10227. _sapp.event.modifiers = mods;
  10228. _sapp.event.scroll_x = x;
  10229. _sapp.event.scroll_y = y;
  10230. _sapp_call_event(&_sapp.event);
  10231. }
  10232. }
  10233. _SOKOL_PRIVATE void _sapp_x11_key_event(sapp_event_type type, sapp_keycode key, bool repeat, uint32_t mods) {
  10234. if (_sapp_events_enabled()) {
  10235. _sapp_init_event(type);
  10236. _sapp.event.key_code = key;
  10237. _sapp.event.key_repeat = repeat;
  10238. _sapp.event.modifiers = mods;
  10239. _sapp_call_event(&_sapp.event);
  10240. /* check if a CLIPBOARD_PASTED event must be sent too */
  10241. if (_sapp.clipboard.enabled &&
  10242. (type == SAPP_EVENTTYPE_KEY_DOWN) &&
  10243. (_sapp.event.modifiers == SAPP_MODIFIER_CTRL) &&
  10244. (_sapp.event.key_code == SAPP_KEYCODE_V))
  10245. {
  10246. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  10247. _sapp_call_event(&_sapp.event);
  10248. }
  10249. }
  10250. }
  10251. _SOKOL_PRIVATE void _sapp_x11_char_event(uint32_t chr, bool repeat, uint32_t mods) {
  10252. if (_sapp_events_enabled()) {
  10253. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  10254. _sapp.event.char_code = chr;
  10255. _sapp.event.key_repeat = repeat;
  10256. _sapp.event.modifiers = mods;
  10257. _sapp_call_event(&_sapp.event);
  10258. }
  10259. }
  10260. _SOKOL_PRIVATE sapp_keycode _sapp_x11_translate_key(int scancode) {
  10261. if ((scancode >= 0) && (scancode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10262. return _sapp.keycodes[scancode];
  10263. } else {
  10264. return SAPP_KEYCODE_INVALID;
  10265. }
  10266. }
  10267. _SOKOL_PRIVATE int32_t _sapp_x11_keysym_to_unicode(KeySym keysym) {
  10268. int min = 0;
  10269. int max = sizeof(_sapp_x11_keysymtab) / sizeof(struct _sapp_x11_codepair) - 1;
  10270. int mid;
  10271. /* First check for Latin-1 characters (1:1 mapping) */
  10272. if ((keysym >= 0x0020 && keysym <= 0x007e) ||
  10273. (keysym >= 0x00a0 && keysym <= 0x00ff))
  10274. {
  10275. return keysym;
  10276. }
  10277. /* Also check for directly encoded 24-bit UCS characters */
  10278. if ((keysym & 0xff000000) == 0x01000000) {
  10279. return keysym & 0x00ffffff;
  10280. }
  10281. /* Binary search in table */
  10282. while (max >= min) {
  10283. mid = (min + max) / 2;
  10284. if (_sapp_x11_keysymtab[mid].keysym < keysym) {
  10285. min = mid + 1;
  10286. }
  10287. else if (_sapp_x11_keysymtab[mid].keysym > keysym) {
  10288. max = mid - 1;
  10289. }
  10290. else {
  10291. return _sapp_x11_keysymtab[mid].ucs;
  10292. }
  10293. }
  10294. /* No matching Unicode value found */
  10295. return -1;
  10296. }
  10297. _SOKOL_PRIVATE bool _sapp_x11_keypress_repeat(int keycode) {
  10298. bool repeat = false;
  10299. if ((keycode >= 0) && (keycode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10300. repeat = _sapp.x11.key_repeat[keycode];
  10301. _sapp.x11.key_repeat[keycode] = true;
  10302. }
  10303. return repeat;
  10304. }
  10305. _SOKOL_PRIVATE void _sapp_x11_keyrelease_repeat(int keycode) {
  10306. if ((keycode >= 0) && (keycode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10307. _sapp.x11.key_repeat[keycode] = false;
  10308. }
  10309. }
  10310. _SOKOL_PRIVATE bool _sapp_x11_parse_dropped_files_list(const char* src) {
  10311. SOKOL_ASSERT(src);
  10312. SOKOL_ASSERT(_sapp.drop.buffer);
  10313. _sapp_clear_drop_buffer();
  10314. _sapp.drop.num_files = 0;
  10315. /*
  10316. src is (potentially percent-encoded) string made of one or multiple paths
  10317. separated by \r\n, each path starting with 'file://'
  10318. */
  10319. bool err = false;
  10320. int src_count = 0;
  10321. char src_chr = 0;
  10322. char* dst_ptr = _sapp.drop.buffer;
  10323. const char* dst_end_ptr = dst_ptr + (_sapp.drop.max_path_length - 1); // room for terminating 0
  10324. while (0 != (src_chr = *src++)) {
  10325. src_count++;
  10326. char dst_chr = 0;
  10327. /* check leading 'file://' */
  10328. if (src_count <= 7) {
  10329. if (((src_count == 1) && (src_chr != 'f')) ||
  10330. ((src_count == 2) && (src_chr != 'i')) ||
  10331. ((src_count == 3) && (src_chr != 'l')) ||
  10332. ((src_count == 4) && (src_chr != 'e')) ||
  10333. ((src_count == 5) && (src_chr != ':')) ||
  10334. ((src_count == 6) && (src_chr != '/')) ||
  10335. ((src_count == 7) && (src_chr != '/')))
  10336. {
  10337. _SAPP_ERROR(LINUX_X11_DROPPED_FILE_URI_WRONG_SCHEME);
  10338. err = true;
  10339. break;
  10340. }
  10341. }
  10342. else if (src_chr == '\r') {
  10343. // skip
  10344. }
  10345. else if (src_chr == '\n') {
  10346. src_count = 0;
  10347. _sapp.drop.num_files++;
  10348. // too many files is not an error
  10349. if (_sapp.drop.num_files >= _sapp.drop.max_files) {
  10350. break;
  10351. }
  10352. dst_ptr = _sapp.drop.buffer + _sapp.drop.num_files * _sapp.drop.max_path_length;
  10353. dst_end_ptr = dst_ptr + (_sapp.drop.max_path_length - 1);
  10354. }
  10355. else if ((src_chr == '%') && src[0] && src[1]) {
  10356. // a percent-encoded byte (most likely UTF-8 multibyte sequence)
  10357. const char digits[3] = { src[0], src[1], 0 };
  10358. src += 2;
  10359. dst_chr = (char) strtol(digits, 0, 16);
  10360. }
  10361. else {
  10362. dst_chr = src_chr;
  10363. }
  10364. if (dst_chr) {
  10365. // dst_end_ptr already has adjustment for terminating zero
  10366. if (dst_ptr < dst_end_ptr) {
  10367. *dst_ptr++ = dst_chr;
  10368. }
  10369. else {
  10370. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  10371. err = true;
  10372. break;
  10373. }
  10374. }
  10375. }
  10376. if (err) {
  10377. _sapp_clear_drop_buffer();
  10378. _sapp.drop.num_files = 0;
  10379. return false;
  10380. }
  10381. else {
  10382. return true;
  10383. }
  10384. }
  10385. _SOKOL_PRIVATE void _sapp_x11_on_genericevent(XEvent* event) {
  10386. if (_sapp.mouse.locked && _sapp.x11.xi.available) {
  10387. if (event->xcookie.extension == _sapp.x11.xi.major_opcode) {
  10388. if (XGetEventData(_sapp.x11.display, &event->xcookie)) {
  10389. if (event->xcookie.evtype == XI_RawMotion) {
  10390. XIRawEvent* re = (XIRawEvent*) event->xcookie.data;
  10391. if (re->valuators.mask_len) {
  10392. const double* values = re->raw_values;
  10393. if (XIMaskIsSet(re->valuators.mask, 0)) {
  10394. _sapp.mouse.dx = (float) *values;
  10395. values++;
  10396. }
  10397. if (XIMaskIsSet(re->valuators.mask, 1)) {
  10398. _sapp.mouse.dy = (float) *values;
  10399. }
  10400. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xmotion.state));
  10401. }
  10402. }
  10403. XFreeEventData(_sapp.x11.display, &event->xcookie);
  10404. }
  10405. }
  10406. }
  10407. }
  10408. _SOKOL_PRIVATE void _sapp_x11_on_focusin(XEvent* event) {
  10409. // NOTE: ignoring NotifyGrab and NotifyUngrab is same behaviour as GLFW
  10410. if ((event->xfocus.mode != NotifyGrab) && (event->xfocus.mode != NotifyUngrab)) {
  10411. _sapp_x11_app_event(SAPP_EVENTTYPE_FOCUSED);
  10412. }
  10413. }
  10414. _SOKOL_PRIVATE void _sapp_x11_on_focusout(XEvent* event) {
  10415. // if focus is lost for any reason, and we're in mouse locked mode, disable mouse lock
  10416. if (_sapp.mouse.locked) {
  10417. _sapp_x11_lock_mouse(false);
  10418. }
  10419. // NOTE: ignoring NotifyGrab and NotifyUngrab is same behaviour as GLFW
  10420. if ((event->xfocus.mode != NotifyGrab) && (event->xfocus.mode != NotifyUngrab)) {
  10421. _sapp_x11_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  10422. }
  10423. }
  10424. _SOKOL_PRIVATE void _sapp_x11_on_keypress(XEvent* event) {
  10425. int keycode = (int)event->xkey.keycode;
  10426. const sapp_keycode key = _sapp_x11_translate_key(keycode);
  10427. const bool repeat = _sapp_x11_keypress_repeat(keycode);
  10428. uint32_t mods = _sapp_x11_mods(event->xkey.state);
  10429. // X11 doesn't set modifier bit on key down, so emulate that
  10430. mods |= _sapp_x11_key_modifier_bit(key);
  10431. if (key != SAPP_KEYCODE_INVALID) {
  10432. _sapp_x11_key_event(SAPP_EVENTTYPE_KEY_DOWN, key, repeat, mods);
  10433. }
  10434. KeySym keysym;
  10435. XLookupString(&event->xkey, NULL, 0, &keysym, NULL);
  10436. int32_t chr = _sapp_x11_keysym_to_unicode(keysym);
  10437. if (chr > 0) {
  10438. _sapp_x11_char_event((uint32_t)chr, repeat, mods);
  10439. }
  10440. }
  10441. _SOKOL_PRIVATE void _sapp_x11_on_keyrelease(XEvent* event) {
  10442. int keycode = (int)event->xkey.keycode;
  10443. const sapp_keycode key = _sapp_x11_translate_key(keycode);
  10444. _sapp_x11_keyrelease_repeat(keycode);
  10445. if (key != SAPP_KEYCODE_INVALID) {
  10446. uint32_t mods = _sapp_x11_mods(event->xkey.state);
  10447. // X11 doesn't clear modifier bit on key up, so emulate that
  10448. mods &= ~_sapp_x11_key_modifier_bit(key);
  10449. _sapp_x11_key_event(SAPP_EVENTTYPE_KEY_UP, key, false, mods);
  10450. }
  10451. }
  10452. _SOKOL_PRIVATE void _sapp_x11_on_buttonpress(XEvent* event) {
  10453. _sapp_x11_mouse_update(event->xbutton.x, event->xbutton.y, false);
  10454. const sapp_mousebutton btn = _sapp_x11_translate_button(event);
  10455. uint32_t mods = _sapp_x11_mods(event->xbutton.state);
  10456. // X11 doesn't set modifier bit on button down, so emulate that
  10457. mods |= _sapp_x11_button_modifier_bit(btn);
  10458. if (btn != SAPP_MOUSEBUTTON_INVALID) {
  10459. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, btn, mods);
  10460. _sapp.x11.mouse_buttons |= (1 << btn);
  10461. }
  10462. else {
  10463. // might be a scroll event
  10464. switch (event->xbutton.button) {
  10465. case 4: _sapp_x11_scroll_event(0.0f, 1.0f, mods); break;
  10466. case 5: _sapp_x11_scroll_event(0.0f, -1.0f, mods); break;
  10467. case 6: _sapp_x11_scroll_event(1.0f, 0.0f, mods); break;
  10468. case 7: _sapp_x11_scroll_event(-1.0f, 0.0f, mods); break;
  10469. }
  10470. }
  10471. }
  10472. _SOKOL_PRIVATE void _sapp_x11_on_buttonrelease(XEvent* event) {
  10473. _sapp_x11_mouse_update(event->xbutton.x, event->xbutton.y, false);
  10474. const sapp_mousebutton btn = _sapp_x11_translate_button(event);
  10475. if (btn != SAPP_MOUSEBUTTON_INVALID) {
  10476. uint32_t mods = _sapp_x11_mods(event->xbutton.state);
  10477. // X11 doesn't clear modifier bit on button up, so emulate that
  10478. mods &= ~_sapp_x11_button_modifier_bit(btn);
  10479. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, btn, mods);
  10480. _sapp.x11.mouse_buttons &= ~(1 << btn);
  10481. }
  10482. }
  10483. _SOKOL_PRIVATE void _sapp_x11_on_enternotify(XEvent* event) {
  10484. // don't send enter/leave events while mouse button held down
  10485. if (0 == _sapp.x11.mouse_buttons) {
  10486. _sapp_x11_mouse_update(event->xcrossing.x, event->xcrossing.y, true);
  10487. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xcrossing.state));
  10488. }
  10489. }
  10490. _SOKOL_PRIVATE void _sapp_x11_on_leavenotify(XEvent* event) {
  10491. if (0 == _sapp.x11.mouse_buttons) {
  10492. _sapp_x11_mouse_update(event->xcrossing.x, event->xcrossing.y, true);
  10493. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xcrossing.state));
  10494. }
  10495. }
  10496. _SOKOL_PRIVATE void _sapp_x11_on_motionnotify(XEvent* event) {
  10497. if (!_sapp.mouse.locked) {
  10498. _sapp_x11_mouse_update(event->xmotion.x, event->xmotion.y, false);
  10499. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xmotion.state));
  10500. }
  10501. }
  10502. _SOKOL_PRIVATE void _sapp_x11_on_configurenotify(XEvent* event) {
  10503. if ((event->xconfigure.width != _sapp.window_width) || (event->xconfigure.height != _sapp.window_height)) {
  10504. _sapp.window_width = event->xconfigure.width;
  10505. _sapp.window_height = event->xconfigure.height;
  10506. _sapp.framebuffer_width = _sapp.window_width;
  10507. _sapp.framebuffer_height = _sapp.window_height;
  10508. _sapp_x11_app_event(SAPP_EVENTTYPE_RESIZED);
  10509. }
  10510. }
  10511. _SOKOL_PRIVATE void _sapp_x11_on_propertynotify(XEvent* event) {
  10512. if (event->xproperty.state == PropertyNewValue) {
  10513. if (event->xproperty.atom == _sapp.x11.WM_STATE) {
  10514. const int state = _sapp_x11_get_window_state();
  10515. if (state != _sapp.x11.window_state) {
  10516. _sapp.x11.window_state = state;
  10517. if (state == IconicState) {
  10518. _sapp_x11_app_event(SAPP_EVENTTYPE_ICONIFIED);
  10519. }
  10520. else if (state == NormalState) {
  10521. _sapp_x11_app_event(SAPP_EVENTTYPE_RESTORED);
  10522. }
  10523. }
  10524. }
  10525. }
  10526. }
  10527. _SOKOL_PRIVATE void _sapp_x11_on_selectionnotify(XEvent* event) {
  10528. if (event->xselection.property == _sapp.x11.xdnd.XdndSelection) {
  10529. char* data = 0;
  10530. uint32_t result = _sapp_x11_get_window_property(event->xselection.requestor,
  10531. event->xselection.property,
  10532. event->xselection.target,
  10533. (unsigned char**) &data);
  10534. if (_sapp.drop.enabled && result) {
  10535. if (_sapp_x11_parse_dropped_files_list(data)) {
  10536. _sapp.mouse.dx = 0.0f;
  10537. _sapp.mouse.dy = 0.0f;
  10538. if (_sapp_events_enabled()) {
  10539. // FIXME: Figure out how to get modifier key state here.
  10540. // The XSelection event has no 'state' item, and
  10541. // XQueryKeymap() always returns a zeroed array.
  10542. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  10543. _sapp_call_event(&_sapp.event);
  10544. }
  10545. }
  10546. }
  10547. if (_sapp.x11.xdnd.version >= 2) {
  10548. XEvent reply;
  10549. _sapp_clear(&reply, sizeof(reply));
  10550. reply.type = ClientMessage;
  10551. reply.xclient.window = _sapp.x11.xdnd.source;
  10552. reply.xclient.message_type = _sapp.x11.xdnd.XdndFinished;
  10553. reply.xclient.format = 32;
  10554. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10555. reply.xclient.data.l[1] = result;
  10556. reply.xclient.data.l[2] = (long)_sapp.x11.xdnd.XdndActionCopy;
  10557. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10558. XFlush(_sapp.x11.display);
  10559. }
  10560. if (data) {
  10561. XFree(data);
  10562. }
  10563. }
  10564. }
  10565. _SOKOL_PRIVATE void _sapp_x11_on_clientmessage(XEvent* event) {
  10566. if (XFilterEvent(event, None)) {
  10567. return;
  10568. }
  10569. if (event->xclient.message_type == _sapp.x11.WM_PROTOCOLS) {
  10570. const Atom protocol = (Atom)event->xclient.data.l[0];
  10571. if (protocol == _sapp.x11.WM_DELETE_WINDOW) {
  10572. _sapp.quit_requested = true;
  10573. }
  10574. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndEnter) {
  10575. const bool is_list = 0 != (event->xclient.data.l[1] & 1);
  10576. _sapp.x11.xdnd.source = (Window)event->xclient.data.l[0];
  10577. _sapp.x11.xdnd.version = event->xclient.data.l[1] >> 24;
  10578. _sapp.x11.xdnd.format = None;
  10579. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10580. return;
  10581. }
  10582. uint32_t count = 0;
  10583. Atom* formats = 0;
  10584. if (is_list) {
  10585. count = _sapp_x11_get_window_property(_sapp.x11.xdnd.source, _sapp.x11.xdnd.XdndTypeList, XA_ATOM, (unsigned char**)&formats);
  10586. } else {
  10587. count = 3;
  10588. formats = (Atom*) event->xclient.data.l + 2;
  10589. }
  10590. for (uint32_t i = 0; i < count; i++) {
  10591. if (formats[i] == _sapp.x11.xdnd.text_uri_list) {
  10592. _sapp.x11.xdnd.format = _sapp.x11.xdnd.text_uri_list;
  10593. break;
  10594. }
  10595. }
  10596. if (is_list && formats) {
  10597. XFree(formats);
  10598. }
  10599. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndDrop) {
  10600. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10601. return;
  10602. }
  10603. Time time = CurrentTime;
  10604. if (_sapp.x11.xdnd.format) {
  10605. if (_sapp.x11.xdnd.version >= 1) {
  10606. time = (Time)event->xclient.data.l[2];
  10607. }
  10608. XConvertSelection(_sapp.x11.display,
  10609. _sapp.x11.xdnd.XdndSelection,
  10610. _sapp.x11.xdnd.format,
  10611. _sapp.x11.xdnd.XdndSelection,
  10612. _sapp.x11.window,
  10613. time);
  10614. } else if (_sapp.x11.xdnd.version >= 2) {
  10615. XEvent reply;
  10616. _sapp_clear(&reply, sizeof(reply));
  10617. reply.type = ClientMessage;
  10618. reply.xclient.window = _sapp.x11.xdnd.source;
  10619. reply.xclient.message_type = _sapp.x11.xdnd.XdndFinished;
  10620. reply.xclient.format = 32;
  10621. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10622. reply.xclient.data.l[1] = 0; // drag was rejected
  10623. reply.xclient.data.l[2] = None;
  10624. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10625. XFlush(_sapp.x11.display);
  10626. }
  10627. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndPosition) {
  10628. // drag operation has moved over the window
  10629. // FIXME: we could track the mouse position here, but
  10630. // this isn't implemented on other platforms either so far
  10631. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10632. return;
  10633. }
  10634. XEvent reply;
  10635. _sapp_clear(&reply, sizeof(reply));
  10636. reply.type = ClientMessage;
  10637. reply.xclient.window = _sapp.x11.xdnd.source;
  10638. reply.xclient.message_type = _sapp.x11.xdnd.XdndStatus;
  10639. reply.xclient.format = 32;
  10640. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10641. if (_sapp.x11.xdnd.format) {
  10642. /* reply that we are ready to copy the dragged data */
  10643. reply.xclient.data.l[1] = 1; // accept with no rectangle
  10644. if (_sapp.x11.xdnd.version >= 2) {
  10645. reply.xclient.data.l[4] = (long)_sapp.x11.xdnd.XdndActionCopy;
  10646. }
  10647. }
  10648. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10649. XFlush(_sapp.x11.display);
  10650. }
  10651. }
  10652. _SOKOL_PRIVATE void _sapp_x11_on_selectionrequest(XEvent* event) {
  10653. XSelectionRequestEvent* req = &event->xselectionrequest;
  10654. if (req->selection != _sapp.x11.CLIPBOARD) {
  10655. return;
  10656. }
  10657. if (!_sapp.clipboard.enabled) {
  10658. return;
  10659. }
  10660. SOKOL_ASSERT(_sapp.clipboard.buffer);
  10661. XSelectionEvent reply;
  10662. _sapp_clear(&reply, sizeof(reply));
  10663. reply.type = SelectionNotify;
  10664. reply.display = req->display;
  10665. reply.requestor = req->requestor;
  10666. reply.selection = req->selection;
  10667. reply.target = req->target;
  10668. reply.property = req->property;
  10669. reply.time = req->time;
  10670. if (req->target == _sapp.x11.UTF8_STRING) {
  10671. XChangeProperty(_sapp.x11.display,
  10672. req->requestor,
  10673. req->property,
  10674. _sapp.x11.UTF8_STRING,
  10675. 8,
  10676. PropModeReplace,
  10677. (unsigned char*) _sapp.clipboard.buffer,
  10678. strlen(_sapp.clipboard.buffer));
  10679. } else if (req->target == _sapp.x11.TARGETS) {
  10680. XChangeProperty(_sapp.x11.display,
  10681. req->requestor,
  10682. req->property,
  10683. XA_ATOM,
  10684. 32,
  10685. PropModeReplace,
  10686. (unsigned char*) &_sapp.x11.UTF8_STRING,
  10687. 1);
  10688. } else {
  10689. reply.property = None;
  10690. }
  10691. XSendEvent(_sapp.x11.display, req->requestor, False, 0, (XEvent*) &reply);
  10692. }
  10693. _SOKOL_PRIVATE void _sapp_x11_process_event(XEvent* event) {
  10694. switch (event->type) {
  10695. case GenericEvent:
  10696. _sapp_x11_on_genericevent(event);
  10697. break;
  10698. case FocusIn:
  10699. _sapp_x11_on_focusin(event);
  10700. break;
  10701. case FocusOut:
  10702. _sapp_x11_on_focusout(event);
  10703. break;
  10704. case KeyPress:
  10705. _sapp_x11_on_keypress(event);
  10706. break;
  10707. case KeyRelease:
  10708. _sapp_x11_on_keyrelease(event);
  10709. break;
  10710. case ButtonPress:
  10711. _sapp_x11_on_buttonpress(event);
  10712. break;
  10713. case ButtonRelease:
  10714. _sapp_x11_on_buttonrelease(event);
  10715. break;
  10716. case EnterNotify:
  10717. _sapp_x11_on_enternotify(event);
  10718. break;
  10719. case LeaveNotify:
  10720. _sapp_x11_on_leavenotify(event);
  10721. break;
  10722. case MotionNotify:
  10723. _sapp_x11_on_motionnotify(event);
  10724. break;
  10725. case ConfigureNotify:
  10726. _sapp_x11_on_configurenotify(event);
  10727. break;
  10728. case PropertyNotify:
  10729. _sapp_x11_on_propertynotify(event);
  10730. break;
  10731. case SelectionNotify:
  10732. _sapp_x11_on_selectionnotify(event);
  10733. break;
  10734. case SelectionRequest:
  10735. _sapp_x11_on_selectionrequest(event);
  10736. break;
  10737. case DestroyNotify:
  10738. // not a bug
  10739. break;
  10740. case ClientMessage:
  10741. _sapp_x11_on_clientmessage(event);
  10742. break;
  10743. }
  10744. }
  10745. #if !defined(_SAPP_GLX)
  10746. _SOKOL_PRIVATE void _sapp_egl_init(void) {
  10747. #if defined(SOKOL_GLCORE)
  10748. if (!eglBindAPI(EGL_OPENGL_API)) {
  10749. _SAPP_PANIC(LINUX_EGL_BIND_OPENGL_API_FAILED);
  10750. }
  10751. #else
  10752. if (!eglBindAPI(EGL_OPENGL_ES_API)) {
  10753. _SAPP_PANIC(LINUX_EGL_BIND_OPENGL_ES_API_FAILED);
  10754. }
  10755. #endif
  10756. _sapp.egl.display = eglGetDisplay((EGLNativeDisplayType)_sapp.x11.display);
  10757. if (EGL_NO_DISPLAY == _sapp.egl.display) {
  10758. _SAPP_PANIC(LINUX_EGL_GET_DISPLAY_FAILED);
  10759. }
  10760. EGLint major, minor;
  10761. if (!eglInitialize(_sapp.egl.display, &major, &minor)) {
  10762. _SAPP_PANIC(LINUX_EGL_INITIALIZE_FAILED);
  10763. }
  10764. EGLint sample_count = _sapp.desc.sample_count > 1 ? _sapp.desc.sample_count : 0;
  10765. EGLint alpha_size = _sapp.desc.alpha ? 8 : 0;
  10766. const EGLint config_attrs[] = {
  10767. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  10768. #if defined(SOKOL_GLCORE)
  10769. EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
  10770. #elif defined(SOKOL_GLES3)
  10771. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  10772. #endif
  10773. EGL_RED_SIZE, 8,
  10774. EGL_GREEN_SIZE, 8,
  10775. EGL_BLUE_SIZE, 8,
  10776. EGL_ALPHA_SIZE, alpha_size,
  10777. EGL_DEPTH_SIZE, 24,
  10778. EGL_STENCIL_SIZE, 8,
  10779. EGL_SAMPLE_BUFFERS, _sapp.desc.sample_count > 1 ? 1 : 0,
  10780. EGL_SAMPLES, sample_count,
  10781. EGL_NONE,
  10782. };
  10783. EGLConfig egl_configs[32];
  10784. EGLint config_count;
  10785. if (!eglChooseConfig(_sapp.egl.display, config_attrs, egl_configs, 32, &config_count) || config_count == 0) {
  10786. _SAPP_PANIC(LINUX_EGL_NO_CONFIGS);
  10787. }
  10788. EGLConfig config = egl_configs[0];
  10789. for (int i = 0; i < config_count; ++i) {
  10790. EGLConfig c = egl_configs[i];
  10791. EGLint r, g, b, a, d, s, n;
  10792. if (eglGetConfigAttrib(_sapp.egl.display, c, EGL_RED_SIZE, &r) &&
  10793. eglGetConfigAttrib(_sapp.egl.display, c, EGL_GREEN_SIZE, &g) &&
  10794. eglGetConfigAttrib(_sapp.egl.display, c, EGL_BLUE_SIZE, &b) &&
  10795. eglGetConfigAttrib(_sapp.egl.display, c, EGL_ALPHA_SIZE, &a) &&
  10796. eglGetConfigAttrib(_sapp.egl.display, c, EGL_DEPTH_SIZE, &d) &&
  10797. eglGetConfigAttrib(_sapp.egl.display, c, EGL_STENCIL_SIZE, &s) &&
  10798. eglGetConfigAttrib(_sapp.egl.display, c, EGL_SAMPLES, &n) &&
  10799. (r == 8) && (g == 8) && (b == 8) && (a == alpha_size) && (d == 24) && (s == 8) && (n == sample_count)) {
  10800. config = c;
  10801. break;
  10802. }
  10803. }
  10804. EGLint visual_id;
  10805. if (!eglGetConfigAttrib(_sapp.egl.display, config, EGL_NATIVE_VISUAL_ID, &visual_id)) {
  10806. _SAPP_PANIC(LINUX_EGL_NO_NATIVE_VISUAL);
  10807. }
  10808. XVisualInfo visual_info_template;
  10809. _sapp_clear(&visual_info_template, sizeof(visual_info_template));
  10810. visual_info_template.visualid = (VisualID)visual_id;
  10811. int num_visuals;
  10812. XVisualInfo* visual_info = XGetVisualInfo(_sapp.x11.display, VisualIDMask, &visual_info_template, &num_visuals);
  10813. if (!visual_info) {
  10814. _SAPP_PANIC(LINUX_EGL_GET_VISUAL_INFO_FAILED);
  10815. }
  10816. _sapp_x11_create_window(visual_info->visual, visual_info->depth);
  10817. XFree(visual_info);
  10818. _sapp.egl.surface = eglCreateWindowSurface(_sapp.egl.display, config, (EGLNativeWindowType)_sapp.x11.window, NULL);
  10819. if (EGL_NO_SURFACE == _sapp.egl.surface) {
  10820. _SAPP_PANIC(LINUX_EGL_CREATE_WINDOW_SURFACE_FAILED);
  10821. }
  10822. EGLint ctx_attrs[] = {
  10823. EGL_CONTEXT_MAJOR_VERSION, _sapp.desc.gl_major_version,
  10824. EGL_CONTEXT_MINOR_VERSION, _sapp.desc.gl_minor_version,
  10825. #if defined(SOKOL_GLCORE)
  10826. EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
  10827. #endif
  10828. EGL_NONE,
  10829. };
  10830. _sapp.egl.context = eglCreateContext(_sapp.egl.display, config, EGL_NO_CONTEXT, ctx_attrs);
  10831. if (EGL_NO_CONTEXT == _sapp.egl.context) {
  10832. _SAPP_PANIC(LINUX_EGL_CREATE_CONTEXT_FAILED);
  10833. }
  10834. if (!eglMakeCurrent(_sapp.egl.display, _sapp.egl.surface, _sapp.egl.surface, _sapp.egl.context)) {
  10835. _SAPP_PANIC(LINUX_EGL_MAKE_CURRENT_FAILED);
  10836. }
  10837. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  10838. eglSwapInterval(_sapp.egl.display, _sapp.swap_interval);
  10839. }
  10840. _SOKOL_PRIVATE void _sapp_egl_destroy(void) {
  10841. if (_sapp.egl.display != EGL_NO_DISPLAY) {
  10842. eglMakeCurrent(_sapp.egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  10843. if (_sapp.egl.context != EGL_NO_CONTEXT) {
  10844. eglDestroyContext(_sapp.egl.display, _sapp.egl.context);
  10845. _sapp.egl.context = EGL_NO_CONTEXT;
  10846. }
  10847. if (_sapp.egl.surface != EGL_NO_SURFACE) {
  10848. eglDestroySurface(_sapp.egl.display, _sapp.egl.surface);
  10849. _sapp.egl.surface = EGL_NO_SURFACE;
  10850. }
  10851. eglTerminate(_sapp.egl.display);
  10852. _sapp.egl.display = EGL_NO_DISPLAY;
  10853. }
  10854. }
  10855. #endif /* _SAPP_GLX */
  10856. _SOKOL_PRIVATE void _sapp_linux_run(const sapp_desc* desc) {
  10857. /* The following lines are here to trigger a linker error instead of an
  10858. obscure runtime error if the user has forgotten to add -pthread to
  10859. the compiler or linker options. They have no other purpose.
  10860. */
  10861. pthread_attr_t pthread_attr;
  10862. pthread_attr_init(&pthread_attr);
  10863. pthread_attr_destroy(&pthread_attr);
  10864. _sapp_init_state(desc);
  10865. _sapp.x11.window_state = NormalState;
  10866. XInitThreads();
  10867. XrmInitialize();
  10868. _sapp.x11.display = XOpenDisplay(NULL);
  10869. if (!_sapp.x11.display) {
  10870. _SAPP_PANIC(LINUX_X11_OPEN_DISPLAY_FAILED);
  10871. }
  10872. _sapp.x11.screen = DefaultScreen(_sapp.x11.display);
  10873. _sapp.x11.root = DefaultRootWindow(_sapp.x11.display);
  10874. _sapp_x11_query_system_dpi();
  10875. _sapp.dpi_scale = _sapp.x11.dpi / 96.0f;
  10876. _sapp_x11_init_extensions();
  10877. _sapp_x11_create_cursors();
  10878. XkbSetDetectableAutoRepeat(_sapp.x11.display, true, NULL);
  10879. _sapp_x11_init_keytable();
  10880. #if defined(_SAPP_GLX)
  10881. _sapp_glx_init();
  10882. Visual* visual = 0;
  10883. int depth = 0;
  10884. _sapp_glx_choose_visual(&visual, &depth);
  10885. _sapp_x11_create_window(visual, depth);
  10886. _sapp_glx_create_context();
  10887. _sapp_glx_swapinterval(_sapp.swap_interval);
  10888. #else
  10889. _sapp_egl_init();
  10890. #endif
  10891. sapp_set_icon(&desc->icon);
  10892. _sapp.valid = true;
  10893. _sapp_x11_show_window();
  10894. if (_sapp.fullscreen) {
  10895. _sapp_x11_set_fullscreen(true);
  10896. }
  10897. XFlush(_sapp.x11.display);
  10898. while (!_sapp.quit_ordered) {
  10899. _sapp_timing_measure(&_sapp.timing);
  10900. int count = XPending(_sapp.x11.display);
  10901. while (count--) {
  10902. XEvent event;
  10903. XNextEvent(_sapp.x11.display, &event);
  10904. _sapp_x11_process_event(&event);
  10905. }
  10906. _sapp_frame();
  10907. #if defined(_SAPP_GLX)
  10908. _sapp_glx_swap_buffers();
  10909. #else
  10910. eglSwapBuffers(_sapp.egl.display, _sapp.egl.surface);
  10911. #endif
  10912. XFlush(_sapp.x11.display);
  10913. /* handle quit-requested, either from window or from sapp_request_quit() */
  10914. if (_sapp.quit_requested && !_sapp.quit_ordered) {
  10915. /* give user code a chance to intervene */
  10916. _sapp_x11_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  10917. /* if user code hasn't intervened, quit the app */
  10918. if (_sapp.quit_requested) {
  10919. _sapp.quit_ordered = true;
  10920. }
  10921. }
  10922. }
  10923. _sapp_call_cleanup();
  10924. #if defined(_SAPP_GLX)
  10925. _sapp_glx_destroy_context();
  10926. #else
  10927. _sapp_egl_destroy();
  10928. #endif
  10929. _sapp_x11_destroy_window();
  10930. _sapp_x11_destroy_cursors();
  10931. XCloseDisplay(_sapp.x11.display);
  10932. _sapp_discard_state();
  10933. }
  10934. #if !defined(SOKOL_NO_ENTRY)
  10935. int main(int argc, char* argv[]) {
  10936. sapp_desc desc = sokol_main(argc, argv);
  10937. _sapp_linux_run(&desc);
  10938. return 0;
  10939. }
  10940. #endif /* SOKOL_NO_ENTRY */
  10941. #endif /* _SAPP_LINUX */
  10942. // ██████ ██ ██ ██████ ██ ██ ██████
  10943. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  10944. // ██████ ██ ██ ██████ ██ ██ ██
  10945. // ██ ██ ██ ██ ██ ██ ██ ██
  10946. // ██ ██████ ██████ ███████ ██ ██████
  10947. //
  10948. // >>public
  10949. #if defined(SOKOL_NO_ENTRY)
  10950. SOKOL_API_IMPL void sapp_run(const sapp_desc* desc) {
  10951. SOKOL_ASSERT(desc);
  10952. #if defined(_SAPP_MACOS)
  10953. _sapp_macos_run(desc);
  10954. #elif defined(_SAPP_IOS)
  10955. _sapp_ios_run(desc);
  10956. #elif defined(_SAPP_EMSCRIPTEN)
  10957. _sapp_emsc_run(desc);
  10958. #elif defined(_SAPP_WIN32)
  10959. _sapp_win32_run(desc);
  10960. #elif defined(_SAPP_LINUX)
  10961. _sapp_linux_run(desc);
  10962. #else
  10963. #error "sapp_run() not supported on this platform"
  10964. #endif
  10965. }
  10966. /* this is just a stub so the linker doesn't complain */
  10967. sapp_desc sokol_main(int argc, char* argv[]) {
  10968. _SOKOL_UNUSED(argc);
  10969. _SOKOL_UNUSED(argv);
  10970. sapp_desc desc;
  10971. _sapp_clear(&desc, sizeof(desc));
  10972. return desc;
  10973. }
  10974. #else
  10975. /* likewise, in normal mode, sapp_run() is just an empty stub */
  10976. SOKOL_API_IMPL void sapp_run(const sapp_desc* desc) {
  10977. _SOKOL_UNUSED(desc);
  10978. }
  10979. #endif
  10980. SOKOL_API_IMPL bool sapp_isvalid(void) {
  10981. return _sapp.valid;
  10982. }
  10983. SOKOL_API_IMPL void* sapp_userdata(void) {
  10984. return _sapp.desc.user_data;
  10985. }
  10986. SOKOL_API_IMPL sapp_desc sapp_query_desc(void) {
  10987. return _sapp.desc;
  10988. }
  10989. SOKOL_API_IMPL uint64_t sapp_frame_count(void) {
  10990. return _sapp.frame_count;
  10991. }
  10992. SOKOL_API_IMPL double sapp_frame_duration(void) {
  10993. return _sapp_timing_get_avg(&_sapp.timing);
  10994. }
  10995. SOKOL_API_IMPL int sapp_width(void) {
  10996. return (_sapp.framebuffer_width > 0) ? _sapp.framebuffer_width : 1;
  10997. }
  10998. SOKOL_API_IMPL float sapp_widthf(void) {
  10999. return (float)sapp_width();
  11000. }
  11001. SOKOL_API_IMPL int sapp_height(void) {
  11002. return (_sapp.framebuffer_height > 0) ? _sapp.framebuffer_height : 1;
  11003. }
  11004. SOKOL_API_IMPL float sapp_heightf(void) {
  11005. return (float)sapp_height();
  11006. }
  11007. SOKOL_API_IMPL int sapp_color_format(void) {
  11008. #if defined(SOKOL_WGPU)
  11009. switch (_sapp.wgpu.render_format) {
  11010. case WGPUTextureFormat_RGBA8Unorm:
  11011. return _SAPP_PIXELFORMAT_RGBA8;
  11012. case WGPUTextureFormat_BGRA8Unorm:
  11013. return _SAPP_PIXELFORMAT_BGRA8;
  11014. default:
  11015. SOKOL_UNREACHABLE;
  11016. return 0;
  11017. }
  11018. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  11019. return _SAPP_PIXELFORMAT_BGRA8;
  11020. #else
  11021. return _SAPP_PIXELFORMAT_RGBA8;
  11022. #endif
  11023. }
  11024. SOKOL_API_IMPL int sapp_depth_format(void) {
  11025. return _SAPP_PIXELFORMAT_DEPTH_STENCIL;
  11026. }
  11027. SOKOL_API_IMPL int sapp_sample_count(void) {
  11028. return _sapp.sample_count;
  11029. }
  11030. SOKOL_API_IMPL bool sapp_high_dpi(void) {
  11031. return _sapp.desc.high_dpi && (_sapp.dpi_scale >= 1.5f);
  11032. }
  11033. SOKOL_API_IMPL float sapp_dpi_scale(void) {
  11034. return _sapp.dpi_scale;
  11035. }
  11036. SOKOL_API_IMPL const void* sapp_egl_get_display(void) {
  11037. SOKOL_ASSERT(_sapp.valid);
  11038. #if defined(_SAPP_ANDROID)
  11039. return _sapp.android.display;
  11040. #elif defined(_SAPP_LINUX) && !defined(_SAPP_GLX)
  11041. return _sapp.egl.display;
  11042. #else
  11043. return 0;
  11044. #endif
  11045. }
  11046. SOKOL_API_IMPL const void* sapp_egl_get_context(void) {
  11047. SOKOL_ASSERT(_sapp.valid);
  11048. #if defined(_SAPP_ANDROID)
  11049. return _sapp.android.context;
  11050. #elif defined(_SAPP_LINUX) && !defined(_SAPP_GLX)
  11051. return _sapp.egl.context;
  11052. #else
  11053. return 0;
  11054. #endif
  11055. }
  11056. SOKOL_API_IMPL void sapp_show_keyboard(bool show) {
  11057. #if defined(_SAPP_IOS)
  11058. _sapp_ios_show_keyboard(show);
  11059. #elif defined(_SAPP_ANDROID)
  11060. _sapp_android_show_keyboard(show);
  11061. #else
  11062. _SOKOL_UNUSED(show);
  11063. #endif
  11064. }
  11065. SOKOL_API_IMPL bool sapp_keyboard_shown(void) {
  11066. return _sapp.onscreen_keyboard_shown;
  11067. }
  11068. SOKOL_API_IMPL bool sapp_is_fullscreen(void) {
  11069. return _sapp.fullscreen;
  11070. }
  11071. SOKOL_API_IMPL void sapp_toggle_fullscreen(void) {
  11072. #if defined(_SAPP_MACOS)
  11073. _sapp_macos_toggle_fullscreen();
  11074. #elif defined(_SAPP_WIN32)
  11075. _sapp_win32_toggle_fullscreen();
  11076. #elif defined(_SAPP_LINUX)
  11077. _sapp_x11_toggle_fullscreen();
  11078. #endif
  11079. }
  11080. /* NOTE that sapp_show_mouse() does not "stack" like the Win32 or macOS API functions! */
  11081. SOKOL_API_IMPL void sapp_show_mouse(bool show) {
  11082. if (_sapp.mouse.shown != show) {
  11083. #if defined(_SAPP_MACOS)
  11084. _sapp_macos_update_cursor(_sapp.mouse.current_cursor, show);
  11085. #elif defined(_SAPP_WIN32)
  11086. _sapp_win32_update_cursor(_sapp.mouse.current_cursor, show, false);
  11087. #elif defined(_SAPP_LINUX)
  11088. _sapp_x11_update_cursor(_sapp.mouse.current_cursor, show);
  11089. #elif defined(_SAPP_EMSCRIPTEN)
  11090. _sapp_emsc_update_cursor(_sapp.mouse.current_cursor, show);
  11091. #endif
  11092. _sapp.mouse.shown = show;
  11093. }
  11094. }
  11095. SOKOL_API_IMPL bool sapp_mouse_shown(void) {
  11096. return _sapp.mouse.shown;
  11097. }
  11098. SOKOL_API_IMPL void sapp_lock_mouse(bool lock) {
  11099. #if defined(_SAPP_MACOS)
  11100. _sapp_macos_lock_mouse(lock);
  11101. #elif defined(_SAPP_EMSCRIPTEN)
  11102. _sapp_emsc_lock_mouse(lock);
  11103. #elif defined(_SAPP_WIN32)
  11104. _sapp_win32_lock_mouse(lock);
  11105. #elif defined(_SAPP_LINUX)
  11106. _sapp_x11_lock_mouse(lock);
  11107. #else
  11108. _sapp.mouse.locked = lock;
  11109. #endif
  11110. }
  11111. SOKOL_API_IMPL bool sapp_mouse_locked(void) {
  11112. return _sapp.mouse.locked;
  11113. }
  11114. SOKOL_API_IMPL void sapp_set_mouse_cursor(sapp_mouse_cursor cursor) {
  11115. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  11116. if (_sapp.mouse.current_cursor != cursor) {
  11117. #if defined(_SAPP_MACOS)
  11118. _sapp_macos_update_cursor(cursor, _sapp.mouse.shown);
  11119. #elif defined(_SAPP_WIN32)
  11120. _sapp_win32_update_cursor(cursor, _sapp.mouse.shown, false);
  11121. #elif defined(_SAPP_LINUX)
  11122. _sapp_x11_update_cursor(cursor, _sapp.mouse.shown);
  11123. #elif defined(_SAPP_EMSCRIPTEN)
  11124. _sapp_emsc_update_cursor(cursor, _sapp.mouse.shown);
  11125. #endif
  11126. _sapp.mouse.current_cursor = cursor;
  11127. }
  11128. }
  11129. SOKOL_API_IMPL sapp_mouse_cursor sapp_get_mouse_cursor(void) {
  11130. return _sapp.mouse.current_cursor;
  11131. }
  11132. SOKOL_API_IMPL void sapp_request_quit(void) {
  11133. _sapp.quit_requested = true;
  11134. }
  11135. SOKOL_API_IMPL void sapp_cancel_quit(void) {
  11136. _sapp.quit_requested = false;
  11137. }
  11138. SOKOL_API_IMPL void sapp_quit(void) {
  11139. _sapp.quit_ordered = true;
  11140. }
  11141. SOKOL_API_IMPL void sapp_consume_event(void) {
  11142. _sapp.event_consumed = true;
  11143. }
  11144. /* NOTE: on HTML5, sapp_set_clipboard_string() must be called from within event handler! */
  11145. SOKOL_API_IMPL void sapp_set_clipboard_string(const char* str) {
  11146. if (!_sapp.clipboard.enabled) {
  11147. return;
  11148. }
  11149. SOKOL_ASSERT(str);
  11150. #if defined(_SAPP_MACOS)
  11151. _sapp_macos_set_clipboard_string(str);
  11152. #elif defined(_SAPP_EMSCRIPTEN)
  11153. _sapp_emsc_set_clipboard_string(str);
  11154. #elif defined(_SAPP_WIN32)
  11155. _sapp_win32_set_clipboard_string(str);
  11156. #elif defined(_SAPP_LINUX)
  11157. _sapp_x11_set_clipboard_string(str);
  11158. #else
  11159. /* not implemented */
  11160. #endif
  11161. _sapp_strcpy(str, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  11162. }
  11163. SOKOL_API_IMPL const char* sapp_get_clipboard_string(void) {
  11164. if (!_sapp.clipboard.enabled) {
  11165. return "";
  11166. }
  11167. #if defined(_SAPP_MACOS)
  11168. return _sapp_macos_get_clipboard_string();
  11169. #elif defined(_SAPP_EMSCRIPTEN)
  11170. return _sapp.clipboard.buffer;
  11171. #elif defined(_SAPP_WIN32)
  11172. return _sapp_win32_get_clipboard_string();
  11173. #elif defined(_SAPP_LINUX)
  11174. return _sapp_x11_get_clipboard_string();
  11175. #else
  11176. /* not implemented */
  11177. return _sapp.clipboard.buffer;
  11178. #endif
  11179. }
  11180. SOKOL_API_IMPL void sapp_set_window_title(const char* title) {
  11181. SOKOL_ASSERT(title);
  11182. _sapp_strcpy(title, _sapp.window_title, sizeof(_sapp.window_title));
  11183. #if defined(_SAPP_MACOS)
  11184. _sapp_macos_update_window_title();
  11185. #elif defined(_SAPP_WIN32)
  11186. _sapp_win32_update_window_title();
  11187. #elif defined(_SAPP_LINUX)
  11188. _sapp_x11_update_window_title();
  11189. #endif
  11190. }
  11191. SOKOL_API_IMPL void sapp_set_icon(const sapp_icon_desc* desc) {
  11192. SOKOL_ASSERT(desc);
  11193. if (desc->sokol_default) {
  11194. if (0 == _sapp.default_icon_pixels) {
  11195. _sapp_setup_default_icon();
  11196. }
  11197. SOKOL_ASSERT(0 != _sapp.default_icon_pixels);
  11198. desc = &_sapp.default_icon_desc;
  11199. }
  11200. const int num_images = _sapp_icon_num_images(desc);
  11201. if (num_images == 0) {
  11202. return;
  11203. }
  11204. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  11205. if (!_sapp_validate_icon_desc(desc, num_images)) {
  11206. return;
  11207. }
  11208. #if defined(_SAPP_MACOS)
  11209. _sapp_macos_set_icon(desc, num_images);
  11210. #elif defined(_SAPP_WIN32)
  11211. _sapp_win32_set_icon(desc, num_images);
  11212. #elif defined(_SAPP_LINUX)
  11213. _sapp_x11_set_icon(desc, num_images);
  11214. #elif defined(_SAPP_EMSCRIPTEN)
  11215. _sapp_emsc_set_icon(desc, num_images);
  11216. #endif
  11217. }
  11218. SOKOL_API_IMPL int sapp_get_num_dropped_files(void) {
  11219. SOKOL_ASSERT(_sapp.drop.enabled);
  11220. return _sapp.drop.num_files;
  11221. }
  11222. SOKOL_API_IMPL const char* sapp_get_dropped_file_path(int index) {
  11223. SOKOL_ASSERT(_sapp.drop.enabled);
  11224. SOKOL_ASSERT((index >= 0) && (index < _sapp.drop.num_files));
  11225. SOKOL_ASSERT(_sapp.drop.buffer);
  11226. if (!_sapp.drop.enabled) {
  11227. return "";
  11228. }
  11229. if ((index < 0) || (index >= _sapp.drop.max_files)) {
  11230. return "";
  11231. }
  11232. return (const char*) _sapp_dropped_file_path_ptr(index);
  11233. }
  11234. SOKOL_API_IMPL uint32_t sapp_html5_get_dropped_file_size(int index) {
  11235. SOKOL_ASSERT(_sapp.drop.enabled);
  11236. SOKOL_ASSERT((index >= 0) && (index < _sapp.drop.num_files));
  11237. #if defined(_SAPP_EMSCRIPTEN)
  11238. if (!_sapp.drop.enabled) {
  11239. return 0;
  11240. }
  11241. return sapp_js_dropped_file_size(index);
  11242. #else
  11243. (void)index;
  11244. return 0;
  11245. #endif
  11246. }
  11247. SOKOL_API_IMPL void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request) {
  11248. SOKOL_ASSERT(_sapp.drop.enabled);
  11249. SOKOL_ASSERT(request);
  11250. SOKOL_ASSERT(request->callback);
  11251. SOKOL_ASSERT(request->buffer.ptr);
  11252. SOKOL_ASSERT(request->buffer.size > 0);
  11253. #if defined(_SAPP_EMSCRIPTEN)
  11254. const int index = request->dropped_file_index;
  11255. sapp_html5_fetch_error error_code = SAPP_HTML5_FETCH_ERROR_NO_ERROR;
  11256. if ((index < 0) || (index >= _sapp.drop.num_files)) {
  11257. error_code = SAPP_HTML5_FETCH_ERROR_OTHER;
  11258. }
  11259. if (sapp_html5_get_dropped_file_size(index) > request->buffer.size) {
  11260. error_code = SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL;
  11261. }
  11262. if (SAPP_HTML5_FETCH_ERROR_NO_ERROR != error_code) {
  11263. _sapp_emsc_invoke_fetch_cb(index,
  11264. false, // success
  11265. (int)error_code,
  11266. request->callback,
  11267. 0, // fetched_size
  11268. (void*)request->buffer.ptr,
  11269. request->buffer.size,
  11270. request->user_data);
  11271. }
  11272. else {
  11273. sapp_js_fetch_dropped_file(index,
  11274. request->callback,
  11275. (void*)request->buffer.ptr,
  11276. request->buffer.size,
  11277. request->user_data);
  11278. }
  11279. #else
  11280. (void)request;
  11281. #endif
  11282. }
  11283. SOKOL_API_IMPL const void* sapp_metal_get_device(void) {
  11284. SOKOL_ASSERT(_sapp.valid);
  11285. #if defined(SOKOL_METAL)
  11286. #if defined(_SAPP_MACOS)
  11287. const void* obj = (__bridge const void*) _sapp.macos.mtl_device;
  11288. #else
  11289. const void* obj = (__bridge const void*) _sapp.ios.mtl_device;
  11290. #endif
  11291. SOKOL_ASSERT(obj);
  11292. return obj;
  11293. #else
  11294. return 0;
  11295. #endif
  11296. }
  11297. SOKOL_API_IMPL const void* sapp_metal_get_current_drawable(void) {
  11298. SOKOL_ASSERT(_sapp.valid);
  11299. #if defined(SOKOL_METAL)
  11300. #if defined(_SAPP_MACOS)
  11301. const void* obj = (__bridge const void*) [_sapp.macos.view currentDrawable];
  11302. #else
  11303. const void* obj = (__bridge const void*) [_sapp.ios.view currentDrawable];
  11304. #endif
  11305. SOKOL_ASSERT(obj);
  11306. return obj;
  11307. #else
  11308. return 0;
  11309. #endif
  11310. }
  11311. SOKOL_API_IMPL const void* sapp_metal_get_depth_stencil_texture(void) {
  11312. SOKOL_ASSERT(_sapp.valid);
  11313. #if defined(SOKOL_METAL)
  11314. #if defined(_SAPP_MACOS)
  11315. const void* obj = (__bridge const void*) [_sapp.macos.view depthStencilTexture];
  11316. #else
  11317. const void* obj = (__bridge const void*) [_sapp.ios.view depthStencilTexture];
  11318. #endif
  11319. return obj;
  11320. #else
  11321. return 0;
  11322. #endif
  11323. }
  11324. SOKOL_API_IMPL const void* sapp_metal_get_msaa_color_texture(void) {
  11325. SOKOL_ASSERT(_sapp.valid);
  11326. #if defined(SOKOL_METAL)
  11327. #if defined(_SAPP_MACOS)
  11328. const void* obj = (__bridge const void*) [_sapp.macos.view multisampleColorTexture];
  11329. #else
  11330. const void* obj = (__bridge const void*) [_sapp.ios.view multisampleColorTexture];
  11331. #endif
  11332. return obj;
  11333. #else
  11334. return 0;
  11335. #endif
  11336. }
  11337. SOKOL_API_IMPL const void* sapp_macos_get_window(void) {
  11338. #if defined(_SAPP_MACOS)
  11339. const void* obj = (__bridge const void*) _sapp.macos.window;
  11340. SOKOL_ASSERT(obj);
  11341. return obj;
  11342. #else
  11343. return 0;
  11344. #endif
  11345. }
  11346. SOKOL_API_IMPL const void* sapp_ios_get_window(void) {
  11347. #if defined(_SAPP_IOS)
  11348. const void* obj = (__bridge const void*) _sapp.ios.window;
  11349. SOKOL_ASSERT(obj);
  11350. return obj;
  11351. #else
  11352. return 0;
  11353. #endif
  11354. }
  11355. SOKOL_API_IMPL const void* sapp_d3d11_get_device(void) {
  11356. SOKOL_ASSERT(_sapp.valid);
  11357. #if defined(SOKOL_D3D11)
  11358. return _sapp.d3d11.device;
  11359. #else
  11360. return 0;
  11361. #endif
  11362. }
  11363. SOKOL_API_IMPL const void* sapp_d3d11_get_device_context(void) {
  11364. SOKOL_ASSERT(_sapp.valid);
  11365. #if defined(SOKOL_D3D11)
  11366. return _sapp.d3d11.device_context;
  11367. #else
  11368. return 0;
  11369. #endif
  11370. }
  11371. SOKOL_API_IMPL const void* sapp_d3d11_get_swap_chain(void) {
  11372. SOKOL_ASSERT(_sapp.valid);
  11373. #if defined(SOKOL_D3D11)
  11374. return _sapp.d3d11.swap_chain;
  11375. #else
  11376. return 0;
  11377. #endif
  11378. }
  11379. SOKOL_API_IMPL const void* sapp_d3d11_get_render_view(void) {
  11380. SOKOL_ASSERT(_sapp.valid);
  11381. #if defined(SOKOL_D3D11)
  11382. if (_sapp.sample_count > 1) {
  11383. SOKOL_ASSERT(_sapp.d3d11.msaa_rtv);
  11384. return _sapp.d3d11.msaa_rtv;
  11385. } else {
  11386. SOKOL_ASSERT(_sapp.d3d11.rtv);
  11387. return _sapp.d3d11.rtv;
  11388. }
  11389. #else
  11390. return 0;
  11391. #endif
  11392. }
  11393. SOKOL_API_IMPL const void* sapp_d3d11_get_resolve_view(void) {
  11394. SOKOL_ASSERT(_sapp.valid);
  11395. #if defined(SOKOL_D3D11)
  11396. if (_sapp.sample_count > 1) {
  11397. SOKOL_ASSERT(_sapp.d3d11.rtv);
  11398. return _sapp.d3d11.rtv;
  11399. } else {
  11400. return 0;
  11401. }
  11402. #else
  11403. return 0;
  11404. #endif
  11405. }
  11406. SOKOL_API_IMPL const void* sapp_d3d11_get_depth_stencil_view(void) {
  11407. SOKOL_ASSERT(_sapp.valid);
  11408. #if defined(SOKOL_D3D11)
  11409. return _sapp.d3d11.dsv;
  11410. #else
  11411. return 0;
  11412. #endif
  11413. }
  11414. SOKOL_API_IMPL const void* sapp_win32_get_hwnd(void) {
  11415. SOKOL_ASSERT(_sapp.valid);
  11416. #if defined(_SAPP_WIN32)
  11417. return _sapp.win32.hwnd;
  11418. #else
  11419. return 0;
  11420. #endif
  11421. }
  11422. SOKOL_API_IMPL const void* sapp_wgpu_get_device(void) {
  11423. SOKOL_ASSERT(_sapp.valid);
  11424. #if defined(SOKOL_WGPU)
  11425. return (const void*) _sapp.wgpu.device;
  11426. #else
  11427. return 0;
  11428. #endif
  11429. }
  11430. SOKOL_API_IMPL const void* sapp_wgpu_get_render_view(void) {
  11431. SOKOL_ASSERT(_sapp.valid);
  11432. #if defined(SOKOL_WGPU)
  11433. if (_sapp.sample_count > 1) {
  11434. SOKOL_ASSERT(_sapp.wgpu.msaa_view);
  11435. return (const void*) _sapp.wgpu.msaa_view;
  11436. } else {
  11437. SOKOL_ASSERT(_sapp.wgpu.swapchain_view);
  11438. return (const void*) _sapp.wgpu.swapchain_view;
  11439. }
  11440. #else
  11441. return 0;
  11442. #endif
  11443. }
  11444. SOKOL_API_IMPL const void* sapp_wgpu_get_resolve_view(void) {
  11445. SOKOL_ASSERT(_sapp.valid);
  11446. #if defined(SOKOL_WGPU)
  11447. if (_sapp.sample_count > 1) {
  11448. SOKOL_ASSERT(_sapp.wgpu.swapchain_view);
  11449. return (const void*) _sapp.wgpu.swapchain_view;
  11450. } else {
  11451. return 0;
  11452. }
  11453. #else
  11454. return 0;
  11455. #endif
  11456. }
  11457. SOKOL_API_IMPL const void* sapp_wgpu_get_depth_stencil_view(void) {
  11458. SOKOL_ASSERT(_sapp.valid);
  11459. #if defined(SOKOL_WGPU)
  11460. return (const void*) _sapp.wgpu.depth_stencil_view;
  11461. #else
  11462. return 0;
  11463. #endif
  11464. }
  11465. SOKOL_API_IMPL uint32_t sapp_gl_get_framebuffer(void) {
  11466. SOKOL_ASSERT(_sapp.valid);
  11467. #if defined(_SAPP_ANY_GL)
  11468. return _sapp.gl.framebuffer;
  11469. #else
  11470. return 0;
  11471. #endif
  11472. }
  11473. SOKOL_API_IMPL int sapp_gl_get_major_version(void) {
  11474. SOKOL_ASSERT(_sapp.valid);
  11475. #if defined(_SAPP_ANY_GL)
  11476. return _sapp.desc.gl_major_version;
  11477. #else
  11478. return 0;
  11479. #endif
  11480. }
  11481. SOKOL_API_IMPL int sapp_gl_get_minor_version(void) {
  11482. SOKOL_ASSERT(_sapp.valid);
  11483. #if defined(_SAPP_ANY_GL)
  11484. return _sapp.desc.gl_minor_version;
  11485. #else
  11486. return 0;
  11487. #endif
  11488. }
  11489. SOKOL_API_IMPL bool sapp_gl_is_gles(void) {
  11490. #if defined(SOKOL_GLES3)
  11491. return true;
  11492. #else
  11493. return false;
  11494. #endif
  11495. }
  11496. SOKOL_API_IMPL const void* sapp_x11_get_window(void) {
  11497. #if defined(_SAPP_LINUX)
  11498. return (void*)_sapp.x11.window;
  11499. #else
  11500. return 0;
  11501. #endif
  11502. }
  11503. SOKOL_API_IMPL const void* sapp_x11_get_display(void) {
  11504. #if defined(_SAPP_LINUX)
  11505. return (void*)_sapp.x11.display;
  11506. #else
  11507. return 0;
  11508. #endif
  11509. }
  11510. SOKOL_API_IMPL const void* sapp_android_get_native_activity(void) {
  11511. // NOTE: _sapp.valid is not asserted here because sapp_android_get_native_activity()
  11512. // needs to be callable from within sokol_main() (see: https://github.com/floooh/sokol/issues/708)
  11513. #if defined(_SAPP_ANDROID)
  11514. return (void*)_sapp.android.activity;
  11515. #else
  11516. return 0;
  11517. #endif
  11518. }
  11519. SOKOL_API_IMPL void sapp_html5_ask_leave_site(bool ask) {
  11520. _sapp.html5_ask_leave_site = ask;
  11521. }
  11522. #endif /* SOKOL_APP_IMPL */