sokol_app.h 472 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310
  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 SOKOL_WIN32_FORCE_MAIN or SOKOL_NO_ENTRY is defined)
  28. SOKOL_NO_ENTRY - define this if sokol_app.h shouldn't "hijack" the main() function
  29. SOKOL_APP_API_DECL - public function declaration prefix (default: extern)
  30. SOKOL_API_DECL - same as SOKOL_APP_API_DECL
  31. SOKOL_API_IMPL - public function implementation prefix (default: -)
  32. Optionally define the following to force debug checks and validations
  33. even in release mode:
  34. SOKOL_DEBUG - by default this is defined if _DEBUG is defined
  35. If sokol_app.h is compiled as a DLL, define the following before
  36. including the declaration or implementation:
  37. SOKOL_DLL
  38. On Windows, SOKOL_DLL will define SOKOL_APP_API_DECL as __declspec(dllexport)
  39. or __declspec(dllimport) as needed.
  40. if SOKOL_WIN32_FORCE_MAIN and SOKOL_WIN32_FORCE_WINMAIN are both defined,
  41. it is up to the developer to define the desired subsystem.
  42. On Linux, SOKOL_GLCORE can use either GLX or EGL.
  43. GLX is default, set SOKOL_FORCE_EGL to override.
  44. For example code, see https://github.com/floooh/sokol-samples/tree/master/sapp
  45. Portions of the Windows and Linux GL initialization, event-, icon- etc... code
  46. have been taken from GLFW (http://www.glfw.org/).
  47. iOS onscreen keyboard support 'inspired' by libgdx.
  48. Link with the following system libraries:
  49. - on macOS with Metal: Cocoa, QuartzCore, Metal, MetalKit
  50. - on macOS with GL: Cocoa, QuartzCore, OpenGL
  51. - on iOS with Metal: Foundation, UIKit, Metal, MetalKit
  52. - on iOS with GL: Foundation, UIKit, OpenGLES, GLKit
  53. - on Linux with EGL: X11, Xi, Xcursor, EGL, GL (or GLESv2), dl, pthread, m(?)
  54. - on Linux with GLX: X11, Xi, Xcursor, GL, dl, pthread, m(?)
  55. - on Android: GLESv3, EGL, log, android
  56. - on Windows with the MSVC or Clang toolchains: no action needed, libs are defined in-source via pragma-comment-lib
  57. - on Windows with MINGW/MSYS2 gcc: compile with '-mwin32' so that _WIN32 is defined
  58. - link with the following libs: -lkernel32 -luser32 -lshell32
  59. - additionally with the GL backend: -lgdi32
  60. - additionally with the D3D11 backend: -ld3d11 -ldxgi
  61. On Linux, you also need to use the -pthread compiler and linker option, otherwise weird
  62. things will happen, see here for details: https://github.com/floooh/sokol/issues/376
  63. On macOS and iOS, the implementation must be compiled as Objective-C.
  64. FEATURE OVERVIEW
  65. ================
  66. sokol_app.h provides a minimalistic cross-platform API which
  67. implements the 'application-wrapper' parts of a 3D application:
  68. - a common application entry function
  69. - creates a window and 3D-API context/device with a 'default framebuffer'
  70. - makes the rendered frame visible
  71. - provides keyboard-, mouse- and low-level touch-events
  72. - platforms: MacOS, iOS, HTML5, Win32, Linux/RaspberryPi, Android
  73. - 3D-APIs: Metal, D3D11, GL4.1, GL4.3, GLES3, WebGL, WebGL2, NOAPI
  74. FEATURE/PLATFORM MATRIX
  75. =======================
  76. | Windows | macOS | Linux | iOS | Android | HTML5
  77. --------------------+---------+-------+-------+-------+---------+--------
  78. gl 4.x | YES | YES | YES | --- | --- | ---
  79. gles3/webgl2 | --- | --- | YES(2)| YES | YES | YES
  80. metal | --- | YES | --- | YES | --- | ---
  81. d3d11 | YES | --- | --- | --- | --- | ---
  82. noapi | YES | TODO | TODO | --- | TODO | ---
  83. KEY_DOWN | YES | YES | YES | SOME | TODO | YES
  84. KEY_UP | YES | YES | YES | SOME | TODO | YES
  85. CHAR | YES | YES | YES | YES | TODO | YES
  86. MOUSE_DOWN | YES | YES | YES | --- | --- | YES
  87. MOUSE_UP | YES | YES | YES | --- | --- | YES
  88. MOUSE_SCROLL | YES | YES | YES | --- | --- | YES
  89. MOUSE_MOVE | YES | YES | YES | --- | --- | YES
  90. MOUSE_ENTER | YES | YES | YES | --- | --- | YES
  91. MOUSE_LEAVE | YES | YES | YES | --- | --- | YES
  92. TOUCHES_BEGAN | --- | --- | --- | YES | YES | YES
  93. TOUCHES_MOVED | --- | --- | --- | YES | YES | YES
  94. TOUCHES_ENDED | --- | --- | --- | YES | YES | YES
  95. TOUCHES_CANCELLED | --- | --- | --- | YES | YES | YES
  96. RESIZED | YES | YES | YES | YES | YES | YES
  97. ICONIFIED | YES | YES | YES | --- | --- | ---
  98. RESTORED | YES | YES | YES | --- | --- | ---
  99. FOCUSED | YES | YES | YES | --- | --- | YES
  100. UNFOCUSED | YES | YES | YES | --- | --- | YES
  101. SUSPENDED | --- | --- | --- | YES | YES | TODO
  102. RESUMED | --- | --- | --- | YES | YES | TODO
  103. QUIT_REQUESTED | YES | YES | YES | --- | --- | YES
  104. IME | TODO | TODO? | TODO | ??? | TODO | ???
  105. key repeat flag | YES | YES | YES | --- | --- | YES
  106. windowed | YES | YES | YES | --- | --- | YES
  107. fullscreen | YES | YES | YES | YES | YES | ---
  108. mouse hide | YES | YES | YES | --- | --- | YES
  109. mouse lock | YES | YES | YES | --- | --- | YES
  110. set cursor type | YES | YES | YES | --- | --- | YES
  111. screen keyboard | --- | --- | --- | YES | TODO | YES
  112. swap interval | YES | YES | YES | YES | TODO | YES
  113. high-dpi | YES | YES | TODO | YES | YES | YES
  114. clipboard | YES | YES | YES | --- | --- | YES
  115. MSAA | YES | YES | YES | YES | YES | YES
  116. drag'n'drop | YES | YES | YES | --- | --- | YES
  117. window icon | YES | YES(1)| YES | --- | --- | YES
  118. (1) macOS has no regular window icons, instead the dock icon is changed
  119. (2) supported with EGL only (not GLX)
  120. STEP BY STEP
  121. ============
  122. --- Add a sokol_main() function to your code which returns a sapp_desc structure
  123. with initialization parameters and callback function pointers. This
  124. function is called very early, usually at the start of the
  125. platform's entry function (e.g. main or WinMain). You should do as
  126. little as possible here, since the rest of your code might be called
  127. from another thread (this depends on the platform):
  128. sapp_desc sokol_main(int argc, char* argv[]) {
  129. return (sapp_desc) {
  130. .width = 640,
  131. .height = 480,
  132. .init_cb = my_init_func,
  133. .frame_cb = my_frame_func,
  134. .cleanup_cb = my_cleanup_func,
  135. .event_cb = my_event_func,
  136. ...
  137. };
  138. }
  139. To get any logging output in case of errors you need to provide a log
  140. callback. The easiest way is via sokol_log.h:
  141. #include "sokol_log.h"
  142. sapp_desc sokol_main(int argc, char* argv[]) {
  143. return (sapp_desc) {
  144. ...
  145. .logger.func = slog_func,
  146. };
  147. }
  148. There are many more setup parameters, but these are the most important.
  149. For a complete list search for the sapp_desc structure declaration
  150. below.
  151. DO NOT call any sokol-app function from inside sokol_main(), since
  152. sokol-app will not be initialized at this point.
  153. The .width and .height parameters are the preferred size of the 3D
  154. rendering canvas. The actual size may differ from this depending on
  155. platform and other circumstances. Also the canvas size may change at
  156. any time (for instance when the user resizes the application window,
  157. or rotates the mobile device). You can just keep .width and .height
  158. zero-initialized to open a default-sized window (what "default-size"
  159. exactly means is platform-specific, but usually it's a size that covers
  160. most of, but not all, of the display).
  161. All provided function callbacks will be called from the same thread,
  162. but this may be different from the thread where sokol_main() was called.
  163. .init_cb (void (*)(void))
  164. This function is called once after the application window,
  165. 3D rendering context and swap chain have been created. The
  166. function takes no arguments and has no return value.
  167. .frame_cb (void (*)(void))
  168. This is the per-frame callback, which is usually called 60
  169. times per second. This is where your application would update
  170. most of its state and perform all rendering.
  171. .cleanup_cb (void (*)(void))
  172. The cleanup callback is called once right before the application
  173. quits.
  174. .event_cb (void (*)(const sapp_event* event))
  175. The event callback is mainly for input handling, but is also
  176. used to communicate other types of events to the application. Keep the
  177. event_cb struct member zero-initialized if your application doesn't require
  178. event handling.
  179. As you can see, those 'standard callbacks' don't have a user_data
  180. argument, so any data that needs to be preserved between callbacks
  181. must live in global variables. If keeping state in global variables
  182. is not an option, there's an alternative set of callbacks with
  183. an additional user_data pointer argument:
  184. .user_data (void*)
  185. The user-data argument for the callbacks below
  186. .init_userdata_cb (void (*)(void* user_data))
  187. .frame_userdata_cb (void (*)(void* user_data))
  188. .cleanup_userdata_cb (void (*)(void* user_data))
  189. .event_userdata_cb (void(*)(const sapp_event* event, void* user_data))
  190. The function sapp_userdata() can be used to query the user_data
  191. pointer provided in the sapp_desc struct.
  192. You can also call sapp_query_desc() to get a copy of the
  193. original sapp_desc structure.
  194. NOTE that there's also an alternative compile mode where sokol_app.h
  195. doesn't "hijack" the main() function. Search below for SOKOL_NO_ENTRY.
  196. --- Implement the initialization callback function (init_cb), this is called
  197. once after the rendering surface, 3D API and swap chain have been
  198. initialized by sokol_app. All sokol-app functions can be called
  199. from inside the initialization callback, the most useful functions
  200. at this point are:
  201. int sapp_width(void)
  202. int sapp_height(void)
  203. Returns the current width and height of the default framebuffer in pixels,
  204. this may change from one frame to the next, and it may be different
  205. from the initial size provided in the sapp_desc struct.
  206. float sapp_widthf(void)
  207. float sapp_heightf(void)
  208. These are alternatives to sapp_width() and sapp_height() which return
  209. the default framebuffer size as float values instead of integer. This
  210. may help to prevent casting back and forth between int and float
  211. in more strongly typed languages than C and C++.
  212. double sapp_frame_duration(void)
  213. Returns the frame duration in seconds averaged over a number of
  214. frames to smooth out any jittering spikes.
  215. int sapp_color_format(void)
  216. int sapp_depth_format(void)
  217. The color and depth-stencil pixelformats of the default framebuffer,
  218. as integer values which are compatible with sokol-gfx's
  219. sg_pixel_format enum (so that they can be plugged directly in places
  220. where sg_pixel_format is expected). Possible values are:
  221. 23 == SG_PIXELFORMAT_RGBA8
  222. 28 == SG_PIXELFORMAT_BGRA8
  223. 42 == SG_PIXELFORMAT_DEPTH
  224. 43 == SG_PIXELFORMAT_DEPTH_STENCIL
  225. int sapp_sample_count(void)
  226. Return the MSAA sample count of the default framebuffer.
  227. const void* sapp_metal_get_device(void)
  228. const void* sapp_metal_get_current_drawable(void)
  229. const void* sapp_metal_get_depth_stencil_texture(void)
  230. const void* sapp_metal_get_msaa_color_texture(void)
  231. If the Metal backend has been selected, these functions return pointers
  232. to various Metal API objects required for rendering, otherwise
  233. they return a null pointer. These void pointers are actually
  234. Objective-C ids converted with a (ARC) __bridge cast so that
  235. the ids can be tunneled through C code. Also note that the returned
  236. pointers may change from one frame to the next, only the Metal device
  237. object is guaranteed to stay the same.
  238. const void* sapp_macos_get_window(void)
  239. On macOS, get the NSWindow object pointer, otherwise a null pointer.
  240. Before being used as Objective-C object, the void* must be converted
  241. back with a (ARC) __bridge cast.
  242. const void* sapp_ios_get_window(void)
  243. On iOS, get the UIWindow object pointer, otherwise a null pointer.
  244. Before being used as Objective-C object, the void* must be converted
  245. back with a (ARC) __bridge cast.
  246. const void* sapp_d3d11_get_device(void)
  247. const void* sapp_d3d11_get_device_context(void)
  248. const void* sapp_d3d11_get_render_view(void)
  249. const void* sapp_d3d11_get_resolve_view(void);
  250. const void* sapp_d3d11_get_depth_stencil_view(void)
  251. Similar to the sapp_metal_* functions, the sapp_d3d11_* functions
  252. return pointers to D3D11 API objects required for rendering,
  253. only if the D3D11 backend has been selected. Otherwise they
  254. return a null pointer. Note that the returned pointers to the
  255. render-target-view and depth-stencil-view may change from one
  256. frame to the next!
  257. const void* sapp_win32_get_hwnd(void)
  258. On Windows, get the window's HWND, otherwise a null pointer. The
  259. HWND has been cast to a void pointer in order to be tunneled
  260. through code which doesn't include Windows.h.
  261. const void* sapp_wgpu_get_device(void)
  262. const void* sapp_wgpu_get_render_view(void)
  263. const void* sapp_wgpu_get_resolve_view(void)
  264. const void* sapp_wgpu_get_depth_stencil_view(void)
  265. These are the WebGPU-specific functions to get the WebGPU
  266. objects and values required for rendering. If sokol_app.h
  267. is not compiled with SOKOL_WGPU, these functions return null.
  268. uint32_t sapp_gl_get_framebuffer(void)
  269. This returns the 'default framebuffer' of the GL context.
  270. Typically this will be zero.
  271. int sapp_gl_get_major_version(void)
  272. int sapp_gl_get_minor_version(void)
  273. Returns the major and minor version of the GL context
  274. (only for SOKOL_GLCORE, all other backends return zero here, including SOKOL_GLES3)
  275. const void* sapp_android_get_native_activity(void);
  276. On Android, get the native activity ANativeActivity pointer, otherwise
  277. a null pointer.
  278. --- Implement the frame-callback function, this function will be called
  279. on the same thread as the init callback, but might be on a different
  280. thread than the sokol_main() function. Note that the size of
  281. the rendering framebuffer might have changed since the frame callback
  282. was called last. Call the functions sapp_width() and sapp_height()
  283. each frame to get the current size.
  284. --- Optionally implement the event-callback to handle input events.
  285. sokol-app provides the following type of input events:
  286. - a 'virtual key' was pressed down or released
  287. - a single text character was entered (provided as UTF-32 encoded
  288. UNICODE code point)
  289. - a mouse button was pressed down or released (left, right, middle)
  290. - mouse-wheel or 2D scrolling events
  291. - the mouse was moved
  292. - the mouse has entered or left the application window boundaries
  293. - low-level, portable multi-touch events (began, moved, ended, cancelled)
  294. - the application window was resized, iconified or restored
  295. - the application was suspended or restored (on mobile platforms)
  296. - the user or application code has asked to quit the application
  297. - a string was pasted to the system clipboard
  298. - one or more files have been dropped onto the application window
  299. To explicitly 'consume' an event and prevent that the event is
  300. forwarded for further handling to the operating system, call
  301. sapp_consume_event() from inside the event handler (NOTE that
  302. this behaviour is currently only implemented for some HTML5
  303. events, support for other platforms and event types will
  304. be added as needed, please open a GitHub ticket and/or provide
  305. a PR if needed).
  306. NOTE: Do *not* call any 3D API rendering functions in the event
  307. callback function, since the 3D API context may not be active when the
  308. event callback is called (it may work on some platforms and 3D APIs,
  309. but not others, and the exact behaviour may change between
  310. sokol-app versions).
  311. --- Implement the cleanup-callback function, this is called once
  312. after the user quits the application (see the section
  313. "APPLICATION QUIT" for detailed information on quitting
  314. behaviour, and how to intercept a pending quit - for instance to show a
  315. "Really Quit?" dialog box). Note that the cleanup-callback isn't
  316. guaranteed to be called on the web and mobile platforms.
  317. MOUSE CURSOR TYPE AND VISIBILITY
  318. ================================
  319. You can show and hide the mouse cursor with
  320. void sapp_show_mouse(bool show)
  321. And to get the current shown status:
  322. bool sapp_mouse_shown(void)
  323. NOTE that hiding the mouse cursor is different and independent from
  324. the MOUSE/POINTER LOCK feature which will also hide the mouse pointer when
  325. active (MOUSE LOCK is described below).
  326. To change the mouse cursor to one of several predefined types, call
  327. the function:
  328. void sapp_set_mouse_cursor(sapp_mouse_cursor cursor)
  329. Setting the default mouse cursor SAPP_MOUSECURSOR_DEFAULT will restore
  330. the standard look.
  331. To get the currently active mouse cursor type, call:
  332. sapp_mouse_cursor sapp_get_mouse_cursor(void)
  333. MOUSE LOCK (AKA POINTER LOCK, AKA MOUSE CAPTURE)
  334. ================================================
  335. In normal mouse mode, no mouse movement events are reported when the
  336. mouse leaves the windows client area or hits the screen border (whether
  337. it's one or the other depends on the platform), and the mouse move events
  338. (SAPP_EVENTTYPE_MOUSE_MOVE) contain absolute mouse positions in
  339. framebuffer pixels in the sapp_event items mouse_x and mouse_y, and
  340. relative movement in framebuffer pixels in the sapp_event items mouse_dx
  341. and mouse_dy.
  342. To get continuous mouse movement (also when the mouse leaves the window
  343. client area or hits the screen border), activate mouse-lock mode
  344. by calling:
  345. sapp_lock_mouse(true)
  346. When mouse lock is activated, the mouse pointer is hidden, the
  347. reported absolute mouse position (sapp_event.mouse_x/y) appears
  348. frozen, and the relative mouse movement in sapp_event.mouse_dx/dy
  349. no longer has a direct relation to framebuffer pixels but instead
  350. uses "raw mouse input" (what "raw mouse input" exactly means also
  351. differs by platform).
  352. To deactivate mouse lock and return to normal mouse mode, call
  353. sapp_lock_mouse(false)
  354. And finally, to check if mouse lock is currently active, call
  355. if (sapp_mouse_locked()) { ... }
  356. On native platforms, the sapp_lock_mouse() and sapp_mouse_locked()
  357. functions work as expected (mouse lock is activated or deactivated
  358. immediately when sapp_lock_mouse() is called, and sapp_mouse_locked()
  359. also immediately returns the new state after sapp_lock_mouse()
  360. is called.
  361. On the web platform, sapp_lock_mouse() and sapp_mouse_locked() behave
  362. differently, as dictated by the limitations of the HTML5 Pointer Lock API:
  363. - sapp_lock_mouse(true) can be called at any time, but it will
  364. only take effect in a 'short-lived input event handler of a specific
  365. type', meaning when one of the following events happens:
  366. - SAPP_EVENTTYPE_MOUSE_DOWN
  367. - SAPP_EVENTTYPE_MOUSE_UP
  368. - SAPP_EVENTTYPE_MOUSE_SCROLL
  369. - SAPP_EVENTTYPE_KEY_UP
  370. - SAPP_EVENTTYPE_KEY_DOWN
  371. - The mouse lock/unlock action on the web platform is asynchronous,
  372. this means that sapp_mouse_locked() won't immediately return
  373. the new status after calling sapp_lock_mouse(), instead the
  374. reported status will only change when the pointer lock has actually
  375. been activated or deactivated in the browser.
  376. - On the web, mouse lock can be deactivated by the user at any time
  377. by pressing the Esc key. When this happens, sokol_app.h behaves
  378. the same as if sapp_lock_mouse(false) is called.
  379. For things like camera manipulation it's most straightforward to lock
  380. and unlock the mouse right from the sokol_app.h event handler, for
  381. instance the following code enters and leaves mouse lock when the
  382. left mouse button is pressed and released, and then uses the relative
  383. movement information to manipulate a camera (taken from the
  384. cgltf-sapp.c sample in the sokol-samples repository
  385. at https://github.com/floooh/sokol-samples):
  386. static void input(const sapp_event* ev) {
  387. switch (ev->type) {
  388. case SAPP_EVENTTYPE_MOUSE_DOWN:
  389. if (ev->mouse_button == SAPP_MOUSEBUTTON_LEFT) {
  390. sapp_lock_mouse(true);
  391. }
  392. break;
  393. case SAPP_EVENTTYPE_MOUSE_UP:
  394. if (ev->mouse_button == SAPP_MOUSEBUTTON_LEFT) {
  395. sapp_lock_mouse(false);
  396. }
  397. break;
  398. case SAPP_EVENTTYPE_MOUSE_MOVE:
  399. if (sapp_mouse_locked()) {
  400. cam_orbit(&state.camera, ev->mouse_dx * 0.25f, ev->mouse_dy * 0.25f);
  401. }
  402. break;
  403. default:
  404. break;
  405. }
  406. }
  407. CLIPBOARD SUPPORT
  408. =================
  409. Applications can send and receive UTF-8 encoded text data from and to the
  410. system clipboard. By default, clipboard support is disabled and
  411. must be enabled at startup via the following sapp_desc struct
  412. members:
  413. sapp_desc.enable_clipboard - set to true to enable clipboard support
  414. sapp_desc.clipboard_size - size of the internal clipboard buffer in bytes
  415. Enabling the clipboard will dynamically allocate a clipboard buffer
  416. for UTF-8 encoded text data of the requested size in bytes, the default
  417. size is 8 KBytes. Strings that don't fit into the clipboard buffer
  418. (including the terminating zero) will be silently clipped, so it's
  419. important that you provide a big enough clipboard size for your
  420. use case.
  421. To send data to the clipboard, call sapp_set_clipboard_string() with
  422. a pointer to an UTF-8 encoded, null-terminated C-string.
  423. NOTE that on the HTML5 platform, sapp_set_clipboard_string() must be
  424. called from inside a 'short-lived event handler', and there are a few
  425. other HTML5-specific caveats to workaround. You'll basically have to
  426. tinker until it works in all browsers :/ (maybe the situation will
  427. improve when all browsers agree on and implement the new
  428. HTML5 navigator.clipboard API).
  429. To get data from the clipboard, check for the SAPP_EVENTTYPE_CLIPBOARD_PASTED
  430. event in your event handler function, and then call sapp_get_clipboard_string()
  431. to obtain the pasted UTF-8 encoded text.
  432. NOTE that behaviour of sapp_get_clipboard_string() is slightly different
  433. depending on platform:
  434. - on the HTML5 platform, the internal clipboard buffer will only be updated
  435. right before the SAPP_EVENTTYPE_CLIPBOARD_PASTED event is sent,
  436. and sapp_get_clipboard_string() will simply return the current content
  437. of the clipboard buffer
  438. - on 'native' platforms, the call to sapp_get_clipboard_string() will
  439. update the internal clipboard buffer with the most recent data
  440. from the system clipboard
  441. Portable code should check for the SAPP_EVENTTYPE_CLIPBOARD_PASTED event,
  442. and then call sapp_get_clipboard_string() right in the event handler.
  443. The SAPP_EVENTTYPE_CLIPBOARD_PASTED event will be generated by sokol-app
  444. as follows:
  445. - on macOS: when the Cmd+V key is pressed down
  446. - on HTML5: when the browser sends a 'paste' event to the global 'window' object
  447. - on all other platforms: when the Ctrl+V key is pressed down
  448. DRAG AND DROP SUPPORT
  449. =====================
  450. PLEASE NOTE: the drag'n'drop feature works differently on WASM/HTML5
  451. and on the native desktop platforms (Win32, Linux and macOS) because
  452. of security-related restrictions in the HTML5 drag'n'drop API. The
  453. WASM/HTML5 specifics are described at the end of this documentation
  454. section:
  455. Like clipboard support, drag'n'drop support must be explicitly enabled
  456. at startup in the sapp_desc struct.
  457. sapp_desc sokol_main(void) {
  458. return (sapp_desc) {
  459. .enable_dragndrop = true, // default is false
  460. ...
  461. };
  462. }
  463. You can also adjust the maximum number of files that are accepted
  464. in a drop operation, and the maximum path length in bytes if needed:
  465. sapp_desc sokol_main(void) {
  466. return (sapp_desc) {
  467. .enable_dragndrop = true, // default is false
  468. .max_dropped_files = 8, // default is 1
  469. .max_dropped_file_path_length = 8192, // in bytes, default is 2048
  470. ...
  471. };
  472. }
  473. When drag'n'drop is enabled, the event callback will be invoked with an
  474. event of type SAPP_EVENTTYPE_FILES_DROPPED whenever the user drops files on
  475. the application window.
  476. After the SAPP_EVENTTYPE_FILES_DROPPED is received, you can query the
  477. number of dropped files, and their absolute paths by calling separate
  478. functions:
  479. void on_event(const sapp_event* ev) {
  480. if (ev->type == SAPP_EVENTTYPE_FILES_DROPPED) {
  481. // the mouse position where the drop happened
  482. float x = ev->mouse_x;
  483. float y = ev->mouse_y;
  484. // get the number of files and their paths like this:
  485. const int num_dropped_files = sapp_get_num_dropped_files();
  486. for (int i = 0; i < num_dropped_files; i++) {
  487. const char* path = sapp_get_dropped_file_path(i);
  488. ...
  489. }
  490. }
  491. }
  492. The returned file paths are UTF-8 encoded strings.
  493. You can call sapp_get_num_dropped_files() and sapp_get_dropped_file_path()
  494. anywhere, also outside the event handler callback, but be aware that the
  495. file path strings will be overwritten with the next drop operation.
  496. In any case, sapp_get_dropped_file_path() will never return a null pointer,
  497. instead an empty string "" will be returned if the drag'n'drop feature
  498. hasn't been enabled, the last drop-operation failed, or the file path index
  499. is out of range.
  500. Drag'n'drop caveats:
  501. - if more files are dropped in a single drop-action
  502. than sapp_desc.max_dropped_files, the additional
  503. files will be silently ignored
  504. - if any of the file paths is longer than
  505. sapp_desc.max_dropped_file_path_length (in number of bytes, after UTF-8
  506. encoding) the entire drop operation will be silently ignored (this
  507. needs some sort of error feedback in the future)
  508. - no mouse positions are reported while the drag is in
  509. process, this may change in the future
  510. Drag'n'drop on HTML5/WASM:
  511. The HTML5 drag'n'drop API doesn't return file paths, but instead
  512. black-box 'file objects' which must be used to load the content
  513. of dropped files. This is the reason why sokol_app.h adds two
  514. HTML5-specific functions to the drag'n'drop API:
  515. uint32_t sapp_html5_get_dropped_file_size(int index)
  516. Returns the size in bytes of a dropped file.
  517. void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request)
  518. Asynchronously loads the content of a dropped file into a
  519. provided memory buffer (which must be big enough to hold
  520. the file content)
  521. To start loading the first dropped file after an SAPP_EVENTTYPE_FILES_DROPPED
  522. event is received:
  523. sapp_html5_fetch_dropped_file(&(sapp_html5_fetch_request){
  524. .dropped_file_index = 0,
  525. .callback = fetch_cb
  526. .buffer = {
  527. .ptr = buf,
  528. .size = sizeof(buf)
  529. },
  530. .user_data = ...
  531. });
  532. Make sure that the memory pointed to by 'buf' stays valid until the
  533. callback function is called!
  534. As result of the asynchronous loading operation (no matter if succeeded or
  535. failed) the 'fetch_cb' function will be called:
  536. void fetch_cb(const sapp_html5_fetch_response* response) {
  537. // IMPORTANT: check if the loading operation actually succeeded:
  538. if (response->succeeded) {
  539. // the size of the loaded file:
  540. const size_t num_bytes = response->data.size;
  541. // and the pointer to the data (same as 'buf' in the fetch-call):
  542. const void* ptr = response->data.ptr;
  543. }
  544. else {
  545. // on error check the error code:
  546. switch (response->error_code) {
  547. case SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL:
  548. ...
  549. break;
  550. case SAPP_HTML5_FETCH_ERROR_OTHER:
  551. ...
  552. break;
  553. }
  554. }
  555. }
  556. Check the droptest-sapp example for a real-world example which works
  557. both on native platforms and the web:
  558. https://github.com/floooh/sokol-samples/blob/master/sapp/droptest-sapp.c
  559. HIGH-DPI RENDERING
  560. ==================
  561. You can set the sapp_desc.high_dpi flag during initialization to request
  562. a full-resolution framebuffer on HighDPI displays. The default behaviour
  563. is sapp_desc.high_dpi=false, this means that the application will
  564. render to a lower-resolution framebuffer on HighDPI displays and the
  565. rendered content will be upscaled by the window system composer.
  566. In a HighDPI scenario, you still request the same window size during
  567. sokol_main(), but the framebuffer sizes returned by sapp_width()
  568. and sapp_height() will be scaled up according to the DPI scaling
  569. ratio.
  570. Note that on some platforms the DPI scaling factor may change at any
  571. time (for instance when a window is moved from a high-dpi display
  572. to a low-dpi display).
  573. To query the current DPI scaling factor, call the function:
  574. float sapp_dpi_scale(void);
  575. For instance on a Retina Mac, returning the following sapp_desc
  576. struct from sokol_main():
  577. sapp_desc sokol_main(void) {
  578. return (sapp_desc) {
  579. .width = 640,
  580. .height = 480,
  581. .high_dpi = true,
  582. ...
  583. };
  584. }
  585. ...the functions the functions sapp_width(), sapp_height()
  586. and sapp_dpi_scale() will return the following values:
  587. sapp_width: 1280
  588. sapp_height: 960
  589. sapp_dpi_scale: 2.0
  590. If the high_dpi flag is false, or you're not running on a Retina display,
  591. the values would be:
  592. sapp_width: 640
  593. sapp_height: 480
  594. sapp_dpi_scale: 1.0
  595. If the window is moved from the Retina display to a low-dpi external display,
  596. the values would change as follows:
  597. sapp_width: 1280 => 640
  598. sapp_height: 960 => 480
  599. sapp_dpi_scale: 2.0 => 1.0
  600. Currently there is no event associated with a DPI change, but an
  601. SAPP_EVENTTYPE_RESIZED will be sent as a side effect of the
  602. framebuffer size changing.
  603. Per-monitor DPI is currently supported on macOS and Windows.
  604. APPLICATION QUIT
  605. ================
  606. Without special quit handling, a sokol_app.h application will quit
  607. 'gracefully' when the user clicks the window close-button unless a
  608. platform's application model prevents this (e.g. on web or mobile).
  609. 'Graceful exit' means that the application-provided cleanup callback will
  610. be called before the application quits.
  611. On native desktop platforms sokol_app.h provides more control over the
  612. application-quit-process. It's possible to initiate a 'programmatic quit'
  613. from the application code, and a quit initiated by the application user can
  614. be intercepted (for instance to show a custom dialog box).
  615. This 'programmatic quit protocol' is implemented through 3 functions
  616. and 1 event:
  617. - sapp_quit(): This function simply quits the application without
  618. giving the user a chance to intervene. Usually this might
  619. be called when the user clicks the 'Ok' button in a 'Really Quit?'
  620. dialog box
  621. - sapp_request_quit(): Calling sapp_request_quit() will send the
  622. event SAPP_EVENTTYPE_QUIT_REQUESTED to the applications event handler
  623. callback, giving the user code a chance to intervene and cancel the
  624. pending quit process (for instance to show a 'Really Quit?' dialog
  625. box). If the event handler callback does nothing, the application
  626. will be quit as usual. To prevent this, call the function
  627. sapp_cancel_quit() from inside the event handler.
  628. - sapp_cancel_quit(): Cancels a pending quit request, either initiated
  629. by the user clicking the window close button, or programmatically
  630. by calling sapp_request_quit(). The only place where calling this
  631. function makes sense is from inside the event handler callback when
  632. the SAPP_EVENTTYPE_QUIT_REQUESTED event has been received.
  633. - SAPP_EVENTTYPE_QUIT_REQUESTED: this event is sent when the user
  634. clicks the window's close button or application code calls the
  635. sapp_request_quit() function. The event handler callback code can handle
  636. this event by calling sapp_cancel_quit() to cancel the quit.
  637. If the event is ignored, the application will quit as usual.
  638. On the web platform, the quit behaviour differs from native platforms,
  639. because of web-specific restrictions:
  640. A `programmatic quit` initiated by calling sapp_quit() or
  641. sapp_request_quit() will work as described above: the cleanup callback is
  642. called, platform-specific cleanup is performed (on the web
  643. this means that JS event handlers are unregistered), and then
  644. the request-animation-loop will be exited. However that's all. The
  645. web page itself will continue to exist (e.g. it's not possible to
  646. programmatically close the browser tab).
  647. On the web it's also not possible to run custom code when the user
  648. closes a browser tab, so it's not possible to prevent this with a
  649. fancy custom dialog box.
  650. Instead the standard "Leave Site?" dialog box can be activated (or
  651. deactivated) with the following function:
  652. sapp_html5_ask_leave_site(bool ask);
  653. The initial state of the associated internal flag can be provided
  654. at startup via sapp_desc.html5_ask_leave_site.
  655. This feature should only be used sparingly in critical situations - for
  656. instance when the user would loose data - since popping up modal dialog
  657. boxes is considered quite rude in the web world. Note that there's no way
  658. to customize the content of this dialog box or run any code as a result
  659. of the user's decision. Also note that the user must have interacted with
  660. the site before the dialog box will appear. These are all security measures
  661. to prevent fishing.
  662. The Dear ImGui HighDPI sample contains example code of how to
  663. implement a 'Really Quit?' dialog box with Dear ImGui (native desktop
  664. platforms only), and for showing the hardwired "Leave Site?" dialog box
  665. when running on the web platform:
  666. https://floooh.github.io/sokol-html5/wasm/imgui-highdpi-sapp.html
  667. FULLSCREEN
  668. ==========
  669. If the sapp_desc.fullscreen flag is true, sokol-app will try to create
  670. a fullscreen window on platforms with a 'proper' window system
  671. (mobile devices will always use fullscreen). The implementation details
  672. depend on the target platform, in general sokol-app will use a
  673. 'soft approach' which doesn't interfere too much with the platform's
  674. window system (for instance borderless fullscreen window instead of
  675. a 'real' fullscreen mode). Such details might change over time
  676. as sokol-app is adapted for different needs.
  677. The most important effect of fullscreen mode to keep in mind is that
  678. the requested canvas width and height will be ignored for the initial
  679. window size, calling sapp_width() and sapp_height() will instead return
  680. the resolution of the fullscreen canvas (however the provided size
  681. might still be used for the non-fullscreen window, in case the user can
  682. switch back from fullscreen- to windowed-mode).
  683. To toggle fullscreen mode programmatically, call sapp_toggle_fullscreen().
  684. To check if the application window is currently in fullscreen mode,
  685. call sapp_is_fullscreen().
  686. WINDOW ICON SUPPORT
  687. ===================
  688. Some sokol_app.h backends allow to change the window icon programmatically:
  689. - on Win32: the small icon in the window's title bar, and the
  690. bigger icon in the task bar
  691. - on Linux: highly dependent on the used window manager, but usually
  692. the window's title bar icon and/or the task bar icon
  693. - on HTML5: the favicon shown in the page's browser tab
  694. - on macOS: the application icon shown in the dock, but only
  695. for currently running applications
  696. NOTE that it is not possible to set the actual application icon which is
  697. displayed by the operating system on the desktop or 'home screen'. Those
  698. icons must be provided 'traditionally' through operating-system-specific
  699. resources which are associated with the application (sokol_app.h might
  700. later support setting the window icon from platform specific resource data
  701. though).
  702. There are two ways to set the window icon:
  703. - at application start in the sokol_main() function by initializing
  704. the sapp_desc.icon nested struct
  705. - or later by calling the function sapp_set_icon()
  706. As a convenient shortcut, sokol_app.h comes with a builtin default-icon
  707. (a rainbow-colored 'S', which at least looks a bit better than the Windows
  708. default icon for applications), which can be activated like this:
  709. At startup in sokol_main():
  710. sapp_desc sokol_main(...) {
  711. return (sapp_desc){
  712. ...
  713. icon.sokol_default = true
  714. };
  715. }
  716. Or later by calling:
  717. sapp_set_icon(&(sapp_icon_desc){ .sokol_default = true });
  718. NOTE that a completely zero-initialized sapp_icon_desc struct will not
  719. update the window icon in any way. This is an 'escape hatch' so that you
  720. can handle the window icon update yourself (or if you do this already,
  721. sokol_app.h won't get in your way, in this case just leave the
  722. sapp_desc.icon struct zero-initialized).
  723. Providing your own icon images works exactly like in GLFW (down to the
  724. data format):
  725. You provide one or more 'candidate images' in different sizes, and the
  726. sokol_app.h platform backends pick the best match for the specific backend
  727. and icon type.
  728. For each candidate image, you need to provide:
  729. - the width in pixels
  730. - the height in pixels
  731. - and the actual pixel data in RGBA8 pixel format (e.g. 0xFFCC8844
  732. on a little-endian CPU means: alpha=0xFF, blue=0xCC, green=0x88, red=0x44)
  733. For instance, if you have 3 candidate images (small, medium, big) of
  734. sizes 16x16, 32x32 and 64x64 the corresponding sapp_icon_desc struct is setup
  735. like this:
  736. // the actual pixel data (RGBA8, origin top-left)
  737. const uint32_t small[16][16] = { ... };
  738. const uint32_t medium[32][32] = { ... };
  739. const uint32_t big[64][64] = { ... };
  740. const sapp_icon_desc icon_desc = {
  741. .images = {
  742. { .width = 16, .height = 16, .pixels = SAPP_RANGE(small) },
  743. { .width = 32, .height = 32, .pixels = SAPP_RANGE(medium) },
  744. // ...or without the SAPP_RANGE helper macro:
  745. { .width = 64, .height = 64, .pixels = { .ptr=big, .size=sizeof(big) } }
  746. }
  747. };
  748. An sapp_icon_desc struct initialized like this can then either be applied
  749. at application start in sokol_main:
  750. sapp_desc sokol_main(...) {
  751. return (sapp_desc){
  752. ...
  753. icon = icon_desc
  754. };
  755. }
  756. ...or later by calling sapp_set_icon():
  757. sapp_set_icon(&icon_desc);
  758. Some window icon caveats:
  759. - once the window icon has been updated, there's no way to go back to
  760. the platform's default icon, this is because some platforms (Linux
  761. and HTML5) don't switch the icon visual back to the default even if
  762. the custom icon is deleted or removed
  763. - on HTML5, if the sokol_app.h icon doesn't show up in the browser
  764. tab, check that there's no traditional favicon 'link' element
  765. is defined in the page's index.html, sokol_app.h will only
  766. append a new favicon link element, but not delete any manually
  767. defined favicon in the page
  768. For an example and test of the window icon feature, check out the
  769. 'icon-sapp' sample on the sokol-samples git repository.
  770. ONSCREEN KEYBOARD
  771. =================
  772. On some platforms which don't provide a physical keyboard, sokol-app
  773. can display the platform's integrated onscreen keyboard for text
  774. input. To request that the onscreen keyboard is shown, call
  775. sapp_show_keyboard(true);
  776. Likewise, to hide the keyboard call:
  777. sapp_show_keyboard(false);
  778. Note that onscreen keyboard functionality is no longer supported
  779. on the browser platform (the previous hacks and workarounds to make browser
  780. keyboards work for on web applications that don't use HTML UIs
  781. never really worked across browsers).
  782. INPUT EVENT BUBBLING ON THE WEB PLATFORM
  783. ========================================
  784. By default, input event bubbling on the web platform is configured in
  785. a way that makes the most sense for 'full-canvas' apps that cover the
  786. entire browser client window area:
  787. - mouse, touch and wheel events do not bubble up, this prevents various
  788. ugly side events, like:
  789. - HTML text overlays being selected on double- or triple-click into
  790. the canvas
  791. - 'scroll bumping' even when the canvas covers the entire client area
  792. - key_up/down events for 'character keys' *do* bubble up (otherwise
  793. the browser will not generate UNICODE character events)
  794. - all other key events *do not* bubble up by default (this prevents side effects
  795. like F1 opening help, or F7 starting 'caret browsing')
  796. - character events do not bubble up (although I haven't noticed any side effects
  797. otherwise)
  798. Event bubbling can be enabled for input event categories during initialization
  799. in the sapp_desc struct:
  800. sapp_desc sokol_main(int argc, char* argv[]) {
  801. return (sapp_desc){
  802. //...
  803. .html5_bubble_mouse_events = true,
  804. .html5_bubble_touch_events = true,
  805. .html5_bubble_wheel_events = true,
  806. .html5_bubble_key_events = true,
  807. .html5_bubble_char_events = true,
  808. };
  809. }
  810. This basically opens the floodgates and lets *all* input events bubble up to the browser.
  811. To prevent individual events from bubbling, call sapp_consume_event() from within
  812. the sokol_app.h event callback when that specific event is reported.
  813. SETTING THE CANVAS OBJECT ON THE WEB PLATFORM
  814. =============================================
  815. On the web, sokol_app.h and the Emscripten SDK functions need to find
  816. the WebGL/WebGPU canvas intended for rendering and attaching event
  817. handlers. This can happen in four ways:
  818. 1. do nothing and just set the id of the canvas object to 'canvas' (preferred)
  819. 2. via a CSS Selector string (preferred)
  820. 3. by setting the `Module.canvas` property to the canvas object
  821. 4. by adding the canvas object to the global variable `specialHTMLTargets[]`
  822. (this is a special variable used by the Emscripten runtime to lookup
  823. event target objects for which document.querySelector() cannot be used)
  824. The easiest way is to just name your canvas object 'canvas':
  825. <canvas id="canvas" ...></canvas>
  826. This works because the default css selector string used by sokol_app.h
  827. is '#canvas'.
  828. If you name your canvas differently, you need to communicate that name to
  829. sokol_app.h via `sapp_desc.html5_canvas_selector` as a regular css selector
  830. string that's compatible with `document.querySelector()`. E.g. if your canvas
  831. object looks like this:
  832. <canvas id="bla" ...></canvas>
  833. The `sapp_desc.html5_canvas_selector` string must be set to '#bla':
  834. .html5_canvas_selector = "#bla"
  835. If the canvas object cannot be looked up via `document.querySelector()` you
  836. need to use one of the alternative methods, both involve the special
  837. Emscripten runtime `Module` object which is usually setup in the index.html
  838. like this before the WASM blob is loaded and instantiated:
  839. <script type='text/javascript'>
  840. var Module = {
  841. // ...
  842. };
  843. </script>
  844. The first option is to set the `Module.canvas` property to your canvas object:
  845. <script type='text/javascript'>
  846. var Module = {
  847. canvas: my_canvas_object,
  848. };
  849. </script>
  850. When sokol_app.h initializes, it will check the global Module object whether
  851. a `Module.canvas` property exists and is an object. This method will add
  852. a new entry to the `specialHTMLTargets[]` object
  853. The other option is to add the canvas under a name chosen by you to the
  854. special `specialHTMLTargets[]` map, which is used by the Emscripten runtime
  855. to lookup 'event target objects' which are not visible to `document.querySelector()`.
  856. Note that `specialHTMLTargets[]` must be updated after the Emscripten runtime
  857. has started but before the WASM code is running. A good place for this is
  858. the special `Module.preRun` array in index.html:
  859. <script type='text/javascript'>
  860. var Module = {
  861. preRun: [
  862. () => {
  863. specialHTMLTargets['my_canvas'] = my_canvas_object;
  864. }
  865. ],
  866. };
  867. </script>
  868. In that case, pass the same string to sokol_app.h which is used as key
  869. in the specialHTMLTargets[] map:
  870. .html5_canvas_selector = "my_canvas"
  871. If sokol_app.h can't find your canvas for some reason check for warning
  872. messages on the browser console.
  873. OPTIONAL: DON'T HIJACK main() (#define SOKOL_NO_ENTRY)
  874. ======================================================
  875. NOTE: SOKOL_NO_ENTRY and sapp_run() is currently not supported on Android.
  876. In its default configuration, sokol_app.h "hijacks" the platform's
  877. standard main() function. This was done because different platforms
  878. have different entry point conventions which are not compatible with
  879. C's main() (for instance WinMain on Windows has completely different
  880. arguments). However, this "main hijacking" posed a problem for
  881. usage scenarios like integrating sokol_app.h with other languages than
  882. C or C++, so an alternative SOKOL_NO_ENTRY mode has been added
  883. in which the user code provides the platform's main function:
  884. - define SOKOL_NO_ENTRY before including the sokol_app.h implementation
  885. - do *not* provide a sokol_main() function
  886. - instead provide the standard main() function of the platform
  887. - from the main function, call the function ```sapp_run()``` which
  888. takes a pointer to an ```sapp_desc``` structure.
  889. - from here on```sapp_run()``` takes over control and calls the provided
  890. init-, frame-, event- and cleanup-callbacks just like in the default model.
  891. sapp_run() behaves differently across platforms:
  892. - on some platforms, sapp_run() will return when the application quits
  893. - on other platforms, sapp_run() will never return, even when the
  894. application quits (the operating system is free to simply terminate
  895. the application at any time)
  896. - on Emscripten specifically, sapp_run() will return immediately while
  897. the frame callback keeps being called
  898. This different behaviour of sapp_run() essentially means that there shouldn't
  899. be any code *after* sapp_run(), because that may either never be called, or in
  900. case of Emscripten will be called at an unexpected time (at application start).
  901. An application also should not depend on the cleanup-callback being called
  902. when cross-platform compatibility is required.
  903. Since sapp_run() returns immediately on Emscripten you shouldn't activate
  904. the 'EXIT_RUNTIME' linker option (this is disabled by default when compiling
  905. for the browser target), since the C/C++ exit runtime would be called immediately at
  906. application start, causing any global objects to be destroyed and global
  907. variables to be zeroed.
  908. WINDOWS CONSOLE OUTPUT
  909. ======================
  910. On Windows, regular windowed applications don't show any stdout/stderr text
  911. output, which can be a bit of a hassle for printf() debugging or generally
  912. logging text to the console. Also, console output by default uses a local
  913. codepage setting and thus international UTF-8 encoded text is printed
  914. as garbage.
  915. To help with these issues, sokol_app.h can be configured at startup
  916. via the following Windows-specific sapp_desc flags:
  917. sapp_desc.win32_console_utf8 (default: false)
  918. When set to true, the output console codepage will be switched
  919. to UTF-8 (and restored to the original codepage on exit)
  920. sapp_desc.win32_console_attach (default: false)
  921. When set to true, stdout and stderr will be attached to the
  922. console of the parent process (if the parent process actually
  923. has a console). This means that if the application was started
  924. in a command line window, stdout and stderr output will be printed
  925. to the terminal, just like a regular command line program. But if
  926. the application is started via double-click, it will behave like
  927. a regular UI application, and stdout/stderr will not be visible.
  928. sapp_desc.win32_console_create (default: false)
  929. When set to true, a new console window will be created and
  930. stdout/stderr will be redirected to that console window. It
  931. doesn't matter if the application is started from the command
  932. line or via double-click.
  933. MEMORY ALLOCATION OVERRIDE
  934. ==========================
  935. You can override the memory allocation functions at initialization time
  936. like this:
  937. void* my_alloc(size_t size, void* user_data) {
  938. return malloc(size);
  939. }
  940. void my_free(void* ptr, void* user_data) {
  941. free(ptr);
  942. }
  943. sapp_desc sokol_main(int argc, char* argv[]) {
  944. return (sapp_desc){
  945. // ...
  946. .allocator = {
  947. .alloc_fn = my_alloc,
  948. .free_fn = my_free,
  949. .user_data = ...,
  950. }
  951. };
  952. }
  953. If no overrides are provided, malloc and free will be used.
  954. This only affects memory allocation calls done by sokol_app.h
  955. itself though, not any allocations in OS libraries.
  956. ERROR REPORTING AND LOGGING
  957. ===========================
  958. To get any logging information at all you need to provide a logging callback in the setup call
  959. the easiest way is to use sokol_log.h:
  960. #include "sokol_log.h"
  961. sapp_desc sokol_main(int argc, char* argv[]) {
  962. return (sapp_desc) {
  963. ...
  964. .logger.func = slog_func,
  965. };
  966. }
  967. To override logging with your own callback, first write a logging function like this:
  968. void my_log(const char* tag, // e.g. 'sapp'
  969. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  970. uint32_t log_item_id, // SAPP_LOGITEM_*
  971. const char* message_or_null, // a message string, may be nullptr in release mode
  972. uint32_t line_nr, // line number in sokol_app.h
  973. const char* filename_or_null, // source filename, may be nullptr in release mode
  974. void* user_data)
  975. {
  976. ...
  977. }
  978. ...and then setup sokol-app like this:
  979. sapp_desc sokol_main(int argc, char* argv[]) {
  980. return (sapp_desc) {
  981. ...
  982. .logger = {
  983. .func = my_log,
  984. .user_data = my_user_data,
  985. }
  986. };
  987. }
  988. The provided logging function must be reentrant (e.g. be callable from
  989. different threads).
  990. If you don't want to provide your own custom logger it is highly recommended to use
  991. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  992. errors.
  993. TEMP NOTE DUMP
  994. ==============
  995. - sapp_desc needs a bool whether to initialize depth-stencil surface
  996. - the Android implementation calls cleanup_cb() and destroys the egl context in onDestroy
  997. at the latest but should do it earlier, in onStop, as an app is "killable" after onStop
  998. on Android Honeycomb and later (it can't be done at the moment as the app may be started
  999. again after onStop and the sokol lifecycle does not yet handle context teardown/bringup)
  1000. LICENSE
  1001. =======
  1002. zlib/libpng license
  1003. Copyright (c) 2018 Andre Weissflog
  1004. This software is provided 'as-is', without any express or implied warranty.
  1005. In no event will the authors be held liable for any damages arising from the
  1006. use of this software.
  1007. Permission is granted to anyone to use this software for any purpose,
  1008. including commercial applications, and to alter it and redistribute it
  1009. freely, subject to the following restrictions:
  1010. 1. The origin of this software must not be misrepresented; you must not
  1011. claim that you wrote the original software. If you use this software in a
  1012. product, an acknowledgment in the product documentation would be
  1013. appreciated but is not required.
  1014. 2. Altered source versions must be plainly marked as such, and must not
  1015. be misrepresented as being the original software.
  1016. 3. This notice may not be removed or altered from any source
  1017. distribution.
  1018. */
  1019. #define SOKOL_APP_INCLUDED (1)
  1020. #include <stddef.h> // size_t
  1021. #include <stdint.h>
  1022. #include <stdbool.h>
  1023. #if defined(SOKOL_API_DECL) && !defined(SOKOL_APP_API_DECL)
  1024. #define SOKOL_APP_API_DECL SOKOL_API_DECL
  1025. #endif
  1026. #ifndef SOKOL_APP_API_DECL
  1027. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_APP_IMPL)
  1028. #define SOKOL_APP_API_DECL __declspec(dllexport)
  1029. #elif defined(_WIN32) && defined(SOKOL_DLL)
  1030. #define SOKOL_APP_API_DECL __declspec(dllimport)
  1031. #else
  1032. #define SOKOL_APP_API_DECL extern
  1033. #endif
  1034. #endif
  1035. #ifdef __cplusplus
  1036. extern "C" {
  1037. #endif
  1038. /* misc constants */
  1039. enum {
  1040. SAPP_MAX_TOUCHPOINTS = 8,
  1041. SAPP_MAX_MOUSEBUTTONS = 3,
  1042. SAPP_MAX_KEYCODES = 512,
  1043. SAPP_MAX_ICONIMAGES = 8,
  1044. };
  1045. /*
  1046. sapp_event_type
  1047. The type of event that's passed to the event handler callback
  1048. in the sapp_event.type field. These are not just "traditional"
  1049. input events, but also notify the application about state changes
  1050. or other user-invoked actions.
  1051. */
  1052. typedef enum sapp_event_type {
  1053. SAPP_EVENTTYPE_INVALID,
  1054. SAPP_EVENTTYPE_KEY_DOWN,
  1055. SAPP_EVENTTYPE_KEY_UP,
  1056. SAPP_EVENTTYPE_CHAR,
  1057. SAPP_EVENTTYPE_MOUSE_DOWN,
  1058. SAPP_EVENTTYPE_MOUSE_UP,
  1059. SAPP_EVENTTYPE_MOUSE_SCROLL,
  1060. SAPP_EVENTTYPE_MOUSE_MOVE,
  1061. SAPP_EVENTTYPE_MOUSE_ENTER,
  1062. SAPP_EVENTTYPE_MOUSE_LEAVE,
  1063. SAPP_EVENTTYPE_TOUCHES_BEGAN,
  1064. SAPP_EVENTTYPE_TOUCHES_MOVED,
  1065. SAPP_EVENTTYPE_TOUCHES_ENDED,
  1066. SAPP_EVENTTYPE_TOUCHES_CANCELLED,
  1067. SAPP_EVENTTYPE_RESIZED,
  1068. SAPP_EVENTTYPE_ICONIFIED,
  1069. SAPP_EVENTTYPE_RESTORED,
  1070. SAPP_EVENTTYPE_FOCUSED,
  1071. SAPP_EVENTTYPE_UNFOCUSED,
  1072. SAPP_EVENTTYPE_SUSPENDED,
  1073. SAPP_EVENTTYPE_RESUMED,
  1074. SAPP_EVENTTYPE_QUIT_REQUESTED,
  1075. SAPP_EVENTTYPE_CLIPBOARD_PASTED,
  1076. SAPP_EVENTTYPE_FILES_DROPPED,
  1077. _SAPP_EVENTTYPE_NUM,
  1078. _SAPP_EVENTTYPE_FORCE_U32 = 0x7FFFFFFF
  1079. } sapp_event_type;
  1080. /*
  1081. sapp_keycode
  1082. The 'virtual keycode' of a KEY_DOWN or KEY_UP event in the
  1083. struct field sapp_event.key_code.
  1084. Note that the keycode values are identical with GLFW.
  1085. */
  1086. typedef enum sapp_keycode {
  1087. SAPP_KEYCODE_INVALID = 0,
  1088. SAPP_KEYCODE_SPACE = 32,
  1089. SAPP_KEYCODE_APOSTROPHE = 39, /* ' */
  1090. SAPP_KEYCODE_COMMA = 44, /* , */
  1091. SAPP_KEYCODE_MINUS = 45, /* - */
  1092. SAPP_KEYCODE_PERIOD = 46, /* . */
  1093. SAPP_KEYCODE_SLASH = 47, /* / */
  1094. SAPP_KEYCODE_0 = 48,
  1095. SAPP_KEYCODE_1 = 49,
  1096. SAPP_KEYCODE_2 = 50,
  1097. SAPP_KEYCODE_3 = 51,
  1098. SAPP_KEYCODE_4 = 52,
  1099. SAPP_KEYCODE_5 = 53,
  1100. SAPP_KEYCODE_6 = 54,
  1101. SAPP_KEYCODE_7 = 55,
  1102. SAPP_KEYCODE_8 = 56,
  1103. SAPP_KEYCODE_9 = 57,
  1104. SAPP_KEYCODE_SEMICOLON = 59, /* ; */
  1105. SAPP_KEYCODE_EQUAL = 61, /* = */
  1106. SAPP_KEYCODE_A = 65,
  1107. SAPP_KEYCODE_B = 66,
  1108. SAPP_KEYCODE_C = 67,
  1109. SAPP_KEYCODE_D = 68,
  1110. SAPP_KEYCODE_E = 69,
  1111. SAPP_KEYCODE_F = 70,
  1112. SAPP_KEYCODE_G = 71,
  1113. SAPP_KEYCODE_H = 72,
  1114. SAPP_KEYCODE_I = 73,
  1115. SAPP_KEYCODE_J = 74,
  1116. SAPP_KEYCODE_K = 75,
  1117. SAPP_KEYCODE_L = 76,
  1118. SAPP_KEYCODE_M = 77,
  1119. SAPP_KEYCODE_N = 78,
  1120. SAPP_KEYCODE_O = 79,
  1121. SAPP_KEYCODE_P = 80,
  1122. SAPP_KEYCODE_Q = 81,
  1123. SAPP_KEYCODE_R = 82,
  1124. SAPP_KEYCODE_S = 83,
  1125. SAPP_KEYCODE_T = 84,
  1126. SAPP_KEYCODE_U = 85,
  1127. SAPP_KEYCODE_V = 86,
  1128. SAPP_KEYCODE_W = 87,
  1129. SAPP_KEYCODE_X = 88,
  1130. SAPP_KEYCODE_Y = 89,
  1131. SAPP_KEYCODE_Z = 90,
  1132. SAPP_KEYCODE_LEFT_BRACKET = 91, /* [ */
  1133. SAPP_KEYCODE_BACKSLASH = 92, /* \ */
  1134. SAPP_KEYCODE_RIGHT_BRACKET = 93, /* ] */
  1135. SAPP_KEYCODE_GRAVE_ACCENT = 96, /* ` */
  1136. SAPP_KEYCODE_WORLD_1 = 161, /* non-US #1 */
  1137. SAPP_KEYCODE_WORLD_2 = 162, /* non-US #2 */
  1138. SAPP_KEYCODE_ESCAPE = 256,
  1139. SAPP_KEYCODE_ENTER = 257,
  1140. SAPP_KEYCODE_TAB = 258,
  1141. SAPP_KEYCODE_BACKSPACE = 259,
  1142. SAPP_KEYCODE_INSERT = 260,
  1143. SAPP_KEYCODE_DELETE = 261,
  1144. SAPP_KEYCODE_RIGHT = 262,
  1145. SAPP_KEYCODE_LEFT = 263,
  1146. SAPP_KEYCODE_DOWN = 264,
  1147. SAPP_KEYCODE_UP = 265,
  1148. SAPP_KEYCODE_PAGE_UP = 266,
  1149. SAPP_KEYCODE_PAGE_DOWN = 267,
  1150. SAPP_KEYCODE_HOME = 268,
  1151. SAPP_KEYCODE_END = 269,
  1152. SAPP_KEYCODE_CAPS_LOCK = 280,
  1153. SAPP_KEYCODE_SCROLL_LOCK = 281,
  1154. SAPP_KEYCODE_NUM_LOCK = 282,
  1155. SAPP_KEYCODE_PRINT_SCREEN = 283,
  1156. SAPP_KEYCODE_PAUSE = 284,
  1157. SAPP_KEYCODE_F1 = 290,
  1158. SAPP_KEYCODE_F2 = 291,
  1159. SAPP_KEYCODE_F3 = 292,
  1160. SAPP_KEYCODE_F4 = 293,
  1161. SAPP_KEYCODE_F5 = 294,
  1162. SAPP_KEYCODE_F6 = 295,
  1163. SAPP_KEYCODE_F7 = 296,
  1164. SAPP_KEYCODE_F8 = 297,
  1165. SAPP_KEYCODE_F9 = 298,
  1166. SAPP_KEYCODE_F10 = 299,
  1167. SAPP_KEYCODE_F11 = 300,
  1168. SAPP_KEYCODE_F12 = 301,
  1169. SAPP_KEYCODE_F13 = 302,
  1170. SAPP_KEYCODE_F14 = 303,
  1171. SAPP_KEYCODE_F15 = 304,
  1172. SAPP_KEYCODE_F16 = 305,
  1173. SAPP_KEYCODE_F17 = 306,
  1174. SAPP_KEYCODE_F18 = 307,
  1175. SAPP_KEYCODE_F19 = 308,
  1176. SAPP_KEYCODE_F20 = 309,
  1177. SAPP_KEYCODE_F21 = 310,
  1178. SAPP_KEYCODE_F22 = 311,
  1179. SAPP_KEYCODE_F23 = 312,
  1180. SAPP_KEYCODE_F24 = 313,
  1181. SAPP_KEYCODE_F25 = 314,
  1182. SAPP_KEYCODE_KP_0 = 320,
  1183. SAPP_KEYCODE_KP_1 = 321,
  1184. SAPP_KEYCODE_KP_2 = 322,
  1185. SAPP_KEYCODE_KP_3 = 323,
  1186. SAPP_KEYCODE_KP_4 = 324,
  1187. SAPP_KEYCODE_KP_5 = 325,
  1188. SAPP_KEYCODE_KP_6 = 326,
  1189. SAPP_KEYCODE_KP_7 = 327,
  1190. SAPP_KEYCODE_KP_8 = 328,
  1191. SAPP_KEYCODE_KP_9 = 329,
  1192. SAPP_KEYCODE_KP_DECIMAL = 330,
  1193. SAPP_KEYCODE_KP_DIVIDE = 331,
  1194. SAPP_KEYCODE_KP_MULTIPLY = 332,
  1195. SAPP_KEYCODE_KP_SUBTRACT = 333,
  1196. SAPP_KEYCODE_KP_ADD = 334,
  1197. SAPP_KEYCODE_KP_ENTER = 335,
  1198. SAPP_KEYCODE_KP_EQUAL = 336,
  1199. SAPP_KEYCODE_LEFT_SHIFT = 340,
  1200. SAPP_KEYCODE_LEFT_CONTROL = 341,
  1201. SAPP_KEYCODE_LEFT_ALT = 342,
  1202. SAPP_KEYCODE_LEFT_SUPER = 343,
  1203. SAPP_KEYCODE_RIGHT_SHIFT = 344,
  1204. SAPP_KEYCODE_RIGHT_CONTROL = 345,
  1205. SAPP_KEYCODE_RIGHT_ALT = 346,
  1206. SAPP_KEYCODE_RIGHT_SUPER = 347,
  1207. SAPP_KEYCODE_MENU = 348,
  1208. } sapp_keycode;
  1209. /*
  1210. Android specific 'tool type' enum for touch events. This lets the
  1211. application check what type of input device was used for
  1212. touch events.
  1213. NOTE: the values must remain in sync with the corresponding
  1214. Android SDK type, so don't change those.
  1215. See https://developer.android.com/reference/android/view/MotionEvent#TOOL_TYPE_UNKNOWN
  1216. */
  1217. typedef enum sapp_android_tooltype {
  1218. SAPP_ANDROIDTOOLTYPE_UNKNOWN = 0, // TOOL_TYPE_UNKNOWN
  1219. SAPP_ANDROIDTOOLTYPE_FINGER = 1, // TOOL_TYPE_FINGER
  1220. SAPP_ANDROIDTOOLTYPE_STYLUS = 2, // TOOL_TYPE_STYLUS
  1221. SAPP_ANDROIDTOOLTYPE_MOUSE = 3, // TOOL_TYPE_MOUSE
  1222. } sapp_android_tooltype;
  1223. /*
  1224. sapp_touchpoint
  1225. Describes a single touchpoint in a multitouch event (TOUCHES_BEGAN,
  1226. TOUCHES_MOVED, TOUCHES_ENDED).
  1227. Touch points are stored in the nested array sapp_event.touches[],
  1228. and the number of touches is stored in sapp_event.num_touches.
  1229. */
  1230. typedef struct sapp_touchpoint {
  1231. uintptr_t identifier;
  1232. float pos_x;
  1233. float pos_y;
  1234. sapp_android_tooltype android_tooltype; // only valid on Android
  1235. bool changed;
  1236. } sapp_touchpoint;
  1237. /*
  1238. sapp_mousebutton
  1239. The currently pressed mouse button in the events MOUSE_DOWN
  1240. and MOUSE_UP, stored in the struct field sapp_event.mouse_button.
  1241. */
  1242. typedef enum sapp_mousebutton {
  1243. SAPP_MOUSEBUTTON_LEFT = 0x0,
  1244. SAPP_MOUSEBUTTON_RIGHT = 0x1,
  1245. SAPP_MOUSEBUTTON_MIDDLE = 0x2,
  1246. SAPP_MOUSEBUTTON_INVALID = 0x100,
  1247. } sapp_mousebutton;
  1248. /*
  1249. These are currently pressed modifier keys (and mouse buttons) which are
  1250. passed in the event struct field sapp_event.modifiers.
  1251. */
  1252. enum {
  1253. SAPP_MODIFIER_SHIFT = 0x1, // left or right shift key
  1254. SAPP_MODIFIER_CTRL = 0x2, // left or right control key
  1255. SAPP_MODIFIER_ALT = 0x4, // left or right alt key
  1256. SAPP_MODIFIER_SUPER = 0x8, // left or right 'super' key
  1257. SAPP_MODIFIER_LMB = 0x100, // left mouse button
  1258. SAPP_MODIFIER_RMB = 0x200, // right mouse button
  1259. SAPP_MODIFIER_MMB = 0x400, // middle mouse button
  1260. };
  1261. /*
  1262. sapp_event
  1263. This is an all-in-one event struct passed to the event handler
  1264. user callback function. Note that it depends on the event
  1265. type what struct fields actually contain useful values, so you
  1266. should first check the event type before reading other struct
  1267. fields.
  1268. */
  1269. typedef struct sapp_event {
  1270. uint64_t frame_count; // current frame counter, always valid, useful for checking if two events were issued in the same frame
  1271. sapp_event_type type; // the event type, always valid
  1272. sapp_keycode key_code; // the virtual key code, only valid in KEY_UP, KEY_DOWN
  1273. uint32_t char_code; // the UTF-32 character code, only valid in CHAR events
  1274. bool key_repeat; // true if this is a key-repeat event, valid in KEY_UP, KEY_DOWN and CHAR
  1275. uint32_t modifiers; // current modifier keys, valid in all key-, char- and mouse-events
  1276. sapp_mousebutton mouse_button; // mouse button that was pressed or released, valid in MOUSE_DOWN, MOUSE_UP
  1277. float mouse_x; // current horizontal mouse position in pixels, always valid except during mouse lock
  1278. float mouse_y; // current vertical mouse position in pixels, always valid except during mouse lock
  1279. float mouse_dx; // relative horizontal mouse movement since last frame, always valid
  1280. float mouse_dy; // relative vertical mouse movement since last frame, always valid
  1281. float scroll_x; // horizontal mouse wheel scroll distance, valid in MOUSE_SCROLL events
  1282. float scroll_y; // vertical mouse wheel scroll distance, valid in MOUSE_SCROLL events
  1283. int num_touches; // number of valid items in the touches[] array
  1284. sapp_touchpoint touches[SAPP_MAX_TOUCHPOINTS]; // current touch points, valid in TOUCHES_BEGIN, TOUCHES_MOVED, TOUCHES_ENDED
  1285. int window_width; // current window- and framebuffer sizes in pixels, always valid
  1286. int window_height;
  1287. int framebuffer_width; // = window_width * dpi_scale
  1288. int framebuffer_height; // = window_height * dpi_scale
  1289. } sapp_event;
  1290. /*
  1291. sg_range
  1292. A general pointer/size-pair struct and constructor macros for passing binary blobs
  1293. into sokol_app.h.
  1294. */
  1295. typedef struct sapp_range {
  1296. const void* ptr;
  1297. size_t size;
  1298. } sapp_range;
  1299. // disabling this for every includer isn't great, but the warnings are also quite pointless
  1300. #if defined(_MSC_VER)
  1301. #pragma warning(disable:4221) /* /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y' */
  1302. #pragma warning(disable:4204) /* VS2015: nonstandard extension used: non-constant aggregate initializer */
  1303. #endif
  1304. #if defined(__cplusplus)
  1305. #define SAPP_RANGE(x) sapp_range{ &x, sizeof(x) }
  1306. #else
  1307. #define SAPP_RANGE(x) (sapp_range){ &x, sizeof(x) }
  1308. #endif
  1309. /*
  1310. sapp_image_desc
  1311. This is used to describe image data to sokol_app.h (at first, window
  1312. icons, later maybe cursor images).
  1313. Note that the actual image pixel format depends on the use case:
  1314. - window icon pixels are RGBA8
  1315. */
  1316. typedef struct sapp_image_desc {
  1317. int width;
  1318. int height;
  1319. sapp_range pixels;
  1320. } sapp_image_desc;
  1321. /*
  1322. sapp_icon_desc
  1323. An icon description structure for use in sapp_desc.icon and
  1324. sapp_set_icon().
  1325. When setting a custom image, the application can provide a number of
  1326. candidates differing in size, and sokol_app.h will pick the image(s)
  1327. closest to the size expected by the platform's window system.
  1328. To set sokol-app's default icon, set .sokol_default to true.
  1329. Otherwise provide candidate images of different sizes in the
  1330. images[] array.
  1331. If both the sokol_default flag is set to true, any image candidates
  1332. will be ignored and the sokol_app.h default icon will be set.
  1333. */
  1334. typedef struct sapp_icon_desc {
  1335. bool sokol_default;
  1336. sapp_image_desc images[SAPP_MAX_ICONIMAGES];
  1337. } sapp_icon_desc;
  1338. /*
  1339. sapp_allocator
  1340. Used in sapp_desc to provide custom memory-alloc and -free functions
  1341. to sokol_app.h. If memory management should be overridden, both the
  1342. alloc_fn and free_fn function must be provided (e.g. it's not valid to
  1343. override one function but not the other).
  1344. */
  1345. typedef struct sapp_allocator {
  1346. void* (*alloc_fn)(size_t size, void* user_data);
  1347. void (*free_fn)(void* ptr, void* user_data);
  1348. void* user_data;
  1349. } sapp_allocator;
  1350. /*
  1351. sapp_log_item
  1352. Log items are defined via X-Macros and expanded to an enum
  1353. 'sapp_log_item', and in debug mode to corresponding
  1354. human readable error messages.
  1355. */
  1356. #define _SAPP_LOG_ITEMS \
  1357. _SAPP_LOGITEM_XMACRO(OK, "Ok") \
  1358. _SAPP_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  1359. _SAPP_LOGITEM_XMACRO(MACOS_INVALID_NSOPENGL_PROFILE, "macos: invalid NSOpenGLProfile (valid choices are 1.0 and 4.1)") \
  1360. _SAPP_LOGITEM_XMACRO(WIN32_LOAD_OPENGL32_DLL_FAILED, "failed loading opengl32.dll") \
  1361. _SAPP_LOGITEM_XMACRO(WIN32_CREATE_HELPER_WINDOW_FAILED, "failed to create helper window") \
  1362. _SAPP_LOGITEM_XMACRO(WIN32_HELPER_WINDOW_GETDC_FAILED, "failed to get helper window DC") \
  1363. _SAPP_LOGITEM_XMACRO(WIN32_DUMMY_CONTEXT_SET_PIXELFORMAT_FAILED, "failed to set pixel format for dummy GL context") \
  1364. _SAPP_LOGITEM_XMACRO(WIN32_CREATE_DUMMY_CONTEXT_FAILED, "failed to create dummy GL context") \
  1365. _SAPP_LOGITEM_XMACRO(WIN32_DUMMY_CONTEXT_MAKE_CURRENT_FAILED, "failed to make dummy GL context current") \
  1366. _SAPP_LOGITEM_XMACRO(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED, "failed to get WGL pixel format attribute") \
  1367. _SAPP_LOGITEM_XMACRO(WIN32_WGL_FIND_PIXELFORMAT_FAILED, "failed to find matching WGL pixel format") \
  1368. _SAPP_LOGITEM_XMACRO(WIN32_WGL_DESCRIBE_PIXELFORMAT_FAILED, "failed to get pixel format descriptor") \
  1369. _SAPP_LOGITEM_XMACRO(WIN32_WGL_SET_PIXELFORMAT_FAILED, "failed to set selected pixel format") \
  1370. _SAPP_LOGITEM_XMACRO(WIN32_WGL_ARB_CREATE_CONTEXT_REQUIRED, "ARB_create_context required") \
  1371. _SAPP_LOGITEM_XMACRO(WIN32_WGL_ARB_CREATE_CONTEXT_PROFILE_REQUIRED, "ARB_create_context_profile required") \
  1372. _SAPP_LOGITEM_XMACRO(WIN32_WGL_OPENGL_VERSION_NOT_SUPPORTED, "requested OpenGL version not supported by GL driver (ERROR_INVALID_VERSION_ARB)") \
  1373. _SAPP_LOGITEM_XMACRO(WIN32_WGL_OPENGL_PROFILE_NOT_SUPPORTED, "requested OpenGL profile not support by GL driver (ERROR_INVALID_PROFILE_ARB)") \
  1374. _SAPP_LOGITEM_XMACRO(WIN32_WGL_INCOMPATIBLE_DEVICE_CONTEXT, "CreateContextAttribsARB failed with ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB") \
  1375. _SAPP_LOGITEM_XMACRO(WIN32_WGL_CREATE_CONTEXT_ATTRIBS_FAILED_OTHER, "CreateContextAttribsARB failed for other reason") \
  1376. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_CREATE_DEVICE_AND_SWAPCHAIN_WITH_DEBUG_FAILED, "D3D11CreateDeviceAndSwapChain() with D3D11_CREATE_DEVICE_DEBUG failed, retrying without debug flag.") \
  1377. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_GET_IDXGIFACTORY_FAILED, "could not obtain IDXGIFactory object") \
  1378. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_GET_IDXGIADAPTER_FAILED, "could not obtain IDXGIAdapter object") \
  1379. _SAPP_LOGITEM_XMACRO(WIN32_D3D11_QUERY_INTERFACE_IDXGIDEVICE1_FAILED, "could not obtain IDXGIDevice1 interface") \
  1380. _SAPP_LOGITEM_XMACRO(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_LOCK, "RegisterRawInputDevices() failed (on mouse lock)") \
  1381. _SAPP_LOGITEM_XMACRO(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_UNLOCK, "RegisterRawInputDevices() failed (on mouse unlock)") \
  1382. _SAPP_LOGITEM_XMACRO(WIN32_GET_RAW_INPUT_DATA_FAILED, "GetRawInputData() failed") \
  1383. _SAPP_LOGITEM_XMACRO(LINUX_GLX_LOAD_LIBGL_FAILED, "failed to load libGL") \
  1384. _SAPP_LOGITEM_XMACRO(LINUX_GLX_LOAD_ENTRY_POINTS_FAILED, "failed to load GLX entry points") \
  1385. _SAPP_LOGITEM_XMACRO(LINUX_GLX_EXTENSION_NOT_FOUND, "GLX extension not found") \
  1386. _SAPP_LOGITEM_XMACRO(LINUX_GLX_QUERY_VERSION_FAILED, "failed to query GLX version") \
  1387. _SAPP_LOGITEM_XMACRO(LINUX_GLX_VERSION_TOO_LOW, "GLX version too low (need at least 1.3)") \
  1388. _SAPP_LOGITEM_XMACRO(LINUX_GLX_NO_GLXFBCONFIGS, "glXGetFBConfigs() returned no configs") \
  1389. _SAPP_LOGITEM_XMACRO(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG, "failed to find a suitable GLXFBConfig") \
  1390. _SAPP_LOGITEM_XMACRO(LINUX_GLX_GET_VISUAL_FROM_FBCONFIG_FAILED, "glXGetVisualFromFBConfig failed") \
  1391. _SAPP_LOGITEM_XMACRO(LINUX_GLX_REQUIRED_EXTENSIONS_MISSING, "GLX extensions ARB_create_context and ARB_create_context_profile missing") \
  1392. _SAPP_LOGITEM_XMACRO(LINUX_GLX_CREATE_CONTEXT_FAILED, "Failed to create GL context via glXCreateContextAttribsARB") \
  1393. _SAPP_LOGITEM_XMACRO(LINUX_GLX_CREATE_WINDOW_FAILED, "glXCreateWindow() failed") \
  1394. _SAPP_LOGITEM_XMACRO(LINUX_X11_CREATE_WINDOW_FAILED, "XCreateWindow() failed") \
  1395. _SAPP_LOGITEM_XMACRO(LINUX_EGL_BIND_OPENGL_API_FAILED, "eglBindAPI(EGL_OPENGL_API) failed") \
  1396. _SAPP_LOGITEM_XMACRO(LINUX_EGL_BIND_OPENGL_ES_API_FAILED, "eglBindAPI(EGL_OPENGL_ES_API) failed") \
  1397. _SAPP_LOGITEM_XMACRO(LINUX_EGL_GET_DISPLAY_FAILED, "eglGetDisplay() failed") \
  1398. _SAPP_LOGITEM_XMACRO(LINUX_EGL_INITIALIZE_FAILED, "eglInitialize() failed") \
  1399. _SAPP_LOGITEM_XMACRO(LINUX_EGL_NO_CONFIGS, "eglChooseConfig() returned no configs") \
  1400. _SAPP_LOGITEM_XMACRO(LINUX_EGL_NO_NATIVE_VISUAL, "eglGetConfigAttrib() for EGL_NATIVE_VISUAL_ID failed") \
  1401. _SAPP_LOGITEM_XMACRO(LINUX_EGL_GET_VISUAL_INFO_FAILED, "XGetVisualInfo() failed") \
  1402. _SAPP_LOGITEM_XMACRO(LINUX_EGL_CREATE_WINDOW_SURFACE_FAILED, "eglCreateWindowSurface() failed") \
  1403. _SAPP_LOGITEM_XMACRO(LINUX_EGL_CREATE_CONTEXT_FAILED, "eglCreateContext() failed") \
  1404. _SAPP_LOGITEM_XMACRO(LINUX_EGL_MAKE_CURRENT_FAILED, "eglMakeCurrent() failed") \
  1405. _SAPP_LOGITEM_XMACRO(LINUX_X11_OPEN_DISPLAY_FAILED, "XOpenDisplay() failed") \
  1406. _SAPP_LOGITEM_XMACRO(LINUX_X11_QUERY_SYSTEM_DPI_FAILED, "failed to query system dpi value, assuming default 96.0") \
  1407. _SAPP_LOGITEM_XMACRO(LINUX_X11_DROPPED_FILE_URI_WRONG_SCHEME, "dropped file URL doesn't start with 'file://'") \
  1408. _SAPP_LOGITEM_XMACRO(LINUX_X11_FAILED_TO_BECOME_OWNER_OF_CLIPBOARD, "X11: Failed to become owner of clipboard selection") \
  1409. _SAPP_LOGITEM_XMACRO(ANDROID_UNSUPPORTED_INPUT_EVENT_INPUT_CB, "unsupported input event encountered in _sapp_android_input_cb()") \
  1410. _SAPP_LOGITEM_XMACRO(ANDROID_UNSUPPORTED_INPUT_EVENT_MAIN_CB, "unsupported input event encountered in _sapp_android_main_cb()") \
  1411. _SAPP_LOGITEM_XMACRO(ANDROID_READ_MSG_FAILED, "failed to read message in _sapp_android_main_cb()") \
  1412. _SAPP_LOGITEM_XMACRO(ANDROID_WRITE_MSG_FAILED, "failed to write message in _sapp_android_msg") \
  1413. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_CREATE, "MSG_CREATE") \
  1414. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_RESUME, "MSG_RESUME") \
  1415. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_PAUSE, "MSG_PAUSE") \
  1416. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_FOCUS, "MSG_FOCUS") \
  1417. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_NO_FOCUS, "MSG_NO_FOCUS") \
  1418. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_SET_NATIVE_WINDOW, "MSG_SET_NATIVE_WINDOW") \
  1419. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_SET_INPUT_QUEUE, "MSG_SET_INPUT_QUEUE") \
  1420. _SAPP_LOGITEM_XMACRO(ANDROID_MSG_DESTROY, "MSG_DESTROY") \
  1421. _SAPP_LOGITEM_XMACRO(ANDROID_UNKNOWN_MSG, "unknown msg type received") \
  1422. _SAPP_LOGITEM_XMACRO(ANDROID_LOOP_THREAD_STARTED, "loop thread started") \
  1423. _SAPP_LOGITEM_XMACRO(ANDROID_LOOP_THREAD_DONE, "loop thread done") \
  1424. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSTART, "NativeActivity onStart()") \
  1425. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONRESUME, "NativeActivity onResume") \
  1426. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSAVEINSTANCESTATE, "NativeActivity onSaveInstanceState") \
  1427. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONWINDOWFOCUSCHANGED, "NativeActivity onWindowFocusChanged") \
  1428. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONPAUSE, "NativeActivity onPause") \
  1429. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONSTOP, "NativeActivity onStop()") \
  1430. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWCREATED, "NativeActivity onNativeWindowCreated") \
  1431. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWDESTROYED, "NativeActivity onNativeWindowDestroyed") \
  1432. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUECREATED, "NativeActivity onInputQueueCreated") \
  1433. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUEDESTROYED, "NativeActivity onInputQueueDestroyed") \
  1434. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONCONFIGURATIONCHANGED, "NativeActivity onConfigurationChanged") \
  1435. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONLOWMEMORY, "NativeActivity onLowMemory") \
  1436. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONDESTROY, "NativeActivity onDestroy") \
  1437. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_DONE, "NativeActivity done") \
  1438. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_ONCREATE, "NativeActivity onCreate") \
  1439. _SAPP_LOGITEM_XMACRO(ANDROID_CREATE_THREAD_PIPE_FAILED, "failed to create thread pipe") \
  1440. _SAPP_LOGITEM_XMACRO(ANDROID_NATIVE_ACTIVITY_CREATE_SUCCESS, "NativeActivity successfully created") \
  1441. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_SURFACE_FAILED, "wgpu: failed to create surface for swapchain") \
  1442. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_SWAPCHAIN_FAILED, "wgpu: failed to create swapchain object") \
  1443. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_TEXTURE_FAILED, "wgpu: failed to create depth-stencil texture for swapchain") \
  1444. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_VIEW_FAILED, "wgpu: failed to create view object for swapchain depth-stencil texture") \
  1445. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_MSAA_TEXTURE_FAILED, "wgpu: failed to create msaa texture for swapchain") \
  1446. _SAPP_LOGITEM_XMACRO(WGPU_SWAPCHAIN_CREATE_MSAA_VIEW_FAILED, "wgpu: failed to create view object for swapchain msaa texture") \
  1447. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_DEVICE_STATUS_ERROR, "wgpu: requesting device failed with status 'error'") \
  1448. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_DEVICE_STATUS_UNKNOWN, "wgpu: requesting device failed with status 'unknown'") \
  1449. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_UNAVAILABLE, "wgpu: requesting adapter failed with 'unavailable'") \
  1450. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_ERROR, "wgpu: requesting adapter failed with status 'error'") \
  1451. _SAPP_LOGITEM_XMACRO(WGPU_REQUEST_ADAPTER_STATUS_UNKNOWN, "wgpu: requesting adapter failed with status 'unknown'") \
  1452. _SAPP_LOGITEM_XMACRO(WGPU_CREATE_INSTANCE_FAILED, "wgpu: failed to create instance") \
  1453. _SAPP_LOGITEM_XMACRO(IMAGE_DATA_SIZE_MISMATCH, "image data size mismatch (must be width*height*4 bytes)") \
  1454. _SAPP_LOGITEM_XMACRO(DROPPED_FILE_PATH_TOO_LONG, "dropped file path too long (sapp_desc.max_dropped_filed_path_length)") \
  1455. _SAPP_LOGITEM_XMACRO(CLIPBOARD_STRING_TOO_BIG, "clipboard string didn't fit into clipboard buffer") \
  1456. #define _SAPP_LOGITEM_XMACRO(item,msg) SAPP_LOGITEM_##item,
  1457. typedef enum sapp_log_item {
  1458. _SAPP_LOG_ITEMS
  1459. } sapp_log_item;
  1460. #undef _SAPP_LOGITEM_XMACRO
  1461. /*
  1462. sapp_logger
  1463. Used in sapp_desc to provide a logging function. Please be aware that
  1464. without logging function, sokol-app will be completely silent, e.g. it will
  1465. not report errors or warnings. For maximum error verbosity, compile in
  1466. debug mode (e.g. NDEBUG *not* defined) and install a logger (for instance
  1467. the standard logging function from sokol_log.h).
  1468. */
  1469. typedef struct sapp_logger {
  1470. void (*func)(
  1471. const char* tag, // always "sapp"
  1472. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  1473. uint32_t log_item_id, // SAPP_LOGITEM_*
  1474. const char* message_or_null, // a message string, may be nullptr in release mode
  1475. uint32_t line_nr, // line number in sokol_app.h
  1476. const char* filename_or_null, // source filename, may be nullptr in release mode
  1477. void* user_data);
  1478. void* user_data;
  1479. } sapp_logger;
  1480. typedef struct sapp_desc {
  1481. void (*init_cb)(void); // these are the user-provided callbacks without user data
  1482. void (*frame_cb)(void);
  1483. void (*cleanup_cb)(void);
  1484. void (*event_cb)(const sapp_event*);
  1485. void* user_data; // these are the user-provided callbacks with user data
  1486. void (*init_userdata_cb)(void*);
  1487. void (*frame_userdata_cb)(void*);
  1488. void (*cleanup_userdata_cb)(void*);
  1489. void (*event_userdata_cb)(const sapp_event*, void*);
  1490. int width; // the preferred width of the window / canvas
  1491. int height; // the preferred height of the window / canvas
  1492. int sample_count; // MSAA sample count
  1493. int swap_interval; // the preferred swap interval (ignored on some platforms)
  1494. bool high_dpi; // whether the rendering canvas is full-resolution on HighDPI displays
  1495. bool fullscreen; // whether the window should be created in fullscreen mode
  1496. bool alpha; // whether the framebuffer should have an alpha channel (ignored on some platforms)
  1497. const char* window_title; // the window title as UTF-8 encoded string
  1498. bool enable_clipboard; // enable clipboard access, default is false
  1499. int clipboard_size; // max size of clipboard content in bytes
  1500. bool enable_dragndrop; // enable file dropping (drag'n'drop), default is false
  1501. int max_dropped_files; // max number of dropped files to process (default: 1)
  1502. int max_dropped_file_path_length; // max length in bytes of a dropped UTF-8 file path (default: 2048)
  1503. sapp_icon_desc icon; // the initial window icon to set
  1504. sapp_allocator allocator; // optional memory allocation overrides (default: malloc/free)
  1505. sapp_logger logger; // logging callback override (default: NO LOGGING!)
  1506. // backend-specific options
  1507. int gl_major_version; // override GL major and minor version (the default GL version is 4.1 on macOS, 4.3 elsewhere)
  1508. int gl_minor_version;
  1509. bool win32_console_utf8; // if true, set the output console codepage to UTF-8
  1510. bool win32_console_create; // if true, attach stdout/stderr to a new console window
  1511. bool win32_console_attach; // if true, attach stdout/stderr to parent process
  1512. const char* html5_canvas_selector; // css selector of the HTML5 canvas element, default is "#canvas"
  1513. bool html5_canvas_resize; // if true, the HTML5 canvas size is set to sapp_desc.width/height, otherwise canvas size is tracked
  1514. bool html5_preserve_drawing_buffer; // HTML5 only: whether to preserve default framebuffer content between frames
  1515. bool html5_premultiplied_alpha; // HTML5 only: whether the rendered pixels use premultiplied alpha convention
  1516. bool html5_ask_leave_site; // initial state of the internal html5_ask_leave_site flag (see sapp_html5_ask_leave_site())
  1517. bool html5_bubble_mouse_events; // if true, mouse events will bubble up to the web page
  1518. bool html5_bubble_touch_events; // same for touch events
  1519. bool html5_bubble_wheel_events; // same for wheel events
  1520. bool html5_bubble_key_events; // if true, bubble up *all* key events to browser, not just key events that represent characters
  1521. bool html5_bubble_char_events; // if true, bubble up character events to browser
  1522. bool html5_use_emsc_set_main_loop; // if true, use emscripten_set_main_loop() instead of emscripten_request_animation_frame_loop()
  1523. bool html5_emsc_set_main_loop_simulate_infinite_loop; // this will be passed as the simulate_infinite_loop arg to emscripten_set_main_loop()
  1524. bool ios_keyboard_resizes_canvas; // if true, showing the iOS keyboard shrinks the canvas
  1525. } sapp_desc;
  1526. /* HTML5 specific: request and response structs for
  1527. asynchronously loading dropped-file content.
  1528. */
  1529. typedef enum sapp_html5_fetch_error {
  1530. SAPP_HTML5_FETCH_ERROR_NO_ERROR,
  1531. SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL,
  1532. SAPP_HTML5_FETCH_ERROR_OTHER,
  1533. } sapp_html5_fetch_error;
  1534. typedef struct sapp_html5_fetch_response {
  1535. bool succeeded; // true if the loading operation has succeeded
  1536. sapp_html5_fetch_error error_code;
  1537. int file_index; // index of the dropped file (0..sapp_get_num_dropped_filed()-1)
  1538. sapp_range data; // pointer and size of the fetched data (data.ptr == buffer.ptr, data.size <= buffer.size)
  1539. sapp_range buffer; // the user-provided buffer ptr/size pair (buffer.ptr == data.ptr, buffer.size >= data.size)
  1540. void* user_data; // user-provided user data pointer
  1541. } sapp_html5_fetch_response;
  1542. typedef struct sapp_html5_fetch_request {
  1543. int dropped_file_index; // 0..sapp_get_num_dropped_files()-1
  1544. void (*callback)(const sapp_html5_fetch_response*); // response callback function pointer (required)
  1545. sapp_range buffer; // ptr/size of a memory buffer to load the data into
  1546. void* user_data; // optional userdata pointer
  1547. } sapp_html5_fetch_request;
  1548. /*
  1549. sapp_mouse_cursor
  1550. Predefined cursor image definitions, set with sapp_set_mouse_cursor(sapp_mouse_cursor cursor)
  1551. */
  1552. typedef enum sapp_mouse_cursor {
  1553. SAPP_MOUSECURSOR_DEFAULT = 0, // equivalent with system default cursor
  1554. SAPP_MOUSECURSOR_ARROW,
  1555. SAPP_MOUSECURSOR_IBEAM,
  1556. SAPP_MOUSECURSOR_CROSSHAIR,
  1557. SAPP_MOUSECURSOR_POINTING_HAND,
  1558. SAPP_MOUSECURSOR_RESIZE_EW,
  1559. SAPP_MOUSECURSOR_RESIZE_NS,
  1560. SAPP_MOUSECURSOR_RESIZE_NWSE,
  1561. SAPP_MOUSECURSOR_RESIZE_NESW,
  1562. SAPP_MOUSECURSOR_RESIZE_ALL,
  1563. SAPP_MOUSECURSOR_NOT_ALLOWED,
  1564. _SAPP_MOUSECURSOR_NUM,
  1565. } sapp_mouse_cursor;
  1566. /* user-provided functions */
  1567. extern sapp_desc sokol_main(int argc, char* argv[]);
  1568. /* returns true after sokol-app has been initialized */
  1569. SOKOL_APP_API_DECL bool sapp_isvalid(void);
  1570. /* returns the current framebuffer width in pixels */
  1571. SOKOL_APP_API_DECL int sapp_width(void);
  1572. /* same as sapp_width(), but returns float */
  1573. SOKOL_APP_API_DECL float sapp_widthf(void);
  1574. /* returns the current framebuffer height in pixels */
  1575. SOKOL_APP_API_DECL int sapp_height(void);
  1576. /* same as sapp_height(), but returns float */
  1577. SOKOL_APP_API_DECL float sapp_heightf(void);
  1578. /* get default framebuffer color pixel format */
  1579. SOKOL_APP_API_DECL int sapp_color_format(void);
  1580. /* get default framebuffer depth pixel format */
  1581. SOKOL_APP_API_DECL int sapp_depth_format(void);
  1582. /* get default framebuffer sample count */
  1583. SOKOL_APP_API_DECL int sapp_sample_count(void);
  1584. /* returns true when high_dpi was requested and actually running in a high-dpi scenario */
  1585. SOKOL_APP_API_DECL bool sapp_high_dpi(void);
  1586. /* returns the dpi scaling factor (window pixels to framebuffer pixels) */
  1587. SOKOL_APP_API_DECL float sapp_dpi_scale(void);
  1588. /* show or hide the mobile device onscreen keyboard */
  1589. SOKOL_APP_API_DECL void sapp_show_keyboard(bool show);
  1590. /* return true if the mobile device onscreen keyboard is currently shown */
  1591. SOKOL_APP_API_DECL bool sapp_keyboard_shown(void);
  1592. /* query fullscreen mode */
  1593. SOKOL_APP_API_DECL bool sapp_is_fullscreen(void);
  1594. /* toggle fullscreen mode */
  1595. SOKOL_APP_API_DECL void sapp_toggle_fullscreen(void);
  1596. /* show or hide the mouse cursor */
  1597. SOKOL_APP_API_DECL void sapp_show_mouse(bool show);
  1598. /* show or hide the mouse cursor */
  1599. SOKOL_APP_API_DECL bool sapp_mouse_shown(void);
  1600. /* enable/disable mouse-pointer-lock mode */
  1601. SOKOL_APP_API_DECL void sapp_lock_mouse(bool lock);
  1602. /* return true if in mouse-pointer-lock mode (this may toggle a few frames later) */
  1603. SOKOL_APP_API_DECL bool sapp_mouse_locked(void);
  1604. /* set mouse cursor type */
  1605. SOKOL_APP_API_DECL void sapp_set_mouse_cursor(sapp_mouse_cursor cursor);
  1606. /* get current mouse cursor type */
  1607. SOKOL_APP_API_DECL sapp_mouse_cursor sapp_get_mouse_cursor(void);
  1608. /* return the userdata pointer optionally provided in sapp_desc */
  1609. SOKOL_APP_API_DECL void* sapp_userdata(void);
  1610. /* return a copy of the sapp_desc structure */
  1611. SOKOL_APP_API_DECL sapp_desc sapp_query_desc(void);
  1612. /* initiate a "soft quit" (sends SAPP_EVENTTYPE_QUIT_REQUESTED) */
  1613. SOKOL_APP_API_DECL void sapp_request_quit(void);
  1614. /* cancel a pending quit (when SAPP_EVENTTYPE_QUIT_REQUESTED has been received) */
  1615. SOKOL_APP_API_DECL void sapp_cancel_quit(void);
  1616. /* initiate a "hard quit" (quit application without sending SAPP_EVENTTYPE_QUIT_REQUESTED) */
  1617. SOKOL_APP_API_DECL void sapp_quit(void);
  1618. /* call from inside event callback to consume the current event (don't forward to platform) */
  1619. SOKOL_APP_API_DECL void sapp_consume_event(void);
  1620. /* get the current frame counter (for comparison with sapp_event.frame_count) */
  1621. SOKOL_APP_API_DECL uint64_t sapp_frame_count(void);
  1622. /* get an averaged/smoothed frame duration in seconds */
  1623. SOKOL_APP_API_DECL double sapp_frame_duration(void);
  1624. /* write string into clipboard */
  1625. SOKOL_APP_API_DECL void sapp_set_clipboard_string(const char* str);
  1626. /* read string from clipboard (usually during SAPP_EVENTTYPE_CLIPBOARD_PASTED) */
  1627. SOKOL_APP_API_DECL const char* sapp_get_clipboard_string(void);
  1628. /* set the window title (only on desktop platforms) */
  1629. SOKOL_APP_API_DECL void sapp_set_window_title(const char* str);
  1630. /* set the window icon (only on Windows and Linux) */
  1631. SOKOL_APP_API_DECL void sapp_set_icon(const sapp_icon_desc* icon_desc);
  1632. /* gets the total number of dropped files (after an SAPP_EVENTTYPE_FILES_DROPPED event) */
  1633. SOKOL_APP_API_DECL int sapp_get_num_dropped_files(void);
  1634. /* gets the dropped file paths */
  1635. SOKOL_APP_API_DECL const char* sapp_get_dropped_file_path(int index);
  1636. /* special run-function for SOKOL_NO_ENTRY (in standard mode this is an empty stub) */
  1637. SOKOL_APP_API_DECL void sapp_run(const sapp_desc* desc);
  1638. /* EGL: get EGLDisplay object */
  1639. SOKOL_APP_API_DECL const void* sapp_egl_get_display(void);
  1640. /* EGL: get EGLContext object */
  1641. SOKOL_APP_API_DECL const void* sapp_egl_get_context(void);
  1642. /* HTML5: enable or disable the hardwired "Leave Site?" dialog box */
  1643. SOKOL_APP_API_DECL void sapp_html5_ask_leave_site(bool ask);
  1644. /* HTML5: get byte size of a dropped file */
  1645. SOKOL_APP_API_DECL uint32_t sapp_html5_get_dropped_file_size(int index);
  1646. /* HTML5: asynchronously load the content of a dropped file */
  1647. SOKOL_APP_API_DECL void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request);
  1648. /* Metal: get bridged pointer to Metal device object */
  1649. SOKOL_APP_API_DECL const void* sapp_metal_get_device(void);
  1650. /* Metal: get bridged pointer to MTKView's current drawable of type CAMetalDrawable */
  1651. SOKOL_APP_API_DECL const void* sapp_metal_get_current_drawable(void);
  1652. /* Metal: get bridged pointer to MTKView's depth-stencil texture of type MTLTexture */
  1653. SOKOL_APP_API_DECL const void* sapp_metal_get_depth_stencil_texture(void);
  1654. /* Metal: get bridged pointer to MTKView's msaa-color-texture of type MTLTexture (may be null) */
  1655. SOKOL_APP_API_DECL const void* sapp_metal_get_msaa_color_texture(void);
  1656. /* macOS: get bridged pointer to macOS NSWindow */
  1657. SOKOL_APP_API_DECL const void* sapp_macos_get_window(void);
  1658. /* iOS: get bridged pointer to iOS UIWindow */
  1659. SOKOL_APP_API_DECL const void* sapp_ios_get_window(void);
  1660. /* D3D11: get pointer to ID3D11Device object */
  1661. SOKOL_APP_API_DECL const void* sapp_d3d11_get_device(void);
  1662. /* D3D11: get pointer to ID3D11DeviceContext object */
  1663. SOKOL_APP_API_DECL const void* sapp_d3d11_get_device_context(void);
  1664. /* D3D11: get pointer to IDXGISwapChain object */
  1665. SOKOL_APP_API_DECL const void* sapp_d3d11_get_swap_chain(void);
  1666. /* D3D11: get pointer to ID3D11RenderTargetView object for rendering */
  1667. SOKOL_APP_API_DECL const void* sapp_d3d11_get_render_view(void);
  1668. /* D3D11: get pointer ID3D11RenderTargetView object for msaa-resolve (may return null) */
  1669. SOKOL_APP_API_DECL const void* sapp_d3d11_get_resolve_view(void);
  1670. /* D3D11: get pointer ID3D11DepthStencilView */
  1671. SOKOL_APP_API_DECL const void* sapp_d3d11_get_depth_stencil_view(void);
  1672. /* Win32: get the HWND window handle */
  1673. SOKOL_APP_API_DECL const void* sapp_win32_get_hwnd(void);
  1674. /* WebGPU: get WGPUDevice handle */
  1675. SOKOL_APP_API_DECL const void* sapp_wgpu_get_device(void);
  1676. /* WebGPU: get swapchain's WGPUTextureView handle for rendering */
  1677. SOKOL_APP_API_DECL const void* sapp_wgpu_get_render_view(void);
  1678. /* WebGPU: get swapchain's MSAA-resolve WGPUTextureView (may return null) */
  1679. SOKOL_APP_API_DECL const void* sapp_wgpu_get_resolve_view(void);
  1680. /* WebGPU: get swapchain's WGPUTextureView for the depth-stencil surface */
  1681. SOKOL_APP_API_DECL const void* sapp_wgpu_get_depth_stencil_view(void);
  1682. /* GL: get framebuffer object */
  1683. SOKOL_APP_API_DECL uint32_t sapp_gl_get_framebuffer(void);
  1684. /* GL: get major version (only valid for desktop GL) */
  1685. SOKOL_APP_API_DECL int sapp_gl_get_major_version(void);
  1686. /* GL: get minor version (only valid for desktop GL) */
  1687. SOKOL_APP_API_DECL int sapp_gl_get_minor_version(void);
  1688. /* Android: get native activity handle */
  1689. SOKOL_APP_API_DECL const void* sapp_android_get_native_activity(void);
  1690. #ifdef __cplusplus
  1691. } /* extern "C" */
  1692. /* reference-based equivalents for C++ */
  1693. inline void sapp_run(const sapp_desc& desc) { return sapp_run(&desc); }
  1694. #endif
  1695. #endif // SOKOL_APP_INCLUDED
  1696. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  1697. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  1698. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  1699. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1700. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  1701. //
  1702. // >>implementation
  1703. #ifdef SOKOL_APP_IMPL
  1704. #define SOKOL_APP_IMPL_INCLUDED (1)
  1705. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  1706. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sapp_desc.allocator to override memory allocation functions"
  1707. #endif
  1708. #include <stdlib.h> // malloc, free
  1709. #include <string.h> // memset, strncmp
  1710. #include <stddef.h> // size_t
  1711. #include <math.h> // roundf
  1712. // helper macros
  1713. #define _sapp_def(val, def) (((val) == 0) ? (def) : (val))
  1714. #define _sapp_absf(a) (((a)<0.0f)?-(a):(a))
  1715. #define _SAPP_MAX_TITLE_LENGTH (128)
  1716. #define _SAPP_FALLBACK_DEFAULT_WINDOW_WIDTH (640)
  1717. #define _SAPP_FALLBACK_DEFAULT_WINDOW_HEIGHT (480)
  1718. // NOTE: the pixel format values *must* be compatible with sg_pixel_format
  1719. #define _SAPP_PIXELFORMAT_RGBA8 (23)
  1720. #define _SAPP_PIXELFORMAT_BGRA8 (28)
  1721. #define _SAPP_PIXELFORMAT_DEPTH (43)
  1722. #define _SAPP_PIXELFORMAT_DEPTH_STENCIL (44)
  1723. // check if the config defines are alright
  1724. #if defined(__APPLE__)
  1725. // see https://clang.llvm.org/docs/LanguageExtensions.html#automatic-reference-counting
  1726. #if !defined(__cplusplus)
  1727. #if __has_feature(objc_arc) && !__has_feature(objc_arc_fields)
  1728. #error "sokol_app.h requires __has_feature(objc_arc_field) if ARC is enabled (use a more recent compiler version)"
  1729. #endif
  1730. #endif
  1731. #define _SAPP_APPLE (1)
  1732. #include <TargetConditionals.h>
  1733. #if defined(TARGET_OS_IPHONE) && !TARGET_OS_IPHONE
  1734. /* MacOS */
  1735. #define _SAPP_MACOS (1)
  1736. #if !defined(SOKOL_METAL) && !defined(SOKOL_GLCORE)
  1737. #error("sokol_app.h: unknown 3D API selected for MacOS, must be SOKOL_METAL or SOKOL_GLCORE")
  1738. #endif
  1739. #else
  1740. /* iOS or iOS Simulator */
  1741. #define _SAPP_IOS (1)
  1742. #if !defined(SOKOL_METAL) && !defined(SOKOL_GLES3)
  1743. #error("sokol_app.h: unknown 3D API selected for iOS, must be SOKOL_METAL or SOKOL_GLES3")
  1744. #endif
  1745. #endif
  1746. #elif defined(__EMSCRIPTEN__)
  1747. /* emscripten (asm.js or wasm) */
  1748. #define _SAPP_EMSCRIPTEN (1)
  1749. #if !defined(SOKOL_GLES3) && !defined(SOKOL_WGPU)
  1750. #error("sokol_app.h: unknown 3D API selected for emscripten, must be SOKOL_GLES3 or SOKOL_WGPU")
  1751. #endif
  1752. #elif defined(_WIN32)
  1753. /* Windows (D3D11 or GL) */
  1754. #define _SAPP_WIN32 (1)
  1755. #if !defined(SOKOL_D3D11) && !defined(SOKOL_GLCORE) && !defined(SOKOL_NOAPI)
  1756. #error("sokol_app.h: unknown 3D API selected for Win32, must be SOKOL_D3D11, SOKOL_GLCORE or SOKOL_NOAPI")
  1757. #endif
  1758. #elif defined(__ANDROID__)
  1759. /* Android */
  1760. #define _SAPP_ANDROID (1)
  1761. #if !defined(SOKOL_GLES3)
  1762. #error("sokol_app.h: unknown 3D API selected for Android, must be SOKOL_GLES3")
  1763. #endif
  1764. #if defined(SOKOL_NO_ENTRY)
  1765. #error("sokol_app.h: SOKOL_NO_ENTRY is not supported on Android")
  1766. #endif
  1767. #elif defined(__linux__) || defined(__unix__)
  1768. /* Linux */
  1769. #define _SAPP_LINUX (1)
  1770. #if defined(SOKOL_GLCORE)
  1771. #if !defined(SOKOL_FORCE_EGL)
  1772. #define _SAPP_GLX (1)
  1773. #endif
  1774. #define GL_GLEXT_PROTOTYPES
  1775. #include <GL/gl.h>
  1776. #elif defined(SOKOL_GLES3)
  1777. #include <GLES3/gl3.h>
  1778. #include <GLES3/gl3ext.h>
  1779. #else
  1780. #error("sokol_app.h: unknown 3D API selected for Linux, must be SOKOL_GLCORE, SOKOL_GLES3")
  1781. #endif
  1782. #else
  1783. #error "sokol_app.h: Unknown platform"
  1784. #endif
  1785. #if defined(SOKOL_GLCORE) || defined(SOKOL_GLES3)
  1786. #define _SAPP_ANY_GL (1)
  1787. #endif
  1788. #ifndef SOKOL_API_IMPL
  1789. #define SOKOL_API_IMPL
  1790. #endif
  1791. #ifndef SOKOL_DEBUG
  1792. #ifndef NDEBUG
  1793. #define SOKOL_DEBUG
  1794. #endif
  1795. #endif
  1796. #ifndef SOKOL_ASSERT
  1797. #include <assert.h>
  1798. #define SOKOL_ASSERT(c) assert(c)
  1799. #endif
  1800. #ifndef SOKOL_UNREACHABLE
  1801. #define SOKOL_UNREACHABLE SOKOL_ASSERT(false)
  1802. #endif
  1803. #ifndef _SOKOL_PRIVATE
  1804. #if defined(__GNUC__) || defined(__clang__)
  1805. #define _SOKOL_PRIVATE __attribute__((unused)) static
  1806. #else
  1807. #define _SOKOL_PRIVATE static
  1808. #endif
  1809. #endif
  1810. #ifndef _SOKOL_UNUSED
  1811. #define _SOKOL_UNUSED(x) (void)(x)
  1812. #endif
  1813. #if defined(_SAPP_APPLE)
  1814. #if defined(SOKOL_METAL)
  1815. #import <Metal/Metal.h>
  1816. #import <MetalKit/MetalKit.h>
  1817. #endif
  1818. #if defined(_SAPP_MACOS)
  1819. #if defined(_SAPP_ANY_GL)
  1820. #ifndef GL_SILENCE_DEPRECATION
  1821. #define GL_SILENCE_DEPRECATION
  1822. #endif
  1823. #include <Cocoa/Cocoa.h>
  1824. #include <OpenGL/gl3.h>
  1825. #endif
  1826. #elif defined(_SAPP_IOS)
  1827. #import <UIKit/UIKit.h>
  1828. #if defined(_SAPP_ANY_GL)
  1829. #import <GLKit/GLKit.h>
  1830. #include <OpenGLES/ES3/gl.h>
  1831. #endif
  1832. #endif
  1833. #include <AvailabilityMacros.h>
  1834. #include <mach/mach_time.h>
  1835. #elif defined(_SAPP_EMSCRIPTEN)
  1836. #if defined(SOKOL_WGPU)
  1837. #include <webgpu/webgpu.h>
  1838. #endif
  1839. #if defined(SOKOL_GLES3)
  1840. #include <GLES3/gl3.h>
  1841. #endif
  1842. #include <emscripten/emscripten.h>
  1843. #include <emscripten/html5.h>
  1844. #elif defined(_SAPP_WIN32)
  1845. #ifdef _MSC_VER
  1846. #pragma warning(push)
  1847. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  1848. #pragma warning(disable:4204) /* nonstandard extension used: non-constant aggregate initializer */
  1849. #pragma warning(disable:4054) /* 'type cast': from function pointer */
  1850. #pragma warning(disable:4055) /* 'type cast': from data pointer */
  1851. #pragma warning(disable:4505) /* unreferenced local function has been removed */
  1852. #pragma warning(disable:4115) /* /W4: 'ID3D11ModuleInstance': named type definition in parentheses (in d3d11.h) */
  1853. #endif
  1854. #ifndef WIN32_LEAN_AND_MEAN
  1855. #define WIN32_LEAN_AND_MEAN
  1856. #endif
  1857. #ifndef NOMINMAX
  1858. #define NOMINMAX
  1859. #endif
  1860. #include <windows.h>
  1861. #include <windowsx.h>
  1862. #include <shellapi.h>
  1863. #if !defined(SOKOL_NO_ENTRY) // if SOKOL_NO_ENTRY is defined, it's the application's responsibility to use the right subsystem
  1864. #if defined(SOKOL_WIN32_FORCE_MAIN) && defined(SOKOL_WIN32_FORCE_WINMAIN)
  1865. // If both are defined, it's the application's responsibility to use the right subsystem
  1866. #elif defined(SOKOL_WIN32_FORCE_MAIN)
  1867. #pragma comment (linker, "/subsystem:console")
  1868. #else
  1869. #pragma comment (linker, "/subsystem:windows")
  1870. #endif
  1871. #endif
  1872. #include <stdio.h> /* freopen_s() */
  1873. #include <wchar.h> /* wcslen() */
  1874. #pragma comment (lib, "kernel32")
  1875. #pragma comment (lib, "user32")
  1876. #pragma comment (lib, "shell32") /* CommandLineToArgvW, DragQueryFileW, DragFinished */
  1877. #pragma comment (lib, "gdi32")
  1878. #if defined(SOKOL_D3D11)
  1879. #pragma comment (lib, "dxgi")
  1880. #pragma comment (lib, "d3d11")
  1881. #endif
  1882. #if defined(SOKOL_D3D11)
  1883. #ifndef D3D11_NO_HELPERS
  1884. #define D3D11_NO_HELPERS
  1885. #endif
  1886. #include <d3d11.h>
  1887. #include <dxgi.h>
  1888. // DXGI_SWAP_EFFECT_FLIP_DISCARD is only defined in newer Windows SDKs, so don't depend on it
  1889. #define _SAPP_DXGI_SWAP_EFFECT_FLIP_DISCARD (4)
  1890. #endif
  1891. #ifndef WM_MOUSEHWHEEL /* see https://github.com/floooh/sokol/issues/138 */
  1892. #define WM_MOUSEHWHEEL (0x020E)
  1893. #endif
  1894. #ifndef WM_DPICHANGED
  1895. #define WM_DPICHANGED (0x02E0)
  1896. #endif
  1897. #elif defined(_SAPP_ANDROID)
  1898. #include <pthread.h>
  1899. #include <unistd.h>
  1900. #include <time.h>
  1901. #include <android/native_activity.h>
  1902. #include <android/looper.h>
  1903. #include <EGL/egl.h>
  1904. #include <GLES3/gl3.h>
  1905. #elif defined(_SAPP_LINUX)
  1906. #define GL_GLEXT_PROTOTYPES
  1907. #include <X11/Xlib.h>
  1908. #include <X11/Xutil.h>
  1909. #include <X11/XKBlib.h>
  1910. #include <X11/keysym.h>
  1911. #include <X11/Xresource.h>
  1912. #include <X11/Xatom.h>
  1913. #include <X11/extensions/XInput2.h>
  1914. #include <X11/Xcursor/Xcursor.h>
  1915. #include <X11/cursorfont.h> /* XC_* font cursors */
  1916. #include <X11/Xmd.h> /* CARD32 */
  1917. #if !defined(_SAPP_GLX)
  1918. #include <EGL/egl.h>
  1919. #endif
  1920. #include <dlfcn.h> /* dlopen, dlsym, dlclose */
  1921. #include <limits.h> /* LONG_MAX */
  1922. #include <pthread.h> /* only used a linker-guard, search for _sapp_linux_run() and see first comment */
  1923. #include <time.h>
  1924. #include <poll.h>
  1925. #endif
  1926. #if defined(_SAPP_APPLE)
  1927. // this is ARC compatible
  1928. #if defined(__cplusplus)
  1929. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { item = type(); }
  1930. #else
  1931. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { item = (type) { 0 }; }
  1932. #endif
  1933. #else
  1934. #define _SAPP_CLEAR_ARC_STRUCT(type, item) { _sapp_clear(&item, sizeof(item)); }
  1935. #endif
  1936. // ███████ ██████ █████ ███ ███ ███████ ████████ ██ ███ ███ ██ ███ ██ ██████
  1937. // ██ ██ ██ ██ ██ ████ ████ ██ ██ ██ ████ ████ ██ ████ ██ ██
  1938. // █████ ██████ ███████ ██ ████ ██ █████ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ███
  1939. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1940. // ██ ██ ██ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ████ ██████
  1941. //
  1942. // >>frame timing
  1943. #define _SAPP_RING_NUM_SLOTS (256)
  1944. typedef struct {
  1945. int head;
  1946. int tail;
  1947. double buf[_SAPP_RING_NUM_SLOTS];
  1948. } _sapp_ring_t;
  1949. _SOKOL_PRIVATE int _sapp_ring_idx(int i) {
  1950. return i % _SAPP_RING_NUM_SLOTS;
  1951. }
  1952. _SOKOL_PRIVATE void _sapp_ring_init(_sapp_ring_t* ring) {
  1953. ring->head = 0;
  1954. ring->tail = 0;
  1955. }
  1956. _SOKOL_PRIVATE bool _sapp_ring_full(_sapp_ring_t* ring) {
  1957. return _sapp_ring_idx(ring->head + 1) == ring->tail;
  1958. }
  1959. _SOKOL_PRIVATE bool _sapp_ring_empty(_sapp_ring_t* ring) {
  1960. return ring->head == ring->tail;
  1961. }
  1962. _SOKOL_PRIVATE int _sapp_ring_count(_sapp_ring_t* ring) {
  1963. int count;
  1964. if (ring->head >= ring->tail) {
  1965. count = ring->head - ring->tail;
  1966. }
  1967. else {
  1968. count = (ring->head + _SAPP_RING_NUM_SLOTS) - ring->tail;
  1969. }
  1970. SOKOL_ASSERT((count >= 0) && (count < _SAPP_RING_NUM_SLOTS));
  1971. return count;
  1972. }
  1973. _SOKOL_PRIVATE void _sapp_ring_enqueue(_sapp_ring_t* ring, double val) {
  1974. SOKOL_ASSERT(!_sapp_ring_full(ring));
  1975. ring->buf[ring->head] = val;
  1976. ring->head = _sapp_ring_idx(ring->head + 1);
  1977. }
  1978. _SOKOL_PRIVATE double _sapp_ring_dequeue(_sapp_ring_t* ring) {
  1979. SOKOL_ASSERT(!_sapp_ring_empty(ring));
  1980. double val = ring->buf[ring->tail];
  1981. ring->tail = _sapp_ring_idx(ring->tail + 1);
  1982. return val;
  1983. }
  1984. /*
  1985. NOTE:
  1986. Q: Why not use CAMetalDrawable.presentedTime on macOS and iOS?
  1987. A: The value appears to be highly unstable during the first few
  1988. seconds, sometimes several frames are dropped in sequence, or
  1989. switch between 120 and 60 Hz for a few frames. Simply measuring
  1990. and averaging the frame time yielded a more stable frame duration.
  1991. Maybe switching to CVDisplayLink would yield better results.
  1992. Until then just measure the time.
  1993. */
  1994. typedef struct {
  1995. #if defined(_SAPP_APPLE)
  1996. struct {
  1997. mach_timebase_info_data_t timebase;
  1998. uint64_t start;
  1999. } mach;
  2000. #elif defined(_SAPP_EMSCRIPTEN)
  2001. // empty
  2002. #elif defined(_SAPP_WIN32)
  2003. struct {
  2004. LARGE_INTEGER freq;
  2005. LARGE_INTEGER start;
  2006. } win;
  2007. #else // Linux, Android, ...
  2008. #ifdef CLOCK_MONOTONIC
  2009. #define _SAPP_CLOCK_MONOTONIC CLOCK_MONOTONIC
  2010. #else
  2011. // on some embedded platforms, CLOCK_MONOTONIC isn't defined
  2012. #define _SAPP_CLOCK_MONOTONIC (1)
  2013. #endif
  2014. struct {
  2015. uint64_t start;
  2016. } posix;
  2017. #endif
  2018. } _sapp_timestamp_t;
  2019. _SOKOL_PRIVATE int64_t _sapp_int64_muldiv(int64_t value, int64_t numer, int64_t denom) {
  2020. int64_t q = value / denom;
  2021. int64_t r = value % denom;
  2022. return q * numer + r * numer / denom;
  2023. }
  2024. _SOKOL_PRIVATE void _sapp_timestamp_init(_sapp_timestamp_t* ts) {
  2025. #if defined(_SAPP_APPLE)
  2026. mach_timebase_info(&ts->mach.timebase);
  2027. ts->mach.start = mach_absolute_time();
  2028. #elif defined(_SAPP_EMSCRIPTEN)
  2029. (void)ts;
  2030. #elif defined(_SAPP_WIN32)
  2031. QueryPerformanceFrequency(&ts->win.freq);
  2032. QueryPerformanceCounter(&ts->win.start);
  2033. #else
  2034. struct timespec tspec;
  2035. clock_gettime(_SAPP_CLOCK_MONOTONIC, &tspec);
  2036. ts->posix.start = (uint64_t)tspec.tv_sec*1000000000 + (uint64_t)tspec.tv_nsec;
  2037. #endif
  2038. }
  2039. _SOKOL_PRIVATE double _sapp_timestamp_now(_sapp_timestamp_t* ts) {
  2040. #if defined(_SAPP_APPLE)
  2041. const uint64_t traw = mach_absolute_time() - ts->mach.start;
  2042. const uint64_t now = (uint64_t) _sapp_int64_muldiv((int64_t)traw, (int64_t)ts->mach.timebase.numer, (int64_t)ts->mach.timebase.denom);
  2043. return (double)now / 1000000000.0;
  2044. #elif defined(_SAPP_EMSCRIPTEN)
  2045. (void)ts;
  2046. SOKOL_ASSERT(false);
  2047. return 0.0;
  2048. #elif defined(_SAPP_WIN32)
  2049. LARGE_INTEGER qpc;
  2050. QueryPerformanceCounter(&qpc);
  2051. const uint64_t now = (uint64_t)_sapp_int64_muldiv(qpc.QuadPart - ts->win.start.QuadPart, 1000000000, ts->win.freq.QuadPart);
  2052. return (double)now / 1000000000.0;
  2053. #else
  2054. struct timespec tspec;
  2055. clock_gettime(_SAPP_CLOCK_MONOTONIC, &tspec);
  2056. const uint64_t now = ((uint64_t)tspec.tv_sec*1000000000 + (uint64_t)tspec.tv_nsec) - ts->posix.start;
  2057. return (double)now / 1000000000.0;
  2058. #endif
  2059. }
  2060. typedef struct {
  2061. double last;
  2062. double accum;
  2063. double avg;
  2064. int spike_count;
  2065. int num;
  2066. _sapp_timestamp_t timestamp;
  2067. _sapp_ring_t ring;
  2068. } _sapp_timing_t;
  2069. _SOKOL_PRIVATE void _sapp_timing_reset(_sapp_timing_t* t) {
  2070. t->last = 0.0;
  2071. t->accum = 0.0;
  2072. t->spike_count = 0;
  2073. t->num = 0;
  2074. _sapp_ring_init(&t->ring);
  2075. }
  2076. _SOKOL_PRIVATE void _sapp_timing_init(_sapp_timing_t* t) {
  2077. t->avg = 1.0 / 60.0; // dummy value until first actual value is available
  2078. _sapp_timing_reset(t);
  2079. _sapp_timestamp_init(&t->timestamp);
  2080. }
  2081. _SOKOL_PRIVATE void _sapp_timing_put(_sapp_timing_t* t, double dur) {
  2082. // arbitrary upper limit to ignore outliers (e.g. during window resizing, or debugging)
  2083. double min_dur = 0.0;
  2084. double max_dur = 0.1;
  2085. // if we have enough samples for a useful average, use a much tighter 'valid window'
  2086. if (_sapp_ring_full(&t->ring)) {
  2087. min_dur = t->avg * 0.8;
  2088. max_dur = t->avg * 1.2;
  2089. }
  2090. if ((dur < min_dur) || (dur > max_dur)) {
  2091. t->spike_count++;
  2092. // if there have been many spikes in a row, the display refresh rate
  2093. // might have changed, so a timing reset is needed
  2094. if (t->spike_count > 20) {
  2095. _sapp_timing_reset(t);
  2096. }
  2097. return;
  2098. }
  2099. if (_sapp_ring_full(&t->ring)) {
  2100. double old_val = _sapp_ring_dequeue(&t->ring);
  2101. t->accum -= old_val;
  2102. t->num -= 1;
  2103. }
  2104. _sapp_ring_enqueue(&t->ring, dur);
  2105. t->accum += dur;
  2106. t->num += 1;
  2107. SOKOL_ASSERT(t->num > 0);
  2108. t->avg = t->accum / t->num;
  2109. t->spike_count = 0;
  2110. }
  2111. _SOKOL_PRIVATE void _sapp_timing_discontinuity(_sapp_timing_t* t) {
  2112. t->last = 0.0;
  2113. }
  2114. _SOKOL_PRIVATE void _sapp_timing_measure(_sapp_timing_t* t) {
  2115. const double now = _sapp_timestamp_now(&t->timestamp);
  2116. if (t->last > 0.0) {
  2117. double dur = now - t->last;
  2118. _sapp_timing_put(t, dur);
  2119. }
  2120. t->last = now;
  2121. }
  2122. _SOKOL_PRIVATE void _sapp_timing_external(_sapp_timing_t* t, double now) {
  2123. if (t->last > 0.0) {
  2124. double dur = now - t->last;
  2125. _sapp_timing_put(t, dur);
  2126. }
  2127. t->last = now;
  2128. }
  2129. _SOKOL_PRIVATE double _sapp_timing_get_avg(_sapp_timing_t* t) {
  2130. return t->avg;
  2131. }
  2132. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  2133. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2134. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  2135. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2136. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  2137. //
  2138. // >> structs
  2139. #if defined(_SAPP_MACOS)
  2140. @interface _sapp_macos_app_delegate : NSObject<NSApplicationDelegate>
  2141. @end
  2142. @interface _sapp_macos_window : NSWindow
  2143. @end
  2144. @interface _sapp_macos_window_delegate : NSObject<NSWindowDelegate>
  2145. @end
  2146. #if defined(SOKOL_METAL)
  2147. @interface _sapp_macos_view : MTKView
  2148. @end
  2149. #elif defined(SOKOL_GLCORE)
  2150. @interface _sapp_macos_view : NSOpenGLView
  2151. - (void)timerFired:(id)sender;
  2152. @end
  2153. #endif // SOKOL_GLCORE
  2154. typedef struct {
  2155. uint32_t flags_changed_store;
  2156. uint8_t mouse_buttons;
  2157. NSWindow* window;
  2158. NSTrackingArea* tracking_area;
  2159. id keyup_monitor;
  2160. _sapp_macos_app_delegate* app_dlg;
  2161. _sapp_macos_window_delegate* win_dlg;
  2162. _sapp_macos_view* view;
  2163. NSCursor* cursors[_SAPP_MOUSECURSOR_NUM];
  2164. #if defined(SOKOL_METAL)
  2165. id<MTLDevice> mtl_device;
  2166. #endif
  2167. } _sapp_macos_t;
  2168. #endif // _SAPP_MACOS
  2169. #if defined(_SAPP_IOS)
  2170. @interface _sapp_app_delegate : NSObject<UIApplicationDelegate>
  2171. @end
  2172. @interface _sapp_textfield_dlg : NSObject<UITextFieldDelegate>
  2173. - (void)keyboardWasShown:(NSNotification*)notif;
  2174. - (void)keyboardWillBeHidden:(NSNotification*)notif;
  2175. - (void)keyboardDidChangeFrame:(NSNotification*)notif;
  2176. @end
  2177. #if defined(SOKOL_METAL)
  2178. @interface _sapp_ios_view : MTKView;
  2179. @end
  2180. #else
  2181. @interface _sapp_ios_view : GLKView
  2182. @end
  2183. #endif
  2184. typedef struct {
  2185. UIWindow* window;
  2186. _sapp_ios_view* view;
  2187. UITextField* textfield;
  2188. _sapp_textfield_dlg* textfield_dlg;
  2189. #if defined(SOKOL_METAL)
  2190. UIViewController* view_ctrl;
  2191. id<MTLDevice> mtl_device;
  2192. #else
  2193. GLKViewController* view_ctrl;
  2194. EAGLContext* eagl_ctx;
  2195. #endif
  2196. bool suspended;
  2197. } _sapp_ios_t;
  2198. #endif // _SAPP_IOS
  2199. #if defined(_SAPP_EMSCRIPTEN)
  2200. #if defined(SOKOL_WGPU)
  2201. typedef struct {
  2202. WGPUInstance instance;
  2203. WGPUAdapter adapter;
  2204. WGPUDevice device;
  2205. WGPUTextureFormat render_format;
  2206. WGPUSurface surface;
  2207. WGPUSwapChain swapchain;
  2208. WGPUTexture msaa_tex;
  2209. WGPUTextureView msaa_view;
  2210. WGPUTexture depth_stencil_tex;
  2211. WGPUTextureView depth_stencil_view;
  2212. WGPUTextureView swapchain_view;
  2213. bool async_init_done;
  2214. } _sapp_wgpu_t;
  2215. #endif
  2216. typedef struct {
  2217. bool mouse_lock_requested;
  2218. uint16_t mouse_buttons;
  2219. } _sapp_emsc_t;
  2220. #endif // _SAPP_EMSCRIPTEN
  2221. #if defined(SOKOL_D3D11) && defined(_SAPP_WIN32)
  2222. typedef struct {
  2223. ID3D11Device* device;
  2224. ID3D11DeviceContext* device_context;
  2225. ID3D11Texture2D* rt;
  2226. ID3D11RenderTargetView* rtv;
  2227. ID3D11Texture2D* msaa_rt;
  2228. ID3D11RenderTargetView* msaa_rtv;
  2229. ID3D11Texture2D* ds;
  2230. ID3D11DepthStencilView* dsv;
  2231. DXGI_SWAP_CHAIN_DESC swap_chain_desc;
  2232. IDXGISwapChain* swap_chain;
  2233. IDXGIDevice1* dxgi_device;
  2234. bool use_dxgi_frame_stats;
  2235. UINT sync_refresh_count;
  2236. } _sapp_d3d11_t;
  2237. #endif
  2238. #if defined(_SAPP_WIN32)
  2239. #ifndef DPI_ENUMS_DECLARED
  2240. typedef enum PROCESS_DPI_AWARENESS
  2241. {
  2242. PROCESS_DPI_UNAWARE = 0,
  2243. PROCESS_SYSTEM_DPI_AWARE = 1,
  2244. PROCESS_PER_MONITOR_DPI_AWARE = 2
  2245. } PROCESS_DPI_AWARENESS;
  2246. typedef enum MONITOR_DPI_TYPE {
  2247. MDT_EFFECTIVE_DPI = 0,
  2248. MDT_ANGULAR_DPI = 1,
  2249. MDT_RAW_DPI = 2,
  2250. MDT_DEFAULT = MDT_EFFECTIVE_DPI
  2251. } MONITOR_DPI_TYPE;
  2252. #endif // DPI_ENUMS_DECLARED
  2253. typedef struct {
  2254. bool aware;
  2255. float content_scale;
  2256. float window_scale;
  2257. float mouse_scale;
  2258. } _sapp_win32_dpi_t;
  2259. typedef struct {
  2260. HWND hwnd;
  2261. HMONITOR hmonitor;
  2262. HDC dc;
  2263. HICON big_icon;
  2264. HICON small_icon;
  2265. HCURSOR cursors[_SAPP_MOUSECURSOR_NUM];
  2266. UINT orig_codepage;
  2267. LONG mouse_locked_x, mouse_locked_y;
  2268. RECT stored_window_rect; // used to restore window pos/size when toggling fullscreen => windowed
  2269. bool is_win10_or_greater;
  2270. bool in_create_window;
  2271. bool iconified;
  2272. bool mouse_tracked;
  2273. uint8_t mouse_capture_mask;
  2274. _sapp_win32_dpi_t dpi;
  2275. bool raw_input_mousepos_valid;
  2276. LONG raw_input_mousepos_x;
  2277. LONG raw_input_mousepos_y;
  2278. uint8_t raw_input_data[256];
  2279. } _sapp_win32_t;
  2280. #if defined(SOKOL_GLCORE)
  2281. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  2282. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  2283. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  2284. #define WGL_PIXEL_TYPE_ARB 0x2013
  2285. #define WGL_TYPE_RGBA_ARB 0x202b
  2286. #define WGL_ACCELERATION_ARB 0x2003
  2287. #define WGL_NO_ACCELERATION_ARB 0x2025
  2288. #define WGL_RED_BITS_ARB 0x2015
  2289. #define WGL_GREEN_BITS_ARB 0x2017
  2290. #define WGL_BLUE_BITS_ARB 0x2019
  2291. #define WGL_ALPHA_BITS_ARB 0x201b
  2292. #define WGL_DEPTH_BITS_ARB 0x2022
  2293. #define WGL_STENCIL_BITS_ARB 0x2023
  2294. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  2295. #define WGL_SAMPLES_ARB 0x2042
  2296. #define WGL_CONTEXT_DEBUG_BIT_ARB 0x00000001
  2297. #define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  2298. #define WGL_CONTEXT_PROFILE_MASK_ARB 0x9126
  2299. #define WGL_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  2300. #define WGL_CONTEXT_MAJOR_VERSION_ARB 0x2091
  2301. #define WGL_CONTEXT_MINOR_VERSION_ARB 0x2092
  2302. #define WGL_CONTEXT_FLAGS_ARB 0x2094
  2303. #define ERROR_INVALID_VERSION_ARB 0x2095
  2304. #define ERROR_INVALID_PROFILE_ARB 0x2096
  2305. #define ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB 0x2054
  2306. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC)(int);
  2307. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC)(HDC,int,int,UINT,const int*,int*);
  2308. typedef const char* (WINAPI * PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void);
  2309. typedef const char* (WINAPI * PFNWGLGETEXTENSIONSSTRINGARBPROC)(HDC);
  2310. typedef HGLRC (WINAPI * PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC,HGLRC,const int*);
  2311. typedef HGLRC (WINAPI * PFN_wglCreateContext)(HDC);
  2312. typedef BOOL (WINAPI * PFN_wglDeleteContext)(HGLRC);
  2313. typedef PROC (WINAPI * PFN_wglGetProcAddress)(LPCSTR);
  2314. typedef HDC (WINAPI * PFN_wglGetCurrentDC)(void);
  2315. typedef BOOL (WINAPI * PFN_wglMakeCurrent)(HDC,HGLRC);
  2316. typedef struct {
  2317. HINSTANCE opengl32;
  2318. HGLRC gl_ctx;
  2319. PFN_wglCreateContext CreateContext;
  2320. PFN_wglDeleteContext DeleteContext;
  2321. PFN_wglGetProcAddress GetProcAddress;
  2322. PFN_wglGetCurrentDC GetCurrentDC;
  2323. PFN_wglMakeCurrent MakeCurrent;
  2324. PFNWGLSWAPINTERVALEXTPROC SwapIntervalEXT;
  2325. PFNWGLGETPIXELFORMATATTRIBIVARBPROC GetPixelFormatAttribivARB;
  2326. PFNWGLGETEXTENSIONSSTRINGEXTPROC GetExtensionsStringEXT;
  2327. PFNWGLGETEXTENSIONSSTRINGARBPROC GetExtensionsStringARB;
  2328. PFNWGLCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
  2329. // special case glGetIntegerv
  2330. void (WINAPI *GetIntegerv)(uint32_t pname, int32_t* data);
  2331. bool ext_swap_control;
  2332. bool arb_multisample;
  2333. bool arb_pixel_format;
  2334. bool arb_create_context;
  2335. bool arb_create_context_profile;
  2336. HWND msg_hwnd;
  2337. HDC msg_dc;
  2338. } _sapp_wgl_t;
  2339. #endif // SOKOL_GLCORE
  2340. #endif // _SAPP_WIN32
  2341. #if defined(_SAPP_ANDROID)
  2342. typedef enum {
  2343. _SOKOL_ANDROID_MSG_CREATE,
  2344. _SOKOL_ANDROID_MSG_RESUME,
  2345. _SOKOL_ANDROID_MSG_PAUSE,
  2346. _SOKOL_ANDROID_MSG_FOCUS,
  2347. _SOKOL_ANDROID_MSG_NO_FOCUS,
  2348. _SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW,
  2349. _SOKOL_ANDROID_MSG_SET_INPUT_QUEUE,
  2350. _SOKOL_ANDROID_MSG_DESTROY,
  2351. } _sapp_android_msg_t;
  2352. typedef struct {
  2353. pthread_t thread;
  2354. pthread_mutex_t mutex;
  2355. pthread_cond_t cond;
  2356. int read_from_main_fd;
  2357. int write_from_main_fd;
  2358. } _sapp_android_pt_t;
  2359. typedef struct {
  2360. ANativeWindow* window;
  2361. AInputQueue* input;
  2362. } _sapp_android_resources_t;
  2363. typedef struct {
  2364. ANativeActivity* activity;
  2365. _sapp_android_pt_t pt;
  2366. _sapp_android_resources_t pending;
  2367. _sapp_android_resources_t current;
  2368. ALooper* looper;
  2369. bool is_thread_started;
  2370. bool is_thread_stopping;
  2371. bool is_thread_stopped;
  2372. bool has_created;
  2373. bool has_resumed;
  2374. bool has_focus;
  2375. EGLConfig config;
  2376. EGLDisplay display;
  2377. EGLContext context;
  2378. EGLSurface surface;
  2379. } _sapp_android_t;
  2380. #endif // _SAPP_ANDROID
  2381. #if defined(_SAPP_LINUX)
  2382. #define _SAPP_X11_XDND_VERSION (5)
  2383. #define _SAPP_X11_MAX_X11_KEYCODES (256)
  2384. #define GLX_VENDOR 1
  2385. #define GLX_RGBA_BIT 0x00000001
  2386. #define GLX_WINDOW_BIT 0x00000001
  2387. #define GLX_DRAWABLE_TYPE 0x8010
  2388. #define GLX_RENDER_TYPE 0x8011
  2389. #define GLX_DOUBLEBUFFER 5
  2390. #define GLX_RED_SIZE 8
  2391. #define GLX_GREEN_SIZE 9
  2392. #define GLX_BLUE_SIZE 10
  2393. #define GLX_ALPHA_SIZE 11
  2394. #define GLX_DEPTH_SIZE 12
  2395. #define GLX_STENCIL_SIZE 13
  2396. #define GLX_SAMPLES 0x186a1
  2397. #define GLX_CONTEXT_CORE_PROFILE_BIT_ARB 0x00000001
  2398. #define GLX_CONTEXT_PROFILE_MASK_ARB 0x9126
  2399. #define GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB 0x00000002
  2400. #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091
  2401. #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092
  2402. #define GLX_CONTEXT_FLAGS_ARB 0x2094
  2403. typedef XID GLXWindow;
  2404. typedef XID GLXDrawable;
  2405. typedef struct __GLXFBConfig* GLXFBConfig;
  2406. typedef struct __GLXcontext* GLXContext;
  2407. typedef void (*__GLXextproc)(void);
  2408. typedef int (*PFNGLXGETFBCONFIGATTRIBPROC)(Display*,GLXFBConfig,int,int*);
  2409. typedef const char* (*PFNGLXGETCLIENTSTRINGPROC)(Display*,int);
  2410. typedef Bool (*PFNGLXQUERYEXTENSIONPROC)(Display*,int*,int*);
  2411. typedef Bool (*PFNGLXQUERYVERSIONPROC)(Display*,int*,int*);
  2412. typedef void (*PFNGLXDESTROYCONTEXTPROC)(Display*,GLXContext);
  2413. typedef Bool (*PFNGLXMAKECURRENTPROC)(Display*,GLXDrawable,GLXContext);
  2414. typedef void (*PFNGLXSWAPBUFFERSPROC)(Display*,GLXDrawable);
  2415. typedef const char* (*PFNGLXQUERYEXTENSIONSSTRINGPROC)(Display*,int);
  2416. typedef GLXFBConfig* (*PFNGLXGETFBCONFIGSPROC)(Display*,int,int*);
  2417. typedef __GLXextproc (* PFNGLXGETPROCADDRESSPROC)(const char *procName);
  2418. typedef void (*PFNGLXSWAPINTERVALEXTPROC)(Display*,GLXDrawable,int);
  2419. typedef XVisualInfo* (*PFNGLXGETVISUALFROMFBCONFIGPROC)(Display*,GLXFBConfig);
  2420. typedef GLXWindow (*PFNGLXCREATEWINDOWPROC)(Display*,GLXFBConfig,Window,const int*);
  2421. typedef void (*PFNGLXDESTROYWINDOWPROC)(Display*,GLXWindow);
  2422. typedef int (*PFNGLXSWAPINTERVALMESAPROC)(int);
  2423. typedef GLXContext (*PFNGLXCREATECONTEXTATTRIBSARBPROC)(Display*,GLXFBConfig,GLXContext,Bool,const int*);
  2424. typedef struct {
  2425. bool available;
  2426. int major_opcode;
  2427. int event_base;
  2428. int error_base;
  2429. int major;
  2430. int minor;
  2431. } _sapp_xi_t;
  2432. typedef struct {
  2433. int version;
  2434. Window source;
  2435. Atom format;
  2436. Atom XdndAware;
  2437. Atom XdndEnter;
  2438. Atom XdndPosition;
  2439. Atom XdndStatus;
  2440. Atom XdndActionCopy;
  2441. Atom XdndDrop;
  2442. Atom XdndFinished;
  2443. Atom XdndSelection;
  2444. Atom XdndTypeList;
  2445. Atom text_uri_list;
  2446. } _sapp_xdnd_t;
  2447. typedef struct {
  2448. uint8_t mouse_buttons;
  2449. Display* display;
  2450. int screen;
  2451. Window root;
  2452. Colormap colormap;
  2453. Window window;
  2454. Cursor hidden_cursor;
  2455. Cursor cursors[_SAPP_MOUSECURSOR_NUM];
  2456. int window_state;
  2457. float dpi;
  2458. unsigned char error_code;
  2459. Atom UTF8_STRING;
  2460. Atom CLIPBOARD;
  2461. Atom TARGETS;
  2462. Atom WM_PROTOCOLS;
  2463. Atom WM_DELETE_WINDOW;
  2464. Atom WM_STATE;
  2465. Atom NET_WM_NAME;
  2466. Atom NET_WM_ICON_NAME;
  2467. Atom NET_WM_ICON;
  2468. Atom NET_WM_STATE;
  2469. Atom NET_WM_STATE_FULLSCREEN;
  2470. _sapp_xi_t xi;
  2471. _sapp_xdnd_t xdnd;
  2472. // XLib manual says keycodes are in the range [8, 255] inclusive.
  2473. // https://tronche.com/gui/x/xlib/input/keyboard-encoding.html
  2474. bool key_repeat[_SAPP_X11_MAX_X11_KEYCODES];
  2475. } _sapp_x11_t;
  2476. #if defined(_SAPP_GLX)
  2477. typedef struct {
  2478. void* libgl;
  2479. int major;
  2480. int minor;
  2481. int event_base;
  2482. int error_base;
  2483. GLXContext ctx;
  2484. GLXWindow window;
  2485. // GLX 1.3 functions
  2486. PFNGLXGETFBCONFIGSPROC GetFBConfigs;
  2487. PFNGLXGETFBCONFIGATTRIBPROC GetFBConfigAttrib;
  2488. PFNGLXGETCLIENTSTRINGPROC GetClientString;
  2489. PFNGLXQUERYEXTENSIONPROC QueryExtension;
  2490. PFNGLXQUERYVERSIONPROC QueryVersion;
  2491. PFNGLXDESTROYCONTEXTPROC DestroyContext;
  2492. PFNGLXMAKECURRENTPROC MakeCurrent;
  2493. PFNGLXSWAPBUFFERSPROC SwapBuffers;
  2494. PFNGLXQUERYEXTENSIONSSTRINGPROC QueryExtensionsString;
  2495. PFNGLXGETVISUALFROMFBCONFIGPROC GetVisualFromFBConfig;
  2496. PFNGLXCREATEWINDOWPROC CreateWindow;
  2497. PFNGLXDESTROYWINDOWPROC DestroyWindow;
  2498. // GLX 1.4 and extension functions
  2499. PFNGLXGETPROCADDRESSPROC GetProcAddress;
  2500. PFNGLXGETPROCADDRESSPROC GetProcAddressARB;
  2501. PFNGLXSWAPINTERVALEXTPROC SwapIntervalEXT;
  2502. PFNGLXSWAPINTERVALMESAPROC SwapIntervalMESA;
  2503. PFNGLXCREATECONTEXTATTRIBSARBPROC CreateContextAttribsARB;
  2504. // special case glGetIntegerv
  2505. void (*GetIntegerv)(uint32_t pname, int32_t* data);
  2506. // extension availability
  2507. bool EXT_swap_control;
  2508. bool MESA_swap_control;
  2509. bool ARB_multisample;
  2510. bool ARB_create_context;
  2511. bool ARB_create_context_profile;
  2512. } _sapp_glx_t;
  2513. #else
  2514. typedef struct {
  2515. EGLDisplay display;
  2516. EGLContext context;
  2517. EGLSurface surface;
  2518. } _sapp_egl_t;
  2519. #endif // _SAPP_GLX
  2520. #endif // _SAPP_LINUX
  2521. #if defined(_SAPP_ANY_GL)
  2522. typedef struct {
  2523. uint32_t framebuffer;
  2524. } _sapp_gl_t;
  2525. #endif
  2526. typedef struct {
  2527. bool enabled;
  2528. int buf_size;
  2529. char* buffer;
  2530. } _sapp_clipboard_t;
  2531. typedef struct {
  2532. bool enabled;
  2533. int max_files;
  2534. int max_path_length;
  2535. int num_files;
  2536. int buf_size;
  2537. char* buffer;
  2538. } _sapp_drop_t;
  2539. typedef struct {
  2540. float x, y;
  2541. float dx, dy;
  2542. bool shown;
  2543. bool locked;
  2544. bool pos_valid;
  2545. sapp_mouse_cursor current_cursor;
  2546. } _sapp_mouse_t;
  2547. typedef struct {
  2548. sapp_desc desc;
  2549. bool valid;
  2550. bool fullscreen;
  2551. bool first_frame;
  2552. bool init_called;
  2553. bool cleanup_called;
  2554. bool quit_requested;
  2555. bool quit_ordered;
  2556. bool event_consumed;
  2557. bool html5_ask_leave_site;
  2558. bool onscreen_keyboard_shown;
  2559. int window_width;
  2560. int window_height;
  2561. int framebuffer_width;
  2562. int framebuffer_height;
  2563. int sample_count;
  2564. int swap_interval;
  2565. float dpi_scale;
  2566. uint64_t frame_count;
  2567. _sapp_timing_t timing;
  2568. sapp_event event;
  2569. _sapp_mouse_t mouse;
  2570. _sapp_clipboard_t clipboard;
  2571. _sapp_drop_t drop;
  2572. sapp_icon_desc default_icon_desc;
  2573. uint32_t* default_icon_pixels;
  2574. #if defined(_SAPP_MACOS)
  2575. _sapp_macos_t macos;
  2576. #elif defined(_SAPP_IOS)
  2577. _sapp_ios_t ios;
  2578. #elif defined(_SAPP_EMSCRIPTEN)
  2579. _sapp_emsc_t emsc;
  2580. #if defined(SOKOL_WGPU)
  2581. _sapp_wgpu_t wgpu;
  2582. #endif
  2583. #elif defined(_SAPP_WIN32)
  2584. _sapp_win32_t win32;
  2585. #if defined(SOKOL_D3D11)
  2586. _sapp_d3d11_t d3d11;
  2587. #elif defined(SOKOL_GLCORE)
  2588. _sapp_wgl_t wgl;
  2589. #endif
  2590. #elif defined(_SAPP_ANDROID)
  2591. _sapp_android_t android;
  2592. #elif defined(_SAPP_LINUX)
  2593. _sapp_x11_t x11;
  2594. #if defined(_SAPP_GLX)
  2595. _sapp_glx_t glx;
  2596. #else
  2597. _sapp_egl_t egl;
  2598. #endif
  2599. #endif
  2600. #if defined(_SAPP_ANY_GL)
  2601. _sapp_gl_t gl;
  2602. #endif
  2603. char html5_canvas_selector[_SAPP_MAX_TITLE_LENGTH];
  2604. char window_title[_SAPP_MAX_TITLE_LENGTH]; // UTF-8
  2605. wchar_t window_title_wide[_SAPP_MAX_TITLE_LENGTH]; // UTF-32 or UCS-2 */
  2606. sapp_keycode keycodes[SAPP_MAX_KEYCODES];
  2607. } _sapp_t;
  2608. static _sapp_t _sapp;
  2609. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  2610. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  2611. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  2612. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2613. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  2614. //
  2615. // >>logging
  2616. #if defined(SOKOL_DEBUG)
  2617. #define _SAPP_LOGITEM_XMACRO(item,msg) #item ": " msg,
  2618. static const char* _sapp_log_messages[] = {
  2619. _SAPP_LOG_ITEMS
  2620. };
  2621. #undef _SAPP_LOGITEM_XMACRO
  2622. #endif // SOKOL_DEBUG
  2623. #define _SAPP_PANIC(code) _sapp_log(SAPP_LOGITEM_ ##code, 0, 0, __LINE__)
  2624. #define _SAPP_ERROR(code) _sapp_log(SAPP_LOGITEM_ ##code, 1, 0, __LINE__)
  2625. #define _SAPP_WARN(code) _sapp_log(SAPP_LOGITEM_ ##code, 2, 0, __LINE__)
  2626. #define _SAPP_INFO(code) _sapp_log(SAPP_LOGITEM_ ##code, 3, 0, __LINE__)
  2627. static void _sapp_log(sapp_log_item log_item, uint32_t log_level, const char* msg, uint32_t line_nr) {
  2628. if (_sapp.desc.logger.func) {
  2629. const char* filename = 0;
  2630. #if defined(SOKOL_DEBUG)
  2631. filename = __FILE__;
  2632. if (0 == msg) {
  2633. msg = _sapp_log_messages[log_item];
  2634. }
  2635. #endif
  2636. _sapp.desc.logger.func("sapp", log_level, log_item, msg, line_nr, filename, _sapp.desc.logger.user_data);
  2637. }
  2638. else {
  2639. // for log level PANIC it would be 'undefined behaviour' to continue
  2640. if (log_level == 0) {
  2641. abort();
  2642. }
  2643. }
  2644. }
  2645. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  2646. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  2647. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  2648. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2649. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  2650. //
  2651. // >>memory
  2652. _SOKOL_PRIVATE void _sapp_clear(void* ptr, size_t size) {
  2653. SOKOL_ASSERT(ptr && (size > 0));
  2654. memset(ptr, 0, size);
  2655. }
  2656. _SOKOL_PRIVATE void* _sapp_malloc(size_t size) {
  2657. SOKOL_ASSERT(size > 0);
  2658. void* ptr;
  2659. if (_sapp.desc.allocator.alloc_fn) {
  2660. ptr = _sapp.desc.allocator.alloc_fn(size, _sapp.desc.allocator.user_data);
  2661. } else {
  2662. ptr = malloc(size);
  2663. }
  2664. if (0 == ptr) {
  2665. _SAPP_PANIC(MALLOC_FAILED);
  2666. }
  2667. return ptr;
  2668. }
  2669. _SOKOL_PRIVATE void* _sapp_malloc_clear(size_t size) {
  2670. void* ptr = _sapp_malloc(size);
  2671. _sapp_clear(ptr, size);
  2672. return ptr;
  2673. }
  2674. _SOKOL_PRIVATE void _sapp_free(void* ptr) {
  2675. if (_sapp.desc.allocator.free_fn) {
  2676. _sapp.desc.allocator.free_fn(ptr, _sapp.desc.allocator.user_data);
  2677. }
  2678. else {
  2679. free(ptr);
  2680. }
  2681. }
  2682. // ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  2683. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  2684. // ███████ █████ ██ ██████ █████ ██████ ███████
  2685. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2686. // ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  2687. //
  2688. // >>helpers
  2689. _SOKOL_PRIVATE void _sapp_call_init(void) {
  2690. if (_sapp.desc.init_cb) {
  2691. _sapp.desc.init_cb();
  2692. }
  2693. else if (_sapp.desc.init_userdata_cb) {
  2694. _sapp.desc.init_userdata_cb(_sapp.desc.user_data);
  2695. }
  2696. _sapp.init_called = true;
  2697. }
  2698. _SOKOL_PRIVATE void _sapp_call_frame(void) {
  2699. if (_sapp.init_called && !_sapp.cleanup_called) {
  2700. if (_sapp.desc.frame_cb) {
  2701. _sapp.desc.frame_cb();
  2702. }
  2703. else if (_sapp.desc.frame_userdata_cb) {
  2704. _sapp.desc.frame_userdata_cb(_sapp.desc.user_data);
  2705. }
  2706. }
  2707. }
  2708. _SOKOL_PRIVATE void _sapp_call_cleanup(void) {
  2709. if (!_sapp.cleanup_called) {
  2710. if (_sapp.desc.cleanup_cb) {
  2711. _sapp.desc.cleanup_cb();
  2712. }
  2713. else if (_sapp.desc.cleanup_userdata_cb) {
  2714. _sapp.desc.cleanup_userdata_cb(_sapp.desc.user_data);
  2715. }
  2716. _sapp.cleanup_called = true;
  2717. }
  2718. }
  2719. _SOKOL_PRIVATE bool _sapp_call_event(const sapp_event* e) {
  2720. if (!_sapp.cleanup_called) {
  2721. if (_sapp.desc.event_cb) {
  2722. _sapp.desc.event_cb(e);
  2723. }
  2724. else if (_sapp.desc.event_userdata_cb) {
  2725. _sapp.desc.event_userdata_cb(e, _sapp.desc.user_data);
  2726. }
  2727. }
  2728. if (_sapp.event_consumed) {
  2729. _sapp.event_consumed = false;
  2730. return true;
  2731. }
  2732. else {
  2733. return false;
  2734. }
  2735. }
  2736. _SOKOL_PRIVATE char* _sapp_dropped_file_path_ptr(int index) {
  2737. SOKOL_ASSERT(_sapp.drop.buffer);
  2738. SOKOL_ASSERT((index >= 0) && (index <= _sapp.drop.max_files));
  2739. int offset = index * _sapp.drop.max_path_length;
  2740. SOKOL_ASSERT(offset < _sapp.drop.buf_size);
  2741. return &_sapp.drop.buffer[offset];
  2742. }
  2743. /* Copy a string into a fixed size buffer with guaranteed zero-
  2744. termination.
  2745. Return false if the string didn't fit into the buffer and had to be clamped.
  2746. FIXME: Currently UTF-8 strings might become invalid if the string
  2747. is clamped, because the last zero-byte might be written into
  2748. the middle of a multi-byte sequence.
  2749. */
  2750. _SOKOL_PRIVATE bool _sapp_strcpy(const char* src, char* dst, int max_len) {
  2751. SOKOL_ASSERT(src && dst && (max_len > 0));
  2752. char* const end = &(dst[max_len-1]);
  2753. char c = 0;
  2754. for (int i = 0; i < max_len; i++) {
  2755. c = *src;
  2756. if (c != 0) {
  2757. src++;
  2758. }
  2759. *dst++ = c;
  2760. }
  2761. /* truncated? */
  2762. if (c != 0) {
  2763. *end = 0;
  2764. return false;
  2765. }
  2766. else {
  2767. return true;
  2768. }
  2769. }
  2770. _SOKOL_PRIVATE sapp_desc _sapp_desc_defaults(const sapp_desc* desc) {
  2771. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  2772. sapp_desc res = *desc;
  2773. res.sample_count = _sapp_def(res.sample_count, 1);
  2774. res.swap_interval = _sapp_def(res.swap_interval, 1);
  2775. // NOTE: can't patch the default for gl_major_version and gl_minor_version
  2776. // independently, because a desired version 4.0 would be patched to 4.2
  2777. // (or expressed differently: zero is a valid value for gl_minor_version
  2778. // and can't be used to indicate 'default')
  2779. if (0 == res.gl_major_version) {
  2780. #if defined(_SAPP_APPLE)
  2781. res.gl_major_version = 4;
  2782. res.gl_minor_version = 1;
  2783. #else
  2784. res.gl_major_version = 4;
  2785. res.gl_minor_version = 3;
  2786. #endif
  2787. }
  2788. res.html5_canvas_selector = _sapp_def(res.html5_canvas_selector, "#canvas");
  2789. res.clipboard_size = _sapp_def(res.clipboard_size, 8192);
  2790. res.max_dropped_files = _sapp_def(res.max_dropped_files, 1);
  2791. res.max_dropped_file_path_length = _sapp_def(res.max_dropped_file_path_length, 2048);
  2792. res.window_title = _sapp_def(res.window_title, "sokol_app");
  2793. return res;
  2794. }
  2795. _SOKOL_PRIVATE void _sapp_init_state(const sapp_desc* desc) {
  2796. SOKOL_ASSERT(desc);
  2797. SOKOL_ASSERT(desc->width >= 0);
  2798. SOKOL_ASSERT(desc->height >= 0);
  2799. SOKOL_ASSERT(desc->sample_count >= 0);
  2800. SOKOL_ASSERT(desc->swap_interval >= 0);
  2801. SOKOL_ASSERT(desc->clipboard_size >= 0);
  2802. SOKOL_ASSERT(desc->max_dropped_files >= 0);
  2803. SOKOL_ASSERT(desc->max_dropped_file_path_length >= 0);
  2804. _SAPP_CLEAR_ARC_STRUCT(_sapp_t, _sapp);
  2805. _sapp.desc = _sapp_desc_defaults(desc);
  2806. _sapp.first_frame = true;
  2807. // NOTE: _sapp.desc.width/height may be 0! Platform backends need to deal with this
  2808. _sapp.window_width = _sapp.desc.width;
  2809. _sapp.window_height = _sapp.desc.height;
  2810. _sapp.framebuffer_width = _sapp.window_width;
  2811. _sapp.framebuffer_height = _sapp.window_height;
  2812. _sapp.sample_count = _sapp.desc.sample_count;
  2813. _sapp.swap_interval = _sapp.desc.swap_interval;
  2814. _sapp_strcpy(_sapp.desc.html5_canvas_selector, _sapp.html5_canvas_selector, sizeof(_sapp.html5_canvas_selector));
  2815. _sapp.desc.html5_canvas_selector = _sapp.html5_canvas_selector;
  2816. _sapp.html5_ask_leave_site = _sapp.desc.html5_ask_leave_site;
  2817. _sapp.clipboard.enabled = _sapp.desc.enable_clipboard;
  2818. if (_sapp.clipboard.enabled) {
  2819. _sapp.clipboard.buf_size = _sapp.desc.clipboard_size;
  2820. _sapp.clipboard.buffer = (char*) _sapp_malloc_clear((size_t)_sapp.clipboard.buf_size);
  2821. }
  2822. _sapp.drop.enabled = _sapp.desc.enable_dragndrop;
  2823. if (_sapp.drop.enabled) {
  2824. _sapp.drop.max_files = _sapp.desc.max_dropped_files;
  2825. _sapp.drop.max_path_length = _sapp.desc.max_dropped_file_path_length;
  2826. _sapp.drop.buf_size = _sapp.drop.max_files * _sapp.drop.max_path_length;
  2827. _sapp.drop.buffer = (char*) _sapp_malloc_clear((size_t)_sapp.drop.buf_size);
  2828. }
  2829. _sapp_strcpy(_sapp.desc.window_title, _sapp.window_title, sizeof(_sapp.window_title));
  2830. _sapp.desc.window_title = _sapp.window_title;
  2831. _sapp.dpi_scale = 1.0f;
  2832. _sapp.fullscreen = _sapp.desc.fullscreen;
  2833. _sapp.mouse.shown = true;
  2834. _sapp_timing_init(&_sapp.timing);
  2835. }
  2836. _SOKOL_PRIVATE void _sapp_discard_state(void) {
  2837. if (_sapp.clipboard.enabled) {
  2838. SOKOL_ASSERT(_sapp.clipboard.buffer);
  2839. _sapp_free((void*)_sapp.clipboard.buffer);
  2840. }
  2841. if (_sapp.drop.enabled) {
  2842. SOKOL_ASSERT(_sapp.drop.buffer);
  2843. _sapp_free((void*)_sapp.drop.buffer);
  2844. }
  2845. if (_sapp.default_icon_pixels) {
  2846. _sapp_free((void*)_sapp.default_icon_pixels);
  2847. }
  2848. _SAPP_CLEAR_ARC_STRUCT(_sapp_t, _sapp);
  2849. }
  2850. _SOKOL_PRIVATE void _sapp_init_event(sapp_event_type type) {
  2851. _sapp_clear(&_sapp.event, sizeof(_sapp.event));
  2852. _sapp.event.type = type;
  2853. _sapp.event.frame_count = _sapp.frame_count;
  2854. _sapp.event.mouse_button = SAPP_MOUSEBUTTON_INVALID;
  2855. _sapp.event.window_width = _sapp.window_width;
  2856. _sapp.event.window_height = _sapp.window_height;
  2857. _sapp.event.framebuffer_width = _sapp.framebuffer_width;
  2858. _sapp.event.framebuffer_height = _sapp.framebuffer_height;
  2859. _sapp.event.mouse_x = _sapp.mouse.x;
  2860. _sapp.event.mouse_y = _sapp.mouse.y;
  2861. _sapp.event.mouse_dx = _sapp.mouse.dx;
  2862. _sapp.event.mouse_dy = _sapp.mouse.dy;
  2863. }
  2864. _SOKOL_PRIVATE bool _sapp_events_enabled(void) {
  2865. /* only send events when an event callback is set, and the init function was called */
  2866. return (_sapp.desc.event_cb || _sapp.desc.event_userdata_cb) && _sapp.init_called;
  2867. }
  2868. _SOKOL_PRIVATE sapp_keycode _sapp_translate_key(int scan_code) {
  2869. if ((scan_code >= 0) && (scan_code < SAPP_MAX_KEYCODES)) {
  2870. return _sapp.keycodes[scan_code];
  2871. }
  2872. else {
  2873. return SAPP_KEYCODE_INVALID;
  2874. }
  2875. }
  2876. _SOKOL_PRIVATE void _sapp_clear_drop_buffer(void) {
  2877. if (_sapp.drop.enabled) {
  2878. SOKOL_ASSERT(_sapp.drop.buffer);
  2879. _sapp_clear(_sapp.drop.buffer, (size_t)_sapp.drop.buf_size);
  2880. }
  2881. }
  2882. _SOKOL_PRIVATE void _sapp_frame(void) {
  2883. if (_sapp.first_frame) {
  2884. _sapp.first_frame = false;
  2885. _sapp_call_init();
  2886. }
  2887. _sapp_call_frame();
  2888. _sapp.frame_count++;
  2889. }
  2890. _SOKOL_PRIVATE bool _sapp_image_validate(const sapp_image_desc* desc) {
  2891. SOKOL_ASSERT(desc->width > 0);
  2892. SOKOL_ASSERT(desc->height > 0);
  2893. SOKOL_ASSERT(desc->pixels.ptr != 0);
  2894. SOKOL_ASSERT(desc->pixels.size > 0);
  2895. const size_t wh_size = (size_t)(desc->width * desc->height) * sizeof(uint32_t);
  2896. if (wh_size != desc->pixels.size) {
  2897. _SAPP_ERROR(IMAGE_DATA_SIZE_MISMATCH);
  2898. return false;
  2899. }
  2900. return true;
  2901. }
  2902. _SOKOL_PRIVATE int _sapp_image_bestmatch(const sapp_image_desc image_descs[], int num_images, int width, int height) {
  2903. int least_diff = 0x7FFFFFFF;
  2904. int least_index = 0;
  2905. for (int i = 0; i < num_images; i++) {
  2906. int diff = (image_descs[i].width * image_descs[i].height) - (width * height);
  2907. if (diff < 0) {
  2908. diff = -diff;
  2909. }
  2910. if (diff < least_diff) {
  2911. least_diff = diff;
  2912. least_index = i;
  2913. }
  2914. }
  2915. return least_index;
  2916. }
  2917. _SOKOL_PRIVATE int _sapp_icon_num_images(const sapp_icon_desc* desc) {
  2918. int index = 0;
  2919. for (; index < SAPP_MAX_ICONIMAGES; index++) {
  2920. if (0 == desc->images[index].pixels.ptr) {
  2921. break;
  2922. }
  2923. }
  2924. return index;
  2925. }
  2926. _SOKOL_PRIVATE bool _sapp_validate_icon_desc(const sapp_icon_desc* desc, int num_images) {
  2927. SOKOL_ASSERT(num_images <= SAPP_MAX_ICONIMAGES);
  2928. for (int i = 0; i < num_images; i++) {
  2929. const sapp_image_desc* img_desc = &desc->images[i];
  2930. if (!_sapp_image_validate(img_desc)) {
  2931. return false;
  2932. }
  2933. }
  2934. return true;
  2935. }
  2936. _SOKOL_PRIVATE void _sapp_setup_default_icon(void) {
  2937. SOKOL_ASSERT(0 == _sapp.default_icon_pixels);
  2938. const int num_icons = 3;
  2939. const int icon_sizes[3] = { 16, 32, 64 }; // must be multiple of 8!
  2940. // allocate a pixel buffer for all icon pixels
  2941. int all_num_pixels = 0;
  2942. for (int i = 0; i < num_icons; i++) {
  2943. all_num_pixels += icon_sizes[i] * icon_sizes[i];
  2944. }
  2945. _sapp.default_icon_pixels = (uint32_t*) _sapp_malloc_clear((size_t)all_num_pixels * sizeof(uint32_t));
  2946. // initialize default_icon_desc struct
  2947. uint32_t* dst = _sapp.default_icon_pixels;
  2948. const uint32_t* dst_end = dst + all_num_pixels;
  2949. (void)dst_end; // silence unused warning in release mode
  2950. for (int i = 0; i < num_icons; i++) {
  2951. const int dim = (int) icon_sizes[i];
  2952. const int num_pixels = dim * dim;
  2953. sapp_image_desc* img_desc = &_sapp.default_icon_desc.images[i];
  2954. img_desc->width = dim;
  2955. img_desc->height = dim;
  2956. img_desc->pixels.ptr = dst;
  2957. img_desc->pixels.size = (size_t)num_pixels * sizeof(uint32_t);
  2958. dst += num_pixels;
  2959. }
  2960. SOKOL_ASSERT(dst == dst_end);
  2961. // Amstrad CPC font 'S'
  2962. const uint8_t tile[8] = {
  2963. 0x3C,
  2964. 0x66,
  2965. 0x60,
  2966. 0x3C,
  2967. 0x06,
  2968. 0x66,
  2969. 0x3C,
  2970. 0x00,
  2971. };
  2972. // rainbow colors
  2973. const uint32_t colors[8] = {
  2974. 0xFF4370FF,
  2975. 0xFF26A7FF,
  2976. 0xFF58EEFF,
  2977. 0xFF57E1D4,
  2978. 0xFF65CC9C,
  2979. 0xFF6ABB66,
  2980. 0xFFF5A542,
  2981. 0xFFC2577E,
  2982. };
  2983. dst = _sapp.default_icon_pixels;
  2984. const uint32_t blank = 0x00FFFFFF;
  2985. const uint32_t shadow = 0xFF000000;
  2986. for (int i = 0; i < num_icons; i++) {
  2987. const int dim = icon_sizes[i];
  2988. SOKOL_ASSERT((dim % 8) == 0);
  2989. const int scale = dim / 8;
  2990. for (int ty = 0, y = 0; ty < 8; ty++) {
  2991. const uint32_t color = colors[ty];
  2992. for (int sy = 0; sy < scale; sy++, y++) {
  2993. uint8_t bits = tile[ty];
  2994. for (int tx = 0, x = 0; tx < 8; tx++, bits<<=1) {
  2995. uint32_t pixel = (0 == (bits & 0x80)) ? blank : color;
  2996. for (int sx = 0; sx < scale; sx++, x++) {
  2997. SOKOL_ASSERT(dst < dst_end);
  2998. *dst++ = pixel;
  2999. }
  3000. }
  3001. }
  3002. }
  3003. }
  3004. SOKOL_ASSERT(dst == dst_end);
  3005. // right shadow
  3006. dst = _sapp.default_icon_pixels;
  3007. for (int i = 0; i < num_icons; i++) {
  3008. const int dim = icon_sizes[i];
  3009. for (int y = 0; y < dim; y++) {
  3010. uint32_t prev_color = blank;
  3011. for (int x = 0; x < dim; x++) {
  3012. const int dst_index = y * dim + x;
  3013. const uint32_t cur_color = dst[dst_index];
  3014. if ((cur_color == blank) && (prev_color != blank)) {
  3015. dst[dst_index] = shadow;
  3016. }
  3017. prev_color = cur_color;
  3018. }
  3019. }
  3020. dst += dim * dim;
  3021. }
  3022. SOKOL_ASSERT(dst == dst_end);
  3023. // bottom shadow
  3024. dst = _sapp.default_icon_pixels;
  3025. for (int i = 0; i < num_icons; i++) {
  3026. const int dim = icon_sizes[i];
  3027. for (int x = 0; x < dim; x++) {
  3028. uint32_t prev_color = blank;
  3029. for (int y = 0; y < dim; y++) {
  3030. const int dst_index = y * dim + x;
  3031. const uint32_t cur_color = dst[dst_index];
  3032. if ((cur_color == blank) && (prev_color != blank)) {
  3033. dst[dst_index] = shadow;
  3034. }
  3035. prev_color = cur_color;
  3036. }
  3037. }
  3038. dst += dim * dim;
  3039. }
  3040. SOKOL_ASSERT(dst == dst_end);
  3041. }
  3042. // █████ ██████ ██████ ██ ███████
  3043. // ██ ██ ██ ██ ██ ██ ██ ██
  3044. // ███████ ██████ ██████ ██ █████
  3045. // ██ ██ ██ ██ ██ ██
  3046. // ██ ██ ██ ██ ███████ ███████
  3047. //
  3048. // >>apple
  3049. #if defined(_SAPP_APPLE)
  3050. #if __has_feature(objc_arc)
  3051. #define _SAPP_OBJC_RELEASE(obj) { obj = nil; }
  3052. #else
  3053. #define _SAPP_OBJC_RELEASE(obj) { [obj release]; obj = nil; }
  3054. #endif
  3055. // ███ ███ █████ ██████ ██████ ███████
  3056. // ████ ████ ██ ██ ██ ██ ██ ██
  3057. // ██ ████ ██ ███████ ██ ██ ██ ███████
  3058. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  3059. // ██ ██ ██ ██ ██████ ██████ ███████
  3060. //
  3061. // >>macos
  3062. #if defined(_SAPP_MACOS)
  3063. _SOKOL_PRIVATE void _sapp_macos_init_keytable(void) {
  3064. _sapp.keycodes[0x1D] = SAPP_KEYCODE_0;
  3065. _sapp.keycodes[0x12] = SAPP_KEYCODE_1;
  3066. _sapp.keycodes[0x13] = SAPP_KEYCODE_2;
  3067. _sapp.keycodes[0x14] = SAPP_KEYCODE_3;
  3068. _sapp.keycodes[0x15] = SAPP_KEYCODE_4;
  3069. _sapp.keycodes[0x17] = SAPP_KEYCODE_5;
  3070. _sapp.keycodes[0x16] = SAPP_KEYCODE_6;
  3071. _sapp.keycodes[0x1A] = SAPP_KEYCODE_7;
  3072. _sapp.keycodes[0x1C] = SAPP_KEYCODE_8;
  3073. _sapp.keycodes[0x19] = SAPP_KEYCODE_9;
  3074. _sapp.keycodes[0x00] = SAPP_KEYCODE_A;
  3075. _sapp.keycodes[0x0B] = SAPP_KEYCODE_B;
  3076. _sapp.keycodes[0x08] = SAPP_KEYCODE_C;
  3077. _sapp.keycodes[0x02] = SAPP_KEYCODE_D;
  3078. _sapp.keycodes[0x0E] = SAPP_KEYCODE_E;
  3079. _sapp.keycodes[0x03] = SAPP_KEYCODE_F;
  3080. _sapp.keycodes[0x05] = SAPP_KEYCODE_G;
  3081. _sapp.keycodes[0x04] = SAPP_KEYCODE_H;
  3082. _sapp.keycodes[0x22] = SAPP_KEYCODE_I;
  3083. _sapp.keycodes[0x26] = SAPP_KEYCODE_J;
  3084. _sapp.keycodes[0x28] = SAPP_KEYCODE_K;
  3085. _sapp.keycodes[0x25] = SAPP_KEYCODE_L;
  3086. _sapp.keycodes[0x2E] = SAPP_KEYCODE_M;
  3087. _sapp.keycodes[0x2D] = SAPP_KEYCODE_N;
  3088. _sapp.keycodes[0x1F] = SAPP_KEYCODE_O;
  3089. _sapp.keycodes[0x23] = SAPP_KEYCODE_P;
  3090. _sapp.keycodes[0x0C] = SAPP_KEYCODE_Q;
  3091. _sapp.keycodes[0x0F] = SAPP_KEYCODE_R;
  3092. _sapp.keycodes[0x01] = SAPP_KEYCODE_S;
  3093. _sapp.keycodes[0x11] = SAPP_KEYCODE_T;
  3094. _sapp.keycodes[0x20] = SAPP_KEYCODE_U;
  3095. _sapp.keycodes[0x09] = SAPP_KEYCODE_V;
  3096. _sapp.keycodes[0x0D] = SAPP_KEYCODE_W;
  3097. _sapp.keycodes[0x07] = SAPP_KEYCODE_X;
  3098. _sapp.keycodes[0x10] = SAPP_KEYCODE_Y;
  3099. _sapp.keycodes[0x06] = SAPP_KEYCODE_Z;
  3100. _sapp.keycodes[0x27] = SAPP_KEYCODE_APOSTROPHE;
  3101. _sapp.keycodes[0x2A] = SAPP_KEYCODE_BACKSLASH;
  3102. _sapp.keycodes[0x2B] = SAPP_KEYCODE_COMMA;
  3103. _sapp.keycodes[0x18] = SAPP_KEYCODE_EQUAL;
  3104. _sapp.keycodes[0x32] = SAPP_KEYCODE_GRAVE_ACCENT;
  3105. _sapp.keycodes[0x21] = SAPP_KEYCODE_LEFT_BRACKET;
  3106. _sapp.keycodes[0x1B] = SAPP_KEYCODE_MINUS;
  3107. _sapp.keycodes[0x2F] = SAPP_KEYCODE_PERIOD;
  3108. _sapp.keycodes[0x1E] = SAPP_KEYCODE_RIGHT_BRACKET;
  3109. _sapp.keycodes[0x29] = SAPP_KEYCODE_SEMICOLON;
  3110. _sapp.keycodes[0x2C] = SAPP_KEYCODE_SLASH;
  3111. _sapp.keycodes[0x0A] = SAPP_KEYCODE_WORLD_1;
  3112. _sapp.keycodes[0x33] = SAPP_KEYCODE_BACKSPACE;
  3113. _sapp.keycodes[0x39] = SAPP_KEYCODE_CAPS_LOCK;
  3114. _sapp.keycodes[0x75] = SAPP_KEYCODE_DELETE;
  3115. _sapp.keycodes[0x7D] = SAPP_KEYCODE_DOWN;
  3116. _sapp.keycodes[0x77] = SAPP_KEYCODE_END;
  3117. _sapp.keycodes[0x24] = SAPP_KEYCODE_ENTER;
  3118. _sapp.keycodes[0x35] = SAPP_KEYCODE_ESCAPE;
  3119. _sapp.keycodes[0x7A] = SAPP_KEYCODE_F1;
  3120. _sapp.keycodes[0x78] = SAPP_KEYCODE_F2;
  3121. _sapp.keycodes[0x63] = SAPP_KEYCODE_F3;
  3122. _sapp.keycodes[0x76] = SAPP_KEYCODE_F4;
  3123. _sapp.keycodes[0x60] = SAPP_KEYCODE_F5;
  3124. _sapp.keycodes[0x61] = SAPP_KEYCODE_F6;
  3125. _sapp.keycodes[0x62] = SAPP_KEYCODE_F7;
  3126. _sapp.keycodes[0x64] = SAPP_KEYCODE_F8;
  3127. _sapp.keycodes[0x65] = SAPP_KEYCODE_F9;
  3128. _sapp.keycodes[0x6D] = SAPP_KEYCODE_F10;
  3129. _sapp.keycodes[0x67] = SAPP_KEYCODE_F11;
  3130. _sapp.keycodes[0x6F] = SAPP_KEYCODE_F12;
  3131. _sapp.keycodes[0x69] = SAPP_KEYCODE_F13;
  3132. _sapp.keycodes[0x6B] = SAPP_KEYCODE_F14;
  3133. _sapp.keycodes[0x71] = SAPP_KEYCODE_F15;
  3134. _sapp.keycodes[0x6A] = SAPP_KEYCODE_F16;
  3135. _sapp.keycodes[0x40] = SAPP_KEYCODE_F17;
  3136. _sapp.keycodes[0x4F] = SAPP_KEYCODE_F18;
  3137. _sapp.keycodes[0x50] = SAPP_KEYCODE_F19;
  3138. _sapp.keycodes[0x5A] = SAPP_KEYCODE_F20;
  3139. _sapp.keycodes[0x73] = SAPP_KEYCODE_HOME;
  3140. _sapp.keycodes[0x72] = SAPP_KEYCODE_INSERT;
  3141. _sapp.keycodes[0x7B] = SAPP_KEYCODE_LEFT;
  3142. _sapp.keycodes[0x3A] = SAPP_KEYCODE_LEFT_ALT;
  3143. _sapp.keycodes[0x3B] = SAPP_KEYCODE_LEFT_CONTROL;
  3144. _sapp.keycodes[0x38] = SAPP_KEYCODE_LEFT_SHIFT;
  3145. _sapp.keycodes[0x37] = SAPP_KEYCODE_LEFT_SUPER;
  3146. _sapp.keycodes[0x6E] = SAPP_KEYCODE_MENU;
  3147. _sapp.keycodes[0x47] = SAPP_KEYCODE_NUM_LOCK;
  3148. _sapp.keycodes[0x79] = SAPP_KEYCODE_PAGE_DOWN;
  3149. _sapp.keycodes[0x74] = SAPP_KEYCODE_PAGE_UP;
  3150. _sapp.keycodes[0x7C] = SAPP_KEYCODE_RIGHT;
  3151. _sapp.keycodes[0x3D] = SAPP_KEYCODE_RIGHT_ALT;
  3152. _sapp.keycodes[0x3E] = SAPP_KEYCODE_RIGHT_CONTROL;
  3153. _sapp.keycodes[0x3C] = SAPP_KEYCODE_RIGHT_SHIFT;
  3154. _sapp.keycodes[0x36] = SAPP_KEYCODE_RIGHT_SUPER;
  3155. _sapp.keycodes[0x31] = SAPP_KEYCODE_SPACE;
  3156. _sapp.keycodes[0x30] = SAPP_KEYCODE_TAB;
  3157. _sapp.keycodes[0x7E] = SAPP_KEYCODE_UP;
  3158. _sapp.keycodes[0x52] = SAPP_KEYCODE_KP_0;
  3159. _sapp.keycodes[0x53] = SAPP_KEYCODE_KP_1;
  3160. _sapp.keycodes[0x54] = SAPP_KEYCODE_KP_2;
  3161. _sapp.keycodes[0x55] = SAPP_KEYCODE_KP_3;
  3162. _sapp.keycodes[0x56] = SAPP_KEYCODE_KP_4;
  3163. _sapp.keycodes[0x57] = SAPP_KEYCODE_KP_5;
  3164. _sapp.keycodes[0x58] = SAPP_KEYCODE_KP_6;
  3165. _sapp.keycodes[0x59] = SAPP_KEYCODE_KP_7;
  3166. _sapp.keycodes[0x5B] = SAPP_KEYCODE_KP_8;
  3167. _sapp.keycodes[0x5C] = SAPP_KEYCODE_KP_9;
  3168. _sapp.keycodes[0x45] = SAPP_KEYCODE_KP_ADD;
  3169. _sapp.keycodes[0x41] = SAPP_KEYCODE_KP_DECIMAL;
  3170. _sapp.keycodes[0x4B] = SAPP_KEYCODE_KP_DIVIDE;
  3171. _sapp.keycodes[0x4C] = SAPP_KEYCODE_KP_ENTER;
  3172. _sapp.keycodes[0x51] = SAPP_KEYCODE_KP_EQUAL;
  3173. _sapp.keycodes[0x43] = SAPP_KEYCODE_KP_MULTIPLY;
  3174. _sapp.keycodes[0x4E] = SAPP_KEYCODE_KP_SUBTRACT;
  3175. }
  3176. _SOKOL_PRIVATE void _sapp_macos_discard_state(void) {
  3177. // NOTE: it's safe to call [release] on a nil object
  3178. if (_sapp.macos.keyup_monitor != nil) {
  3179. [NSEvent removeMonitor:_sapp.macos.keyup_monitor];
  3180. // NOTE: removeMonitor also releases the object
  3181. _sapp.macos.keyup_monitor = nil;
  3182. }
  3183. _SAPP_OBJC_RELEASE(_sapp.macos.tracking_area);
  3184. _SAPP_OBJC_RELEASE(_sapp.macos.app_dlg);
  3185. _SAPP_OBJC_RELEASE(_sapp.macos.win_dlg);
  3186. _SAPP_OBJC_RELEASE(_sapp.macos.view);
  3187. #if defined(SOKOL_METAL)
  3188. _SAPP_OBJC_RELEASE(_sapp.macos.mtl_device);
  3189. #endif
  3190. _SAPP_OBJC_RELEASE(_sapp.macos.window);
  3191. }
  3192. // undocumented methods for creating cursors (see GLFW 3.4 and imgui_impl_osx.mm)
  3193. @interface NSCursor()
  3194. + (id)_windowResizeNorthWestSouthEastCursor;
  3195. + (id)_windowResizeNorthEastSouthWestCursor;
  3196. + (id)_windowResizeNorthSouthCursor;
  3197. + (id)_windowResizeEastWestCursor;
  3198. @end
  3199. _SOKOL_PRIVATE void _sapp_macos_init_cursors(void) {
  3200. _sapp.macos.cursors[SAPP_MOUSECURSOR_DEFAULT] = nil; // not a bug
  3201. _sapp.macos.cursors[SAPP_MOUSECURSOR_ARROW] = [NSCursor arrowCursor];
  3202. _sapp.macos.cursors[SAPP_MOUSECURSOR_IBEAM] = [NSCursor IBeamCursor];
  3203. _sapp.macos.cursors[SAPP_MOUSECURSOR_CROSSHAIR] = [NSCursor crosshairCursor];
  3204. _sapp.macos.cursors[SAPP_MOUSECURSOR_POINTING_HAND] = [NSCursor pointingHandCursor];
  3205. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_EW] = [NSCursor respondsToSelector:@selector(_windowResizeEastWestCursor)] ? [NSCursor _windowResizeEastWestCursor] : [NSCursor resizeLeftRightCursor];
  3206. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NS] = [NSCursor respondsToSelector:@selector(_windowResizeNorthSouthCursor)] ? [NSCursor _windowResizeNorthSouthCursor] : [NSCursor resizeUpDownCursor];
  3207. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NWSE] = [NSCursor respondsToSelector:@selector(_windowResizeNorthWestSouthEastCursor)] ? [NSCursor _windowResizeNorthWestSouthEastCursor] : [NSCursor closedHandCursor];
  3208. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_NESW] = [NSCursor respondsToSelector:@selector(_windowResizeNorthEastSouthWestCursor)] ? [NSCursor _windowResizeNorthEastSouthWestCursor] : [NSCursor closedHandCursor];
  3209. _sapp.macos.cursors[SAPP_MOUSECURSOR_RESIZE_ALL] = [NSCursor closedHandCursor];
  3210. _sapp.macos.cursors[SAPP_MOUSECURSOR_NOT_ALLOWED] = [NSCursor operationNotAllowedCursor];
  3211. }
  3212. _SOKOL_PRIVATE void _sapp_macos_run(const sapp_desc* desc) {
  3213. _sapp_init_state(desc);
  3214. _sapp_macos_init_keytable();
  3215. [NSApplication sharedApplication];
  3216. // set the application dock icon as early as possible, otherwise
  3217. // the dummy icon will be visible for a short time
  3218. sapp_set_icon(&_sapp.desc.icon);
  3219. _sapp.macos.app_dlg = [[_sapp_macos_app_delegate alloc] init];
  3220. NSApp.delegate = _sapp.macos.app_dlg;
  3221. // workaround for "no key-up sent while Cmd is pressed" taken from GLFW:
  3222. NSEvent* (^keyup_monitor)(NSEvent*) = ^NSEvent* (NSEvent* event) {
  3223. if ([event modifierFlags] & NSEventModifierFlagCommand) {
  3224. [[NSApp keyWindow] sendEvent:event];
  3225. }
  3226. return event;
  3227. };
  3228. _sapp.macos.keyup_monitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyUp handler:keyup_monitor];
  3229. [NSApp run];
  3230. // NOTE: [NSApp run] never returns, instead cleanup code
  3231. // must be put into applicationWillTerminate
  3232. }
  3233. /* MacOS entry function */
  3234. #if !defined(SOKOL_NO_ENTRY)
  3235. int main(int argc, char* argv[]) {
  3236. sapp_desc desc = sokol_main(argc, argv);
  3237. _sapp_macos_run(&desc);
  3238. return 0;
  3239. }
  3240. #endif /* SOKOL_NO_ENTRY */
  3241. _SOKOL_PRIVATE uint32_t _sapp_macos_mods(NSEvent* ev) {
  3242. const NSEventModifierFlags f = (ev == nil) ? NSEvent.modifierFlags : ev.modifierFlags;
  3243. const NSUInteger b = NSEvent.pressedMouseButtons;
  3244. uint32_t m = 0;
  3245. if (f & NSEventModifierFlagShift) {
  3246. m |= SAPP_MODIFIER_SHIFT;
  3247. }
  3248. if (f & NSEventModifierFlagControl) {
  3249. m |= SAPP_MODIFIER_CTRL;
  3250. }
  3251. if (f & NSEventModifierFlagOption) {
  3252. m |= SAPP_MODIFIER_ALT;
  3253. }
  3254. if (f & NSEventModifierFlagCommand) {
  3255. m |= SAPP_MODIFIER_SUPER;
  3256. }
  3257. if (0 != (b & (1<<0))) {
  3258. m |= SAPP_MODIFIER_LMB;
  3259. }
  3260. if (0 != (b & (1<<1))) {
  3261. m |= SAPP_MODIFIER_RMB;
  3262. }
  3263. if (0 != (b & (1<<2))) {
  3264. m |= SAPP_MODIFIER_MMB;
  3265. }
  3266. return m;
  3267. }
  3268. _SOKOL_PRIVATE void _sapp_macos_mouse_event(sapp_event_type type, sapp_mousebutton btn, uint32_t mod) {
  3269. if (_sapp_events_enabled()) {
  3270. _sapp_init_event(type);
  3271. _sapp.event.mouse_button = btn;
  3272. _sapp.event.modifiers = mod;
  3273. _sapp_call_event(&_sapp.event);
  3274. }
  3275. }
  3276. _SOKOL_PRIVATE void _sapp_macos_key_event(sapp_event_type type, sapp_keycode key, bool repeat, uint32_t mod) {
  3277. if (_sapp_events_enabled()) {
  3278. _sapp_init_event(type);
  3279. _sapp.event.key_code = key;
  3280. _sapp.event.key_repeat = repeat;
  3281. _sapp.event.modifiers = mod;
  3282. _sapp_call_event(&_sapp.event);
  3283. }
  3284. }
  3285. _SOKOL_PRIVATE void _sapp_macos_app_event(sapp_event_type type) {
  3286. if (_sapp_events_enabled()) {
  3287. _sapp_init_event(type);
  3288. _sapp_call_event(&_sapp.event);
  3289. }
  3290. }
  3291. /* NOTE: unlike the iOS version of this function, the macOS version
  3292. can dynamically update the DPI scaling factor when a window is moved
  3293. between HighDPI / LowDPI screens.
  3294. */
  3295. _SOKOL_PRIVATE void _sapp_macos_update_dimensions(void) {
  3296. if (_sapp.desc.high_dpi) {
  3297. _sapp.dpi_scale = [_sapp.macos.window screen].backingScaleFactor;
  3298. }
  3299. else {
  3300. _sapp.dpi_scale = 1.0f;
  3301. }
  3302. _sapp.macos.view.layer.contentsScale = _sapp.dpi_scale; // NOTE: needed because we set layerContentsPlacement to a non-scaling value in windowWillStartLiveResize.
  3303. const NSRect bounds = [_sapp.macos.view bounds];
  3304. _sapp.window_width = (int)roundf(bounds.size.width);
  3305. _sapp.window_height = (int)roundf(bounds.size.height);
  3306. #if defined(SOKOL_METAL)
  3307. _sapp.framebuffer_width = (int)roundf(bounds.size.width * _sapp.dpi_scale);
  3308. _sapp.framebuffer_height = (int)roundf(bounds.size.height * _sapp.dpi_scale);
  3309. const CGSize fb_size = _sapp.macos.view.drawableSize;
  3310. const int cur_fb_width = (int)roundf(fb_size.width);
  3311. const int cur_fb_height = (int)roundf(fb_size.height);
  3312. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  3313. (_sapp.framebuffer_height != cur_fb_height);
  3314. #elif defined(SOKOL_GLCORE)
  3315. const int cur_fb_width = (int)roundf(bounds.size.width * _sapp.dpi_scale);
  3316. const int cur_fb_height = (int)roundf(bounds.size.height * _sapp.dpi_scale);
  3317. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  3318. (_sapp.framebuffer_height != cur_fb_height);
  3319. _sapp.framebuffer_width = cur_fb_width;
  3320. _sapp.framebuffer_height = cur_fb_height;
  3321. #endif
  3322. if (_sapp.framebuffer_width == 0) {
  3323. _sapp.framebuffer_width = 1;
  3324. }
  3325. if (_sapp.framebuffer_height == 0) {
  3326. _sapp.framebuffer_height = 1;
  3327. }
  3328. if (_sapp.window_width == 0) {
  3329. _sapp.window_width = 1;
  3330. }
  3331. if (_sapp.window_height == 0) {
  3332. _sapp.window_height = 1;
  3333. }
  3334. if (dim_changed) {
  3335. #if defined(SOKOL_METAL)
  3336. CGSize drawable_size = { (CGFloat) _sapp.framebuffer_width, (CGFloat) _sapp.framebuffer_height };
  3337. _sapp.macos.view.drawableSize = drawable_size;
  3338. #else
  3339. // nothing to do for GL?
  3340. #endif
  3341. if (!_sapp.first_frame) {
  3342. _sapp_macos_app_event(SAPP_EVENTTYPE_RESIZED);
  3343. }
  3344. }
  3345. }
  3346. _SOKOL_PRIVATE void _sapp_macos_toggle_fullscreen(void) {
  3347. /* NOTE: the _sapp.fullscreen flag is also notified by the
  3348. windowDidEnterFullscreen / windowDidExitFullscreen
  3349. event handlers
  3350. */
  3351. _sapp.fullscreen = !_sapp.fullscreen;
  3352. [_sapp.macos.window toggleFullScreen:nil];
  3353. }
  3354. _SOKOL_PRIVATE void _sapp_macos_set_clipboard_string(const char* str) {
  3355. @autoreleasepool {
  3356. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  3357. [pasteboard declareTypes:@[NSPasteboardTypeString] owner:nil];
  3358. [pasteboard setString:@(str) forType:NSPasteboardTypeString];
  3359. }
  3360. }
  3361. _SOKOL_PRIVATE const char* _sapp_macos_get_clipboard_string(void) {
  3362. SOKOL_ASSERT(_sapp.clipboard.buffer);
  3363. @autoreleasepool {
  3364. _sapp.clipboard.buffer[0] = 0;
  3365. NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
  3366. if (![[pasteboard types] containsObject:NSPasteboardTypeString]) {
  3367. return _sapp.clipboard.buffer;
  3368. }
  3369. NSString* str = [pasteboard stringForType:NSPasteboardTypeString];
  3370. if (!str) {
  3371. return _sapp.clipboard.buffer;
  3372. }
  3373. _sapp_strcpy([str UTF8String], _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  3374. }
  3375. return _sapp.clipboard.buffer;
  3376. }
  3377. _SOKOL_PRIVATE void _sapp_macos_update_window_title(void) {
  3378. [_sapp.macos.window setTitle: [NSString stringWithUTF8String:_sapp.window_title]];
  3379. }
  3380. _SOKOL_PRIVATE void _sapp_macos_mouse_update_from_nspoint(NSPoint mouse_pos, bool clear_dxdy) {
  3381. if (!_sapp.mouse.locked) {
  3382. float new_x = mouse_pos.x * _sapp.dpi_scale;
  3383. float new_y = _sapp.framebuffer_height - (mouse_pos.y * _sapp.dpi_scale) - 1;
  3384. if (clear_dxdy) {
  3385. _sapp.mouse.dx = 0.0f;
  3386. _sapp.mouse.dy = 0.0f;
  3387. }
  3388. else if (_sapp.mouse.pos_valid) {
  3389. // don't update dx/dy in the very first update
  3390. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  3391. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  3392. }
  3393. _sapp.mouse.x = new_x;
  3394. _sapp.mouse.y = new_y;
  3395. _sapp.mouse.pos_valid = true;
  3396. }
  3397. }
  3398. _SOKOL_PRIVATE void _sapp_macos_mouse_update_from_nsevent(NSEvent* event, bool clear_dxdy) {
  3399. _sapp_macos_mouse_update_from_nspoint(event.locationInWindow, clear_dxdy);
  3400. }
  3401. _SOKOL_PRIVATE void _sapp_macos_show_mouse(bool visible) {
  3402. /* NOTE: this function is only called when the mouse visibility actually changes */
  3403. if (visible) {
  3404. CGDisplayShowCursor(kCGDirectMainDisplay);
  3405. }
  3406. else {
  3407. CGDisplayHideCursor(kCGDirectMainDisplay);
  3408. }
  3409. }
  3410. _SOKOL_PRIVATE void _sapp_macos_lock_mouse(bool lock) {
  3411. if (lock == _sapp.mouse.locked) {
  3412. return;
  3413. }
  3414. _sapp.mouse.dx = 0.0f;
  3415. _sapp.mouse.dy = 0.0f;
  3416. _sapp.mouse.locked = lock;
  3417. /*
  3418. NOTE that this code doesn't warp the mouse cursor to the window
  3419. center as everybody else does it. This lead to a spike in the
  3420. *second* mouse-moved event after the warp happened. The
  3421. mouse centering doesn't seem to be required (mouse-moved events
  3422. are reported correctly even when the cursor is at an edge of the screen).
  3423. NOTE also that the hide/show of the mouse cursor should properly
  3424. stack with calls to sapp_show_mouse()
  3425. */
  3426. if (_sapp.mouse.locked) {
  3427. CGAssociateMouseAndMouseCursorPosition(NO);
  3428. [NSCursor hide];
  3429. }
  3430. else {
  3431. [NSCursor unhide];
  3432. CGAssociateMouseAndMouseCursorPosition(YES);
  3433. }
  3434. }
  3435. _SOKOL_PRIVATE void _sapp_macos_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  3436. // show/hide cursor only if visibility status has changed (required because show/hide stacks)
  3437. if (shown != _sapp.mouse.shown) {
  3438. if (shown) {
  3439. [NSCursor unhide];
  3440. }
  3441. else {
  3442. [NSCursor hide];
  3443. }
  3444. }
  3445. // update cursor type
  3446. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  3447. if (_sapp.macos.cursors[cursor]) {
  3448. [_sapp.macos.cursors[cursor] set];
  3449. }
  3450. else {
  3451. [[NSCursor arrowCursor] set];
  3452. }
  3453. }
  3454. _SOKOL_PRIVATE void _sapp_macos_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  3455. NSDockTile* dock_tile = NSApp.dockTile;
  3456. const int wanted_width = (int) dock_tile.size.width;
  3457. const int wanted_height = (int) dock_tile.size.height;
  3458. const int img_index = _sapp_image_bestmatch(icon_desc->images, num_images, wanted_width, wanted_height);
  3459. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  3460. CGColorSpaceRef cg_color_space = CGColorSpaceCreateDeviceRGB();
  3461. CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)img_desc->pixels.ptr, (CFIndex)img_desc->pixels.size);
  3462. CGDataProviderRef cg_data_provider = CGDataProviderCreateWithCFData(cf_data);
  3463. CGImageRef cg_img = CGImageCreate(
  3464. (size_t)img_desc->width, // width
  3465. (size_t)img_desc->height, // height
  3466. 8, // bitsPerComponent
  3467. 32, // bitsPerPixel
  3468. (size_t)img_desc->width * 4,// bytesPerRow
  3469. cg_color_space, // space
  3470. kCGImageAlphaLast | kCGImageByteOrderDefault, // bitmapInfo
  3471. cg_data_provider, // provider
  3472. NULL, // decode
  3473. false, // shouldInterpolate
  3474. kCGRenderingIntentDefault);
  3475. CFRelease(cf_data);
  3476. CGDataProviderRelease(cg_data_provider);
  3477. CGColorSpaceRelease(cg_color_space);
  3478. NSImage* ns_image = [[NSImage alloc] initWithCGImage:cg_img size:dock_tile.size];
  3479. dock_tile.contentView = [NSImageView imageViewWithImage:ns_image];
  3480. [dock_tile display];
  3481. _SAPP_OBJC_RELEASE(ns_image);
  3482. CGImageRelease(cg_img);
  3483. }
  3484. _SOKOL_PRIVATE void _sapp_macos_frame(void) {
  3485. _sapp_frame();
  3486. if (_sapp.quit_requested || _sapp.quit_ordered) {
  3487. [_sapp.macos.window performClose:nil];
  3488. }
  3489. }
  3490. @implementation _sapp_macos_app_delegate
  3491. - (void)applicationDidFinishLaunching:(NSNotification*)aNotification {
  3492. _SOKOL_UNUSED(aNotification);
  3493. _sapp_macos_init_cursors();
  3494. if ((_sapp.window_width == 0) || (_sapp.window_height == 0)) {
  3495. // use 4/5 of screen size as default size
  3496. NSRect screen_rect = NSScreen.mainScreen.frame;
  3497. if (_sapp.window_width == 0) {
  3498. _sapp.window_width = (int)roundf((screen_rect.size.width * 4.0f) / 5.0f);
  3499. }
  3500. if (_sapp.window_height == 0) {
  3501. _sapp.window_height = (int)roundf((screen_rect.size.height * 4.0f) / 5.0f);
  3502. }
  3503. }
  3504. const NSUInteger style =
  3505. NSWindowStyleMaskTitled |
  3506. NSWindowStyleMaskClosable |
  3507. NSWindowStyleMaskMiniaturizable |
  3508. NSWindowStyleMaskResizable;
  3509. NSRect window_rect = NSMakeRect(0, 0, _sapp.window_width, _sapp.window_height);
  3510. _sapp.macos.window = [[_sapp_macos_window alloc]
  3511. initWithContentRect:window_rect
  3512. styleMask:style
  3513. backing:NSBackingStoreBuffered
  3514. defer:NO];
  3515. _sapp.macos.window.releasedWhenClosed = NO; // this is necessary for proper cleanup in applicationWillTerminate
  3516. _sapp.macos.window.title = [NSString stringWithUTF8String:_sapp.window_title];
  3517. _sapp.macos.window.acceptsMouseMovedEvents = YES;
  3518. _sapp.macos.window.restorable = YES;
  3519. _sapp.macos.win_dlg = [[_sapp_macos_window_delegate alloc] init];
  3520. _sapp.macos.window.delegate = _sapp.macos.win_dlg;
  3521. #if defined(SOKOL_METAL)
  3522. NSInteger max_fps = 60;
  3523. #if (__MAC_OS_X_VERSION_MAX_ALLOWED >= 120000)
  3524. if (@available(macOS 12.0, *)) {
  3525. max_fps = [NSScreen.mainScreen maximumFramesPerSecond];
  3526. }
  3527. #endif
  3528. _sapp.macos.mtl_device = MTLCreateSystemDefaultDevice();
  3529. _sapp.macos.view = [[_sapp_macos_view alloc] init];
  3530. [_sapp.macos.view updateTrackingAreas];
  3531. _sapp.macos.view.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  3532. _sapp.macos.view.device = _sapp.macos.mtl_device;
  3533. _sapp.macos.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
  3534. _sapp.macos.view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  3535. _sapp.macos.view.sampleCount = (NSUInteger) _sapp.sample_count;
  3536. _sapp.macos.view.autoResizeDrawable = false;
  3537. _sapp.macos.window.contentView = _sapp.macos.view;
  3538. [_sapp.macos.window makeFirstResponder:_sapp.macos.view];
  3539. _sapp.macos.view.layer.magnificationFilter = kCAFilterNearest;
  3540. #elif defined(SOKOL_GLCORE)
  3541. NSOpenGLPixelFormatAttribute attrs[32];
  3542. int i = 0;
  3543. attrs[i++] = NSOpenGLPFAAccelerated;
  3544. attrs[i++] = NSOpenGLPFADoubleBuffer;
  3545. attrs[i++] = NSOpenGLPFAOpenGLProfile;
  3546. const int glVersion = _sapp.desc.gl_major_version * 10 + _sapp.desc.gl_minor_version;
  3547. switch(glVersion) {
  3548. case 10: attrs[i++] = NSOpenGLProfileVersionLegacy; break;
  3549. case 32: attrs[i++] = NSOpenGLProfileVersion3_2Core; break;
  3550. case 41: attrs[i++] = NSOpenGLProfileVersion4_1Core; break;
  3551. default:
  3552. _SAPP_PANIC(MACOS_INVALID_NSOPENGL_PROFILE);
  3553. }
  3554. attrs[i++] = NSOpenGLPFAColorSize; attrs[i++] = 24;
  3555. attrs[i++] = NSOpenGLPFAAlphaSize; attrs[i++] = 8;
  3556. attrs[i++] = NSOpenGLPFADepthSize; attrs[i++] = 24;
  3557. attrs[i++] = NSOpenGLPFAStencilSize; attrs[i++] = 8;
  3558. if (_sapp.sample_count > 1) {
  3559. attrs[i++] = NSOpenGLPFAMultisample;
  3560. attrs[i++] = NSOpenGLPFASampleBuffers; attrs[i++] = 1;
  3561. attrs[i++] = NSOpenGLPFASamples; attrs[i++] = (NSOpenGLPixelFormatAttribute)_sapp.sample_count;
  3562. }
  3563. else {
  3564. attrs[i++] = NSOpenGLPFASampleBuffers; attrs[i++] = 0;
  3565. }
  3566. attrs[i++] = 0;
  3567. NSOpenGLPixelFormat* glpixelformat_obj = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
  3568. SOKOL_ASSERT(glpixelformat_obj != nil);
  3569. _sapp.macos.view = [[_sapp_macos_view alloc]
  3570. initWithFrame:window_rect
  3571. pixelFormat:glpixelformat_obj];
  3572. _SAPP_OBJC_RELEASE(glpixelformat_obj);
  3573. [_sapp.macos.view updateTrackingAreas];
  3574. if (_sapp.desc.high_dpi) {
  3575. [_sapp.macos.view setWantsBestResolutionOpenGLSurface:YES];
  3576. }
  3577. else {
  3578. [_sapp.macos.view setWantsBestResolutionOpenGLSurface:NO];
  3579. }
  3580. _sapp.macos.window.contentView = _sapp.macos.view;
  3581. [_sapp.macos.window makeFirstResponder:_sapp.macos.view];
  3582. NSTimer* timer_obj = [NSTimer timerWithTimeInterval:0.001
  3583. target:_sapp.macos.view
  3584. selector:@selector(timerFired:)
  3585. userInfo:nil
  3586. repeats:YES];
  3587. [[NSRunLoop currentRunLoop] addTimer:timer_obj forMode:NSDefaultRunLoopMode];
  3588. timer_obj = nil;
  3589. #endif
  3590. [_sapp.macos.window center];
  3591. _sapp.valid = true;
  3592. if (_sapp.fullscreen) {
  3593. /* ^^^ on GL, this already toggles a rendered frame, so set the valid flag before */
  3594. [_sapp.macos.window toggleFullScreen:self];
  3595. }
  3596. NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
  3597. [NSApp activateIgnoringOtherApps:YES];
  3598. [_sapp.macos.window makeKeyAndOrderFront:nil];
  3599. _sapp_macos_update_dimensions();
  3600. [NSEvent setMouseCoalescingEnabled:NO];
  3601. // workaround for window not being focused during a long init callback
  3602. // for details see: https://github.com/floooh/sokol/pull/982
  3603. // also see: https://gitlab.gnome.org/GNOME/gtk/-/issues/2342
  3604. NSEvent *focusevent = [NSEvent otherEventWithType:NSEventTypeAppKitDefined
  3605. location:NSZeroPoint
  3606. modifierFlags:0x40
  3607. timestamp:0
  3608. windowNumber:0
  3609. context:nil
  3610. subtype:NSEventSubtypeApplicationActivated
  3611. data1:0
  3612. data2:0];
  3613. [NSApp postEvent:focusevent atStart:YES];
  3614. }
  3615. - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)sender {
  3616. _SOKOL_UNUSED(sender);
  3617. return YES;
  3618. }
  3619. - (void)applicationWillTerminate:(NSNotification*)notification {
  3620. _SOKOL_UNUSED(notification);
  3621. _sapp_call_cleanup();
  3622. _sapp_macos_discard_state();
  3623. _sapp_discard_state();
  3624. }
  3625. @end
  3626. @implementation _sapp_macos_window_delegate
  3627. - (BOOL)windowShouldClose:(id)sender {
  3628. _SOKOL_UNUSED(sender);
  3629. /* only give user-code a chance to intervene when sapp_quit() wasn't already called */
  3630. if (!_sapp.quit_ordered) {
  3631. /* if window should be closed and event handling is enabled, give user code
  3632. a chance to intervene via sapp_cancel_quit()
  3633. */
  3634. _sapp.quit_requested = true;
  3635. _sapp_macos_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  3636. /* user code hasn't intervened, quit the app */
  3637. if (_sapp.quit_requested) {
  3638. _sapp.quit_ordered = true;
  3639. }
  3640. }
  3641. if (_sapp.quit_ordered) {
  3642. return YES;
  3643. }
  3644. else {
  3645. return NO;
  3646. }
  3647. }
  3648. #if defined(SOKOL_METAL)
  3649. - (void)windowWillStartLiveResize:(NSNotification *)notification {
  3650. // Work around the MTKView resizing glitch by "anchoring" the layer to the window corner opposite
  3651. // to the currently manipulated corner (or edge). This prevents the content stretching back and
  3652. // forth during resizing. This is a workaround for this issue: https://github.com/floooh/sokol/issues/700
  3653. // Can be removed if/when migrating to CAMetalLayer: https://github.com/floooh/sokol/issues/727
  3654. bool resizing_from_left = _sapp.mouse.x < _sapp.window_width/2;
  3655. bool resizing_from_top = _sapp.mouse.y < _sapp.window_height/2;
  3656. NSViewLayerContentsPlacement placement;
  3657. if (resizing_from_left) {
  3658. placement = resizing_from_top ? NSViewLayerContentsPlacementBottomRight : NSViewLayerContentsPlacementTopRight;
  3659. } else {
  3660. placement = resizing_from_top ? NSViewLayerContentsPlacementBottomLeft : NSViewLayerContentsPlacementTopLeft;
  3661. }
  3662. _sapp.macos.view.layerContentsPlacement = placement;
  3663. }
  3664. #endif
  3665. - (void)windowDidResize:(NSNotification*)notification {
  3666. _SOKOL_UNUSED(notification);
  3667. _sapp_macos_update_dimensions();
  3668. }
  3669. - (void)windowDidChangeScreen:(NSNotification*)notification {
  3670. _SOKOL_UNUSED(notification);
  3671. _sapp_timing_reset(&_sapp.timing);
  3672. _sapp_macos_update_dimensions();
  3673. }
  3674. - (void)windowDidMiniaturize:(NSNotification*)notification {
  3675. _SOKOL_UNUSED(notification);
  3676. _sapp_macos_app_event(SAPP_EVENTTYPE_ICONIFIED);
  3677. }
  3678. - (void)windowDidDeminiaturize:(NSNotification*)notification {
  3679. _SOKOL_UNUSED(notification);
  3680. _sapp_macos_app_event(SAPP_EVENTTYPE_RESTORED);
  3681. }
  3682. - (void)windowDidBecomeKey:(NSNotification*)notification {
  3683. _SOKOL_UNUSED(notification);
  3684. _sapp_macos_app_event(SAPP_EVENTTYPE_FOCUSED);
  3685. }
  3686. - (void)windowDidResignKey:(NSNotification*)notification {
  3687. _SOKOL_UNUSED(notification);
  3688. _sapp_macos_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  3689. }
  3690. - (void)windowDidEnterFullScreen:(NSNotification*)notification {
  3691. _SOKOL_UNUSED(notification);
  3692. _sapp.fullscreen = true;
  3693. }
  3694. - (void)windowDidExitFullScreen:(NSNotification*)notification {
  3695. _SOKOL_UNUSED(notification);
  3696. _sapp.fullscreen = false;
  3697. }
  3698. @end
  3699. @implementation _sapp_macos_window
  3700. - (instancetype)initWithContentRect:(NSRect)contentRect
  3701. styleMask:(NSWindowStyleMask)style
  3702. backing:(NSBackingStoreType)backingStoreType
  3703. defer:(BOOL)flag {
  3704. if (self = [super initWithContentRect:contentRect styleMask:style backing:backingStoreType defer:flag]) {
  3705. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  3706. [self registerForDraggedTypes:[NSArray arrayWithObject:NSPasteboardTypeFileURL]];
  3707. #endif
  3708. }
  3709. return self;
  3710. }
  3711. - (NSDragOperation)draggingEntered:(id<NSDraggingInfo>)sender {
  3712. return NSDragOperationCopy;
  3713. }
  3714. - (NSDragOperation)draggingUpdated:(id<NSDraggingInfo>)sender {
  3715. return NSDragOperationCopy;
  3716. }
  3717. - (BOOL)performDragOperation:(id<NSDraggingInfo>)sender {
  3718. #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  3719. NSPasteboard *pboard = [sender draggingPasteboard];
  3720. if ([pboard.types containsObject:NSPasteboardTypeFileURL]) {
  3721. _sapp_clear_drop_buffer();
  3722. _sapp.drop.num_files = ((int)pboard.pasteboardItems.count > _sapp.drop.max_files) ? _sapp.drop.max_files : (int)pboard.pasteboardItems.count;
  3723. bool drop_failed = false;
  3724. for (int i = 0; i < _sapp.drop.num_files; i++) {
  3725. NSURL *fileUrl = [NSURL fileURLWithPath:[pboard.pasteboardItems[(NSUInteger)i] stringForType:NSPasteboardTypeFileURL]];
  3726. if (!_sapp_strcpy(fileUrl.standardizedURL.path.UTF8String, _sapp_dropped_file_path_ptr(i), _sapp.drop.max_path_length)) {
  3727. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  3728. drop_failed = true;
  3729. break;
  3730. }
  3731. }
  3732. if (!drop_failed) {
  3733. if (_sapp_events_enabled()) {
  3734. _sapp_macos_mouse_update_from_nspoint(sender.draggingLocation, true);
  3735. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  3736. _sapp.event.modifiers = _sapp_macos_mods(nil);
  3737. _sapp_call_event(&_sapp.event);
  3738. }
  3739. }
  3740. else {
  3741. _sapp_clear_drop_buffer();
  3742. _sapp.drop.num_files = 0;
  3743. }
  3744. return YES;
  3745. }
  3746. #endif
  3747. return NO;
  3748. }
  3749. @end
  3750. @implementation _sapp_macos_view
  3751. #if defined(SOKOL_GLCORE)
  3752. - (void)timerFired:(id)sender {
  3753. _SOKOL_UNUSED(sender);
  3754. [self setNeedsDisplay:YES];
  3755. }
  3756. - (void)prepareOpenGL {
  3757. [super prepareOpenGL];
  3758. GLint swapInt = 1;
  3759. NSOpenGLContext* ctx = [_sapp.macos.view openGLContext];
  3760. [ctx setValues:&swapInt forParameter:NSOpenGLContextParameterSwapInterval];
  3761. [ctx makeCurrentContext];
  3762. }
  3763. #endif
  3764. _SOKOL_PRIVATE void _sapp_macos_poll_input_events(void) {
  3765. /*
  3766. NOTE: late event polling temporarily out-commented to check if this
  3767. causes infrequent and almost impossible to reproduce problems with the
  3768. window close events, see:
  3769. https://github.com/floooh/sokol/pull/483#issuecomment-805148815
  3770. const NSEventMask mask = NSEventMaskLeftMouseDown |
  3771. NSEventMaskLeftMouseUp|
  3772. NSEventMaskRightMouseDown |
  3773. NSEventMaskRightMouseUp |
  3774. NSEventMaskMouseMoved |
  3775. NSEventMaskLeftMouseDragged |
  3776. NSEventMaskRightMouseDragged |
  3777. NSEventMaskMouseEntered |
  3778. NSEventMaskMouseExited |
  3779. NSEventMaskKeyDown |
  3780. NSEventMaskKeyUp |
  3781. NSEventMaskCursorUpdate |
  3782. NSEventMaskScrollWheel |
  3783. NSEventMaskTabletPoint |
  3784. NSEventMaskTabletProximity |
  3785. NSEventMaskOtherMouseDown |
  3786. NSEventMaskOtherMouseUp |
  3787. NSEventMaskOtherMouseDragged |
  3788. NSEventMaskPressure |
  3789. NSEventMaskDirectTouch;
  3790. @autoreleasepool {
  3791. for (;;) {
  3792. // NOTE: using NSDefaultRunLoopMode here causes stuttering in the GL backend,
  3793. // see: https://github.com/floooh/sokol/issues/486
  3794. NSEvent* event = [NSApp nextEventMatchingMask:mask untilDate:nil inMode:NSEventTrackingRunLoopMode dequeue:YES];
  3795. if (event == nil) {
  3796. break;
  3797. }
  3798. [NSApp sendEvent:event];
  3799. }
  3800. }
  3801. */
  3802. }
  3803. - (void)drawRect:(NSRect)rect {
  3804. _SOKOL_UNUSED(rect);
  3805. #if defined(_SAPP_ANY_GL)
  3806. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  3807. #endif
  3808. _sapp_timing_measure(&_sapp.timing);
  3809. /* Catch any last-moment input events */
  3810. _sapp_macos_poll_input_events();
  3811. @autoreleasepool {
  3812. _sapp_macos_frame();
  3813. }
  3814. #if defined(_SAPP_ANY_GL)
  3815. [[_sapp.macos.view openGLContext] flushBuffer];
  3816. #endif
  3817. }
  3818. - (BOOL)isOpaque {
  3819. return YES;
  3820. }
  3821. - (BOOL)canBecomeKeyView {
  3822. return YES;
  3823. }
  3824. - (BOOL)acceptsFirstResponder {
  3825. return YES;
  3826. }
  3827. - (void)updateTrackingAreas {
  3828. if (_sapp.macos.tracking_area != nil) {
  3829. [self removeTrackingArea:_sapp.macos.tracking_area];
  3830. _SAPP_OBJC_RELEASE(_sapp.macos.tracking_area);
  3831. }
  3832. const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
  3833. NSTrackingActiveInKeyWindow |
  3834. NSTrackingEnabledDuringMouseDrag |
  3835. NSTrackingCursorUpdate |
  3836. NSTrackingInVisibleRect |
  3837. NSTrackingAssumeInside;
  3838. _sapp.macos.tracking_area = [[NSTrackingArea alloc] initWithRect:[self bounds] options:options owner:self userInfo:nil];
  3839. [self addTrackingArea:_sapp.macos.tracking_area];
  3840. [super updateTrackingAreas];
  3841. }
  3842. // helper function to make GL context active
  3843. static void _sapp_gl_make_current(void) {
  3844. #if defined(SOKOL_GLCORE)
  3845. [[_sapp.macos.view openGLContext] makeCurrentContext];
  3846. #endif
  3847. }
  3848. - (void)mouseEntered:(NSEvent*)event {
  3849. _sapp_gl_make_current();
  3850. _sapp_macos_mouse_update_from_nsevent(event, true);
  3851. /* don't send mouse enter/leave while dragging (so that it behaves the same as
  3852. on Windows while SetCapture is active
  3853. */
  3854. if (0 == _sapp.macos.mouse_buttons) {
  3855. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3856. }
  3857. }
  3858. - (void)mouseExited:(NSEvent*)event {
  3859. _sapp_gl_make_current();
  3860. _sapp_macos_mouse_update_from_nsevent(event, true);
  3861. if (0 == _sapp.macos.mouse_buttons) {
  3862. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3863. }
  3864. }
  3865. - (void)mouseDown:(NSEvent*)event {
  3866. _sapp_gl_make_current();
  3867. _sapp_macos_mouse_update_from_nsevent(event, false);
  3868. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_LEFT, _sapp_macos_mods(event));
  3869. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_LEFT);
  3870. }
  3871. - (void)mouseUp:(NSEvent*)event {
  3872. _sapp_gl_make_current();
  3873. _sapp_macos_mouse_update_from_nsevent(event, false);
  3874. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_LEFT, _sapp_macos_mods(event));
  3875. _sapp.macos.mouse_buttons &= ~(1<<SAPP_MOUSEBUTTON_LEFT);
  3876. }
  3877. - (void)rightMouseDown:(NSEvent*)event {
  3878. _sapp_gl_make_current();
  3879. _sapp_macos_mouse_update_from_nsevent(event, false);
  3880. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_RIGHT, _sapp_macos_mods(event));
  3881. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_RIGHT);
  3882. }
  3883. - (void)rightMouseUp:(NSEvent*)event {
  3884. _sapp_gl_make_current();
  3885. _sapp_macos_mouse_update_from_nsevent(event, false);
  3886. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_RIGHT, _sapp_macos_mods(event));
  3887. _sapp.macos.mouse_buttons &= ~(1<<SAPP_MOUSEBUTTON_RIGHT);
  3888. }
  3889. - (void)otherMouseDown:(NSEvent*)event {
  3890. _sapp_gl_make_current();
  3891. _sapp_macos_mouse_update_from_nsevent(event, false);
  3892. if (2 == event.buttonNumber) {
  3893. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_MIDDLE, _sapp_macos_mods(event));
  3894. _sapp.macos.mouse_buttons |= (1<<SAPP_MOUSEBUTTON_MIDDLE);
  3895. }
  3896. }
  3897. - (void)otherMouseUp:(NSEvent*)event {
  3898. _sapp_gl_make_current();
  3899. _sapp_macos_mouse_update_from_nsevent(event, false);
  3900. if (2 == event.buttonNumber) {
  3901. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_MIDDLE, _sapp_macos_mods(event));
  3902. _sapp.macos.mouse_buttons &= (1<<SAPP_MOUSEBUTTON_MIDDLE);
  3903. }
  3904. }
  3905. - (void)otherMouseDragged:(NSEvent*)event {
  3906. _sapp_gl_make_current();
  3907. _sapp_macos_mouse_update_from_nsevent(event, false);
  3908. if (2 == event.buttonNumber) {
  3909. if (_sapp.mouse.locked) {
  3910. _sapp.mouse.dx = [event deltaX];
  3911. _sapp.mouse.dy = [event deltaY];
  3912. }
  3913. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3914. }
  3915. }
  3916. - (void)mouseMoved:(NSEvent*)event {
  3917. _sapp_gl_make_current();
  3918. _sapp_macos_mouse_update_from_nsevent(event, false);
  3919. if (_sapp.mouse.locked) {
  3920. _sapp.mouse.dx = [event deltaX];
  3921. _sapp.mouse.dy = [event deltaY];
  3922. }
  3923. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID , _sapp_macos_mods(event));
  3924. }
  3925. - (void)mouseDragged:(NSEvent*)event {
  3926. _sapp_gl_make_current();
  3927. _sapp_macos_mouse_update_from_nsevent(event, false);
  3928. if (_sapp.mouse.locked) {
  3929. _sapp.mouse.dx = [event deltaX];
  3930. _sapp.mouse.dy = [event deltaY];
  3931. }
  3932. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID , _sapp_macos_mods(event));
  3933. }
  3934. - (void)rightMouseDragged:(NSEvent*)event {
  3935. _sapp_gl_make_current();
  3936. _sapp_macos_mouse_update_from_nsevent(event, false);
  3937. if (_sapp.mouse.locked) {
  3938. _sapp.mouse.dx = [event deltaX];
  3939. _sapp.mouse.dy = [event deltaY];
  3940. }
  3941. _sapp_macos_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_macos_mods(event));
  3942. }
  3943. - (void)scrollWheel:(NSEvent*)event {
  3944. _sapp_gl_make_current();
  3945. _sapp_macos_mouse_update_from_nsevent(event, true);
  3946. if (_sapp_events_enabled()) {
  3947. float dx = (float) event.scrollingDeltaX;
  3948. float dy = (float) event.scrollingDeltaY;
  3949. if (event.hasPreciseScrollingDeltas) {
  3950. dx *= 0.1;
  3951. dy *= 0.1;
  3952. }
  3953. if ((_sapp_absf(dx) > 0.0f) || (_sapp_absf(dy) > 0.0f)) {
  3954. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  3955. _sapp.event.modifiers = _sapp_macos_mods(event);
  3956. _sapp.event.scroll_x = dx;
  3957. _sapp.event.scroll_y = dy;
  3958. _sapp_call_event(&_sapp.event);
  3959. }
  3960. }
  3961. }
  3962. - (void)keyDown:(NSEvent*)event {
  3963. if (_sapp_events_enabled()) {
  3964. _sapp_gl_make_current();
  3965. const uint32_t mods = _sapp_macos_mods(event);
  3966. const sapp_keycode key_code = _sapp_translate_key(event.keyCode);
  3967. _sapp_macos_key_event(SAPP_EVENTTYPE_KEY_DOWN, key_code, event.isARepeat, mods);
  3968. const NSString* chars = event.characters;
  3969. const NSUInteger len = chars.length;
  3970. if (len > 0) {
  3971. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  3972. _sapp.event.modifiers = mods;
  3973. for (NSUInteger i = 0; i < len; i++) {
  3974. const unichar codepoint = [chars characterAtIndex:i];
  3975. if ((codepoint & 0xFF00) == 0xF700) {
  3976. continue;
  3977. }
  3978. _sapp.event.char_code = codepoint;
  3979. _sapp.event.key_repeat = event.isARepeat;
  3980. _sapp_call_event(&_sapp.event);
  3981. }
  3982. }
  3983. /* if this is a Cmd+V (paste), also send a CLIPBOARD_PASTE event */
  3984. if (_sapp.clipboard.enabled && (mods == SAPP_MODIFIER_SUPER) && (key_code == SAPP_KEYCODE_V)) {
  3985. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  3986. _sapp_call_event(&_sapp.event);
  3987. }
  3988. }
  3989. }
  3990. - (void)keyUp:(NSEvent*)event {
  3991. _sapp_gl_make_current();
  3992. _sapp_macos_key_event(SAPP_EVENTTYPE_KEY_UP,
  3993. _sapp_translate_key(event.keyCode),
  3994. event.isARepeat,
  3995. _sapp_macos_mods(event));
  3996. }
  3997. - (void)flagsChanged:(NSEvent*)event {
  3998. const uint32_t old_f = _sapp.macos.flags_changed_store;
  3999. const uint32_t new_f = (uint32_t)event.modifierFlags;
  4000. _sapp.macos.flags_changed_store = new_f;
  4001. sapp_keycode key_code = SAPP_KEYCODE_INVALID;
  4002. bool down = false;
  4003. if ((new_f ^ old_f) & NSEventModifierFlagShift) {
  4004. key_code = SAPP_KEYCODE_LEFT_SHIFT;
  4005. down = 0 != (new_f & NSEventModifierFlagShift);
  4006. }
  4007. if ((new_f ^ old_f) & NSEventModifierFlagControl) {
  4008. key_code = SAPP_KEYCODE_LEFT_CONTROL;
  4009. down = 0 != (new_f & NSEventModifierFlagControl);
  4010. }
  4011. if ((new_f ^ old_f) & NSEventModifierFlagOption) {
  4012. key_code = SAPP_KEYCODE_LEFT_ALT;
  4013. down = 0 != (new_f & NSEventModifierFlagOption);
  4014. }
  4015. if ((new_f ^ old_f) & NSEventModifierFlagCommand) {
  4016. key_code = SAPP_KEYCODE_LEFT_SUPER;
  4017. down = 0 != (new_f & NSEventModifierFlagCommand);
  4018. }
  4019. if (key_code != SAPP_KEYCODE_INVALID) {
  4020. _sapp_macos_key_event(down ? SAPP_EVENTTYPE_KEY_DOWN : SAPP_EVENTTYPE_KEY_UP,
  4021. key_code,
  4022. false,
  4023. _sapp_macos_mods(event));
  4024. }
  4025. }
  4026. @end
  4027. #endif // macOS
  4028. // ██ ██████ ███████
  4029. // ██ ██ ██ ██
  4030. // ██ ██ ██ ███████
  4031. // ██ ██ ██ ██
  4032. // ██ ██████ ███████
  4033. //
  4034. // >>ios
  4035. #if defined(_SAPP_IOS)
  4036. _SOKOL_PRIVATE void _sapp_ios_discard_state(void) {
  4037. // NOTE: it's safe to call [release] on a nil object
  4038. _SAPP_OBJC_RELEASE(_sapp.ios.textfield_dlg);
  4039. _SAPP_OBJC_RELEASE(_sapp.ios.textfield);
  4040. #if defined(SOKOL_METAL)
  4041. _SAPP_OBJC_RELEASE(_sapp.ios.view_ctrl);
  4042. _SAPP_OBJC_RELEASE(_sapp.ios.mtl_device);
  4043. #else
  4044. _SAPP_OBJC_RELEASE(_sapp.ios.view_ctrl);
  4045. _SAPP_OBJC_RELEASE(_sapp.ios.eagl_ctx);
  4046. #endif
  4047. _SAPP_OBJC_RELEASE(_sapp.ios.view);
  4048. _SAPP_OBJC_RELEASE(_sapp.ios.window);
  4049. }
  4050. _SOKOL_PRIVATE void _sapp_ios_run(const sapp_desc* desc) {
  4051. _sapp_init_state(desc);
  4052. static int argc = 1;
  4053. static char* argv[] = { (char*)"sokol_app" };
  4054. UIApplicationMain(argc, argv, nil, NSStringFromClass([_sapp_app_delegate class]));
  4055. }
  4056. /* iOS entry function */
  4057. #if !defined(SOKOL_NO_ENTRY)
  4058. int main(int argc, char* argv[]) {
  4059. sapp_desc desc = sokol_main(argc, argv);
  4060. _sapp_ios_run(&desc);
  4061. return 0;
  4062. }
  4063. #endif /* SOKOL_NO_ENTRY */
  4064. _SOKOL_PRIVATE void _sapp_ios_app_event(sapp_event_type type) {
  4065. if (_sapp_events_enabled()) {
  4066. _sapp_init_event(type);
  4067. _sapp_call_event(&_sapp.event);
  4068. }
  4069. }
  4070. _SOKOL_PRIVATE void _sapp_ios_touch_event(sapp_event_type type, NSSet<UITouch *>* touches, UIEvent* event) {
  4071. if (_sapp_events_enabled()) {
  4072. _sapp_init_event(type);
  4073. NSEnumerator* enumerator = event.allTouches.objectEnumerator;
  4074. UITouch* ios_touch;
  4075. while ((ios_touch = [enumerator nextObject])) {
  4076. if ((_sapp.event.num_touches + 1) < SAPP_MAX_TOUCHPOINTS) {
  4077. CGPoint ios_pos = [ios_touch locationInView:_sapp.ios.view];
  4078. sapp_touchpoint* cur_point = &_sapp.event.touches[_sapp.event.num_touches++];
  4079. cur_point->identifier = (uintptr_t) ios_touch;
  4080. cur_point->pos_x = ios_pos.x * _sapp.dpi_scale;
  4081. cur_point->pos_y = ios_pos.y * _sapp.dpi_scale;
  4082. cur_point->changed = [touches containsObject:ios_touch];
  4083. }
  4084. }
  4085. if (_sapp.event.num_touches > 0) {
  4086. _sapp_call_event(&_sapp.event);
  4087. }
  4088. }
  4089. }
  4090. _SOKOL_PRIVATE void _sapp_ios_update_dimensions(void) {
  4091. CGRect screen_rect = UIScreen.mainScreen.bounds;
  4092. _sapp.framebuffer_width = (int)roundf(screen_rect.size.width * _sapp.dpi_scale);
  4093. _sapp.framebuffer_height = (int)roundf(screen_rect.size.height * _sapp.dpi_scale);
  4094. _sapp.window_width = (int)roundf(screen_rect.size.width);
  4095. _sapp.window_height = (int)roundf(screen_rect.size.height);
  4096. int cur_fb_width, cur_fb_height;
  4097. #if defined(SOKOL_METAL)
  4098. const CGSize fb_size = _sapp.ios.view.drawableSize;
  4099. cur_fb_width = (int)roundf(fb_size.width);
  4100. cur_fb_height = (int)roundf(fb_size.height);
  4101. #else
  4102. cur_fb_width = (int)roundf(_sapp.ios.view.drawableWidth);
  4103. cur_fb_height = (int)roundf(_sapp.ios.view.drawableHeight);
  4104. #endif
  4105. const bool dim_changed = (_sapp.framebuffer_width != cur_fb_width) ||
  4106. (_sapp.framebuffer_height != cur_fb_height);
  4107. if (dim_changed) {
  4108. #if defined(SOKOL_METAL)
  4109. const CGSize drawable_size = { (CGFloat) _sapp.framebuffer_width, (CGFloat) _sapp.framebuffer_height };
  4110. _sapp.ios.view.drawableSize = drawable_size;
  4111. #else
  4112. // nothing to do here, GLKView correctly respects the view's contentScaleFactor
  4113. #endif
  4114. if (!_sapp.first_frame) {
  4115. _sapp_ios_app_event(SAPP_EVENTTYPE_RESIZED);
  4116. }
  4117. }
  4118. }
  4119. _SOKOL_PRIVATE void _sapp_ios_frame(void) {
  4120. _sapp_ios_update_dimensions();
  4121. _sapp_frame();
  4122. }
  4123. _SOKOL_PRIVATE void _sapp_ios_show_keyboard(bool shown) {
  4124. /* if not happened yet, create an invisible text field */
  4125. if (nil == _sapp.ios.textfield) {
  4126. _sapp.ios.textfield_dlg = [[_sapp_textfield_dlg alloc] init];
  4127. _sapp.ios.textfield = [[UITextField alloc] initWithFrame:CGRectMake(10, 10, 100, 50)];
  4128. _sapp.ios.textfield.keyboardType = UIKeyboardTypeDefault;
  4129. _sapp.ios.textfield.returnKeyType = UIReturnKeyDefault;
  4130. _sapp.ios.textfield.autocapitalizationType = UITextAutocapitalizationTypeNone;
  4131. _sapp.ios.textfield.autocorrectionType = UITextAutocorrectionTypeNo;
  4132. _sapp.ios.textfield.spellCheckingType = UITextSpellCheckingTypeNo;
  4133. _sapp.ios.textfield.hidden = YES;
  4134. _sapp.ios.textfield.text = @"x";
  4135. _sapp.ios.textfield.delegate = _sapp.ios.textfield_dlg;
  4136. [_sapp.ios.view_ctrl.view addSubview:_sapp.ios.textfield];
  4137. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4138. selector:@selector(keyboardWasShown:)
  4139. name:UIKeyboardDidShowNotification object:nil];
  4140. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4141. selector:@selector(keyboardWillBeHidden:)
  4142. name:UIKeyboardWillHideNotification object:nil];
  4143. [[NSNotificationCenter defaultCenter] addObserver:_sapp.ios.textfield_dlg
  4144. selector:@selector(keyboardDidChangeFrame:)
  4145. name:UIKeyboardDidChangeFrameNotification object:nil];
  4146. }
  4147. if (shown) {
  4148. /* setting the text field as first responder brings up the onscreen keyboard */
  4149. [_sapp.ios.textfield becomeFirstResponder];
  4150. }
  4151. else {
  4152. [_sapp.ios.textfield resignFirstResponder];
  4153. }
  4154. }
  4155. @implementation _sapp_app_delegate
  4156. - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
  4157. CGRect screen_rect = UIScreen.mainScreen.bounds;
  4158. _sapp.ios.window = [[UIWindow alloc] initWithFrame:screen_rect];
  4159. _sapp.window_width = (int)roundf(screen_rect.size.width);
  4160. _sapp.window_height = (int)roundf(screen_rect.size.height);
  4161. if (_sapp.desc.high_dpi) {
  4162. _sapp.dpi_scale = (float) UIScreen.mainScreen.nativeScale;
  4163. }
  4164. else {
  4165. _sapp.dpi_scale = 1.0f;
  4166. }
  4167. _sapp.framebuffer_width = (int)roundf(_sapp.window_width * _sapp.dpi_scale);
  4168. _sapp.framebuffer_height = (int)roundf(_sapp.window_height * _sapp.dpi_scale);
  4169. NSInteger max_fps = UIScreen.mainScreen.maximumFramesPerSecond;
  4170. #if defined(SOKOL_METAL)
  4171. _sapp.ios.mtl_device = MTLCreateSystemDefaultDevice();
  4172. _sapp.ios.view = [[_sapp_ios_view alloc] init];
  4173. _sapp.ios.view.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  4174. _sapp.ios.view.device = _sapp.ios.mtl_device;
  4175. _sapp.ios.view.colorPixelFormat = MTLPixelFormatBGRA8Unorm;
  4176. _sapp.ios.view.depthStencilPixelFormat = MTLPixelFormatDepth32Float_Stencil8;
  4177. _sapp.ios.view.sampleCount = (NSUInteger)_sapp.sample_count;
  4178. /* NOTE: iOS MTKView seems to ignore thew view's contentScaleFactor
  4179. and automatically renders at Retina resolution. We'll disable
  4180. autoResize and instead do the resizing in _sapp_ios_update_dimensions()
  4181. */
  4182. _sapp.ios.view.autoResizeDrawable = false;
  4183. _sapp.ios.view.userInteractionEnabled = YES;
  4184. _sapp.ios.view.multipleTouchEnabled = YES;
  4185. _sapp.ios.view_ctrl = [[UIViewController alloc] init];
  4186. _sapp.ios.view_ctrl.modalPresentationStyle = UIModalPresentationFullScreen;
  4187. _sapp.ios.view_ctrl.view = _sapp.ios.view;
  4188. _sapp.ios.window.rootViewController = _sapp.ios.view_ctrl;
  4189. #else
  4190. _sapp.ios.eagl_ctx = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES3];
  4191. _sapp.ios.view = [[_sapp_ios_view alloc] initWithFrame:screen_rect];
  4192. _sapp.ios.view.drawableColorFormat = GLKViewDrawableColorFormatRGBA8888;
  4193. _sapp.ios.view.drawableDepthFormat = GLKViewDrawableDepthFormat24;
  4194. _sapp.ios.view.drawableStencilFormat = GLKViewDrawableStencilFormatNone;
  4195. GLKViewDrawableMultisample msaa = _sapp.sample_count > 1 ? GLKViewDrawableMultisample4X : GLKViewDrawableMultisampleNone;
  4196. _sapp.ios.view.drawableMultisample = msaa;
  4197. _sapp.ios.view.context = _sapp.ios.eagl_ctx;
  4198. _sapp.ios.view.enableSetNeedsDisplay = NO;
  4199. _sapp.ios.view.userInteractionEnabled = YES;
  4200. _sapp.ios.view.multipleTouchEnabled = YES;
  4201. // on GLKView, contentScaleFactor appears to work just fine!
  4202. if (_sapp.desc.high_dpi) {
  4203. _sapp.ios.view.contentScaleFactor = _sapp.dpi_scale;
  4204. }
  4205. else {
  4206. _sapp.ios.view.contentScaleFactor = 1.0;
  4207. }
  4208. _sapp.ios.view_ctrl = [[GLKViewController alloc] init];
  4209. _sapp.ios.view_ctrl.view = _sapp.ios.view;
  4210. _sapp.ios.view_ctrl.preferredFramesPerSecond = max_fps / _sapp.swap_interval;
  4211. _sapp.ios.window.rootViewController = _sapp.ios.view_ctrl;
  4212. #endif
  4213. [_sapp.ios.window makeKeyAndVisible];
  4214. _sapp.valid = true;
  4215. return YES;
  4216. }
  4217. - (void)applicationWillResignActive:(UIApplication *)application {
  4218. if (!_sapp.ios.suspended) {
  4219. _sapp.ios.suspended = true;
  4220. _sapp_ios_app_event(SAPP_EVENTTYPE_SUSPENDED);
  4221. }
  4222. }
  4223. - (void)applicationDidBecomeActive:(UIApplication *)application {
  4224. if (_sapp.ios.suspended) {
  4225. _sapp.ios.suspended = false;
  4226. _sapp_ios_app_event(SAPP_EVENTTYPE_RESUMED);
  4227. }
  4228. }
  4229. /* NOTE: this method will rarely ever be called, iOS application
  4230. which are terminated by the user are usually killed via signal 9
  4231. by the operating system.
  4232. */
  4233. - (void)applicationWillTerminate:(UIApplication *)application {
  4234. _SOKOL_UNUSED(application);
  4235. _sapp_call_cleanup();
  4236. _sapp_ios_discard_state();
  4237. _sapp_discard_state();
  4238. }
  4239. @end
  4240. @implementation _sapp_textfield_dlg
  4241. - (void)keyboardWasShown:(NSNotification*)notif {
  4242. _sapp.onscreen_keyboard_shown = true;
  4243. /* query the keyboard's size, and modify the content view's size */
  4244. if (_sapp.desc.ios_keyboard_resizes_canvas) {
  4245. NSDictionary* info = notif.userInfo;
  4246. CGFloat kbd_h = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
  4247. CGRect view_frame = UIScreen.mainScreen.bounds;
  4248. view_frame.size.height -= kbd_h;
  4249. _sapp.ios.view.frame = view_frame;
  4250. }
  4251. }
  4252. - (void)keyboardWillBeHidden:(NSNotification*)notif {
  4253. _sapp.onscreen_keyboard_shown = false;
  4254. if (_sapp.desc.ios_keyboard_resizes_canvas) {
  4255. _sapp.ios.view.frame = UIScreen.mainScreen.bounds;
  4256. }
  4257. }
  4258. - (void)keyboardDidChangeFrame:(NSNotification*)notif {
  4259. /* this is for the case when the screen rotation changes while the keyboard is open */
  4260. if (_sapp.onscreen_keyboard_shown && _sapp.desc.ios_keyboard_resizes_canvas) {
  4261. NSDictionary* info = notif.userInfo;
  4262. CGFloat kbd_h = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
  4263. CGRect view_frame = UIScreen.mainScreen.bounds;
  4264. view_frame.size.height -= kbd_h;
  4265. _sapp.ios.view.frame = view_frame;
  4266. }
  4267. }
  4268. - (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
  4269. if (_sapp_events_enabled()) {
  4270. const NSUInteger len = string.length;
  4271. if (len > 0) {
  4272. for (NSUInteger i = 0; i < len; i++) {
  4273. unichar c = [string characterAtIndex:i];
  4274. if (c >= 32) {
  4275. /* ignore surrogates for now */
  4276. if ((c < 0xD800) || (c > 0xDFFF)) {
  4277. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  4278. _sapp.event.char_code = c;
  4279. _sapp_call_event(&_sapp.event);
  4280. }
  4281. }
  4282. if (c <= 32) {
  4283. sapp_keycode k = SAPP_KEYCODE_INVALID;
  4284. switch (c) {
  4285. case 10: k = SAPP_KEYCODE_ENTER; break;
  4286. case 32: k = SAPP_KEYCODE_SPACE; break;
  4287. default: break;
  4288. }
  4289. if (k != SAPP_KEYCODE_INVALID) {
  4290. _sapp_init_event(SAPP_EVENTTYPE_KEY_DOWN);
  4291. _sapp.event.key_code = k;
  4292. _sapp_call_event(&_sapp.event);
  4293. _sapp_init_event(SAPP_EVENTTYPE_KEY_UP);
  4294. _sapp.event.key_code = k;
  4295. _sapp_call_event(&_sapp.event);
  4296. }
  4297. }
  4298. }
  4299. }
  4300. else {
  4301. /* this was a backspace */
  4302. _sapp_init_event(SAPP_EVENTTYPE_KEY_DOWN);
  4303. _sapp.event.key_code = SAPP_KEYCODE_BACKSPACE;
  4304. _sapp_call_event(&_sapp.event);
  4305. _sapp_init_event(SAPP_EVENTTYPE_KEY_UP);
  4306. _sapp.event.key_code = SAPP_KEYCODE_BACKSPACE;
  4307. _sapp_call_event(&_sapp.event);
  4308. }
  4309. }
  4310. return NO;
  4311. }
  4312. @end
  4313. @implementation _sapp_ios_view
  4314. - (void)drawRect:(CGRect)rect {
  4315. _SOKOL_UNUSED(rect);
  4316. #if defined(_SAPP_ANY_GL)
  4317. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  4318. #endif
  4319. _sapp_timing_measure(&_sapp.timing);
  4320. @autoreleasepool {
  4321. _sapp_ios_frame();
  4322. }
  4323. }
  4324. - (BOOL)isOpaque {
  4325. return YES;
  4326. }
  4327. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4328. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_BEGAN, touches, event);
  4329. }
  4330. - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4331. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_MOVED, touches, event);
  4332. }
  4333. - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4334. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_ENDED, touches, event);
  4335. }
  4336. - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent*)event {
  4337. _sapp_ios_touch_event(SAPP_EVENTTYPE_TOUCHES_CANCELLED, touches, event);
  4338. }
  4339. @end
  4340. #endif /* TARGET_OS_IPHONE */
  4341. #endif /* _SAPP_APPLE */
  4342. // ███████ ███ ███ ███████ ██████ ██████ ██ ██████ ████████ ███████ ███ ██
  4343. // ██ ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  4344. // █████ ██ ████ ██ ███████ ██ ██████ ██ ██████ ██ █████ ██ ██ ██
  4345. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  4346. // ███████ ██ ██ ███████ ██████ ██ ██ ██ ██ ██ ███████ ██ ████
  4347. //
  4348. // >>emscripten
  4349. #if defined(_SAPP_EMSCRIPTEN)
  4350. #if defined(EM_JS_DEPS)
  4351. EM_JS_DEPS(sokol_app, "$withStackSave,$stringToUTF8OnStack,$findCanvasEventTarget");
  4352. #endif
  4353. #ifdef __cplusplus
  4354. extern "C" {
  4355. #endif
  4356. typedef void (*_sapp_html5_fetch_callback) (const sapp_html5_fetch_response*);
  4357. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_onpaste(const char* str) {
  4358. if (_sapp.clipboard.enabled) {
  4359. _sapp_strcpy(str, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  4360. if (_sapp_events_enabled()) {
  4361. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  4362. _sapp_call_event(&_sapp.event);
  4363. }
  4364. }
  4365. }
  4366. /* https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload */
  4367. EMSCRIPTEN_KEEPALIVE int _sapp_html5_get_ask_leave_site(void) {
  4368. return _sapp.html5_ask_leave_site ? 1 : 0;
  4369. }
  4370. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_begin_drop(int num) {
  4371. if (!_sapp.drop.enabled) {
  4372. return;
  4373. }
  4374. if (num < 0) {
  4375. num = 0;
  4376. }
  4377. if (num > _sapp.drop.max_files) {
  4378. num = _sapp.drop.max_files;
  4379. }
  4380. _sapp.drop.num_files = num;
  4381. _sapp_clear_drop_buffer();
  4382. }
  4383. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_drop(int i, const char* name) {
  4384. /* NOTE: name is only the filename part, not a path */
  4385. if (!_sapp.drop.enabled) {
  4386. return;
  4387. }
  4388. if (0 == name) {
  4389. return;
  4390. }
  4391. SOKOL_ASSERT(_sapp.drop.num_files <= _sapp.drop.max_files);
  4392. if ((i < 0) || (i >= _sapp.drop.num_files)) {
  4393. return;
  4394. }
  4395. if (!_sapp_strcpy(name, _sapp_dropped_file_path_ptr(i), _sapp.drop.max_path_length)) {
  4396. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  4397. _sapp.drop.num_files = 0;
  4398. }
  4399. }
  4400. EMSCRIPTEN_KEEPALIVE void _sapp_emsc_end_drop(int x, int y, int mods) {
  4401. if (!_sapp.drop.enabled) {
  4402. return;
  4403. }
  4404. if (0 == _sapp.drop.num_files) {
  4405. /* there was an error copying the filenames */
  4406. _sapp_clear_drop_buffer();
  4407. return;
  4408. }
  4409. if (_sapp_events_enabled()) {
  4410. _sapp.mouse.x = (float)x * _sapp.dpi_scale;
  4411. _sapp.mouse.y = (float)y * _sapp.dpi_scale;
  4412. _sapp.mouse.dx = 0.0f;
  4413. _sapp.mouse.dy = 0.0f;
  4414. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  4415. // see sapp_js_add_dragndrop_listeners for mods constants
  4416. if (mods & 1) { _sapp.event.modifiers |= SAPP_MODIFIER_SHIFT; }
  4417. if (mods & 2) { _sapp.event.modifiers |= SAPP_MODIFIER_CTRL; }
  4418. if (mods & 4) { _sapp.event.modifiers |= SAPP_MODIFIER_ALT; }
  4419. if (mods & 8) { _sapp.event.modifiers |= SAPP_MODIFIER_SUPER; }
  4420. _sapp_call_event(&_sapp.event);
  4421. }
  4422. }
  4423. 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) {
  4424. sapp_html5_fetch_response response;
  4425. _sapp_clear(&response, sizeof(response));
  4426. response.succeeded = (0 != success);
  4427. response.error_code = (sapp_html5_fetch_error) error_code;
  4428. response.file_index = index;
  4429. response.data.ptr = buf_ptr;
  4430. response.data.size = fetched_size;
  4431. response.buffer.ptr = buf_ptr;
  4432. response.buffer.size = buf_size;
  4433. response.user_data = user_data;
  4434. callback(&response);
  4435. }
  4436. #ifdef __cplusplus
  4437. } /* extern "C" */
  4438. #endif
  4439. EM_JS(void, sapp_js_add_beforeunload_listener, (void), {
  4440. Module.sokol_beforeunload = (event) => {
  4441. if (__sapp_html5_get_ask_leave_site() != 0) {
  4442. event.preventDefault();
  4443. event.returnValue = ' ';
  4444. }
  4445. };
  4446. window.addEventListener('beforeunload', Module.sokol_beforeunload);
  4447. });
  4448. EM_JS(void, sapp_js_remove_beforeunload_listener, (void), {
  4449. window.removeEventListener('beforeunload', Module.sokol_beforeunload);
  4450. });
  4451. EM_JS(void, sapp_js_add_clipboard_listener, (void), {
  4452. Module.sokol_paste = (event) => {
  4453. const pasted_str = event.clipboardData.getData('text');
  4454. withStackSave(() => {
  4455. const cstr = stringToUTF8OnStack(pasted_str);
  4456. __sapp_emsc_onpaste(cstr);
  4457. });
  4458. };
  4459. window.addEventListener('paste', Module.sokol_paste);
  4460. });
  4461. EM_JS(void, sapp_js_remove_clipboard_listener, (void), {
  4462. window.removeEventListener('paste', Module.sokol_paste);
  4463. });
  4464. EM_JS(void, sapp_js_write_clipboard, (const char* c_str), {
  4465. const str = UTF8ToString(c_str);
  4466. const ta = document.createElement('textarea');
  4467. ta.setAttribute('autocomplete', 'off');
  4468. ta.setAttribute('autocorrect', 'off');
  4469. ta.setAttribute('autocapitalize', 'off');
  4470. ta.setAttribute('spellcheck', 'false');
  4471. ta.style.left = -100 + 'px';
  4472. ta.style.top = -100 + 'px';
  4473. ta.style.height = 1;
  4474. ta.style.width = 1;
  4475. ta.value = str;
  4476. document.body.appendChild(ta);
  4477. ta.select();
  4478. document.execCommand('copy');
  4479. document.body.removeChild(ta);
  4480. });
  4481. _SOKOL_PRIVATE void _sapp_emsc_set_clipboard_string(const char* str) {
  4482. sapp_js_write_clipboard(str);
  4483. }
  4484. EM_JS(void, sapp_js_add_dragndrop_listeners, (void), {
  4485. Module.sokol_drop_files = [];
  4486. Module.sokol_dragenter = (event) => {
  4487. event.stopPropagation();
  4488. event.preventDefault();
  4489. };
  4490. Module.sokol_dragleave = (event) => {
  4491. event.stopPropagation();
  4492. event.preventDefault();
  4493. };
  4494. Module.sokol_dragover = (event) => {
  4495. event.stopPropagation();
  4496. event.preventDefault();
  4497. };
  4498. Module.sokol_drop = (event) => {
  4499. event.stopPropagation();
  4500. event.preventDefault();
  4501. const files = event.dataTransfer.files;
  4502. Module.sokol_dropped_files = files;
  4503. __sapp_emsc_begin_drop(files.length);
  4504. for (let i = 0; i < files.length; i++) {
  4505. withStackSave(() => {
  4506. const cstr = stringToUTF8OnStack(files[i].name);
  4507. __sapp_emsc_drop(i, cstr);
  4508. });
  4509. }
  4510. let mods = 0;
  4511. if (event.shiftKey) { mods |= 1; }
  4512. if (event.ctrlKey) { mods |= 2; }
  4513. if (event.altKey) { mods |= 4; }
  4514. if (event.metaKey) { mods |= 8; }
  4515. // FIXME? see computation of targetX/targetY in emscripten via getClientBoundingRect
  4516. __sapp_emsc_end_drop(event.clientX, event.clientY, mods);
  4517. };
  4518. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4519. const canvas = Module.sapp_emsc_target;
  4520. canvas.addEventListener('dragenter', Module.sokol_dragenter, false);
  4521. canvas.addEventListener('dragleave', Module.sokol_dragleave, false);
  4522. canvas.addEventListener('dragover', Module.sokol_dragover, false);
  4523. canvas.addEventListener('drop', Module.sokol_drop, false);
  4524. });
  4525. EM_JS(uint32_t, sapp_js_dropped_file_size, (int index), {
  4526. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4527. const files = Module.sokol_dropped_files;
  4528. if ((index < 0) || (index >= files.length)) {
  4529. return 0;
  4530. }
  4531. else {
  4532. return files[index].size;
  4533. }
  4534. });
  4535. 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), {
  4536. const reader = new FileReader();
  4537. reader.onload = (loadEvent) => {
  4538. const content = loadEvent.target.result;
  4539. if (content.byteLength > buf_size) {
  4540. // SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL
  4541. __sapp_emsc_invoke_fetch_cb(index, 0, 1, callback, 0, buf_ptr, buf_size, user_data);
  4542. }
  4543. else {
  4544. HEAPU8.set(new Uint8Array(content), buf_ptr);
  4545. __sapp_emsc_invoke_fetch_cb(index, 1, 0, callback, content.byteLength, buf_ptr, buf_size, user_data);
  4546. }
  4547. };
  4548. reader.onerror = () => {
  4549. // SAPP_HTML5_FETCH_ERROR_OTHER
  4550. __sapp_emsc_invoke_fetch_cb(index, 0, 2, callback, 0, buf_ptr, buf_size, user_data);
  4551. };
  4552. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4553. const files = Module.sokol_dropped_files;
  4554. reader.readAsArrayBuffer(files[index]);
  4555. });
  4556. EM_JS(void, sapp_js_remove_dragndrop_listeners, (void), {
  4557. \x2F\x2A\x2A @suppress {missingProperties} \x2A\x2F
  4558. const canvas = Module.sapp_emsc_target;
  4559. canvas.removeEventListener('dragenter', Module.sokol_dragenter);
  4560. canvas.removeEventListener('dragleave', Module.sokol_dragleave);
  4561. canvas.removeEventListener('dragover', Module.sokol_dragover);
  4562. canvas.removeEventListener('drop', Module.sokol_drop);
  4563. });
  4564. EM_JS(void, sapp_js_init, (const char* c_str_target_selector), {
  4565. const target_selector_str = UTF8ToString(c_str_target_selector);
  4566. if (Module['canvas'] !== undefined) {
  4567. if (typeof Module['canvas'] === 'object') {
  4568. specialHTMLTargets[target_selector_str] = Module['canvas'];
  4569. } else {
  4570. console.warn("sokol_app.h: Module['canvas'] is set but is not an object");
  4571. }
  4572. }
  4573. Module.sapp_emsc_target = findCanvasEventTarget(target_selector_str);
  4574. if (!Module.sapp_emsc_target) {
  4575. console.warn("sokol_app.h: can't find html5_canvas_selector ", target_selector_str);
  4576. }
  4577. if (!Module.sapp_emsc_target.requestPointerLock) {
  4578. console.warn("sokol_app.h: target doesn't support requestPointerLock: ", target_selector_str);
  4579. }
  4580. });
  4581. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_pointerlockchange_cb(int emsc_type, const EmscriptenPointerlockChangeEvent* emsc_event, void* user_data) {
  4582. _SOKOL_UNUSED(emsc_type);
  4583. _SOKOL_UNUSED(user_data);
  4584. _sapp.mouse.locked = emsc_event->isActive;
  4585. return EM_TRUE;
  4586. }
  4587. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_pointerlockerror_cb(int emsc_type, const void* reserved, void* user_data) {
  4588. _SOKOL_UNUSED(emsc_type);
  4589. _SOKOL_UNUSED(reserved);
  4590. _SOKOL_UNUSED(user_data);
  4591. _sapp.mouse.locked = false;
  4592. _sapp.emsc.mouse_lock_requested = false;
  4593. return true;
  4594. }
  4595. EM_JS(void, sapp_js_request_pointerlock, (void), {
  4596. if (Module.sapp_emsc_target) {
  4597. if (Module.sapp_emsc_target.requestPointerLock) {
  4598. Module.sapp_emsc_target.requestPointerLock();
  4599. }
  4600. }
  4601. });
  4602. EM_JS(void, sapp_js_exit_pointerlock, (void), {
  4603. if (document.exitPointerLock) {
  4604. document.exitPointerLock();
  4605. }
  4606. });
  4607. _SOKOL_PRIVATE void _sapp_emsc_lock_mouse(bool lock) {
  4608. if (lock) {
  4609. /* request mouse-lock during event handler invocation (see _sapp_emsc_update_mouse_lock_state) */
  4610. _sapp.emsc.mouse_lock_requested = true;
  4611. }
  4612. else {
  4613. /* NOTE: the _sapp.mouse_locked state will be set in the pointerlockchange callback */
  4614. _sapp.emsc.mouse_lock_requested = false;
  4615. sapp_js_exit_pointerlock();
  4616. }
  4617. }
  4618. /* called from inside event handlers to check if mouse lock had been requested,
  4619. and if yes, actually enter mouse lock.
  4620. */
  4621. _SOKOL_PRIVATE void _sapp_emsc_update_mouse_lock_state(void) {
  4622. if (_sapp.emsc.mouse_lock_requested) {
  4623. _sapp.emsc.mouse_lock_requested = false;
  4624. sapp_js_request_pointerlock();
  4625. }
  4626. }
  4627. // set mouse cursor type
  4628. EM_JS(void, sapp_js_set_cursor, (int cursor_type, int shown), {
  4629. if (Module.sapp_emsc_target) {
  4630. let cursor;
  4631. if (shown === 0) {
  4632. cursor = "none";
  4633. }
  4634. else switch (cursor_type) {
  4635. case 0: cursor = "auto"; break; // SAPP_MOUSECURSOR_DEFAULT
  4636. case 1: cursor = "default"; break; // SAPP_MOUSECURSOR_ARROW
  4637. case 2: cursor = "text"; break; // SAPP_MOUSECURSOR_IBEAM
  4638. case 3: cursor = "crosshair"; break; // SAPP_MOUSECURSOR_CROSSHAIR
  4639. case 4: cursor = "pointer"; break; // SAPP_MOUSECURSOR_POINTING_HAND
  4640. case 5: cursor = "ew-resize"; break; // SAPP_MOUSECURSOR_RESIZE_EW
  4641. case 6: cursor = "ns-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NS
  4642. case 7: cursor = "nwse-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NWSE
  4643. case 8: cursor = "nesw-resize"; break; // SAPP_MOUSECURSOR_RESIZE_NESW
  4644. case 9: cursor = "all-scroll"; break; // SAPP_MOUSECURSOR_RESIZE_ALL
  4645. case 10: cursor = "not-allowed"; break; // SAPP_MOUSECURSOR_NOT_ALLOWED
  4646. default: cursor = "auto"; break;
  4647. }
  4648. Module.sapp_emsc_target.style.cursor = cursor;
  4649. }
  4650. });
  4651. _SOKOL_PRIVATE void _sapp_emsc_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  4652. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  4653. sapp_js_set_cursor((int)cursor, shown ? 1 : 0);
  4654. }
  4655. /* JS helper functions to update browser tab favicon */
  4656. EM_JS(void, sapp_js_clear_favicon, (void), {
  4657. const link = document.getElementById('sokol-app-favicon');
  4658. if (link) {
  4659. document.head.removeChild(link);
  4660. }
  4661. });
  4662. EM_JS(void, sapp_js_set_favicon, (int w, int h, const uint8_t* pixels), {
  4663. const canvas = document.createElement('canvas');
  4664. canvas.width = w;
  4665. canvas.height = h;
  4666. const ctx = canvas.getContext('2d');
  4667. const img_data = ctx.createImageData(w, h);
  4668. img_data.data.set(HEAPU8.subarray(pixels, pixels + w*h*4));
  4669. ctx.putImageData(img_data, 0, 0);
  4670. const new_link = document.createElement('link');
  4671. new_link.id = 'sokol-app-favicon';
  4672. new_link.rel = 'shortcut icon';
  4673. new_link.href = canvas.toDataURL();
  4674. document.head.appendChild(new_link);
  4675. });
  4676. _SOKOL_PRIVATE void _sapp_emsc_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  4677. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  4678. sapp_js_clear_favicon();
  4679. // find the best matching image candidate for 16x16 pixels
  4680. int img_index = _sapp_image_bestmatch(icon_desc->images, num_images, 16, 16);
  4681. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  4682. sapp_js_set_favicon(img_desc->width, img_desc->height, (const uint8_t*) img_desc->pixels.ptr);
  4683. }
  4684. _SOKOL_PRIVATE uint32_t _sapp_emsc_mouse_button_mods(uint16_t buttons) {
  4685. uint32_t m = 0;
  4686. if (0 != (buttons & (1<<0))) { m |= SAPP_MODIFIER_LMB; }
  4687. if (0 != (buttons & (1<<1))) { m |= SAPP_MODIFIER_RMB; } // not a bug
  4688. if (0 != (buttons & (1<<2))) { m |= SAPP_MODIFIER_MMB; } // not a bug
  4689. return m;
  4690. }
  4691. _SOKOL_PRIVATE uint32_t _sapp_emsc_mouse_event_mods(const EmscriptenMouseEvent* ev) {
  4692. uint32_t m = 0;
  4693. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  4694. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  4695. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  4696. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  4697. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  4698. return m;
  4699. }
  4700. _SOKOL_PRIVATE uint32_t _sapp_emsc_key_event_mods(const EmscriptenKeyboardEvent* ev) {
  4701. uint32_t m = 0;
  4702. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  4703. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  4704. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  4705. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  4706. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  4707. return m;
  4708. }
  4709. _SOKOL_PRIVATE uint32_t _sapp_emsc_touch_event_mods(const EmscriptenTouchEvent* ev) {
  4710. uint32_t m = 0;
  4711. if (ev->ctrlKey) { m |= SAPP_MODIFIER_CTRL; }
  4712. if (ev->shiftKey) { m |= SAPP_MODIFIER_SHIFT; }
  4713. if (ev->altKey) { m |= SAPP_MODIFIER_ALT; }
  4714. if (ev->metaKey) { m |= SAPP_MODIFIER_SUPER; }
  4715. m |= _sapp_emsc_mouse_button_mods(_sapp.emsc.mouse_buttons);
  4716. return m;
  4717. }
  4718. #if defined(SOKOL_WGPU)
  4719. _SOKOL_PRIVATE void _sapp_emsc_wgpu_size_changed(void);
  4720. #endif
  4721. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_size_changed(int event_type, const EmscriptenUiEvent* ui_event, void* user_data) {
  4722. _SOKOL_UNUSED(event_type);
  4723. _SOKOL_UNUSED(user_data);
  4724. double w, h;
  4725. emscripten_get_element_css_size(_sapp.html5_canvas_selector, &w, &h);
  4726. /* The above method might report zero when toggling HTML5 fullscreen,
  4727. in that case use the window's inner width reported by the
  4728. emscripten event. This works ok when toggling *into* fullscreen
  4729. but doesn't properly restore the previous canvas size when switching
  4730. back from fullscreen.
  4731. In general, due to the HTML5's fullscreen API's flaky nature it is
  4732. recommended to use 'soft fullscreen' (stretching the WebGL canvas
  4733. over the browser windows client rect) with a CSS definition like this:
  4734. position: absolute;
  4735. top: 0px;
  4736. left: 0px;
  4737. margin: 0px;
  4738. border: 0;
  4739. width: 100%;
  4740. height: 100%;
  4741. overflow: hidden;
  4742. display: block;
  4743. */
  4744. if (w < 1.0) {
  4745. w = ui_event->windowInnerWidth;
  4746. }
  4747. else {
  4748. _sapp.window_width = (int)roundf(w);
  4749. }
  4750. if (h < 1.0) {
  4751. h = ui_event->windowInnerHeight;
  4752. }
  4753. else {
  4754. _sapp.window_height = (int)roundf(h);
  4755. }
  4756. if (_sapp.desc.high_dpi) {
  4757. _sapp.dpi_scale = emscripten_get_device_pixel_ratio();
  4758. }
  4759. _sapp.framebuffer_width = (int)roundf(w * _sapp.dpi_scale);
  4760. _sapp.framebuffer_height = (int)roundf(h * _sapp.dpi_scale);
  4761. SOKOL_ASSERT((_sapp.framebuffer_width > 0) && (_sapp.framebuffer_height > 0));
  4762. emscripten_set_canvas_element_size(_sapp.html5_canvas_selector, _sapp.framebuffer_width, _sapp.framebuffer_height);
  4763. #if defined(SOKOL_WGPU)
  4764. // on WebGPU: recreate size-dependent rendering surfaces
  4765. _sapp_emsc_wgpu_size_changed();
  4766. #endif
  4767. if (_sapp_events_enabled()) {
  4768. _sapp_init_event(SAPP_EVENTTYPE_RESIZED);
  4769. _sapp_call_event(&_sapp.event);
  4770. }
  4771. return true;
  4772. }
  4773. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_mouse_cb(int emsc_type, const EmscriptenMouseEvent* emsc_event, void* user_data) {
  4774. _SOKOL_UNUSED(user_data);
  4775. bool consume_event = !_sapp.desc.html5_bubble_mouse_events;
  4776. _sapp.emsc.mouse_buttons = emsc_event->buttons;
  4777. if (_sapp.mouse.locked) {
  4778. _sapp.mouse.dx = (float) emsc_event->movementX;
  4779. _sapp.mouse.dy = (float) emsc_event->movementY;
  4780. } else {
  4781. float new_x = emsc_event->targetX * _sapp.dpi_scale;
  4782. float new_y = emsc_event->targetY * _sapp.dpi_scale;
  4783. if (_sapp.mouse.pos_valid) {
  4784. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  4785. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  4786. }
  4787. _sapp.mouse.x = new_x;
  4788. _sapp.mouse.y = new_y;
  4789. _sapp.mouse.pos_valid = true;
  4790. }
  4791. if (_sapp_events_enabled() && (emsc_event->button >= 0) && (emsc_event->button < SAPP_MAX_MOUSEBUTTONS)) {
  4792. sapp_event_type type;
  4793. bool is_button_event = false;
  4794. bool clear_dxdy = false;
  4795. switch (emsc_type) {
  4796. case EMSCRIPTEN_EVENT_MOUSEDOWN:
  4797. type = SAPP_EVENTTYPE_MOUSE_DOWN;
  4798. is_button_event = true;
  4799. break;
  4800. case EMSCRIPTEN_EVENT_MOUSEUP:
  4801. type = SAPP_EVENTTYPE_MOUSE_UP;
  4802. is_button_event = true;
  4803. break;
  4804. case EMSCRIPTEN_EVENT_MOUSEMOVE:
  4805. type = SAPP_EVENTTYPE_MOUSE_MOVE;
  4806. break;
  4807. case EMSCRIPTEN_EVENT_MOUSEENTER:
  4808. type = SAPP_EVENTTYPE_MOUSE_ENTER;
  4809. clear_dxdy = true;
  4810. break;
  4811. case EMSCRIPTEN_EVENT_MOUSELEAVE:
  4812. type = SAPP_EVENTTYPE_MOUSE_LEAVE;
  4813. clear_dxdy = true;
  4814. break;
  4815. default:
  4816. type = SAPP_EVENTTYPE_INVALID;
  4817. break;
  4818. }
  4819. if (clear_dxdy) {
  4820. _sapp.mouse.dx = 0.0f;
  4821. _sapp.mouse.dy = 0.0f;
  4822. }
  4823. if (type != SAPP_EVENTTYPE_INVALID) {
  4824. _sapp_init_event(type);
  4825. _sapp.event.modifiers = _sapp_emsc_mouse_event_mods(emsc_event);
  4826. if (is_button_event) {
  4827. switch (emsc_event->button) {
  4828. case 0: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_LEFT; break;
  4829. case 1: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_MIDDLE; break;
  4830. case 2: _sapp.event.mouse_button = SAPP_MOUSEBUTTON_RIGHT; break;
  4831. default: _sapp.event.mouse_button = (sapp_mousebutton)emsc_event->button; break;
  4832. }
  4833. } else {
  4834. _sapp.event.mouse_button = SAPP_MOUSEBUTTON_INVALID;
  4835. }
  4836. consume_event |= _sapp_call_event(&_sapp.event);
  4837. }
  4838. // mouse lock can only be activated in mouse button events (not in move, enter or leave)
  4839. if (is_button_event) {
  4840. _sapp_emsc_update_mouse_lock_state();
  4841. }
  4842. }
  4843. return consume_event;
  4844. }
  4845. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_wheel_cb(int emsc_type, const EmscriptenWheelEvent* emsc_event, void* user_data) {
  4846. _SOKOL_UNUSED(emsc_type);
  4847. _SOKOL_UNUSED(user_data);
  4848. bool consume_event = !_sapp.desc.html5_bubble_wheel_events;
  4849. _sapp.emsc.mouse_buttons = emsc_event->mouse.buttons;
  4850. if (_sapp_events_enabled()) {
  4851. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  4852. _sapp.event.modifiers = _sapp_emsc_mouse_event_mods(&emsc_event->mouse);
  4853. /* see https://github.com/floooh/sokol/issues/339 */
  4854. float scale;
  4855. switch (emsc_event->deltaMode) {
  4856. case DOM_DELTA_PIXEL: scale = -0.04f; break;
  4857. case DOM_DELTA_LINE: scale = -1.33f; break;
  4858. case DOM_DELTA_PAGE: scale = -10.0f; break; // FIXME: this is a guess
  4859. default: scale = -0.1f; break; // shouldn't happen
  4860. }
  4861. _sapp.event.scroll_x = scale * (float)emsc_event->deltaX;
  4862. _sapp.event.scroll_y = scale * (float)emsc_event->deltaY;
  4863. consume_event |= _sapp_call_event(&_sapp.event);
  4864. }
  4865. _sapp_emsc_update_mouse_lock_state();
  4866. return consume_event;
  4867. }
  4868. static struct {
  4869. const char* str;
  4870. sapp_keycode code;
  4871. } _sapp_emsc_keymap[] = {
  4872. { "Backspace", SAPP_KEYCODE_BACKSPACE },
  4873. { "Tab", SAPP_KEYCODE_TAB },
  4874. { "Enter", SAPP_KEYCODE_ENTER },
  4875. { "ShiftLeft", SAPP_KEYCODE_LEFT_SHIFT },
  4876. { "ShiftRight", SAPP_KEYCODE_RIGHT_SHIFT },
  4877. { "ControlLeft", SAPP_KEYCODE_LEFT_CONTROL },
  4878. { "ControlRight", SAPP_KEYCODE_RIGHT_CONTROL },
  4879. { "AltLeft", SAPP_KEYCODE_LEFT_ALT },
  4880. { "AltRight", SAPP_KEYCODE_RIGHT_ALT },
  4881. { "Pause", SAPP_KEYCODE_PAUSE },
  4882. { "CapsLock", SAPP_KEYCODE_CAPS_LOCK },
  4883. { "Escape", SAPP_KEYCODE_ESCAPE },
  4884. { "Space", SAPP_KEYCODE_SPACE },
  4885. { "PageUp", SAPP_KEYCODE_PAGE_UP },
  4886. { "PageDown", SAPP_KEYCODE_PAGE_DOWN },
  4887. { "End", SAPP_KEYCODE_END },
  4888. { "Home", SAPP_KEYCODE_HOME },
  4889. { "ArrowLeft", SAPP_KEYCODE_LEFT },
  4890. { "ArrowUp", SAPP_KEYCODE_UP },
  4891. { "ArrowRight", SAPP_KEYCODE_RIGHT },
  4892. { "ArrowDown", SAPP_KEYCODE_DOWN },
  4893. { "PrintScreen", SAPP_KEYCODE_PRINT_SCREEN },
  4894. { "Insert", SAPP_KEYCODE_INSERT },
  4895. { "Delete", SAPP_KEYCODE_DELETE },
  4896. { "Digit0", SAPP_KEYCODE_0 },
  4897. { "Digit1", SAPP_KEYCODE_1 },
  4898. { "Digit2", SAPP_KEYCODE_2 },
  4899. { "Digit3", SAPP_KEYCODE_3 },
  4900. { "Digit4", SAPP_KEYCODE_4 },
  4901. { "Digit5", SAPP_KEYCODE_5 },
  4902. { "Digit6", SAPP_KEYCODE_6 },
  4903. { "Digit7", SAPP_KEYCODE_7 },
  4904. { "Digit8", SAPP_KEYCODE_8 },
  4905. { "Digit9", SAPP_KEYCODE_9 },
  4906. { "KeyA", SAPP_KEYCODE_A },
  4907. { "KeyB", SAPP_KEYCODE_B },
  4908. { "KeyC", SAPP_KEYCODE_C },
  4909. { "KeyD", SAPP_KEYCODE_D },
  4910. { "KeyE", SAPP_KEYCODE_E },
  4911. { "KeyF", SAPP_KEYCODE_F },
  4912. { "KeyG", SAPP_KEYCODE_G },
  4913. { "KeyH", SAPP_KEYCODE_H },
  4914. { "KeyI", SAPP_KEYCODE_I },
  4915. { "KeyJ", SAPP_KEYCODE_J },
  4916. { "KeyK", SAPP_KEYCODE_K },
  4917. { "KeyL", SAPP_KEYCODE_L },
  4918. { "KeyM", SAPP_KEYCODE_M },
  4919. { "KeyN", SAPP_KEYCODE_N },
  4920. { "KeyO", SAPP_KEYCODE_O },
  4921. { "KeyP", SAPP_KEYCODE_P },
  4922. { "KeyQ", SAPP_KEYCODE_Q },
  4923. { "KeyR", SAPP_KEYCODE_R },
  4924. { "KeyS", SAPP_KEYCODE_S },
  4925. { "KeyT", SAPP_KEYCODE_T },
  4926. { "KeyU", SAPP_KEYCODE_U },
  4927. { "KeyV", SAPP_KEYCODE_V },
  4928. { "KeyW", SAPP_KEYCODE_W },
  4929. { "KeyX", SAPP_KEYCODE_X },
  4930. { "KeyY", SAPP_KEYCODE_Y },
  4931. { "KeyZ", SAPP_KEYCODE_Z },
  4932. { "MetaLeft", SAPP_KEYCODE_LEFT_SUPER },
  4933. { "MetaRight", SAPP_KEYCODE_RIGHT_SUPER },
  4934. { "Numpad0", SAPP_KEYCODE_KP_0 },
  4935. { "Numpad1", SAPP_KEYCODE_KP_1 },
  4936. { "Numpad2", SAPP_KEYCODE_KP_2 },
  4937. { "Numpad3", SAPP_KEYCODE_KP_3 },
  4938. { "Numpad4", SAPP_KEYCODE_KP_4 },
  4939. { "Numpad5", SAPP_KEYCODE_KP_5 },
  4940. { "Numpad6", SAPP_KEYCODE_KP_6 },
  4941. { "Numpad7", SAPP_KEYCODE_KP_7 },
  4942. { "Numpad8", SAPP_KEYCODE_KP_8 },
  4943. { "Numpad9", SAPP_KEYCODE_KP_9 },
  4944. { "NumpadMultiply", SAPP_KEYCODE_KP_MULTIPLY },
  4945. { "NumpadAdd", SAPP_KEYCODE_KP_ADD },
  4946. { "NumpadSubtract", SAPP_KEYCODE_KP_SUBTRACT },
  4947. { "NumpadDecimal", SAPP_KEYCODE_KP_DECIMAL },
  4948. { "NumpadDivide", SAPP_KEYCODE_KP_DIVIDE },
  4949. { "F1", SAPP_KEYCODE_F1 },
  4950. { "F2", SAPP_KEYCODE_F2 },
  4951. { "F3", SAPP_KEYCODE_F3 },
  4952. { "F4", SAPP_KEYCODE_F4 },
  4953. { "F5", SAPP_KEYCODE_F5 },
  4954. { "F6", SAPP_KEYCODE_F6 },
  4955. { "F7", SAPP_KEYCODE_F7 },
  4956. { "F8", SAPP_KEYCODE_F8 },
  4957. { "F9", SAPP_KEYCODE_F9 },
  4958. { "F10", SAPP_KEYCODE_F10 },
  4959. { "F11", SAPP_KEYCODE_F11 },
  4960. { "F12", SAPP_KEYCODE_F12 },
  4961. { "NumLock", SAPP_KEYCODE_NUM_LOCK },
  4962. { "ScrollLock", SAPP_KEYCODE_SCROLL_LOCK },
  4963. { "Semicolon", SAPP_KEYCODE_SEMICOLON },
  4964. { "Equal", SAPP_KEYCODE_EQUAL },
  4965. { "Comma", SAPP_KEYCODE_COMMA },
  4966. { "Minus", SAPP_KEYCODE_MINUS },
  4967. { "Period", SAPP_KEYCODE_PERIOD },
  4968. { "Slash", SAPP_KEYCODE_SLASH },
  4969. { "Backquote", SAPP_KEYCODE_GRAVE_ACCENT },
  4970. { "BracketLeft", SAPP_KEYCODE_LEFT_BRACKET },
  4971. { "Backslash", SAPP_KEYCODE_BACKSLASH },
  4972. { "BracketRight", SAPP_KEYCODE_RIGHT_BRACKET },
  4973. { "Quote", SAPP_KEYCODE_GRAVE_ACCENT }, // FIXME: ???
  4974. { 0, SAPP_KEYCODE_INVALID },
  4975. };
  4976. _SOKOL_PRIVATE sapp_keycode _sapp_emsc_translate_key(const char* str) {
  4977. int i = 0;
  4978. const char* keystr;
  4979. while (( keystr = _sapp_emsc_keymap[i].str )) {
  4980. if (0 == strcmp(str, keystr)) {
  4981. return _sapp_emsc_keymap[i].code;
  4982. }
  4983. i += 1;
  4984. }
  4985. return SAPP_KEYCODE_INVALID;
  4986. }
  4987. // returns true if the key code is a 'character key', this is used to decide
  4988. // if a key event needs to bubble up to create a char event
  4989. _SOKOL_PRIVATE bool _sapp_emsc_is_char_key(sapp_keycode key_code) {
  4990. return key_code < SAPP_KEYCODE_WORLD_1;
  4991. }
  4992. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_key_cb(int emsc_type, const EmscriptenKeyboardEvent* emsc_event, void* user_data) {
  4993. _SOKOL_UNUSED(user_data);
  4994. bool consume_event = false;
  4995. if (_sapp_events_enabled()) {
  4996. sapp_event_type type;
  4997. switch (emsc_type) {
  4998. case EMSCRIPTEN_EVENT_KEYDOWN:
  4999. type = SAPP_EVENTTYPE_KEY_DOWN;
  5000. break;
  5001. case EMSCRIPTEN_EVENT_KEYUP:
  5002. type = SAPP_EVENTTYPE_KEY_UP;
  5003. break;
  5004. case EMSCRIPTEN_EVENT_KEYPRESS:
  5005. type = SAPP_EVENTTYPE_CHAR;
  5006. break;
  5007. default:
  5008. type = SAPP_EVENTTYPE_INVALID;
  5009. break;
  5010. }
  5011. if (type != SAPP_EVENTTYPE_INVALID) {
  5012. bool send_keyup_followup = false;
  5013. _sapp_init_event(type);
  5014. _sapp.event.key_repeat = emsc_event->repeat;
  5015. _sapp.event.modifiers = _sapp_emsc_key_event_mods(emsc_event);
  5016. if (type == SAPP_EVENTTYPE_CHAR) {
  5017. // NOTE: charCode doesn't appear to be supported on Android Chrome
  5018. _sapp.event.char_code = emsc_event->charCode;
  5019. consume_event |= !_sapp.desc.html5_bubble_char_events;
  5020. } else {
  5021. if (0 != emsc_event->code[0]) {
  5022. // This code path is for desktop browsers which send untranslated 'physical' key code strings
  5023. // (which is what we actually want for key events)
  5024. _sapp.event.key_code = _sapp_emsc_translate_key(emsc_event->code);
  5025. } else {
  5026. // This code path is for mobile browsers which only send localized key code
  5027. // strings. Note that the translation will only work for a small subset
  5028. // of localization-agnostic keys (like Enter, arrow keys, etc...), but
  5029. // regular alpha-numeric keys will all result in an SAPP_KEYCODE_INVALID)
  5030. _sapp.event.key_code = _sapp_emsc_translate_key(emsc_event->key);
  5031. }
  5032. // Special hack for macOS: if the Super key is pressed, macOS doesn't
  5033. // send keyUp events. As a workaround, to prevent keys from
  5034. // "sticking", we'll send a keyup event following a keydown
  5035. // when the SUPER key is pressed
  5036. if ((type == SAPP_EVENTTYPE_KEY_DOWN) &&
  5037. (_sapp.event.key_code != SAPP_KEYCODE_LEFT_SUPER) &&
  5038. (_sapp.event.key_code != SAPP_KEYCODE_RIGHT_SUPER) &&
  5039. (_sapp.event.modifiers & SAPP_MODIFIER_SUPER))
  5040. {
  5041. send_keyup_followup = true;
  5042. }
  5043. // 'character key events' will always need to bubble up, otherwise the browser
  5044. // wouldn't be able to generate character events.
  5045. if (!_sapp_emsc_is_char_key(_sapp.event.key_code)) {
  5046. consume_event |= !_sapp.desc.html5_bubble_key_events;
  5047. }
  5048. }
  5049. consume_event |= _sapp_call_event(&_sapp.event);
  5050. if (send_keyup_followup) {
  5051. _sapp.event.type = SAPP_EVENTTYPE_KEY_UP;
  5052. consume_event |= _sapp_call_event(&_sapp.event);
  5053. }
  5054. }
  5055. }
  5056. _sapp_emsc_update_mouse_lock_state();
  5057. return consume_event;
  5058. }
  5059. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_touch_cb(int emsc_type, const EmscriptenTouchEvent* emsc_event, void* user_data) {
  5060. _SOKOL_UNUSED(user_data);
  5061. bool consume_event = !_sapp.desc.html5_bubble_touch_events;
  5062. if (_sapp_events_enabled()) {
  5063. sapp_event_type type;
  5064. switch (emsc_type) {
  5065. case EMSCRIPTEN_EVENT_TOUCHSTART:
  5066. type = SAPP_EVENTTYPE_TOUCHES_BEGAN;
  5067. break;
  5068. case EMSCRIPTEN_EVENT_TOUCHMOVE:
  5069. type = SAPP_EVENTTYPE_TOUCHES_MOVED;
  5070. break;
  5071. case EMSCRIPTEN_EVENT_TOUCHEND:
  5072. type = SAPP_EVENTTYPE_TOUCHES_ENDED;
  5073. break;
  5074. case EMSCRIPTEN_EVENT_TOUCHCANCEL:
  5075. type = SAPP_EVENTTYPE_TOUCHES_CANCELLED;
  5076. break;
  5077. default:
  5078. type = SAPP_EVENTTYPE_INVALID;
  5079. break;
  5080. }
  5081. if (type != SAPP_EVENTTYPE_INVALID) {
  5082. _sapp_init_event(type);
  5083. _sapp.event.modifiers = _sapp_emsc_touch_event_mods(emsc_event);
  5084. _sapp.event.num_touches = emsc_event->numTouches;
  5085. if (_sapp.event.num_touches > SAPP_MAX_TOUCHPOINTS) {
  5086. _sapp.event.num_touches = SAPP_MAX_TOUCHPOINTS;
  5087. }
  5088. for (int i = 0; i < _sapp.event.num_touches; i++) {
  5089. const EmscriptenTouchPoint* src = &emsc_event->touches[i];
  5090. sapp_touchpoint* dst = &_sapp.event.touches[i];
  5091. dst->identifier = (uintptr_t)src->identifier;
  5092. dst->pos_x = src->targetX * _sapp.dpi_scale;
  5093. dst->pos_y = src->targetY * _sapp.dpi_scale;
  5094. dst->changed = src->isChanged;
  5095. }
  5096. consume_event |= _sapp_call_event(&_sapp.event);
  5097. }
  5098. }
  5099. return consume_event;
  5100. }
  5101. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_focus_cb(int emsc_type, const EmscriptenFocusEvent* emsc_event, void* user_data) {
  5102. _SOKOL_UNUSED(emsc_type);
  5103. _SOKOL_UNUSED(emsc_event);
  5104. _SOKOL_UNUSED(user_data);
  5105. if (_sapp_events_enabled()) {
  5106. _sapp_init_event(SAPP_EVENTTYPE_FOCUSED);
  5107. _sapp_call_event(&_sapp.event);
  5108. }
  5109. return true;
  5110. }
  5111. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_blur_cb(int emsc_type, const EmscriptenFocusEvent* emsc_event, void* user_data) {
  5112. _SOKOL_UNUSED(emsc_type);
  5113. _SOKOL_UNUSED(emsc_event);
  5114. _SOKOL_UNUSED(user_data);
  5115. if (_sapp_events_enabled()) {
  5116. _sapp_init_event(SAPP_EVENTTYPE_UNFOCUSED);
  5117. _sapp_call_event(&_sapp.event);
  5118. }
  5119. return true;
  5120. }
  5121. #if defined(SOKOL_GLES3)
  5122. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_webgl_context_cb(int emsc_type, const void* reserved, void* user_data) {
  5123. _SOKOL_UNUSED(reserved);
  5124. _SOKOL_UNUSED(user_data);
  5125. sapp_event_type type;
  5126. switch (emsc_type) {
  5127. case EMSCRIPTEN_EVENT_WEBGLCONTEXTLOST: type = SAPP_EVENTTYPE_SUSPENDED; break;
  5128. case EMSCRIPTEN_EVENT_WEBGLCONTEXTRESTORED: type = SAPP_EVENTTYPE_RESUMED; break;
  5129. default: type = SAPP_EVENTTYPE_INVALID; break;
  5130. }
  5131. if (_sapp_events_enabled() && (SAPP_EVENTTYPE_INVALID != type)) {
  5132. _sapp_init_event(type);
  5133. _sapp_call_event(&_sapp.event);
  5134. }
  5135. return true;
  5136. }
  5137. _SOKOL_PRIVATE void _sapp_emsc_webgl_init(void) {
  5138. EmscriptenWebGLContextAttributes attrs;
  5139. emscripten_webgl_init_context_attributes(&attrs);
  5140. attrs.alpha = _sapp.desc.alpha;
  5141. attrs.depth = true;
  5142. attrs.stencil = true;
  5143. attrs.antialias = _sapp.sample_count > 1;
  5144. attrs.premultipliedAlpha = _sapp.desc.html5_premultiplied_alpha;
  5145. attrs.preserveDrawingBuffer = _sapp.desc.html5_preserve_drawing_buffer;
  5146. attrs.enableExtensionsByDefault = true;
  5147. attrs.majorVersion = 2;
  5148. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(_sapp.html5_canvas_selector, &attrs);
  5149. // FIXME: error message?
  5150. emscripten_webgl_make_context_current(ctx);
  5151. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  5152. // FIXME: remove PVRTC support here and in sokol-gfx at some point
  5153. // some WebGL extension are not enabled automatically by emscripten
  5154. emscripten_webgl_enable_extension(ctx, "WEBKIT_WEBGL_compressed_texture_pvrtc");
  5155. }
  5156. #endif
  5157. #if defined(SOKOL_WGPU)
  5158. _SOKOL_PRIVATE void _sapp_emsc_wgpu_create_swapchain(void) {
  5159. SOKOL_ASSERT(_sapp.wgpu.instance);
  5160. SOKOL_ASSERT(_sapp.wgpu.device);
  5161. SOKOL_ASSERT(0 == _sapp.wgpu.surface);
  5162. SOKOL_ASSERT(0 == _sapp.wgpu.swapchain);
  5163. SOKOL_ASSERT(0 == _sapp.wgpu.msaa_tex);
  5164. SOKOL_ASSERT(0 == _sapp.wgpu.msaa_view);
  5165. SOKOL_ASSERT(0 == _sapp.wgpu.depth_stencil_tex);
  5166. SOKOL_ASSERT(0 == _sapp.wgpu.depth_stencil_view);
  5167. SOKOL_ASSERT(0 == _sapp.wgpu.swapchain_view);
  5168. WGPUSurfaceDescriptorFromCanvasHTMLSelector canvas_desc;
  5169. _sapp_clear(&canvas_desc, sizeof(canvas_desc));
  5170. canvas_desc.chain.sType = WGPUSType_SurfaceDescriptorFromCanvasHTMLSelector;
  5171. canvas_desc.selector = _sapp.html5_canvas_selector;
  5172. WGPUSurfaceDescriptor surf_desc;
  5173. _sapp_clear(&surf_desc, sizeof(surf_desc));
  5174. surf_desc.nextInChain = &canvas_desc.chain;
  5175. _sapp.wgpu.surface = wgpuInstanceCreateSurface(_sapp.wgpu.instance, &surf_desc);
  5176. if (0 == _sapp.wgpu.surface) {
  5177. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_SURFACE_FAILED);
  5178. }
  5179. _sapp.wgpu.render_format = wgpuSurfaceGetPreferredFormat(_sapp.wgpu.surface, _sapp.wgpu.adapter);
  5180. WGPUSwapChainDescriptor sc_desc;
  5181. _sapp_clear(&sc_desc, sizeof(sc_desc));
  5182. sc_desc.usage = WGPUTextureUsage_RenderAttachment;
  5183. sc_desc.format = _sapp.wgpu.render_format;
  5184. sc_desc.width = (uint32_t)_sapp.framebuffer_width;
  5185. sc_desc.height = (uint32_t)_sapp.framebuffer_height;
  5186. sc_desc.presentMode = WGPUPresentMode_Fifo;
  5187. _sapp.wgpu.swapchain = wgpuDeviceCreateSwapChain(_sapp.wgpu.device, _sapp.wgpu.surface, &sc_desc);
  5188. if (0 == _sapp.wgpu.swapchain) {
  5189. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_SWAPCHAIN_FAILED);
  5190. }
  5191. WGPUTextureDescriptor ds_desc;
  5192. _sapp_clear(&ds_desc, sizeof(ds_desc));
  5193. ds_desc.usage = WGPUTextureUsage_RenderAttachment;
  5194. ds_desc.dimension = WGPUTextureDimension_2D;
  5195. ds_desc.size.width = (uint32_t)_sapp.framebuffer_width;
  5196. ds_desc.size.height = (uint32_t)_sapp.framebuffer_height;
  5197. ds_desc.size.depthOrArrayLayers = 1;
  5198. ds_desc.format = WGPUTextureFormat_Depth32FloatStencil8;
  5199. ds_desc.mipLevelCount = 1;
  5200. ds_desc.sampleCount = (uint32_t)_sapp.sample_count;
  5201. _sapp.wgpu.depth_stencil_tex = wgpuDeviceCreateTexture(_sapp.wgpu.device, &ds_desc);
  5202. if (0 == _sapp.wgpu.depth_stencil_tex) {
  5203. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_TEXTURE_FAILED);
  5204. }
  5205. _sapp.wgpu.depth_stencil_view = wgpuTextureCreateView(_sapp.wgpu.depth_stencil_tex, 0);
  5206. if (0 == _sapp.wgpu.depth_stencil_view) {
  5207. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_DEPTH_STENCIL_VIEW_FAILED);
  5208. }
  5209. if (_sapp.sample_count > 1) {
  5210. WGPUTextureDescriptor msaa_desc;
  5211. _sapp_clear(&msaa_desc, sizeof(msaa_desc));
  5212. msaa_desc.usage = WGPUTextureUsage_RenderAttachment;
  5213. msaa_desc.dimension = WGPUTextureDimension_2D;
  5214. msaa_desc.size.width = (uint32_t)_sapp.framebuffer_width;
  5215. msaa_desc.size.height = (uint32_t)_sapp.framebuffer_height;
  5216. msaa_desc.size.depthOrArrayLayers = 1;
  5217. msaa_desc.format = _sapp.wgpu.render_format;
  5218. msaa_desc.mipLevelCount = 1;
  5219. msaa_desc.sampleCount = (uint32_t)_sapp.sample_count;
  5220. _sapp.wgpu.msaa_tex = wgpuDeviceCreateTexture(_sapp.wgpu.device, &msaa_desc);
  5221. if (0 == _sapp.wgpu.msaa_tex) {
  5222. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_MSAA_TEXTURE_FAILED);
  5223. }
  5224. _sapp.wgpu.msaa_view = wgpuTextureCreateView(_sapp.wgpu.msaa_tex, 0);
  5225. if (0 == _sapp.wgpu.msaa_view) {
  5226. _SAPP_PANIC(WGPU_SWAPCHAIN_CREATE_MSAA_VIEW_FAILED);
  5227. }
  5228. }
  5229. }
  5230. _SOKOL_PRIVATE void _sapp_emsc_wgpu_discard_swapchain(void) {
  5231. if (_sapp.wgpu.msaa_view) {
  5232. wgpuTextureViewRelease(_sapp.wgpu.msaa_view);
  5233. _sapp.wgpu.msaa_view = 0;
  5234. }
  5235. if (_sapp.wgpu.msaa_tex) {
  5236. wgpuTextureRelease(_sapp.wgpu.msaa_tex);
  5237. _sapp.wgpu.msaa_tex = 0;
  5238. }
  5239. if (_sapp.wgpu.depth_stencil_view) {
  5240. wgpuTextureViewRelease(_sapp.wgpu.depth_stencil_view);
  5241. _sapp.wgpu.depth_stencil_view = 0;
  5242. }
  5243. if (_sapp.wgpu.depth_stencil_tex) {
  5244. wgpuTextureRelease(_sapp.wgpu.depth_stencil_tex);
  5245. _sapp.wgpu.depth_stencil_tex = 0;
  5246. }
  5247. if (_sapp.wgpu.swapchain) {
  5248. wgpuSwapChainRelease(_sapp.wgpu.swapchain);
  5249. _sapp.wgpu.swapchain = 0;
  5250. }
  5251. if (_sapp.wgpu.surface) {
  5252. wgpuSurfaceRelease(_sapp.wgpu.surface);
  5253. _sapp.wgpu.surface = 0;
  5254. }
  5255. }
  5256. _SOKOL_PRIVATE void _sapp_emsc_wgpu_size_changed(void) {
  5257. _sapp_emsc_wgpu_discard_swapchain();
  5258. _sapp_emsc_wgpu_create_swapchain();
  5259. }
  5260. _SOKOL_PRIVATE void _sapp_emsc_wgpu_request_device_cb(WGPURequestDeviceStatus status, WGPUDevice device, const char* msg, void* userdata) {
  5261. _SOKOL_UNUSED(msg);
  5262. _SOKOL_UNUSED(userdata);
  5263. SOKOL_ASSERT(!_sapp.wgpu.async_init_done);
  5264. if (status != WGPURequestDeviceStatus_Success) {
  5265. if (status == WGPURequestDeviceStatus_Error) {
  5266. _SAPP_PANIC(WGPU_REQUEST_DEVICE_STATUS_ERROR);
  5267. } else {
  5268. _SAPP_PANIC(WGPU_REQUEST_DEVICE_STATUS_UNKNOWN);
  5269. }
  5270. }
  5271. SOKOL_ASSERT(device);
  5272. _sapp.wgpu.device = device;
  5273. _sapp_emsc_wgpu_create_swapchain();
  5274. _sapp.wgpu.async_init_done = true;
  5275. }
  5276. _SOKOL_PRIVATE void _sapp_emsc_wgpu_request_adapter_cb(WGPURequestAdapterStatus status, WGPUAdapter adapter, const char* msg, void* userdata) {
  5277. _SOKOL_UNUSED(msg);
  5278. _SOKOL_UNUSED(userdata);
  5279. if (status != WGPURequestAdapterStatus_Success) {
  5280. switch (status) {
  5281. case WGPURequestAdapterStatus_Unavailable: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_UNAVAILABLE); break;
  5282. case WGPURequestAdapterStatus_Error: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_ERROR); break;
  5283. default: _SAPP_PANIC(WGPU_REQUEST_ADAPTER_STATUS_UNKNOWN); break;
  5284. }
  5285. }
  5286. SOKOL_ASSERT(adapter);
  5287. _sapp.wgpu.adapter = adapter;
  5288. size_t cur_feature_index = 1;
  5289. #define _SAPP_WGPU_MAX_REQUESTED_FEATURES (8)
  5290. WGPUFeatureName requiredFeatures[_SAPP_WGPU_MAX_REQUESTED_FEATURES] = {
  5291. WGPUFeatureName_Depth32FloatStencil8,
  5292. };
  5293. // check for optional features we're interested in
  5294. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionBC)) {
  5295. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5296. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionBC;
  5297. }
  5298. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionETC2)) {
  5299. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5300. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionETC2;
  5301. }
  5302. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_TextureCompressionASTC)) {
  5303. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5304. requiredFeatures[cur_feature_index++] = WGPUFeatureName_TextureCompressionASTC;
  5305. }
  5306. if (wgpuAdapterHasFeature(adapter, WGPUFeatureName_Float32Filterable)) {
  5307. SOKOL_ASSERT(cur_feature_index < _SAPP_WGPU_MAX_REQUESTED_FEATURES);
  5308. requiredFeatures[cur_feature_index++] = WGPUFeatureName_Float32Filterable;
  5309. }
  5310. #undef _SAPP_WGPU_MAX_REQUESTED_FEATURES
  5311. WGPUDeviceDescriptor dev_desc;
  5312. _sapp_clear(&dev_desc, sizeof(dev_desc));
  5313. dev_desc.requiredFeatureCount = cur_feature_index;
  5314. dev_desc.requiredFeatures = requiredFeatures,
  5315. wgpuAdapterRequestDevice(adapter, &dev_desc, _sapp_emsc_wgpu_request_device_cb, 0);
  5316. }
  5317. _SOKOL_PRIVATE void _sapp_emsc_wgpu_init(void) {
  5318. SOKOL_ASSERT(0 == _sapp.wgpu.instance);
  5319. SOKOL_ASSERT(!_sapp.wgpu.async_init_done);
  5320. _sapp.wgpu.instance = wgpuCreateInstance(0);
  5321. if (0 == _sapp.wgpu.instance) {
  5322. _SAPP_PANIC(WGPU_CREATE_INSTANCE_FAILED);
  5323. }
  5324. // FIXME: power preference?
  5325. wgpuInstanceRequestAdapter(_sapp.wgpu.instance, 0, _sapp_emsc_wgpu_request_adapter_cb, 0);
  5326. }
  5327. _SOKOL_PRIVATE void _sapp_emsc_wgpu_frame(void) {
  5328. if (_sapp.wgpu.async_init_done) {
  5329. _sapp.wgpu.swapchain_view = wgpuSwapChainGetCurrentTextureView(_sapp.wgpu.swapchain);
  5330. _sapp_frame();
  5331. wgpuTextureViewRelease(_sapp.wgpu.swapchain_view);
  5332. _sapp.wgpu.swapchain_view = 0;
  5333. }
  5334. }
  5335. #endif // SOKOL_WGPU
  5336. _SOKOL_PRIVATE void _sapp_emsc_register_eventhandlers(void) {
  5337. // NOTE: HTML canvas doesn't receive input focus, this is why key event handlers are added
  5338. // to the window object (this could be worked around by adding a "tab index" to the
  5339. // canvas)
  5340. emscripten_set_mousedown_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5341. emscripten_set_mouseup_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5342. emscripten_set_mousemove_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5343. emscripten_set_mouseenter_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5344. emscripten_set_mouseleave_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_mouse_cb);
  5345. emscripten_set_wheel_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_wheel_cb);
  5346. emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5347. emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5348. emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_key_cb);
  5349. emscripten_set_touchstart_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5350. emscripten_set_touchmove_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5351. emscripten_set_touchend_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5352. emscripten_set_touchcancel_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_touch_cb);
  5353. emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, _sapp_emsc_pointerlockchange_cb);
  5354. emscripten_set_pointerlockerror_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, _sapp_emsc_pointerlockerror_cb);
  5355. emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_focus_cb);
  5356. emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, _sapp_emsc_blur_cb);
  5357. sapp_js_add_beforeunload_listener();
  5358. if (_sapp.clipboard.enabled) {
  5359. sapp_js_add_clipboard_listener();
  5360. }
  5361. if (_sapp.drop.enabled) {
  5362. sapp_js_add_dragndrop_listeners();
  5363. }
  5364. #if defined(SOKOL_GLES3)
  5365. emscripten_set_webglcontextlost_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_webgl_context_cb);
  5366. emscripten_set_webglcontextrestored_callback(_sapp.html5_canvas_selector, 0, true, _sapp_emsc_webgl_context_cb);
  5367. #endif
  5368. }
  5369. _SOKOL_PRIVATE void _sapp_emsc_unregister_eventhandlers(void) {
  5370. emscripten_set_mousedown_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5371. emscripten_set_mouseup_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5372. emscripten_set_mousemove_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5373. emscripten_set_mouseenter_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5374. emscripten_set_mouseleave_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5375. emscripten_set_wheel_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5376. emscripten_set_keydown_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5377. emscripten_set_keyup_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5378. emscripten_set_keypress_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5379. emscripten_set_touchstart_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5380. emscripten_set_touchmove_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5381. emscripten_set_touchend_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5382. emscripten_set_touchcancel_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5383. emscripten_set_pointerlockchange_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, 0);
  5384. emscripten_set_pointerlockerror_callback(EMSCRIPTEN_EVENT_TARGET_DOCUMENT, 0, true, 0);
  5385. emscripten_set_focus_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5386. emscripten_set_blur_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5387. if (!_sapp.desc.html5_canvas_resize) {
  5388. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, true, 0);
  5389. }
  5390. sapp_js_remove_beforeunload_listener();
  5391. if (_sapp.clipboard.enabled) {
  5392. sapp_js_remove_clipboard_listener();
  5393. }
  5394. if (_sapp.drop.enabled) {
  5395. sapp_js_remove_dragndrop_listeners();
  5396. }
  5397. #if defined(SOKOL_GLES3)
  5398. emscripten_set_webglcontextlost_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5399. emscripten_set_webglcontextrestored_callback(_sapp.html5_canvas_selector, 0, true, 0);
  5400. #endif
  5401. }
  5402. _SOKOL_PRIVATE EM_BOOL _sapp_emsc_frame_animation_loop(double time, void* userData) {
  5403. _SOKOL_UNUSED(userData);
  5404. _sapp_timing_external(&_sapp.timing, time / 1000.0);
  5405. #if defined(SOKOL_WGPU)
  5406. _sapp_emsc_wgpu_frame();
  5407. #else
  5408. _sapp_frame();
  5409. #endif
  5410. // quit-handling
  5411. if (_sapp.quit_requested) {
  5412. _sapp_init_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  5413. _sapp_call_event(&_sapp.event);
  5414. if (_sapp.quit_requested) {
  5415. _sapp.quit_ordered = true;
  5416. }
  5417. }
  5418. if (_sapp.quit_ordered) {
  5419. _sapp_emsc_unregister_eventhandlers();
  5420. _sapp_call_cleanup();
  5421. _sapp_discard_state();
  5422. return EM_FALSE;
  5423. }
  5424. return EM_TRUE;
  5425. }
  5426. _SOKOL_PRIVATE void _sapp_emsc_frame_main_loop(void) {
  5427. const double time = emscripten_performance_now();
  5428. if (!_sapp_emsc_frame_animation_loop(time, 0)) {
  5429. emscripten_cancel_main_loop();
  5430. }
  5431. }
  5432. _SOKOL_PRIVATE void _sapp_emsc_run(const sapp_desc* desc) {
  5433. _sapp_init_state(desc);
  5434. sapp_js_init(_sapp.html5_canvas_selector);
  5435. double w, h;
  5436. if (_sapp.desc.html5_canvas_resize) {
  5437. w = (double) _sapp_def(_sapp.desc.width, _SAPP_FALLBACK_DEFAULT_WINDOW_WIDTH);
  5438. h = (double) _sapp_def(_sapp.desc.height, _SAPP_FALLBACK_DEFAULT_WINDOW_HEIGHT);
  5439. }
  5440. else {
  5441. emscripten_get_element_css_size(_sapp.html5_canvas_selector, &w, &h);
  5442. emscripten_set_resize_callback(EMSCRIPTEN_EVENT_TARGET_WINDOW, 0, false, _sapp_emsc_size_changed);
  5443. }
  5444. if (_sapp.desc.high_dpi) {
  5445. _sapp.dpi_scale = emscripten_get_device_pixel_ratio();
  5446. }
  5447. _sapp.window_width = (int)roundf(w);
  5448. _sapp.window_height = (int)roundf(h);
  5449. _sapp.framebuffer_width = (int)roundf(w * _sapp.dpi_scale);
  5450. _sapp.framebuffer_height = (int)roundf(h * _sapp.dpi_scale);
  5451. emscripten_set_canvas_element_size(_sapp.html5_canvas_selector, _sapp.framebuffer_width, _sapp.framebuffer_height);
  5452. #if defined(SOKOL_GLES3)
  5453. _sapp_emsc_webgl_init();
  5454. #elif defined(SOKOL_WGPU)
  5455. _sapp_emsc_wgpu_init();
  5456. #endif
  5457. _sapp.valid = true;
  5458. _sapp_emsc_register_eventhandlers();
  5459. sapp_set_icon(&desc->icon);
  5460. // start the frame loop
  5461. if (_sapp.desc.html5_use_emsc_set_main_loop) {
  5462. emscripten_set_main_loop(_sapp_emsc_frame_main_loop, 0, _sapp.desc.html5_emsc_set_main_loop_simulate_infinite_loop);
  5463. } else {
  5464. emscripten_request_animation_frame_loop(_sapp_emsc_frame_animation_loop, 0);
  5465. }
  5466. // NOT A BUG: do not call _sapp_discard_state() here, instead this is
  5467. // called in _sapp_emsc_frame() when the application is ordered to quit
  5468. }
  5469. #if !defined(SOKOL_NO_ENTRY)
  5470. int main(int argc, char* argv[]) {
  5471. sapp_desc desc = sokol_main(argc, argv);
  5472. _sapp_emsc_run(&desc);
  5473. return 0;
  5474. }
  5475. #endif /* SOKOL_NO_ENTRY */
  5476. #endif /* _SAPP_EMSCRIPTEN */
  5477. // ██████ ██ ██ ██ ███████ ██ ██████ ███████ ██████ ███████
  5478. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5479. // ██ ███ ██ ███████ █████ ██ ██████ █████ ██████ ███████
  5480. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  5481. // ██████ ███████ ██ ██ ███████ ███████ ██ ███████ ██ ██ ███████
  5482. //
  5483. // >>gl helpers
  5484. #if defined(SOKOL_GLCORE)
  5485. typedef struct {
  5486. int red_bits;
  5487. int green_bits;
  5488. int blue_bits;
  5489. int alpha_bits;
  5490. int depth_bits;
  5491. int stencil_bits;
  5492. int samples;
  5493. bool doublebuffer;
  5494. uintptr_t handle;
  5495. } _sapp_gl_fbconfig;
  5496. _SOKOL_PRIVATE void _sapp_gl_init_fbconfig(_sapp_gl_fbconfig* fbconfig) {
  5497. _sapp_clear(fbconfig, sizeof(_sapp_gl_fbconfig));
  5498. /* -1 means "don't care" */
  5499. fbconfig->red_bits = -1;
  5500. fbconfig->green_bits = -1;
  5501. fbconfig->blue_bits = -1;
  5502. fbconfig->alpha_bits = -1;
  5503. fbconfig->depth_bits = -1;
  5504. fbconfig->stencil_bits = -1;
  5505. fbconfig->samples = -1;
  5506. }
  5507. typedef struct {
  5508. int least_missing;
  5509. int least_color_diff;
  5510. int least_extra_diff;
  5511. bool best_match;
  5512. } _sapp_gl_fbselect;
  5513. _SOKOL_PRIVATE void _sapp_gl_init_fbselect(_sapp_gl_fbselect* fbselect) {
  5514. _sapp_clear(fbselect, sizeof(_sapp_gl_fbselect));
  5515. fbselect->least_missing = 1000000;
  5516. fbselect->least_color_diff = 10000000;
  5517. fbselect->least_extra_diff = 10000000;
  5518. fbselect->best_match = false;
  5519. }
  5520. // NOTE: this is used only in the WGL code path
  5521. _SOKOL_PRIVATE bool _sapp_gl_select_fbconfig(_sapp_gl_fbselect* fbselect, const _sapp_gl_fbconfig* desired, const _sapp_gl_fbconfig* current) {
  5522. int missing = 0;
  5523. if (desired->doublebuffer != current->doublebuffer) {
  5524. return false;
  5525. }
  5526. if ((desired->alpha_bits > 0) && (current->alpha_bits == 0)) {
  5527. missing++;
  5528. }
  5529. if ((desired->depth_bits > 0) && (current->depth_bits == 0)) {
  5530. missing++;
  5531. }
  5532. if ((desired->stencil_bits > 0) && (current->stencil_bits == 0)) {
  5533. missing++;
  5534. }
  5535. if ((desired->samples > 0) && (current->samples == 0)) {
  5536. /* Technically, several multisampling buffers could be
  5537. involved, but that's a lower level implementation detail and
  5538. not important to us here, so we count them as one
  5539. */
  5540. missing++;
  5541. }
  5542. /* These polynomials make many small channel size differences matter
  5543. less than one large channel size difference
  5544. Calculate color channel size difference value
  5545. */
  5546. int color_diff = 0;
  5547. if (desired->red_bits != -1) {
  5548. color_diff += (desired->red_bits - current->red_bits) * (desired->red_bits - current->red_bits);
  5549. }
  5550. if (desired->green_bits != -1) {
  5551. color_diff += (desired->green_bits - current->green_bits) * (desired->green_bits - current->green_bits);
  5552. }
  5553. if (desired->blue_bits != -1) {
  5554. color_diff += (desired->blue_bits - current->blue_bits) * (desired->blue_bits - current->blue_bits);
  5555. }
  5556. /* Calculate non-color channel size difference value */
  5557. int extra_diff = 0;
  5558. if (desired->alpha_bits != -1) {
  5559. extra_diff += (desired->alpha_bits - current->alpha_bits) * (desired->alpha_bits - current->alpha_bits);
  5560. }
  5561. if (desired->depth_bits != -1) {
  5562. extra_diff += (desired->depth_bits - current->depth_bits) * (desired->depth_bits - current->depth_bits);
  5563. }
  5564. if (desired->stencil_bits != -1) {
  5565. extra_diff += (desired->stencil_bits - current->stencil_bits) * (desired->stencil_bits - current->stencil_bits);
  5566. }
  5567. if (desired->samples != -1) {
  5568. extra_diff += (desired->samples - current->samples) * (desired->samples - current->samples);
  5569. }
  5570. /* Figure out if the current one is better than the best one found so far
  5571. Least number of missing buffers is the most important heuristic,
  5572. then color buffer size match and lastly size match for other buffers
  5573. */
  5574. bool new_closest = false;
  5575. if (missing < fbselect->least_missing) {
  5576. new_closest = true;
  5577. } else if (missing == fbselect->least_missing) {
  5578. if ((color_diff < fbselect->least_color_diff) ||
  5579. ((color_diff == fbselect->least_color_diff) && (extra_diff < fbselect->least_extra_diff)))
  5580. {
  5581. new_closest = true;
  5582. }
  5583. }
  5584. if (new_closest) {
  5585. fbselect->least_missing = missing;
  5586. fbselect->least_color_diff = color_diff;
  5587. fbselect->least_extra_diff = extra_diff;
  5588. fbselect->best_match = (missing | color_diff | extra_diff) == 0;
  5589. }
  5590. return new_closest;
  5591. }
  5592. // NOTE: this is used only in the GLX code path
  5593. _SOKOL_PRIVATE const _sapp_gl_fbconfig* _sapp_gl_choose_fbconfig(const _sapp_gl_fbconfig* desired, const _sapp_gl_fbconfig* alternatives, int count) {
  5594. int missing, least_missing = 1000000;
  5595. int color_diff, least_color_diff = 10000000;
  5596. int extra_diff, least_extra_diff = 10000000;
  5597. const _sapp_gl_fbconfig* current;
  5598. const _sapp_gl_fbconfig* closest = 0;
  5599. for (int i = 0; i < count; i++) {
  5600. current = alternatives + i;
  5601. if (desired->doublebuffer != current->doublebuffer) {
  5602. continue;
  5603. }
  5604. missing = 0;
  5605. if (desired->alpha_bits > 0 && current->alpha_bits == 0) {
  5606. missing++;
  5607. }
  5608. if (desired->depth_bits > 0 && current->depth_bits == 0) {
  5609. missing++;
  5610. }
  5611. if (desired->stencil_bits > 0 && current->stencil_bits == 0) {
  5612. missing++;
  5613. }
  5614. if (desired->samples > 0 && current->samples == 0) {
  5615. /* Technically, several multisampling buffers could be
  5616. involved, but that's a lower level implementation detail and
  5617. not important to us here, so we count them as one
  5618. */
  5619. missing++;
  5620. }
  5621. /* These polynomials make many small channel size differences matter
  5622. less than one large channel size difference
  5623. Calculate color channel size difference value
  5624. */
  5625. color_diff = 0;
  5626. if (desired->red_bits != -1) {
  5627. color_diff += (desired->red_bits - current->red_bits) * (desired->red_bits - current->red_bits);
  5628. }
  5629. if (desired->green_bits != -1) {
  5630. color_diff += (desired->green_bits - current->green_bits) * (desired->green_bits - current->green_bits);
  5631. }
  5632. if (desired->blue_bits != -1) {
  5633. color_diff += (desired->blue_bits - current->blue_bits) * (desired->blue_bits - current->blue_bits);
  5634. }
  5635. /* Calculate non-color channel size difference value */
  5636. extra_diff = 0;
  5637. if (desired->alpha_bits != -1) {
  5638. extra_diff += (desired->alpha_bits - current->alpha_bits) * (desired->alpha_bits - current->alpha_bits);
  5639. }
  5640. if (desired->depth_bits != -1) {
  5641. extra_diff += (desired->depth_bits - current->depth_bits) * (desired->depth_bits - current->depth_bits);
  5642. }
  5643. if (desired->stencil_bits != -1) {
  5644. extra_diff += (desired->stencil_bits - current->stencil_bits) * (desired->stencil_bits - current->stencil_bits);
  5645. }
  5646. if (desired->samples != -1) {
  5647. extra_diff += (desired->samples - current->samples) * (desired->samples - current->samples);
  5648. }
  5649. /* Figure out if the current one is better than the best one found so far
  5650. Least number of missing buffers is the most important heuristic,
  5651. then color buffer size match and lastly size match for other buffers
  5652. */
  5653. if (missing < least_missing) {
  5654. closest = current;
  5655. }
  5656. else if (missing == least_missing) {
  5657. if ((color_diff < least_color_diff) ||
  5658. (color_diff == least_color_diff && extra_diff < least_extra_diff))
  5659. {
  5660. closest = current;
  5661. }
  5662. }
  5663. if (current == closest) {
  5664. least_missing = missing;
  5665. least_color_diff = color_diff;
  5666. least_extra_diff = extra_diff;
  5667. }
  5668. }
  5669. return closest;
  5670. }
  5671. #endif
  5672. // ██ ██ ██ ███ ██ ██████ ██████ ██ ██ ███████
  5673. // ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██
  5674. // ██ █ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █ ██ ███████
  5675. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██ ██
  5676. // ███ ███ ██ ██ ████ ██████ ██████ ███ ███ ███████
  5677. //
  5678. // >>windows
  5679. #if defined(_SAPP_WIN32)
  5680. _SOKOL_PRIVATE bool _sapp_win32_utf8_to_wide(const char* src, wchar_t* dst, int dst_num_bytes) {
  5681. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  5682. _sapp_clear(dst, (size_t)dst_num_bytes);
  5683. const int dst_chars = dst_num_bytes / (int)sizeof(wchar_t);
  5684. const int dst_needed = MultiByteToWideChar(CP_UTF8, 0, src, -1, 0, 0);
  5685. if ((dst_needed > 0) && (dst_needed < dst_chars)) {
  5686. MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, dst_chars);
  5687. return true;
  5688. }
  5689. else {
  5690. /* input string doesn't fit into destination buffer */
  5691. return false;
  5692. }
  5693. }
  5694. _SOKOL_PRIVATE void _sapp_win32_app_event(sapp_event_type type) {
  5695. if (_sapp_events_enabled()) {
  5696. _sapp_init_event(type);
  5697. _sapp_call_event(&_sapp.event);
  5698. }
  5699. }
  5700. _SOKOL_PRIVATE void _sapp_win32_init_keytable(void) {
  5701. /* same as GLFW */
  5702. _sapp.keycodes[0x00B] = SAPP_KEYCODE_0;
  5703. _sapp.keycodes[0x002] = SAPP_KEYCODE_1;
  5704. _sapp.keycodes[0x003] = SAPP_KEYCODE_2;
  5705. _sapp.keycodes[0x004] = SAPP_KEYCODE_3;
  5706. _sapp.keycodes[0x005] = SAPP_KEYCODE_4;
  5707. _sapp.keycodes[0x006] = SAPP_KEYCODE_5;
  5708. _sapp.keycodes[0x007] = SAPP_KEYCODE_6;
  5709. _sapp.keycodes[0x008] = SAPP_KEYCODE_7;
  5710. _sapp.keycodes[0x009] = SAPP_KEYCODE_8;
  5711. _sapp.keycodes[0x00A] = SAPP_KEYCODE_9;
  5712. _sapp.keycodes[0x01E] = SAPP_KEYCODE_A;
  5713. _sapp.keycodes[0x030] = SAPP_KEYCODE_B;
  5714. _sapp.keycodes[0x02E] = SAPP_KEYCODE_C;
  5715. _sapp.keycodes[0x020] = SAPP_KEYCODE_D;
  5716. _sapp.keycodes[0x012] = SAPP_KEYCODE_E;
  5717. _sapp.keycodes[0x021] = SAPP_KEYCODE_F;
  5718. _sapp.keycodes[0x022] = SAPP_KEYCODE_G;
  5719. _sapp.keycodes[0x023] = SAPP_KEYCODE_H;
  5720. _sapp.keycodes[0x017] = SAPP_KEYCODE_I;
  5721. _sapp.keycodes[0x024] = SAPP_KEYCODE_J;
  5722. _sapp.keycodes[0x025] = SAPP_KEYCODE_K;
  5723. _sapp.keycodes[0x026] = SAPP_KEYCODE_L;
  5724. _sapp.keycodes[0x032] = SAPP_KEYCODE_M;
  5725. _sapp.keycodes[0x031] = SAPP_KEYCODE_N;
  5726. _sapp.keycodes[0x018] = SAPP_KEYCODE_O;
  5727. _sapp.keycodes[0x019] = SAPP_KEYCODE_P;
  5728. _sapp.keycodes[0x010] = SAPP_KEYCODE_Q;
  5729. _sapp.keycodes[0x013] = SAPP_KEYCODE_R;
  5730. _sapp.keycodes[0x01F] = SAPP_KEYCODE_S;
  5731. _sapp.keycodes[0x014] = SAPP_KEYCODE_T;
  5732. _sapp.keycodes[0x016] = SAPP_KEYCODE_U;
  5733. _sapp.keycodes[0x02F] = SAPP_KEYCODE_V;
  5734. _sapp.keycodes[0x011] = SAPP_KEYCODE_W;
  5735. _sapp.keycodes[0x02D] = SAPP_KEYCODE_X;
  5736. _sapp.keycodes[0x015] = SAPP_KEYCODE_Y;
  5737. _sapp.keycodes[0x02C] = SAPP_KEYCODE_Z;
  5738. _sapp.keycodes[0x028] = SAPP_KEYCODE_APOSTROPHE;
  5739. _sapp.keycodes[0x02B] = SAPP_KEYCODE_BACKSLASH;
  5740. _sapp.keycodes[0x033] = SAPP_KEYCODE_COMMA;
  5741. _sapp.keycodes[0x00D] = SAPP_KEYCODE_EQUAL;
  5742. _sapp.keycodes[0x029] = SAPP_KEYCODE_GRAVE_ACCENT;
  5743. _sapp.keycodes[0x01A] = SAPP_KEYCODE_LEFT_BRACKET;
  5744. _sapp.keycodes[0x00C] = SAPP_KEYCODE_MINUS;
  5745. _sapp.keycodes[0x034] = SAPP_KEYCODE_PERIOD;
  5746. _sapp.keycodes[0x01B] = SAPP_KEYCODE_RIGHT_BRACKET;
  5747. _sapp.keycodes[0x027] = SAPP_KEYCODE_SEMICOLON;
  5748. _sapp.keycodes[0x035] = SAPP_KEYCODE_SLASH;
  5749. _sapp.keycodes[0x056] = SAPP_KEYCODE_WORLD_2;
  5750. _sapp.keycodes[0x00E] = SAPP_KEYCODE_BACKSPACE;
  5751. _sapp.keycodes[0x153] = SAPP_KEYCODE_DELETE;
  5752. _sapp.keycodes[0x14F] = SAPP_KEYCODE_END;
  5753. _sapp.keycodes[0x01C] = SAPP_KEYCODE_ENTER;
  5754. _sapp.keycodes[0x001] = SAPP_KEYCODE_ESCAPE;
  5755. _sapp.keycodes[0x147] = SAPP_KEYCODE_HOME;
  5756. _sapp.keycodes[0x152] = SAPP_KEYCODE_INSERT;
  5757. _sapp.keycodes[0x15D] = SAPP_KEYCODE_MENU;
  5758. _sapp.keycodes[0x151] = SAPP_KEYCODE_PAGE_DOWN;
  5759. _sapp.keycodes[0x149] = SAPP_KEYCODE_PAGE_UP;
  5760. _sapp.keycodes[0x045] = SAPP_KEYCODE_PAUSE;
  5761. _sapp.keycodes[0x146] = SAPP_KEYCODE_PAUSE;
  5762. _sapp.keycodes[0x039] = SAPP_KEYCODE_SPACE;
  5763. _sapp.keycodes[0x00F] = SAPP_KEYCODE_TAB;
  5764. _sapp.keycodes[0x03A] = SAPP_KEYCODE_CAPS_LOCK;
  5765. _sapp.keycodes[0x145] = SAPP_KEYCODE_NUM_LOCK;
  5766. _sapp.keycodes[0x046] = SAPP_KEYCODE_SCROLL_LOCK;
  5767. _sapp.keycodes[0x03B] = SAPP_KEYCODE_F1;
  5768. _sapp.keycodes[0x03C] = SAPP_KEYCODE_F2;
  5769. _sapp.keycodes[0x03D] = SAPP_KEYCODE_F3;
  5770. _sapp.keycodes[0x03E] = SAPP_KEYCODE_F4;
  5771. _sapp.keycodes[0x03F] = SAPP_KEYCODE_F5;
  5772. _sapp.keycodes[0x040] = SAPP_KEYCODE_F6;
  5773. _sapp.keycodes[0x041] = SAPP_KEYCODE_F7;
  5774. _sapp.keycodes[0x042] = SAPP_KEYCODE_F8;
  5775. _sapp.keycodes[0x043] = SAPP_KEYCODE_F9;
  5776. _sapp.keycodes[0x044] = SAPP_KEYCODE_F10;
  5777. _sapp.keycodes[0x057] = SAPP_KEYCODE_F11;
  5778. _sapp.keycodes[0x058] = SAPP_KEYCODE_F12;
  5779. _sapp.keycodes[0x064] = SAPP_KEYCODE_F13;
  5780. _sapp.keycodes[0x065] = SAPP_KEYCODE_F14;
  5781. _sapp.keycodes[0x066] = SAPP_KEYCODE_F15;
  5782. _sapp.keycodes[0x067] = SAPP_KEYCODE_F16;
  5783. _sapp.keycodes[0x068] = SAPP_KEYCODE_F17;
  5784. _sapp.keycodes[0x069] = SAPP_KEYCODE_F18;
  5785. _sapp.keycodes[0x06A] = SAPP_KEYCODE_F19;
  5786. _sapp.keycodes[0x06B] = SAPP_KEYCODE_F20;
  5787. _sapp.keycodes[0x06C] = SAPP_KEYCODE_F21;
  5788. _sapp.keycodes[0x06D] = SAPP_KEYCODE_F22;
  5789. _sapp.keycodes[0x06E] = SAPP_KEYCODE_F23;
  5790. _sapp.keycodes[0x076] = SAPP_KEYCODE_F24;
  5791. _sapp.keycodes[0x038] = SAPP_KEYCODE_LEFT_ALT;
  5792. _sapp.keycodes[0x01D] = SAPP_KEYCODE_LEFT_CONTROL;
  5793. _sapp.keycodes[0x02A] = SAPP_KEYCODE_LEFT_SHIFT;
  5794. _sapp.keycodes[0x15B] = SAPP_KEYCODE_LEFT_SUPER;
  5795. _sapp.keycodes[0x137] = SAPP_KEYCODE_PRINT_SCREEN;
  5796. _sapp.keycodes[0x138] = SAPP_KEYCODE_RIGHT_ALT;
  5797. _sapp.keycodes[0x11D] = SAPP_KEYCODE_RIGHT_CONTROL;
  5798. _sapp.keycodes[0x036] = SAPP_KEYCODE_RIGHT_SHIFT;
  5799. _sapp.keycodes[0x136] = SAPP_KEYCODE_RIGHT_SHIFT;
  5800. _sapp.keycodes[0x15C] = SAPP_KEYCODE_RIGHT_SUPER;
  5801. _sapp.keycodes[0x150] = SAPP_KEYCODE_DOWN;
  5802. _sapp.keycodes[0x14B] = SAPP_KEYCODE_LEFT;
  5803. _sapp.keycodes[0x14D] = SAPP_KEYCODE_RIGHT;
  5804. _sapp.keycodes[0x148] = SAPP_KEYCODE_UP;
  5805. _sapp.keycodes[0x052] = SAPP_KEYCODE_KP_0;
  5806. _sapp.keycodes[0x04F] = SAPP_KEYCODE_KP_1;
  5807. _sapp.keycodes[0x050] = SAPP_KEYCODE_KP_2;
  5808. _sapp.keycodes[0x051] = SAPP_KEYCODE_KP_3;
  5809. _sapp.keycodes[0x04B] = SAPP_KEYCODE_KP_4;
  5810. _sapp.keycodes[0x04C] = SAPP_KEYCODE_KP_5;
  5811. _sapp.keycodes[0x04D] = SAPP_KEYCODE_KP_6;
  5812. _sapp.keycodes[0x047] = SAPP_KEYCODE_KP_7;
  5813. _sapp.keycodes[0x048] = SAPP_KEYCODE_KP_8;
  5814. _sapp.keycodes[0x049] = SAPP_KEYCODE_KP_9;
  5815. _sapp.keycodes[0x04E] = SAPP_KEYCODE_KP_ADD;
  5816. _sapp.keycodes[0x053] = SAPP_KEYCODE_KP_DECIMAL;
  5817. _sapp.keycodes[0x135] = SAPP_KEYCODE_KP_DIVIDE;
  5818. _sapp.keycodes[0x11C] = SAPP_KEYCODE_KP_ENTER;
  5819. _sapp.keycodes[0x037] = SAPP_KEYCODE_KP_MULTIPLY;
  5820. _sapp.keycodes[0x04A] = SAPP_KEYCODE_KP_SUBTRACT;
  5821. }
  5822. #endif // _SAPP_WIN32
  5823. #if defined(_SAPP_WIN32)
  5824. #if defined(SOKOL_D3D11)
  5825. #if defined(__cplusplus)
  5826. #define _sapp_d3d11_Release(self) (self)->Release()
  5827. #define _sapp_win32_refiid(iid) iid
  5828. #else
  5829. #define _sapp_d3d11_Release(self) (self)->lpVtbl->Release(self)
  5830. #define _sapp_win32_refiid(iid) &iid
  5831. #endif
  5832. #define _SAPP_SAFE_RELEASE(obj) if (obj) { _sapp_d3d11_Release(obj); obj=0; }
  5833. static const IID _sapp_IID_ID3D11Texture2D = { 0x6f15aaf2,0xd208,0x4e89, {0x9a,0xb4,0x48,0x95,0x35,0xd3,0x4f,0x9c} };
  5834. static const IID _sapp_IID_IDXGIDevice1 = { 0x77db970f,0x6276,0x48ba, {0xba,0x28,0x07,0x01,0x43,0xb4,0x39,0x2c} };
  5835. static const IID _sapp_IID_IDXGIFactory = { 0x7b7166ec,0x21c7,0x44ae, {0xb2,0x1a,0xc9,0xae,0x32,0x1a,0xe3,0x69} };
  5836. static inline HRESULT _sapp_dxgi_GetBuffer(IDXGISwapChain* self, UINT Buffer, REFIID riid, void** ppSurface) {
  5837. #if defined(__cplusplus)
  5838. return self->GetBuffer(Buffer, riid, ppSurface);
  5839. #else
  5840. return self->lpVtbl->GetBuffer(self, Buffer, riid, ppSurface);
  5841. #endif
  5842. }
  5843. static inline HRESULT _sapp_d3d11_QueryInterface(ID3D11Device* self, REFIID riid, void** ppvObject) {
  5844. #if defined(__cplusplus)
  5845. return self->QueryInterface(riid, ppvObject);
  5846. #else
  5847. return self->lpVtbl->QueryInterface(self, riid, ppvObject);
  5848. #endif
  5849. }
  5850. static inline HRESULT _sapp_d3d11_CreateRenderTargetView(ID3D11Device* self, ID3D11Resource *pResource, const D3D11_RENDER_TARGET_VIEW_DESC* pDesc, ID3D11RenderTargetView** ppRTView) {
  5851. #if defined(__cplusplus)
  5852. return self->CreateRenderTargetView(pResource, pDesc, ppRTView);
  5853. #else
  5854. return self->lpVtbl->CreateRenderTargetView(self, pResource, pDesc, ppRTView);
  5855. #endif
  5856. }
  5857. static inline HRESULT _sapp_d3d11_CreateTexture2D(ID3D11Device* self, const D3D11_TEXTURE2D_DESC* pDesc, const D3D11_SUBRESOURCE_DATA* pInitialData, ID3D11Texture2D** ppTexture2D) {
  5858. #if defined(__cplusplus)
  5859. return self->CreateTexture2D(pDesc, pInitialData, ppTexture2D);
  5860. #else
  5861. return self->lpVtbl->CreateTexture2D(self, pDesc, pInitialData, ppTexture2D);
  5862. #endif
  5863. }
  5864. static inline HRESULT _sapp_d3d11_CreateDepthStencilView(ID3D11Device* self, ID3D11Resource* pResource, const D3D11_DEPTH_STENCIL_VIEW_DESC* pDesc, ID3D11DepthStencilView** ppDepthStencilView) {
  5865. #if defined(__cplusplus)
  5866. return self->CreateDepthStencilView(pResource, pDesc, ppDepthStencilView);
  5867. #else
  5868. return self->lpVtbl->CreateDepthStencilView(self, pResource, pDesc, ppDepthStencilView);
  5869. #endif
  5870. }
  5871. static inline HRESULT _sapp_dxgi_ResizeBuffers(IDXGISwapChain* self, UINT BufferCount, UINT Width, UINT Height, DXGI_FORMAT NewFormat, UINT SwapChainFlags) {
  5872. #if defined(__cplusplus)
  5873. return self->ResizeBuffers(BufferCount, Width, Height, NewFormat, SwapChainFlags);
  5874. #else
  5875. return self->lpVtbl->ResizeBuffers(self, BufferCount, Width, Height, NewFormat, SwapChainFlags);
  5876. #endif
  5877. }
  5878. static inline HRESULT _sapp_dxgi_Present(IDXGISwapChain* self, UINT SyncInterval, UINT Flags) {
  5879. #if defined(__cplusplus)
  5880. return self->Present(SyncInterval, Flags);
  5881. #else
  5882. return self->lpVtbl->Present(self, SyncInterval, Flags);
  5883. #endif
  5884. }
  5885. static inline HRESULT _sapp_dxgi_GetFrameStatistics(IDXGISwapChain* self, DXGI_FRAME_STATISTICS* pStats) {
  5886. #if defined(__cplusplus)
  5887. return self->GetFrameStatistics(pStats);
  5888. #else
  5889. return self->lpVtbl->GetFrameStatistics(self, pStats);
  5890. #endif
  5891. }
  5892. static inline HRESULT _sapp_dxgi_SetMaximumFrameLatency(IDXGIDevice1* self, UINT MaxLatency) {
  5893. #if defined(__cplusplus)
  5894. return self->SetMaximumFrameLatency(MaxLatency);
  5895. #else
  5896. return self->lpVtbl->SetMaximumFrameLatency(self, MaxLatency);
  5897. #endif
  5898. }
  5899. static inline HRESULT _sapp_dxgi_GetAdapter(IDXGIDevice1* self, IDXGIAdapter** pAdapter) {
  5900. #if defined(__cplusplus)
  5901. return self->GetAdapter(pAdapter);
  5902. #else
  5903. return self->lpVtbl->GetAdapter(self, pAdapter);
  5904. #endif
  5905. }
  5906. static inline HRESULT _sapp_dxgi_GetParent(IDXGIObject* self, REFIID riid, void** ppParent) {
  5907. #if defined(__cplusplus)
  5908. return self->GetParent(riid, ppParent);
  5909. #else
  5910. return self->lpVtbl->GetParent(self, riid, ppParent);
  5911. #endif
  5912. }
  5913. static inline HRESULT _sapp_dxgi_MakeWindowAssociation(IDXGIFactory* self, HWND WindowHandle, UINT Flags) {
  5914. #if defined(__cplusplus)
  5915. return self->MakeWindowAssociation(WindowHandle, Flags);
  5916. #else
  5917. return self->lpVtbl->MakeWindowAssociation(self, WindowHandle, Flags);
  5918. #endif
  5919. }
  5920. _SOKOL_PRIVATE void _sapp_d3d11_create_device_and_swapchain(void) {
  5921. DXGI_SWAP_CHAIN_DESC* sc_desc = &_sapp.d3d11.swap_chain_desc;
  5922. sc_desc->BufferDesc.Width = (UINT)_sapp.framebuffer_width;
  5923. sc_desc->BufferDesc.Height = (UINT)_sapp.framebuffer_height;
  5924. sc_desc->BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  5925. sc_desc->BufferDesc.RefreshRate.Numerator = 60;
  5926. sc_desc->BufferDesc.RefreshRate.Denominator = 1;
  5927. sc_desc->OutputWindow = _sapp.win32.hwnd;
  5928. sc_desc->Windowed = true;
  5929. if (_sapp.win32.is_win10_or_greater) {
  5930. sc_desc->BufferCount = 2;
  5931. sc_desc->SwapEffect = (DXGI_SWAP_EFFECT) _SAPP_DXGI_SWAP_EFFECT_FLIP_DISCARD;
  5932. _sapp.d3d11.use_dxgi_frame_stats = true;
  5933. }
  5934. else {
  5935. sc_desc->BufferCount = 1;
  5936. sc_desc->SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
  5937. _sapp.d3d11.use_dxgi_frame_stats = false;
  5938. }
  5939. sc_desc->SampleDesc.Count = 1;
  5940. sc_desc->SampleDesc.Quality = 0;
  5941. sc_desc->BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
  5942. UINT create_flags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT;
  5943. #if defined(SOKOL_DEBUG)
  5944. create_flags |= D3D11_CREATE_DEVICE_DEBUG;
  5945. #endif
  5946. D3D_FEATURE_LEVEL feature_level;
  5947. HRESULT hr = D3D11CreateDeviceAndSwapChain(
  5948. NULL, /* pAdapter (use default) */
  5949. D3D_DRIVER_TYPE_HARDWARE, /* DriverType */
  5950. NULL, /* Software */
  5951. create_flags, /* Flags */
  5952. NULL, /* pFeatureLevels */
  5953. 0, /* FeatureLevels */
  5954. D3D11_SDK_VERSION, /* SDKVersion */
  5955. sc_desc, /* pSwapChainDesc */
  5956. &_sapp.d3d11.swap_chain, /* ppSwapChain */
  5957. &_sapp.d3d11.device, /* ppDevice */
  5958. &feature_level, /* pFeatureLevel */
  5959. &_sapp.d3d11.device_context); /* ppImmediateContext */
  5960. _SOKOL_UNUSED(hr);
  5961. #if defined(SOKOL_DEBUG)
  5962. if (!SUCCEEDED(hr)) {
  5963. // if initialization with D3D11_CREATE_DEVICE_DEBUG fails, this could be because the
  5964. // 'D3D11 debug layer' stopped working, indicated by the error message:
  5965. // ===
  5966. // D3D11CreateDevice: Flags (0x2) were specified which require the D3D11 SDK Layers for Windows 10, but they are not present on the system.
  5967. // These flags must be removed, or the Windows 10 SDK must be installed.
  5968. // Flags include: D3D11_CREATE_DEVICE_DEBUG
  5969. // ===
  5970. //
  5971. // ...just retry with the DEBUG flag switched off
  5972. _SAPP_ERROR(WIN32_D3D11_CREATE_DEVICE_AND_SWAPCHAIN_WITH_DEBUG_FAILED);
  5973. create_flags &= ~D3D11_CREATE_DEVICE_DEBUG;
  5974. hr = D3D11CreateDeviceAndSwapChain(
  5975. NULL, /* pAdapter (use default) */
  5976. D3D_DRIVER_TYPE_HARDWARE, /* DriverType */
  5977. NULL, /* Software */
  5978. create_flags, /* Flags */
  5979. NULL, /* pFeatureLevels */
  5980. 0, /* FeatureLevels */
  5981. D3D11_SDK_VERSION, /* SDKVersion */
  5982. sc_desc, /* pSwapChainDesc */
  5983. &_sapp.d3d11.swap_chain, /* ppSwapChain */
  5984. &_sapp.d3d11.device, /* ppDevice */
  5985. &feature_level, /* pFeatureLevel */
  5986. &_sapp.d3d11.device_context); /* ppImmediateContext */
  5987. }
  5988. #endif
  5989. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.swap_chain && _sapp.d3d11.device && _sapp.d3d11.device_context);
  5990. // minimize frame latency, disable Alt-Enter
  5991. hr = _sapp_d3d11_QueryInterface(_sapp.d3d11.device, _sapp_win32_refiid(_sapp_IID_IDXGIDevice1), (void**)&_sapp.d3d11.dxgi_device);
  5992. if (SUCCEEDED(hr) && _sapp.d3d11.dxgi_device) {
  5993. _sapp_dxgi_SetMaximumFrameLatency(_sapp.d3d11.dxgi_device, 1);
  5994. IDXGIAdapter* dxgi_adapter = 0;
  5995. hr = _sapp_dxgi_GetAdapter(_sapp.d3d11.dxgi_device, &dxgi_adapter);
  5996. if (SUCCEEDED(hr) && dxgi_adapter) {
  5997. IDXGIFactory* dxgi_factory = 0;
  5998. hr = _sapp_dxgi_GetParent((IDXGIObject*)dxgi_adapter, _sapp_win32_refiid(_sapp_IID_IDXGIFactory), (void**)&dxgi_factory);
  5999. if (SUCCEEDED(hr)) {
  6000. _sapp_dxgi_MakeWindowAssociation(dxgi_factory, _sapp.win32.hwnd, DXGI_MWA_NO_ALT_ENTER|DXGI_MWA_NO_PRINT_SCREEN);
  6001. _SAPP_SAFE_RELEASE(dxgi_factory);
  6002. }
  6003. else {
  6004. _SAPP_ERROR(WIN32_D3D11_GET_IDXGIFACTORY_FAILED);
  6005. }
  6006. _SAPP_SAFE_RELEASE(dxgi_adapter);
  6007. }
  6008. else {
  6009. _SAPP_ERROR(WIN32_D3D11_GET_IDXGIADAPTER_FAILED);
  6010. }
  6011. }
  6012. else {
  6013. _SAPP_PANIC(WIN32_D3D11_QUERY_INTERFACE_IDXGIDEVICE1_FAILED);
  6014. }
  6015. }
  6016. _SOKOL_PRIVATE void _sapp_d3d11_destroy_device_and_swapchain(void) {
  6017. _SAPP_SAFE_RELEASE(_sapp.d3d11.swap_chain);
  6018. _SAPP_SAFE_RELEASE(_sapp.d3d11.dxgi_device);
  6019. _SAPP_SAFE_RELEASE(_sapp.d3d11.device_context);
  6020. _SAPP_SAFE_RELEASE(_sapp.d3d11.device);
  6021. }
  6022. _SOKOL_PRIVATE void _sapp_d3d11_create_default_render_target(void) {
  6023. SOKOL_ASSERT(0 == _sapp.d3d11.rt);
  6024. SOKOL_ASSERT(0 == _sapp.d3d11.rtv);
  6025. SOKOL_ASSERT(0 == _sapp.d3d11.msaa_rt);
  6026. SOKOL_ASSERT(0 == _sapp.d3d11.msaa_rtv);
  6027. SOKOL_ASSERT(0 == _sapp.d3d11.ds);
  6028. SOKOL_ASSERT(0 == _sapp.d3d11.dsv);
  6029. HRESULT hr;
  6030. /* view for the swapchain-created framebuffer */
  6031. hr = _sapp_dxgi_GetBuffer(_sapp.d3d11.swap_chain, 0, _sapp_win32_refiid(_sapp_IID_ID3D11Texture2D), (void**)&_sapp.d3d11.rt);
  6032. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.rt);
  6033. hr = _sapp_d3d11_CreateRenderTargetView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.rt, NULL, &_sapp.d3d11.rtv);
  6034. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.rtv);
  6035. /* common desc for MSAA and depth-stencil texture */
  6036. D3D11_TEXTURE2D_DESC tex_desc;
  6037. _sapp_clear(&tex_desc, sizeof(tex_desc));
  6038. tex_desc.Width = (UINT)_sapp.framebuffer_width;
  6039. tex_desc.Height = (UINT)_sapp.framebuffer_height;
  6040. tex_desc.MipLevels = 1;
  6041. tex_desc.ArraySize = 1;
  6042. tex_desc.Usage = D3D11_USAGE_DEFAULT;
  6043. tex_desc.BindFlags = D3D11_BIND_RENDER_TARGET;
  6044. tex_desc.SampleDesc.Count = (UINT) _sapp.sample_count;
  6045. tex_desc.SampleDesc.Quality = (UINT) (_sapp.sample_count > 1 ? D3D11_STANDARD_MULTISAMPLE_PATTERN : 0);
  6046. /* create MSAA texture and view if antialiasing requested */
  6047. if (_sapp.sample_count > 1) {
  6048. tex_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
  6049. hr = _sapp_d3d11_CreateTexture2D(_sapp.d3d11.device, &tex_desc, NULL, &_sapp.d3d11.msaa_rt);
  6050. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.msaa_rt);
  6051. hr = _sapp_d3d11_CreateRenderTargetView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.msaa_rt, NULL, &_sapp.d3d11.msaa_rtv);
  6052. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.msaa_rtv);
  6053. }
  6054. /* texture and view for the depth-stencil-surface */
  6055. tex_desc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
  6056. tex_desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
  6057. hr = _sapp_d3d11_CreateTexture2D(_sapp.d3d11.device, &tex_desc, NULL, &_sapp.d3d11.ds);
  6058. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.ds);
  6059. hr = _sapp_d3d11_CreateDepthStencilView(_sapp.d3d11.device, (ID3D11Resource*)_sapp.d3d11.ds, NULL, &_sapp.d3d11.dsv);
  6060. SOKOL_ASSERT(SUCCEEDED(hr) && _sapp.d3d11.dsv);
  6061. }
  6062. _SOKOL_PRIVATE void _sapp_d3d11_destroy_default_render_target(void) {
  6063. _SAPP_SAFE_RELEASE(_sapp.d3d11.rt);
  6064. _SAPP_SAFE_RELEASE(_sapp.d3d11.rtv);
  6065. _SAPP_SAFE_RELEASE(_sapp.d3d11.msaa_rt);
  6066. _SAPP_SAFE_RELEASE(_sapp.d3d11.msaa_rtv);
  6067. _SAPP_SAFE_RELEASE(_sapp.d3d11.ds);
  6068. _SAPP_SAFE_RELEASE(_sapp.d3d11.dsv);
  6069. }
  6070. _SOKOL_PRIVATE void _sapp_d3d11_resize_default_render_target(void) {
  6071. if (_sapp.d3d11.swap_chain) {
  6072. _sapp_d3d11_destroy_default_render_target();
  6073. _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);
  6074. _sapp_d3d11_create_default_render_target();
  6075. }
  6076. }
  6077. _SOKOL_PRIVATE void _sapp_d3d11_present(bool do_not_wait) {
  6078. UINT flags = 0;
  6079. if (_sapp.win32.is_win10_or_greater && do_not_wait) {
  6080. /* this hack/workaround somewhat improves window-movement and -sizing
  6081. responsiveness when rendering is controlled via WM_TIMER during window
  6082. move and resize on NVIDIA cards on Win10 with recent drivers.
  6083. */
  6084. flags = DXGI_PRESENT_DO_NOT_WAIT;
  6085. }
  6086. _sapp_dxgi_Present(_sapp.d3d11.swap_chain, (UINT)_sapp.swap_interval, flags);
  6087. }
  6088. #endif /* SOKOL_D3D11 */
  6089. #if defined(SOKOL_GLCORE)
  6090. _SOKOL_PRIVATE void _sapp_wgl_init(void) {
  6091. _sapp.wgl.opengl32 = LoadLibraryA("opengl32.dll");
  6092. if (!_sapp.wgl.opengl32) {
  6093. _SAPP_PANIC(WIN32_LOAD_OPENGL32_DLL_FAILED);
  6094. }
  6095. SOKOL_ASSERT(_sapp.wgl.opengl32);
  6096. _sapp.wgl.CreateContext = (PFN_wglCreateContext)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglCreateContext");
  6097. SOKOL_ASSERT(_sapp.wgl.CreateContext);
  6098. _sapp.wgl.DeleteContext = (PFN_wglDeleteContext)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglDeleteContext");
  6099. SOKOL_ASSERT(_sapp.wgl.DeleteContext);
  6100. _sapp.wgl.GetProcAddress = (PFN_wglGetProcAddress)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglGetProcAddress");
  6101. SOKOL_ASSERT(_sapp.wgl.GetProcAddress);
  6102. _sapp.wgl.GetCurrentDC = (PFN_wglGetCurrentDC)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglGetCurrentDC");
  6103. SOKOL_ASSERT(_sapp.wgl.GetCurrentDC);
  6104. _sapp.wgl.MakeCurrent = (PFN_wglMakeCurrent)(void*) GetProcAddress(_sapp.wgl.opengl32, "wglMakeCurrent");
  6105. SOKOL_ASSERT(_sapp.wgl.MakeCurrent);
  6106. _sapp.wgl.GetIntegerv = (void(WINAPI*)(uint32_t, int32_t*)) GetProcAddress(_sapp.wgl.opengl32, "glGetIntegerv");
  6107. SOKOL_ASSERT(_sapp.wgl.GetIntegerv);
  6108. _sapp.wgl.msg_hwnd = CreateWindowExW(WS_EX_OVERLAPPEDWINDOW,
  6109. L"SOKOLAPP",
  6110. L"sokol-app message window",
  6111. WS_CLIPSIBLINGS|WS_CLIPCHILDREN,
  6112. 0, 0, 1, 1,
  6113. NULL, NULL,
  6114. GetModuleHandleW(NULL),
  6115. NULL);
  6116. if (!_sapp.wgl.msg_hwnd) {
  6117. _SAPP_PANIC(WIN32_CREATE_HELPER_WINDOW_FAILED);
  6118. }
  6119. SOKOL_ASSERT(_sapp.wgl.msg_hwnd);
  6120. ShowWindow(_sapp.wgl.msg_hwnd, SW_HIDE);
  6121. MSG msg;
  6122. while (PeekMessageW(&msg, _sapp.wgl.msg_hwnd, 0, 0, PM_REMOVE)) {
  6123. TranslateMessage(&msg);
  6124. DispatchMessageW(&msg);
  6125. }
  6126. _sapp.wgl.msg_dc = GetDC(_sapp.wgl.msg_hwnd);
  6127. if (!_sapp.wgl.msg_dc) {
  6128. _SAPP_PANIC(WIN32_HELPER_WINDOW_GETDC_FAILED);
  6129. }
  6130. }
  6131. _SOKOL_PRIVATE void _sapp_wgl_shutdown(void) {
  6132. SOKOL_ASSERT(_sapp.wgl.opengl32 && _sapp.wgl.msg_hwnd);
  6133. DestroyWindow(_sapp.wgl.msg_hwnd); _sapp.wgl.msg_hwnd = 0;
  6134. FreeLibrary(_sapp.wgl.opengl32); _sapp.wgl.opengl32 = 0;
  6135. }
  6136. _SOKOL_PRIVATE bool _sapp_wgl_has_ext(const char* ext, const char* extensions) {
  6137. SOKOL_ASSERT(ext && extensions);
  6138. const char* start = extensions;
  6139. while (true) {
  6140. const char* where = strstr(start, ext);
  6141. if (!where) {
  6142. return false;
  6143. }
  6144. const char* terminator = where + strlen(ext);
  6145. if ((where == start) || (*(where - 1) == ' ')) {
  6146. if (*terminator == ' ' || *terminator == '\0') {
  6147. break;
  6148. }
  6149. }
  6150. start = terminator;
  6151. }
  6152. return true;
  6153. }
  6154. _SOKOL_PRIVATE bool _sapp_wgl_ext_supported(const char* ext) {
  6155. SOKOL_ASSERT(ext);
  6156. if (_sapp.wgl.GetExtensionsStringEXT) {
  6157. const char* extensions = _sapp.wgl.GetExtensionsStringEXT();
  6158. if (extensions) {
  6159. if (_sapp_wgl_has_ext(ext, extensions)) {
  6160. return true;
  6161. }
  6162. }
  6163. }
  6164. if (_sapp.wgl.GetExtensionsStringARB) {
  6165. const char* extensions = _sapp.wgl.GetExtensionsStringARB(_sapp.wgl.GetCurrentDC());
  6166. if (extensions) {
  6167. if (_sapp_wgl_has_ext(ext, extensions)) {
  6168. return true;
  6169. }
  6170. }
  6171. }
  6172. return false;
  6173. }
  6174. _SOKOL_PRIVATE void _sapp_wgl_load_extensions(void) {
  6175. SOKOL_ASSERT(_sapp.wgl.msg_dc);
  6176. PIXELFORMATDESCRIPTOR pfd;
  6177. _sapp_clear(&pfd, sizeof(pfd));
  6178. pfd.nSize = sizeof(pfd);
  6179. pfd.nVersion = 1;
  6180. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  6181. pfd.iPixelType = PFD_TYPE_RGBA;
  6182. pfd.cColorBits = 24;
  6183. if (!SetPixelFormat(_sapp.wgl.msg_dc, ChoosePixelFormat(_sapp.wgl.msg_dc, &pfd), &pfd)) {
  6184. _SAPP_PANIC(WIN32_DUMMY_CONTEXT_SET_PIXELFORMAT_FAILED);
  6185. }
  6186. HGLRC rc = _sapp.wgl.CreateContext(_sapp.wgl.msg_dc);
  6187. if (!rc) {
  6188. _SAPP_PANIC(WIN32_CREATE_DUMMY_CONTEXT_FAILED);
  6189. }
  6190. if (!_sapp.wgl.MakeCurrent(_sapp.wgl.msg_dc, rc)) {
  6191. _SAPP_PANIC(WIN32_DUMMY_CONTEXT_MAKE_CURRENT_FAILED);
  6192. }
  6193. _sapp.wgl.GetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)(void*) _sapp.wgl.GetProcAddress("wglGetExtensionsStringEXT");
  6194. _sapp.wgl.GetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)(void*) _sapp.wgl.GetProcAddress("wglGetExtensionsStringARB");
  6195. _sapp.wgl.CreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)(void*) _sapp.wgl.GetProcAddress("wglCreateContextAttribsARB");
  6196. _sapp.wgl.SwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)(void*) _sapp.wgl.GetProcAddress("wglSwapIntervalEXT");
  6197. _sapp.wgl.GetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)(void*) _sapp.wgl.GetProcAddress("wglGetPixelFormatAttribivARB");
  6198. _sapp.wgl.arb_multisample = _sapp_wgl_ext_supported("WGL_ARB_multisample");
  6199. _sapp.wgl.arb_create_context = _sapp_wgl_ext_supported("WGL_ARB_create_context");
  6200. _sapp.wgl.arb_create_context_profile = _sapp_wgl_ext_supported("WGL_ARB_create_context_profile");
  6201. _sapp.wgl.ext_swap_control = _sapp_wgl_ext_supported("WGL_EXT_swap_control");
  6202. _sapp.wgl.arb_pixel_format = _sapp_wgl_ext_supported("WGL_ARB_pixel_format");
  6203. _sapp.wgl.MakeCurrent(_sapp.wgl.msg_dc, 0);
  6204. _sapp.wgl.DeleteContext(rc);
  6205. }
  6206. _SOKOL_PRIVATE int _sapp_wgl_attrib(int pixel_format, int attrib) {
  6207. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6208. int value = 0;
  6209. if (!_sapp.wgl.GetPixelFormatAttribivARB(_sapp.win32.dc, pixel_format, 0, 1, &attrib, &value)) {
  6210. _SAPP_PANIC(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED);
  6211. }
  6212. return value;
  6213. }
  6214. _SOKOL_PRIVATE void _sapp_wgl_attribiv(int pixel_format, int num_attribs, const int* attribs, int* results) {
  6215. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6216. if (!_sapp.wgl.GetPixelFormatAttribivARB(_sapp.win32.dc, pixel_format, 0, num_attribs, attribs, results)) {
  6217. _SAPP_PANIC(WIN32_GET_PIXELFORMAT_ATTRIB_FAILED);
  6218. }
  6219. }
  6220. _SOKOL_PRIVATE int _sapp_wgl_find_pixel_format(void) {
  6221. SOKOL_ASSERT(_sapp.win32.dc);
  6222. SOKOL_ASSERT(_sapp.wgl.arb_pixel_format);
  6223. #define _sapp_wgl_num_query_tags (12)
  6224. const int query_tags[_sapp_wgl_num_query_tags] = {
  6225. WGL_SUPPORT_OPENGL_ARB,
  6226. WGL_DRAW_TO_WINDOW_ARB,
  6227. WGL_PIXEL_TYPE_ARB,
  6228. WGL_ACCELERATION_ARB,
  6229. WGL_DOUBLE_BUFFER_ARB,
  6230. WGL_RED_BITS_ARB,
  6231. WGL_GREEN_BITS_ARB,
  6232. WGL_BLUE_BITS_ARB,
  6233. WGL_ALPHA_BITS_ARB,
  6234. WGL_DEPTH_BITS_ARB,
  6235. WGL_STENCIL_BITS_ARB,
  6236. WGL_SAMPLES_ARB,
  6237. };
  6238. const int result_support_opengl_index = 0;
  6239. const int result_draw_to_window_index = 1;
  6240. const int result_pixel_type_index = 2;
  6241. const int result_acceleration_index = 3;
  6242. const int result_double_buffer_index = 4;
  6243. const int result_red_bits_index = 5;
  6244. const int result_green_bits_index = 6;
  6245. const int result_blue_bits_index = 7;
  6246. const int result_alpha_bits_index = 8;
  6247. const int result_depth_bits_index = 9;
  6248. const int result_stencil_bits_index = 10;
  6249. const int result_samples_index = 11;
  6250. int query_results[_sapp_wgl_num_query_tags] = {0};
  6251. // Drop the last item if multisample extension is not supported.
  6252. // If in future querying with multiple extensions, will have to shuffle index values to have active extensions on the end.
  6253. int query_count = _sapp_wgl_num_query_tags;
  6254. if (!_sapp.wgl.arb_multisample) {
  6255. query_count = _sapp_wgl_num_query_tags - 1;
  6256. }
  6257. int native_count = _sapp_wgl_attrib(1, WGL_NUMBER_PIXEL_FORMATS_ARB);
  6258. _sapp_gl_fbconfig desired;
  6259. _sapp_gl_init_fbconfig(&desired);
  6260. desired.red_bits = 8;
  6261. desired.green_bits = 8;
  6262. desired.blue_bits = 8;
  6263. desired.alpha_bits = 8;
  6264. desired.depth_bits = 24;
  6265. desired.stencil_bits = 8;
  6266. desired.doublebuffer = true;
  6267. desired.samples = (_sapp.sample_count > 1) ? _sapp.sample_count : 0;
  6268. int pixel_format = 0;
  6269. _sapp_gl_fbselect fbselect;
  6270. _sapp_gl_init_fbselect(&fbselect);
  6271. for (int i = 0; i < native_count; i++) {
  6272. const int n = i + 1;
  6273. _sapp_wgl_attribiv(n, query_count, query_tags, query_results);
  6274. if (query_results[result_support_opengl_index] == 0
  6275. || query_results[result_draw_to_window_index] == 0
  6276. || query_results[result_pixel_type_index] != WGL_TYPE_RGBA_ARB
  6277. || query_results[result_acceleration_index] == WGL_NO_ACCELERATION_ARB)
  6278. {
  6279. continue;
  6280. }
  6281. _sapp_gl_fbconfig u;
  6282. _sapp_clear(&u, sizeof(u));
  6283. u.red_bits = query_results[result_red_bits_index];
  6284. u.green_bits = query_results[result_green_bits_index];
  6285. u.blue_bits = query_results[result_blue_bits_index];
  6286. u.alpha_bits = query_results[result_alpha_bits_index];
  6287. u.depth_bits = query_results[result_depth_bits_index];
  6288. u.stencil_bits = query_results[result_stencil_bits_index];
  6289. u.doublebuffer = 0 != query_results[result_double_buffer_index];
  6290. u.samples = query_results[result_samples_index]; // NOTE: If arb_multisample is not supported - just takes the default 0
  6291. // Test if this pixel format is better than the previous one
  6292. if (_sapp_gl_select_fbconfig(&fbselect, &desired, &u)) {
  6293. pixel_format = (uintptr_t)n;
  6294. // Early exit if matching as good as possible
  6295. if (fbselect.best_match) {
  6296. break;
  6297. }
  6298. }
  6299. }
  6300. return pixel_format;
  6301. }
  6302. _SOKOL_PRIVATE void _sapp_wgl_create_context(void) {
  6303. int pixel_format = _sapp_wgl_find_pixel_format();
  6304. if (0 == pixel_format) {
  6305. _SAPP_PANIC(WIN32_WGL_FIND_PIXELFORMAT_FAILED);
  6306. }
  6307. PIXELFORMATDESCRIPTOR pfd;
  6308. if (!DescribePixelFormat(_sapp.win32.dc, pixel_format, sizeof(pfd), &pfd)) {
  6309. _SAPP_PANIC(WIN32_WGL_DESCRIBE_PIXELFORMAT_FAILED);
  6310. }
  6311. if (!SetPixelFormat(_sapp.win32.dc, pixel_format, &pfd)) {
  6312. _SAPP_PANIC(WIN32_WGL_SET_PIXELFORMAT_FAILED);
  6313. }
  6314. if (!_sapp.wgl.arb_create_context) {
  6315. _SAPP_PANIC(WIN32_WGL_ARB_CREATE_CONTEXT_REQUIRED);
  6316. }
  6317. if (!_sapp.wgl.arb_create_context_profile) {
  6318. _SAPP_PANIC(WIN32_WGL_ARB_CREATE_CONTEXT_PROFILE_REQUIRED);
  6319. }
  6320. const int attrs[] = {
  6321. WGL_CONTEXT_MAJOR_VERSION_ARB, _sapp.desc.gl_major_version,
  6322. WGL_CONTEXT_MINOR_VERSION_ARB, _sapp.desc.gl_minor_version,
  6323. #if defined(SOKOL_DEBUG)
  6324. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,
  6325. #else
  6326. WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
  6327. #endif
  6328. WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
  6329. 0, 0
  6330. };
  6331. _sapp.wgl.gl_ctx = _sapp.wgl.CreateContextAttribsARB(_sapp.win32.dc, 0, attrs);
  6332. if (!_sapp.wgl.gl_ctx) {
  6333. const DWORD err = GetLastError();
  6334. if (err == (0xc0070000 | ERROR_INVALID_VERSION_ARB)) {
  6335. _SAPP_PANIC(WIN32_WGL_OPENGL_VERSION_NOT_SUPPORTED);
  6336. }
  6337. else if (err == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) {
  6338. _SAPP_PANIC(WIN32_WGL_OPENGL_PROFILE_NOT_SUPPORTED);
  6339. }
  6340. else if (err == (0xc0070000 | ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB)) {
  6341. _SAPP_PANIC(WIN32_WGL_INCOMPATIBLE_DEVICE_CONTEXT);
  6342. }
  6343. else {
  6344. _SAPP_PANIC(WIN32_WGL_CREATE_CONTEXT_ATTRIBS_FAILED_OTHER);
  6345. }
  6346. }
  6347. _sapp.wgl.MakeCurrent(_sapp.win32.dc, _sapp.wgl.gl_ctx);
  6348. if (_sapp.wgl.ext_swap_control) {
  6349. /* FIXME: DwmIsCompositionEnabled() (see GLFW) */
  6350. _sapp.wgl.SwapIntervalEXT(_sapp.swap_interval);
  6351. }
  6352. const uint32_t gl_framebuffer_binding = 0x8CA6;
  6353. _sapp.wgl.GetIntegerv(gl_framebuffer_binding, (int32_t*)&_sapp.gl.framebuffer);
  6354. }
  6355. _SOKOL_PRIVATE void _sapp_wgl_destroy_context(void) {
  6356. SOKOL_ASSERT(_sapp.wgl.gl_ctx);
  6357. _sapp.wgl.DeleteContext(_sapp.wgl.gl_ctx);
  6358. _sapp.wgl.gl_ctx = 0;
  6359. }
  6360. _SOKOL_PRIVATE void _sapp_wgl_swap_buffers(void) {
  6361. SOKOL_ASSERT(_sapp.win32.dc);
  6362. /* FIXME: DwmIsCompositionEnabled? (see GLFW) */
  6363. SwapBuffers(_sapp.win32.dc);
  6364. }
  6365. #endif /* SOKOL_GLCORE */
  6366. _SOKOL_PRIVATE bool _sapp_win32_wide_to_utf8(const wchar_t* src, char* dst, int dst_num_bytes) {
  6367. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  6368. _sapp_clear(dst, (size_t)dst_num_bytes);
  6369. const int bytes_needed = WideCharToMultiByte(CP_UTF8, 0, src, -1, NULL, 0, NULL, NULL);
  6370. if (bytes_needed <= dst_num_bytes) {
  6371. WideCharToMultiByte(CP_UTF8, 0, src, -1, dst, dst_num_bytes, NULL, NULL);
  6372. return true;
  6373. }
  6374. else {
  6375. return false;
  6376. }
  6377. }
  6378. /* updates current window and framebuffer size from the window's client rect, returns true if size has changed */
  6379. _SOKOL_PRIVATE bool _sapp_win32_update_dimensions(void) {
  6380. RECT rect;
  6381. if (GetClientRect(_sapp.win32.hwnd, &rect)) {
  6382. float window_width = (float)(rect.right - rect.left) / _sapp.win32.dpi.window_scale;
  6383. float window_height = (float)(rect.bottom - rect.top) / _sapp.win32.dpi.window_scale;
  6384. _sapp.window_width = (int)roundf(window_width);
  6385. _sapp.window_height = (int)roundf(window_height);
  6386. int fb_width = (int)roundf(window_width * _sapp.win32.dpi.content_scale);
  6387. int fb_height = (int)roundf(window_height * _sapp.win32.dpi.content_scale);
  6388. /* prevent a framebuffer size of 0 when window is minimized */
  6389. if (0 == fb_width) {
  6390. fb_width = 1;
  6391. }
  6392. if (0 == fb_height) {
  6393. fb_height = 1;
  6394. }
  6395. if ((fb_width != _sapp.framebuffer_width) || (fb_height != _sapp.framebuffer_height)) {
  6396. _sapp.framebuffer_width = fb_width;
  6397. _sapp.framebuffer_height = fb_height;
  6398. return true;
  6399. }
  6400. }
  6401. else {
  6402. _sapp.window_width = _sapp.window_height = 1;
  6403. _sapp.framebuffer_width = _sapp.framebuffer_height = 1;
  6404. }
  6405. return false;
  6406. }
  6407. _SOKOL_PRIVATE void _sapp_win32_set_fullscreen(bool fullscreen, UINT swp_flags) {
  6408. HMONITOR monitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONEAREST);
  6409. MONITORINFO minfo;
  6410. _sapp_clear(&minfo, sizeof(minfo));
  6411. minfo.cbSize = sizeof(MONITORINFO);
  6412. GetMonitorInfo(monitor, &minfo);
  6413. const RECT mr = minfo.rcMonitor;
  6414. const int monitor_w = mr.right - mr.left;
  6415. const int monitor_h = mr.bottom - mr.top;
  6416. const DWORD win_ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  6417. DWORD win_style;
  6418. RECT rect = { 0, 0, 0, 0 };
  6419. _sapp.fullscreen = fullscreen;
  6420. if (!_sapp.fullscreen) {
  6421. win_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
  6422. rect = _sapp.win32.stored_window_rect;
  6423. }
  6424. else {
  6425. GetWindowRect(_sapp.win32.hwnd, &_sapp.win32.stored_window_rect);
  6426. win_style = WS_POPUP | WS_SYSMENU | WS_VISIBLE;
  6427. rect.left = mr.left;
  6428. rect.top = mr.top;
  6429. rect.right = rect.left + monitor_w;
  6430. rect.bottom = rect.top + monitor_h;
  6431. AdjustWindowRectEx(&rect, win_style, FALSE, win_ex_style);
  6432. }
  6433. const int win_w = rect.right - rect.left;
  6434. const int win_h = rect.bottom - rect.top;
  6435. const int win_x = rect.left;
  6436. const int win_y = rect.top;
  6437. SetWindowLongPtr(_sapp.win32.hwnd, GWL_STYLE, win_style);
  6438. SetWindowPos(_sapp.win32.hwnd, HWND_TOP, win_x, win_y, win_w, win_h, swp_flags | SWP_FRAMECHANGED);
  6439. }
  6440. _SOKOL_PRIVATE void _sapp_win32_toggle_fullscreen(void) {
  6441. _sapp_win32_set_fullscreen(!_sapp.fullscreen, SWP_SHOWWINDOW);
  6442. }
  6443. _SOKOL_PRIVATE void _sapp_win32_init_cursor(sapp_mouse_cursor cursor) {
  6444. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  6445. // NOTE: the OCR_* constants are only defined if OEMRESOURCE is defined
  6446. // before windows.h is included, but we can't guarantee that because
  6447. // the sokol_app.h implementation may be included with other implementations
  6448. // in the same compilation unit
  6449. int id = 0;
  6450. switch (cursor) {
  6451. case SAPP_MOUSECURSOR_ARROW: id = 32512; break; // OCR_NORMAL
  6452. case SAPP_MOUSECURSOR_IBEAM: id = 32513; break; // OCR_IBEAM
  6453. case SAPP_MOUSECURSOR_CROSSHAIR: id = 32515; break; // OCR_CROSS
  6454. case SAPP_MOUSECURSOR_POINTING_HAND: id = 32649; break; // OCR_HAND
  6455. case SAPP_MOUSECURSOR_RESIZE_EW: id = 32644; break; // OCR_SIZEWE
  6456. case SAPP_MOUSECURSOR_RESIZE_NS: id = 32645; break; // OCR_SIZENS
  6457. case SAPP_MOUSECURSOR_RESIZE_NWSE: id = 32642; break; // OCR_SIZENWSE
  6458. case SAPP_MOUSECURSOR_RESIZE_NESW: id = 32643; break; // OCR_SIZENESW
  6459. case SAPP_MOUSECURSOR_RESIZE_ALL: id = 32646; break; // OCR_SIZEALL
  6460. case SAPP_MOUSECURSOR_NOT_ALLOWED: id = 32648; break; // OCR_NO
  6461. default: break;
  6462. }
  6463. if (id != 0) {
  6464. _sapp.win32.cursors[cursor] = (HCURSOR)LoadImageW(NULL, MAKEINTRESOURCEW(id), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE|LR_SHARED);
  6465. }
  6466. // fallback: default cursor
  6467. if (0 == _sapp.win32.cursors[cursor]) {
  6468. // 32512 => IDC_ARROW
  6469. _sapp.win32.cursors[cursor] = LoadCursorW(NULL, MAKEINTRESOURCEW(32512));
  6470. }
  6471. SOKOL_ASSERT(0 != _sapp.win32.cursors[cursor]);
  6472. }
  6473. _SOKOL_PRIVATE void _sapp_win32_init_cursors(void) {
  6474. for (int i = 0; i < _SAPP_MOUSECURSOR_NUM; i++) {
  6475. _sapp_win32_init_cursor((sapp_mouse_cursor)i);
  6476. }
  6477. }
  6478. _SOKOL_PRIVATE bool _sapp_win32_cursor_in_content_area(void) {
  6479. POINT pos;
  6480. if (!GetCursorPos(&pos)) {
  6481. return false;
  6482. }
  6483. if (WindowFromPoint(pos) != _sapp.win32.hwnd) {
  6484. return false;
  6485. }
  6486. RECT area;
  6487. GetClientRect(_sapp.win32.hwnd, &area);
  6488. ClientToScreen(_sapp.win32.hwnd, (POINT*)&area.left);
  6489. ClientToScreen(_sapp.win32.hwnd, (POINT*)&area.right);
  6490. return PtInRect(&area, pos) == TRUE;
  6491. }
  6492. _SOKOL_PRIVATE void _sapp_win32_update_cursor(sapp_mouse_cursor cursor, bool shown, bool skip_area_test) {
  6493. // NOTE: when called from WM_SETCURSOR, the area test would be redundant
  6494. if (!skip_area_test) {
  6495. if (!_sapp_win32_cursor_in_content_area()) {
  6496. return;
  6497. }
  6498. }
  6499. if (!shown) {
  6500. SetCursor(NULL);
  6501. }
  6502. else {
  6503. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  6504. SOKOL_ASSERT(0 != _sapp.win32.cursors[cursor]);
  6505. SetCursor(_sapp.win32.cursors[cursor]);
  6506. }
  6507. }
  6508. _SOKOL_PRIVATE void _sapp_win32_capture_mouse(uint8_t btn_mask) {
  6509. if (0 == _sapp.win32.mouse_capture_mask) {
  6510. SetCapture(_sapp.win32.hwnd);
  6511. }
  6512. _sapp.win32.mouse_capture_mask |= btn_mask;
  6513. }
  6514. _SOKOL_PRIVATE void _sapp_win32_release_mouse(uint8_t btn_mask) {
  6515. if (0 != _sapp.win32.mouse_capture_mask) {
  6516. _sapp.win32.mouse_capture_mask &= ~btn_mask;
  6517. if (0 == _sapp.win32.mouse_capture_mask) {
  6518. ReleaseCapture();
  6519. }
  6520. }
  6521. }
  6522. _SOKOL_PRIVATE void _sapp_win32_lock_mouse(bool lock) {
  6523. if (lock == _sapp.mouse.locked) {
  6524. return;
  6525. }
  6526. _sapp.mouse.dx = 0.0f;
  6527. _sapp.mouse.dy = 0.0f;
  6528. _sapp.mouse.locked = lock;
  6529. _sapp_win32_release_mouse(0xFF);
  6530. if (_sapp.mouse.locked) {
  6531. /* store the current mouse position, so it can be restored when unlocked */
  6532. POINT pos;
  6533. BOOL res = GetCursorPos(&pos);
  6534. SOKOL_ASSERT(res); _SOKOL_UNUSED(res);
  6535. _sapp.win32.mouse_locked_x = pos.x;
  6536. _sapp.win32.mouse_locked_y = pos.y;
  6537. /* while the mouse is locked, make the mouse cursor invisible and
  6538. confine the mouse movement to a small rectangle inside our window
  6539. (so that we don't miss any mouse up events)
  6540. */
  6541. RECT client_rect = {
  6542. _sapp.win32.mouse_locked_x,
  6543. _sapp.win32.mouse_locked_y,
  6544. _sapp.win32.mouse_locked_x,
  6545. _sapp.win32.mouse_locked_y
  6546. };
  6547. ClipCursor(&client_rect);
  6548. /* make the mouse cursor invisible, this will stack with sapp_show_mouse() */
  6549. ShowCursor(FALSE);
  6550. /* enable raw input for mouse, starts sending WM_INPUT messages to WinProc (see GLFW) */
  6551. const RAWINPUTDEVICE rid = {
  6552. 0x01, // usUsagePage: HID_USAGE_PAGE_GENERIC
  6553. 0x02, // usUsage: HID_USAGE_GENERIC_MOUSE
  6554. 0, // dwFlags
  6555. _sapp.win32.hwnd // hwndTarget
  6556. };
  6557. if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
  6558. _SAPP_ERROR(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_LOCK);
  6559. }
  6560. /* in case the raw mouse device only supports absolute position reporting,
  6561. we need to skip the dx/dy compution for the first WM_INPUT event
  6562. */
  6563. _sapp.win32.raw_input_mousepos_valid = false;
  6564. }
  6565. else {
  6566. /* disable raw input for mouse */
  6567. const RAWINPUTDEVICE rid = { 0x01, 0x02, RIDEV_REMOVE, NULL };
  6568. if (!RegisterRawInputDevices(&rid, 1, sizeof(rid))) {
  6569. _SAPP_ERROR(WIN32_REGISTER_RAW_INPUT_DEVICES_FAILED_MOUSE_UNLOCK);
  6570. }
  6571. /* let the mouse roam freely again */
  6572. ClipCursor(NULL);
  6573. ShowCursor(TRUE);
  6574. /* restore the 'pre-locked' mouse position */
  6575. BOOL res = SetCursorPos(_sapp.win32.mouse_locked_x, _sapp.win32.mouse_locked_y);
  6576. SOKOL_ASSERT(res); _SOKOL_UNUSED(res);
  6577. }
  6578. }
  6579. _SOKOL_PRIVATE bool _sapp_win32_update_monitor(void) {
  6580. const HMONITOR cur_monitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONULL);
  6581. if (cur_monitor != _sapp.win32.hmonitor) {
  6582. _sapp.win32.hmonitor = cur_monitor;
  6583. return true;
  6584. }
  6585. else {
  6586. return false;
  6587. }
  6588. }
  6589. _SOKOL_PRIVATE uint32_t _sapp_win32_mods(void) {
  6590. uint32_t mods = 0;
  6591. if (GetKeyState(VK_SHIFT) & (1<<15)) {
  6592. mods |= SAPP_MODIFIER_SHIFT;
  6593. }
  6594. if (GetKeyState(VK_CONTROL) & (1<<15)) {
  6595. mods |= SAPP_MODIFIER_CTRL;
  6596. }
  6597. if (GetKeyState(VK_MENU) & (1<<15)) {
  6598. mods |= SAPP_MODIFIER_ALT;
  6599. }
  6600. if ((GetKeyState(VK_LWIN) | GetKeyState(VK_RWIN)) & (1<<15)) {
  6601. mods |= SAPP_MODIFIER_SUPER;
  6602. }
  6603. const bool swapped = (TRUE == GetSystemMetrics(SM_SWAPBUTTON));
  6604. if (GetAsyncKeyState(VK_LBUTTON)) {
  6605. mods |= swapped ? SAPP_MODIFIER_RMB : SAPP_MODIFIER_LMB;
  6606. }
  6607. if (GetAsyncKeyState(VK_RBUTTON)) {
  6608. mods |= swapped ? SAPP_MODIFIER_LMB : SAPP_MODIFIER_RMB;
  6609. }
  6610. if (GetAsyncKeyState(VK_MBUTTON)) {
  6611. mods |= SAPP_MODIFIER_MMB;
  6612. }
  6613. return mods;
  6614. }
  6615. _SOKOL_PRIVATE void _sapp_win32_mouse_update(LPARAM lParam) {
  6616. if (!_sapp.mouse.locked) {
  6617. const float new_x = (float)GET_X_LPARAM(lParam) * _sapp.win32.dpi.mouse_scale;
  6618. const float new_y = (float)GET_Y_LPARAM(lParam) * _sapp.win32.dpi.mouse_scale;
  6619. if (_sapp.mouse.pos_valid) {
  6620. // don't update dx/dy in the very first event
  6621. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  6622. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  6623. }
  6624. _sapp.mouse.x = new_x;
  6625. _sapp.mouse.y = new_y;
  6626. _sapp.mouse.pos_valid = true;
  6627. }
  6628. }
  6629. _SOKOL_PRIVATE void _sapp_win32_mouse_event(sapp_event_type type, sapp_mousebutton btn) {
  6630. if (_sapp_events_enabled()) {
  6631. _sapp_init_event(type);
  6632. _sapp.event.modifiers = _sapp_win32_mods();
  6633. _sapp.event.mouse_button = btn;
  6634. _sapp_call_event(&_sapp.event);
  6635. }
  6636. }
  6637. _SOKOL_PRIVATE void _sapp_win32_scroll_event(float x, float y) {
  6638. if (_sapp_events_enabled()) {
  6639. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  6640. _sapp.event.modifiers = _sapp_win32_mods();
  6641. _sapp.event.scroll_x = -x / 30.0f;
  6642. _sapp.event.scroll_y = y / 30.0f;
  6643. _sapp_call_event(&_sapp.event);
  6644. }
  6645. }
  6646. _SOKOL_PRIVATE void _sapp_win32_key_event(sapp_event_type type, int vk, bool repeat) {
  6647. if (_sapp_events_enabled() && (vk < SAPP_MAX_KEYCODES)) {
  6648. _sapp_init_event(type);
  6649. _sapp.event.modifiers = _sapp_win32_mods();
  6650. _sapp.event.key_code = _sapp.keycodes[vk];
  6651. _sapp.event.key_repeat = repeat;
  6652. _sapp_call_event(&_sapp.event);
  6653. /* check if a CLIPBOARD_PASTED event must be sent too */
  6654. if (_sapp.clipboard.enabled &&
  6655. (type == SAPP_EVENTTYPE_KEY_DOWN) &&
  6656. (_sapp.event.modifiers == SAPP_MODIFIER_CTRL) &&
  6657. (_sapp.event.key_code == SAPP_KEYCODE_V))
  6658. {
  6659. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  6660. _sapp_call_event(&_sapp.event);
  6661. }
  6662. }
  6663. }
  6664. _SOKOL_PRIVATE void _sapp_win32_char_event(uint32_t c, bool repeat) {
  6665. if (_sapp_events_enabled() && (c >= 32)) {
  6666. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  6667. _sapp.event.modifiers = _sapp_win32_mods();
  6668. _sapp.event.char_code = c;
  6669. _sapp.event.key_repeat = repeat;
  6670. _sapp_call_event(&_sapp.event);
  6671. }
  6672. }
  6673. _SOKOL_PRIVATE void _sapp_win32_dpi_changed(HWND hWnd, LPRECT proposed_win_rect) {
  6674. /* called on WM_DPICHANGED, which will only be sent to the application
  6675. if sapp_desc.high_dpi is true and the Windows version is recent enough
  6676. to support DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2
  6677. */
  6678. SOKOL_ASSERT(_sapp.desc.high_dpi);
  6679. HINSTANCE user32 = LoadLibraryA("user32.dll");
  6680. if (!user32) {
  6681. return;
  6682. }
  6683. typedef UINT(WINAPI * GETDPIFORWINDOW_T)(HWND hwnd);
  6684. GETDPIFORWINDOW_T fn_getdpiforwindow = (GETDPIFORWINDOW_T)(void*)GetProcAddress(user32, "GetDpiForWindow");
  6685. if (fn_getdpiforwindow) {
  6686. UINT dpix = fn_getdpiforwindow(_sapp.win32.hwnd);
  6687. // NOTE: for high-dpi apps, mouse_scale remains one
  6688. _sapp.win32.dpi.window_scale = (float)dpix / 96.0f;
  6689. _sapp.win32.dpi.content_scale = _sapp.win32.dpi.window_scale;
  6690. _sapp.dpi_scale = _sapp.win32.dpi.window_scale;
  6691. SetWindowPos(hWnd, 0,
  6692. proposed_win_rect->left,
  6693. proposed_win_rect->top,
  6694. proposed_win_rect->right - proposed_win_rect->left,
  6695. proposed_win_rect->bottom - proposed_win_rect->top,
  6696. SWP_NOZORDER | SWP_NOACTIVATE);
  6697. }
  6698. FreeLibrary(user32);
  6699. }
  6700. _SOKOL_PRIVATE void _sapp_win32_files_dropped(HDROP hdrop) {
  6701. if (!_sapp.drop.enabled) {
  6702. return;
  6703. }
  6704. _sapp_clear_drop_buffer();
  6705. bool drop_failed = false;
  6706. const int count = (int) DragQueryFileW(hdrop, 0xffffffff, NULL, 0);
  6707. _sapp.drop.num_files = (count > _sapp.drop.max_files) ? _sapp.drop.max_files : count;
  6708. for (UINT i = 0; i < (UINT)_sapp.drop.num_files; i++) {
  6709. const UINT num_chars = DragQueryFileW(hdrop, i, NULL, 0) + 1;
  6710. WCHAR* buffer = (WCHAR*) _sapp_malloc_clear(num_chars * sizeof(WCHAR));
  6711. DragQueryFileW(hdrop, i, buffer, num_chars);
  6712. if (!_sapp_win32_wide_to_utf8(buffer, _sapp_dropped_file_path_ptr((int)i), _sapp.drop.max_path_length)) {
  6713. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  6714. drop_failed = true;
  6715. }
  6716. _sapp_free(buffer);
  6717. }
  6718. DragFinish(hdrop);
  6719. if (!drop_failed) {
  6720. if (_sapp_events_enabled()) {
  6721. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  6722. _sapp.event.modifiers = _sapp_win32_mods();
  6723. _sapp_call_event(&_sapp.event);
  6724. }
  6725. }
  6726. else {
  6727. _sapp_clear_drop_buffer();
  6728. _sapp.drop.num_files = 0;
  6729. }
  6730. }
  6731. _SOKOL_PRIVATE void _sapp_win32_timing_measure(void) {
  6732. #if defined(SOKOL_D3D11)
  6733. // on D3D11, use the more precise DXGI timestamp
  6734. if (_sapp.d3d11.use_dxgi_frame_stats) {
  6735. DXGI_FRAME_STATISTICS dxgi_stats;
  6736. _sapp_clear(&dxgi_stats, sizeof(dxgi_stats));
  6737. HRESULT hr = _sapp_dxgi_GetFrameStatistics(_sapp.d3d11.swap_chain, &dxgi_stats);
  6738. if (SUCCEEDED(hr)) {
  6739. if (dxgi_stats.SyncRefreshCount != _sapp.d3d11.sync_refresh_count) {
  6740. if ((_sapp.d3d11.sync_refresh_count + 1) != dxgi_stats.SyncRefreshCount) {
  6741. _sapp_timing_discontinuity(&_sapp.timing);
  6742. }
  6743. _sapp.d3d11.sync_refresh_count = dxgi_stats.SyncRefreshCount;
  6744. LARGE_INTEGER qpc = dxgi_stats.SyncQPCTime;
  6745. const uint64_t now = (uint64_t)_sapp_int64_muldiv(qpc.QuadPart - _sapp.timing.timestamp.win.start.QuadPart, 1000000000, _sapp.timing.timestamp.win.freq.QuadPart);
  6746. _sapp_timing_external(&_sapp.timing, (double)now / 1000000000.0);
  6747. }
  6748. return;
  6749. }
  6750. }
  6751. // fallback if swap model isn't "flip-discard" or GetFrameStatistics failed for another reason
  6752. _sapp_timing_measure(&_sapp.timing);
  6753. #endif
  6754. #if defined(SOKOL_GLCORE)
  6755. _sapp_timing_measure(&_sapp.timing);
  6756. #endif
  6757. #if defined(SOKOL_NOAPI)
  6758. _sapp_timing_measure(&_sapp.timing);
  6759. #endif
  6760. }
  6761. _SOKOL_PRIVATE LRESULT CALLBACK _sapp_win32_wndproc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  6762. if (!_sapp.win32.in_create_window) {
  6763. switch (uMsg) {
  6764. case WM_CLOSE:
  6765. /* only give user a chance to intervene when sapp_quit() wasn't already called */
  6766. if (!_sapp.quit_ordered) {
  6767. /* if window should be closed and event handling is enabled, give user code
  6768. a change to intervene via sapp_cancel_quit()
  6769. */
  6770. _sapp.quit_requested = true;
  6771. _sapp_win32_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  6772. /* if user code hasn't intervened, quit the app */
  6773. if (_sapp.quit_requested) {
  6774. _sapp.quit_ordered = true;
  6775. }
  6776. }
  6777. if (_sapp.quit_ordered) {
  6778. PostQuitMessage(0);
  6779. }
  6780. return 0;
  6781. case WM_SYSCOMMAND:
  6782. switch (wParam & 0xFFF0) {
  6783. case SC_SCREENSAVE:
  6784. case SC_MONITORPOWER:
  6785. if (_sapp.fullscreen) {
  6786. /* disable screen saver and blanking in fullscreen mode */
  6787. return 0;
  6788. }
  6789. break;
  6790. case SC_KEYMENU:
  6791. /* user trying to access menu via ALT */
  6792. return 0;
  6793. }
  6794. break;
  6795. case WM_ERASEBKGND:
  6796. return 1;
  6797. case WM_SIZE:
  6798. {
  6799. const bool iconified = wParam == SIZE_MINIMIZED;
  6800. if (iconified != _sapp.win32.iconified) {
  6801. _sapp.win32.iconified = iconified;
  6802. if (iconified) {
  6803. _sapp_win32_app_event(SAPP_EVENTTYPE_ICONIFIED);
  6804. }
  6805. else {
  6806. _sapp_win32_app_event(SAPP_EVENTTYPE_RESTORED);
  6807. }
  6808. }
  6809. }
  6810. break;
  6811. case WM_SETFOCUS:
  6812. _sapp_win32_app_event(SAPP_EVENTTYPE_FOCUSED);
  6813. break;
  6814. case WM_KILLFOCUS:
  6815. /* if focus is lost for any reason, and we're in mouse locked mode, disable mouse lock */
  6816. if (_sapp.mouse.locked) {
  6817. _sapp_win32_lock_mouse(false);
  6818. }
  6819. _sapp_win32_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  6820. break;
  6821. case WM_SETCURSOR:
  6822. if (LOWORD(lParam) == HTCLIENT) {
  6823. _sapp_win32_update_cursor(_sapp.mouse.current_cursor, _sapp.mouse.shown, true);
  6824. return TRUE;
  6825. }
  6826. break;
  6827. case WM_DPICHANGED:
  6828. {
  6829. /* Update window's DPI and size if its moved to another monitor with a different DPI
  6830. Only sent if DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 is used.
  6831. */
  6832. _sapp_win32_dpi_changed(hWnd, (LPRECT)lParam);
  6833. break;
  6834. }
  6835. case WM_LBUTTONDOWN:
  6836. _sapp_win32_mouse_update(lParam);
  6837. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_LEFT);
  6838. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_LEFT);
  6839. break;
  6840. case WM_RBUTTONDOWN:
  6841. _sapp_win32_mouse_update(lParam);
  6842. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_RIGHT);
  6843. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_RIGHT);
  6844. break;
  6845. case WM_MBUTTONDOWN:
  6846. _sapp_win32_mouse_update(lParam);
  6847. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, SAPP_MOUSEBUTTON_MIDDLE);
  6848. _sapp_win32_capture_mouse(1<<SAPP_MOUSEBUTTON_MIDDLE);
  6849. break;
  6850. case WM_LBUTTONUP:
  6851. _sapp_win32_mouse_update(lParam);
  6852. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_LEFT);
  6853. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_LEFT);
  6854. break;
  6855. case WM_RBUTTONUP:
  6856. _sapp_win32_mouse_update(lParam);
  6857. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_RIGHT);
  6858. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_RIGHT);
  6859. break;
  6860. case WM_MBUTTONUP:
  6861. _sapp_win32_mouse_update(lParam);
  6862. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, SAPP_MOUSEBUTTON_MIDDLE);
  6863. _sapp_win32_release_mouse(1<<SAPP_MOUSEBUTTON_MIDDLE);
  6864. break;
  6865. case WM_MOUSEMOVE:
  6866. if (!_sapp.mouse.locked) {
  6867. _sapp_win32_mouse_update(lParam);
  6868. if (!_sapp.win32.mouse_tracked) {
  6869. _sapp.win32.mouse_tracked = true;
  6870. TRACKMOUSEEVENT tme;
  6871. _sapp_clear(&tme, sizeof(tme));
  6872. tme.cbSize = sizeof(tme);
  6873. tme.dwFlags = TME_LEAVE;
  6874. tme.hwndTrack = _sapp.win32.hwnd;
  6875. TrackMouseEvent(&tme);
  6876. _sapp.mouse.dx = 0.0f;
  6877. _sapp.mouse.dy = 0.0f;
  6878. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID);
  6879. }
  6880. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID);
  6881. }
  6882. break;
  6883. case WM_INPUT:
  6884. /* raw mouse input during mouse-lock */
  6885. if (_sapp.mouse.locked) {
  6886. HRAWINPUT ri = (HRAWINPUT) lParam;
  6887. UINT size = sizeof(_sapp.win32.raw_input_data);
  6888. // see: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getrawinputdata
  6889. if ((UINT)-1 == GetRawInputData(ri, RID_INPUT, &_sapp.win32.raw_input_data, &size, sizeof(RAWINPUTHEADER))) {
  6890. _SAPP_ERROR(WIN32_GET_RAW_INPUT_DATA_FAILED);
  6891. break;
  6892. }
  6893. const RAWINPUT* raw_mouse_data = (const RAWINPUT*) &_sapp.win32.raw_input_data;
  6894. if (raw_mouse_data->data.mouse.usFlags & MOUSE_MOVE_ABSOLUTE) {
  6895. /* mouse only reports absolute position
  6896. NOTE: This code is untested and will most likely behave wrong in Remote Desktop sessions.
  6897. (such remote desktop sessions are setting the MOUSE_MOVE_ABSOLUTE flag).
  6898. See: https://github.com/floooh/sokol/issues/806 and
  6899. https://github.com/microsoft/DirectXTK/commit/ef56b63f3739381e451f7a5a5bd2c9779d2a7555)
  6900. */
  6901. LONG new_x = raw_mouse_data->data.mouse.lLastX;
  6902. LONG new_y = raw_mouse_data->data.mouse.lLastY;
  6903. if (_sapp.win32.raw_input_mousepos_valid) {
  6904. _sapp.mouse.dx = (float) (new_x - _sapp.win32.raw_input_mousepos_x);
  6905. _sapp.mouse.dy = (float) (new_y - _sapp.win32.raw_input_mousepos_y);
  6906. }
  6907. _sapp.win32.raw_input_mousepos_x = new_x;
  6908. _sapp.win32.raw_input_mousepos_y = new_y;
  6909. _sapp.win32.raw_input_mousepos_valid = true;
  6910. }
  6911. else {
  6912. /* mouse reports movement delta (this seems to be the common case) */
  6913. _sapp.mouse.dx = (float) raw_mouse_data->data.mouse.lLastX;
  6914. _sapp.mouse.dy = (float) raw_mouse_data->data.mouse.lLastY;
  6915. }
  6916. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID);
  6917. }
  6918. break;
  6919. case WM_MOUSELEAVE:
  6920. if (!_sapp.mouse.locked) {
  6921. _sapp.mouse.dx = 0.0f;
  6922. _sapp.mouse.dy = 0.0f;
  6923. _sapp.win32.mouse_tracked = false;
  6924. _sapp_win32_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID);
  6925. }
  6926. break;
  6927. case WM_MOUSEWHEEL:
  6928. _sapp_win32_scroll_event(0.0f, (float)((SHORT)HIWORD(wParam)));
  6929. break;
  6930. case WM_MOUSEHWHEEL:
  6931. _sapp_win32_scroll_event((float)((SHORT)HIWORD(wParam)), 0.0f);
  6932. break;
  6933. case WM_CHAR:
  6934. _sapp_win32_char_event((uint32_t)wParam, !!(lParam&0x40000000));
  6935. break;
  6936. case WM_KEYDOWN:
  6937. case WM_SYSKEYDOWN:
  6938. _sapp_win32_key_event(SAPP_EVENTTYPE_KEY_DOWN, (int)(HIWORD(lParam)&0x1FF), !!(lParam&0x40000000));
  6939. break;
  6940. case WM_KEYUP:
  6941. case WM_SYSKEYUP:
  6942. _sapp_win32_key_event(SAPP_EVENTTYPE_KEY_UP, (int)(HIWORD(lParam)&0x1FF), false);
  6943. break;
  6944. case WM_ENTERSIZEMOVE:
  6945. SetTimer(_sapp.win32.hwnd, 1, USER_TIMER_MINIMUM, NULL);
  6946. break;
  6947. case WM_EXITSIZEMOVE:
  6948. KillTimer(_sapp.win32.hwnd, 1);
  6949. break;
  6950. case WM_TIMER:
  6951. _sapp_win32_timing_measure();
  6952. _sapp_frame();
  6953. #if defined(SOKOL_D3D11)
  6954. // present with DXGI_PRESENT_DO_NOT_WAIT
  6955. _sapp_d3d11_present(true);
  6956. #endif
  6957. #if defined(SOKOL_GLCORE)
  6958. _sapp_wgl_swap_buffers();
  6959. #endif
  6960. /* NOTE: resizing the swap-chain during resize leads to a substantial
  6961. memory spike (hundreds of megabytes for a few seconds).
  6962. if (_sapp_win32_update_dimensions()) {
  6963. #if defined(SOKOL_D3D11)
  6964. _sapp_d3d11_resize_default_render_target();
  6965. #endif
  6966. _sapp_win32_app_event(SAPP_EVENTTYPE_RESIZED);
  6967. }
  6968. */
  6969. break;
  6970. case WM_NCLBUTTONDOWN:
  6971. /* workaround for half-second pause when starting to move window
  6972. see: https://gamedev.net/forums/topic/672094-keeping-things-moving-during-win32-moveresize-events/5254386/
  6973. */
  6974. if (SendMessage(_sapp.win32.hwnd, WM_NCHITTEST, wParam, lParam) == HTCAPTION) {
  6975. POINT point = { 0, 0 };
  6976. if (GetCursorPos(&point)) {
  6977. ScreenToClient(_sapp.win32.hwnd, &point);
  6978. PostMessage(_sapp.win32.hwnd, WM_MOUSEMOVE, 0, ((uint32_t)point.x)|(((uint32_t)point.y) << 16));
  6979. }
  6980. }
  6981. break;
  6982. case WM_DROPFILES:
  6983. _sapp_win32_files_dropped((HDROP)wParam);
  6984. break;
  6985. case WM_DISPLAYCHANGE:
  6986. // refresh rate might have changed
  6987. _sapp_timing_reset(&_sapp.timing);
  6988. break;
  6989. default:
  6990. break;
  6991. }
  6992. }
  6993. return DefWindowProcW(hWnd, uMsg, wParam, lParam);
  6994. }
  6995. _SOKOL_PRIVATE void _sapp_win32_create_window(void) {
  6996. WNDCLASSW wndclassw;
  6997. _sapp_clear(&wndclassw, sizeof(wndclassw));
  6998. wndclassw.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  6999. wndclassw.lpfnWndProc = (WNDPROC) _sapp_win32_wndproc;
  7000. wndclassw.hInstance = GetModuleHandleW(NULL);
  7001. wndclassw.hCursor = LoadCursor(NULL, IDC_ARROW);
  7002. wndclassw.hIcon = LoadIcon(NULL, IDI_WINLOGO);
  7003. wndclassw.lpszClassName = L"SOKOLAPP";
  7004. RegisterClassW(&wndclassw);
  7005. /* NOTE: regardless whether fullscreen is requested or not, a regular
  7006. windowed-mode window will always be created first (however in hidden
  7007. mode, so that no windowed-mode window pops up before the fullscreen window)
  7008. */
  7009. const DWORD win_ex_style = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
  7010. RECT rect = { 0, 0, 0, 0 };
  7011. DWORD win_style = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX;
  7012. rect.right = (int) ((float)_sapp.window_width * _sapp.win32.dpi.window_scale);
  7013. rect.bottom = (int) ((float)_sapp.window_height * _sapp.win32.dpi.window_scale);
  7014. const bool use_default_width = 0 == _sapp.window_width;
  7015. const bool use_default_height = 0 == _sapp.window_height;
  7016. AdjustWindowRectEx(&rect, win_style, FALSE, win_ex_style);
  7017. const int win_width = rect.right - rect.left;
  7018. const int win_height = rect.bottom - rect.top;
  7019. _sapp.win32.in_create_window = true;
  7020. _sapp.win32.hwnd = CreateWindowExW(
  7021. win_ex_style, // dwExStyle
  7022. L"SOKOLAPP", // lpClassName
  7023. _sapp.window_title_wide, // lpWindowName
  7024. win_style, // dwStyle
  7025. CW_USEDEFAULT, // X
  7026. SW_HIDE, // Y (NOTE: CW_USEDEFAULT is not used for position here, but internally calls ShowWindow!
  7027. use_default_width ? CW_USEDEFAULT : win_width, // nWidth
  7028. use_default_height ? CW_USEDEFAULT : win_height, // nHeight (NOTE: if width is CW_USEDEFAULT, height is actually ignored)
  7029. NULL, // hWndParent
  7030. NULL, // hMenu
  7031. GetModuleHandle(NULL), // hInstance
  7032. NULL); // lParam
  7033. _sapp.win32.in_create_window = false;
  7034. _sapp.win32.dc = GetDC(_sapp.win32.hwnd);
  7035. _sapp.win32.hmonitor = MonitorFromWindow(_sapp.win32.hwnd, MONITOR_DEFAULTTONULL);
  7036. SOKOL_ASSERT(_sapp.win32.dc);
  7037. /* this will get the actual windowed-mode window size, if fullscreen
  7038. is requested, the set_fullscreen function will then capture the
  7039. current window rectangle, which then might be used later to
  7040. restore the window position when switching back to windowed
  7041. */
  7042. _sapp_win32_update_dimensions();
  7043. if (_sapp.fullscreen) {
  7044. _sapp_win32_set_fullscreen(_sapp.fullscreen, SWP_HIDEWINDOW);
  7045. _sapp_win32_update_dimensions();
  7046. }
  7047. ShowWindow(_sapp.win32.hwnd, SW_SHOW);
  7048. DragAcceptFiles(_sapp.win32.hwnd, 1);
  7049. }
  7050. _SOKOL_PRIVATE void _sapp_win32_destroy_window(void) {
  7051. DestroyWindow(_sapp.win32.hwnd); _sapp.win32.hwnd = 0;
  7052. UnregisterClassW(L"SOKOLAPP", GetModuleHandleW(NULL));
  7053. }
  7054. _SOKOL_PRIVATE void _sapp_win32_destroy_icons(void) {
  7055. if (_sapp.win32.big_icon) {
  7056. DestroyIcon(_sapp.win32.big_icon);
  7057. _sapp.win32.big_icon = 0;
  7058. }
  7059. if (_sapp.win32.small_icon) {
  7060. DestroyIcon(_sapp.win32.small_icon);
  7061. _sapp.win32.small_icon = 0;
  7062. }
  7063. }
  7064. _SOKOL_PRIVATE void _sapp_win32_init_console(void) {
  7065. if (_sapp.desc.win32_console_create || _sapp.desc.win32_console_attach) {
  7066. BOOL con_valid = FALSE;
  7067. if (_sapp.desc.win32_console_create) {
  7068. con_valid = AllocConsole();
  7069. }
  7070. else if (_sapp.desc.win32_console_attach) {
  7071. con_valid = AttachConsole(ATTACH_PARENT_PROCESS);
  7072. }
  7073. if (con_valid) {
  7074. FILE* res_fp = 0;
  7075. errno_t err;
  7076. err = freopen_s(&res_fp, "CON", "w", stdout);
  7077. (void)err;
  7078. err = freopen_s(&res_fp, "CON", "w", stderr);
  7079. (void)err;
  7080. }
  7081. }
  7082. if (_sapp.desc.win32_console_utf8) {
  7083. _sapp.win32.orig_codepage = GetConsoleOutputCP();
  7084. SetConsoleOutputCP(CP_UTF8);
  7085. }
  7086. }
  7087. _SOKOL_PRIVATE void _sapp_win32_restore_console(void) {
  7088. if (_sapp.desc.win32_console_utf8) {
  7089. SetConsoleOutputCP(_sapp.win32.orig_codepage);
  7090. }
  7091. }
  7092. _SOKOL_PRIVATE void _sapp_win32_init_dpi(void) {
  7093. DECLARE_HANDLE(DPI_AWARENESS_CONTEXT_T);
  7094. typedef BOOL(WINAPI * SETPROCESSDPIAWARE_T)(void);
  7095. typedef bool (WINAPI * SETPROCESSDPIAWARENESSCONTEXT_T)(DPI_AWARENESS_CONTEXT_T); // since Windows 10, version 1703
  7096. typedef HRESULT(WINAPI * SETPROCESSDPIAWARENESS_T)(PROCESS_DPI_AWARENESS);
  7097. typedef HRESULT(WINAPI * GETDPIFORMONITOR_T)(HMONITOR, MONITOR_DPI_TYPE, UINT*, UINT*);
  7098. SETPROCESSDPIAWARE_T fn_setprocessdpiaware = 0;
  7099. SETPROCESSDPIAWARENESS_T fn_setprocessdpiawareness = 0;
  7100. GETDPIFORMONITOR_T fn_getdpiformonitor = 0;
  7101. SETPROCESSDPIAWARENESSCONTEXT_T fn_setprocessdpiawarenesscontext =0;
  7102. HINSTANCE user32 = LoadLibraryA("user32.dll");
  7103. if (user32) {
  7104. fn_setprocessdpiaware = (SETPROCESSDPIAWARE_T)(void*) GetProcAddress(user32, "SetProcessDPIAware");
  7105. fn_setprocessdpiawarenesscontext = (SETPROCESSDPIAWARENESSCONTEXT_T)(void*) GetProcAddress(user32, "SetProcessDpiAwarenessContext");
  7106. }
  7107. HINSTANCE shcore = LoadLibraryA("shcore.dll");
  7108. if (shcore) {
  7109. fn_setprocessdpiawareness = (SETPROCESSDPIAWARENESS_T)(void*) GetProcAddress(shcore, "SetProcessDpiAwareness");
  7110. fn_getdpiformonitor = (GETDPIFORMONITOR_T)(void*) GetProcAddress(shcore, "GetDpiForMonitor");
  7111. }
  7112. /*
  7113. NOTE on SetProcessDpiAware() vs SetProcessDpiAwareness() vs SetProcessDpiAwarenessContext():
  7114. These are different attempts to get DPI handling on Windows right, from oldest
  7115. to newest. SetProcessDpiAwarenessContext() is required for the new
  7116. DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 method.
  7117. */
  7118. if (fn_setprocessdpiawareness) {
  7119. if (_sapp.desc.high_dpi) {
  7120. /* app requests HighDPI rendering, first try the Win10 Creator Update per-monitor-dpi awareness,
  7121. if that fails, fall back to system-dpi-awareness
  7122. */
  7123. _sapp.win32.dpi.aware = true;
  7124. DPI_AWARENESS_CONTEXT_T per_monitor_aware_v2 = (DPI_AWARENESS_CONTEXT_T)-4;
  7125. if (!(fn_setprocessdpiawarenesscontext && fn_setprocessdpiawarenesscontext(per_monitor_aware_v2))) {
  7126. // fallback to system-dpi-aware
  7127. fn_setprocessdpiawareness(PROCESS_SYSTEM_DPI_AWARE);
  7128. }
  7129. }
  7130. else {
  7131. /* if the app didn't request HighDPI rendering, let Windows do the upscaling */
  7132. _sapp.win32.dpi.aware = false;
  7133. fn_setprocessdpiawareness(PROCESS_DPI_UNAWARE);
  7134. }
  7135. }
  7136. else if (fn_setprocessdpiaware) {
  7137. // fallback for Windows 7
  7138. _sapp.win32.dpi.aware = true;
  7139. fn_setprocessdpiaware();
  7140. }
  7141. /* get dpi scale factor for main monitor */
  7142. if (fn_getdpiformonitor && _sapp.win32.dpi.aware) {
  7143. POINT pt = { 1, 1 };
  7144. HMONITOR hm = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
  7145. UINT dpix, dpiy;
  7146. HRESULT hr = fn_getdpiformonitor(hm, MDT_EFFECTIVE_DPI, &dpix, &dpiy);
  7147. _SOKOL_UNUSED(hr);
  7148. SOKOL_ASSERT(SUCCEEDED(hr));
  7149. /* clamp window scale to an integer factor */
  7150. _sapp.win32.dpi.window_scale = (float)dpix / 96.0f;
  7151. }
  7152. else {
  7153. _sapp.win32.dpi.window_scale = 1.0f;
  7154. }
  7155. if (_sapp.desc.high_dpi) {
  7156. _sapp.win32.dpi.content_scale = _sapp.win32.dpi.window_scale;
  7157. _sapp.win32.dpi.mouse_scale = 1.0f;
  7158. }
  7159. else {
  7160. _sapp.win32.dpi.content_scale = 1.0f;
  7161. _sapp.win32.dpi.mouse_scale = 1.0f / _sapp.win32.dpi.window_scale;
  7162. }
  7163. _sapp.dpi_scale = _sapp.win32.dpi.content_scale;
  7164. if (user32) {
  7165. FreeLibrary(user32);
  7166. }
  7167. if (shcore) {
  7168. FreeLibrary(shcore);
  7169. }
  7170. }
  7171. _SOKOL_PRIVATE bool _sapp_win32_set_clipboard_string(const char* str) {
  7172. SOKOL_ASSERT(str);
  7173. SOKOL_ASSERT(_sapp.win32.hwnd);
  7174. SOKOL_ASSERT(_sapp.clipboard.enabled && (_sapp.clipboard.buf_size > 0));
  7175. if (!OpenClipboard(_sapp.win32.hwnd)) {
  7176. return false;
  7177. }
  7178. HANDLE object = 0;
  7179. wchar_t* wchar_buf = 0;
  7180. const SIZE_T wchar_buf_size = (SIZE_T)_sapp.clipboard.buf_size * sizeof(wchar_t);
  7181. object = GlobalAlloc(GMEM_MOVEABLE, wchar_buf_size);
  7182. if (NULL == object) {
  7183. goto error;
  7184. }
  7185. wchar_buf = (wchar_t*) GlobalLock(object);
  7186. if (NULL == wchar_buf) {
  7187. goto error;
  7188. }
  7189. if (!_sapp_win32_utf8_to_wide(str, wchar_buf, (int)wchar_buf_size)) {
  7190. goto error;
  7191. }
  7192. GlobalUnlock(object);
  7193. wchar_buf = 0;
  7194. EmptyClipboard();
  7195. // NOTE: when successful, SetClipboardData() takes ownership of memory object!
  7196. if (NULL == SetClipboardData(CF_UNICODETEXT, object)) {
  7197. goto error;
  7198. }
  7199. CloseClipboard();
  7200. return true;
  7201. error:
  7202. if (wchar_buf) {
  7203. GlobalUnlock(object);
  7204. }
  7205. if (object) {
  7206. GlobalFree(object);
  7207. }
  7208. CloseClipboard();
  7209. return false;
  7210. }
  7211. _SOKOL_PRIVATE const char* _sapp_win32_get_clipboard_string(void) {
  7212. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  7213. SOKOL_ASSERT(_sapp.win32.hwnd);
  7214. if (!OpenClipboard(_sapp.win32.hwnd)) {
  7215. /* silently ignore any errors and just return the current
  7216. content of the local clipboard buffer
  7217. */
  7218. return _sapp.clipboard.buffer;
  7219. }
  7220. HANDLE object = GetClipboardData(CF_UNICODETEXT);
  7221. if (!object) {
  7222. CloseClipboard();
  7223. return _sapp.clipboard.buffer;
  7224. }
  7225. const wchar_t* wchar_buf = (const wchar_t*) GlobalLock(object);
  7226. if (!wchar_buf) {
  7227. CloseClipboard();
  7228. return _sapp.clipboard.buffer;
  7229. }
  7230. if (!_sapp_win32_wide_to_utf8(wchar_buf, _sapp.clipboard.buffer, _sapp.clipboard.buf_size)) {
  7231. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  7232. }
  7233. GlobalUnlock(object);
  7234. CloseClipboard();
  7235. return _sapp.clipboard.buffer;
  7236. }
  7237. _SOKOL_PRIVATE void _sapp_win32_update_window_title(void) {
  7238. _sapp_win32_utf8_to_wide(_sapp.window_title, _sapp.window_title_wide, sizeof(_sapp.window_title_wide));
  7239. SetWindowTextW(_sapp.win32.hwnd, _sapp.window_title_wide);
  7240. }
  7241. _SOKOL_PRIVATE HICON _sapp_win32_create_icon_from_image(const sapp_image_desc* desc) {
  7242. BITMAPV5HEADER bi;
  7243. _sapp_clear(&bi, sizeof(bi));
  7244. bi.bV5Size = sizeof(bi);
  7245. bi.bV5Width = desc->width;
  7246. bi.bV5Height = -desc->height; // NOTE the '-' here to indicate that origin is top-left
  7247. bi.bV5Planes = 1;
  7248. bi.bV5BitCount = 32;
  7249. bi.bV5Compression = BI_BITFIELDS;
  7250. bi.bV5RedMask = 0x00FF0000;
  7251. bi.bV5GreenMask = 0x0000FF00;
  7252. bi.bV5BlueMask = 0x000000FF;
  7253. bi.bV5AlphaMask = 0xFF000000;
  7254. uint8_t* target = 0;
  7255. const uint8_t* source = (const uint8_t*)desc->pixels.ptr;
  7256. HDC dc = GetDC(NULL);
  7257. HBITMAP color = CreateDIBSection(dc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, (void**)&target, NULL, (DWORD)0);
  7258. ReleaseDC(NULL, dc);
  7259. if (0 == color) {
  7260. return NULL;
  7261. }
  7262. SOKOL_ASSERT(target);
  7263. HBITMAP mask = CreateBitmap(desc->width, desc->height, 1, 1, NULL);
  7264. if (0 == mask) {
  7265. DeleteObject(color);
  7266. return NULL;
  7267. }
  7268. for (int i = 0; i < (desc->width*desc->height); i++) {
  7269. target[0] = source[2];
  7270. target[1] = source[1];
  7271. target[2] = source[0];
  7272. target[3] = source[3];
  7273. target += 4;
  7274. source += 4;
  7275. }
  7276. ICONINFO icon_info;
  7277. _sapp_clear(&icon_info, sizeof(icon_info));
  7278. icon_info.fIcon = true;
  7279. icon_info.xHotspot = 0;
  7280. icon_info.yHotspot = 0;
  7281. icon_info.hbmMask = mask;
  7282. icon_info.hbmColor = color;
  7283. HICON icon_handle = CreateIconIndirect(&icon_info);
  7284. DeleteObject(color);
  7285. DeleteObject(mask);
  7286. return icon_handle;
  7287. }
  7288. _SOKOL_PRIVATE void _sapp_win32_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  7289. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  7290. int big_img_index = _sapp_image_bestmatch(icon_desc->images, num_images, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
  7291. int sml_img_index = _sapp_image_bestmatch(icon_desc->images, num_images, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
  7292. HICON big_icon = _sapp_win32_create_icon_from_image(&icon_desc->images[big_img_index]);
  7293. HICON sml_icon = _sapp_win32_create_icon_from_image(&icon_desc->images[sml_img_index]);
  7294. // if icon creation or lookup has failed for some reason, leave the currently set icon untouched
  7295. if (0 != big_icon) {
  7296. SendMessage(_sapp.win32.hwnd, WM_SETICON, ICON_BIG, (LPARAM) big_icon);
  7297. if (0 != _sapp.win32.big_icon) {
  7298. DestroyIcon(_sapp.win32.big_icon);
  7299. }
  7300. _sapp.win32.big_icon = big_icon;
  7301. }
  7302. if (0 != sml_icon) {
  7303. SendMessage(_sapp.win32.hwnd, WM_SETICON, ICON_SMALL, (LPARAM) sml_icon);
  7304. if (0 != _sapp.win32.small_icon) {
  7305. DestroyIcon(_sapp.win32.small_icon);
  7306. }
  7307. _sapp.win32.small_icon = sml_icon;
  7308. }
  7309. }
  7310. /* don't laugh, but this seems to be the easiest and most robust
  7311. way to check if we're running on Win10
  7312. From: https://github.com/videolan/vlc/blob/232fb13b0d6110c4d1b683cde24cf9a7f2c5c2ea/modules/video_output/win32/d3d11_swapchain.c#L263
  7313. */
  7314. _SOKOL_PRIVATE bool _sapp_win32_is_win10_or_greater(void) {
  7315. HMODULE h = GetModuleHandleW(L"kernel32.dll");
  7316. if (NULL != h) {
  7317. return (NULL != GetProcAddress(h, "GetSystemCpuSetInformation"));
  7318. }
  7319. else {
  7320. return false;
  7321. }
  7322. }
  7323. _SOKOL_PRIVATE void _sapp_win32_run(const sapp_desc* desc) {
  7324. _sapp_init_state(desc);
  7325. _sapp_win32_init_console();
  7326. _sapp.win32.is_win10_or_greater = _sapp_win32_is_win10_or_greater();
  7327. _sapp_win32_init_keytable();
  7328. _sapp_win32_utf8_to_wide(_sapp.window_title, _sapp.window_title_wide, sizeof(_sapp.window_title_wide));
  7329. _sapp_win32_init_dpi();
  7330. _sapp_win32_init_cursors();
  7331. _sapp_win32_create_window();
  7332. sapp_set_icon(&desc->icon);
  7333. #if defined(SOKOL_D3D11)
  7334. _sapp_d3d11_create_device_and_swapchain();
  7335. _sapp_d3d11_create_default_render_target();
  7336. #endif
  7337. #if defined(SOKOL_GLCORE)
  7338. _sapp_wgl_init();
  7339. _sapp_wgl_load_extensions();
  7340. _sapp_wgl_create_context();
  7341. #endif
  7342. _sapp.valid = true;
  7343. bool done = false;
  7344. while (!(done || _sapp.quit_ordered)) {
  7345. _sapp_win32_timing_measure();
  7346. MSG msg;
  7347. while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
  7348. if (WM_QUIT == msg.message) {
  7349. done = true;
  7350. continue;
  7351. }
  7352. else {
  7353. TranslateMessage(&msg);
  7354. DispatchMessageW(&msg);
  7355. }
  7356. }
  7357. _sapp_frame();
  7358. #if defined(SOKOL_D3D11)
  7359. _sapp_d3d11_present(false);
  7360. if (IsIconic(_sapp.win32.hwnd)) {
  7361. Sleep((DWORD)(16 * _sapp.swap_interval));
  7362. }
  7363. #endif
  7364. #if defined(SOKOL_GLCORE)
  7365. _sapp_wgl_swap_buffers();
  7366. #endif
  7367. /* check for window resized, this cannot happen in WM_SIZE as it explodes memory usage */
  7368. if (_sapp_win32_update_dimensions()) {
  7369. #if defined(SOKOL_D3D11)
  7370. _sapp_d3d11_resize_default_render_target();
  7371. #endif
  7372. _sapp_win32_app_event(SAPP_EVENTTYPE_RESIZED);
  7373. }
  7374. /* check if the window monitor has changed, need to reset timing because
  7375. the new monitor might have a different refresh rate
  7376. */
  7377. if (_sapp_win32_update_monitor()) {
  7378. _sapp_timing_reset(&_sapp.timing);
  7379. }
  7380. if (_sapp.quit_requested) {
  7381. PostMessage(_sapp.win32.hwnd, WM_CLOSE, 0, 0);
  7382. }
  7383. }
  7384. _sapp_call_cleanup();
  7385. #if defined(SOKOL_D3D11)
  7386. _sapp_d3d11_destroy_default_render_target();
  7387. _sapp_d3d11_destroy_device_and_swapchain();
  7388. #elif defined(SOKOL_GLCORE)
  7389. _sapp_wgl_destroy_context();
  7390. _sapp_wgl_shutdown();
  7391. #endif
  7392. _sapp_win32_destroy_window();
  7393. _sapp_win32_destroy_icons();
  7394. _sapp_win32_restore_console();
  7395. _sapp_discard_state();
  7396. }
  7397. _SOKOL_PRIVATE char** _sapp_win32_command_line_to_utf8_argv(LPWSTR w_command_line, int* o_argc) {
  7398. int argc = 0;
  7399. char** argv = 0;
  7400. char* args;
  7401. LPWSTR* w_argv = CommandLineToArgvW(w_command_line, &argc);
  7402. if (w_argv == NULL) {
  7403. // FIXME: chicken egg problem, can't report errors before sokol_main() is called!
  7404. } else {
  7405. size_t size = wcslen(w_command_line) * 4;
  7406. argv = (char**) _sapp_malloc_clear(((size_t)argc + 1) * sizeof(char*) + size);
  7407. SOKOL_ASSERT(argv);
  7408. args = (char*) &argv[argc + 1];
  7409. int n;
  7410. for (int i = 0; i < argc; ++i) {
  7411. n = WideCharToMultiByte(CP_UTF8, 0, w_argv[i], -1, args, (int)size, NULL, NULL);
  7412. if (n == 0) {
  7413. // FIXME: chicken egg problem, can't report errors before sokol_main() is called!
  7414. break;
  7415. }
  7416. argv[i] = args;
  7417. size -= (size_t)n;
  7418. args += n;
  7419. }
  7420. LocalFree(w_argv);
  7421. }
  7422. *o_argc = argc;
  7423. return argv;
  7424. }
  7425. #if !defined(SOKOL_NO_ENTRY)
  7426. #if defined(SOKOL_WIN32_FORCE_MAIN)
  7427. int main(int argc, char* argv[]) {
  7428. sapp_desc desc = sokol_main(argc, argv);
  7429. _sapp_win32_run(&desc);
  7430. return 0;
  7431. }
  7432. #endif /* SOKOL_WIN32_FORCE_MAIN */
  7433. #if defined(SOKOL_WIN32_FORCE_WINMAIN) || !defined(SOKOL_WIN32_FORCE_MAIN)
  7434. int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) {
  7435. _SOKOL_UNUSED(hInstance);
  7436. _SOKOL_UNUSED(hPrevInstance);
  7437. _SOKOL_UNUSED(lpCmdLine);
  7438. _SOKOL_UNUSED(nCmdShow);
  7439. int argc_utf8 = 0;
  7440. char** argv_utf8 = _sapp_win32_command_line_to_utf8_argv(GetCommandLineW(), &argc_utf8);
  7441. sapp_desc desc = sokol_main(argc_utf8, argv_utf8);
  7442. _sapp_win32_run(&desc);
  7443. _sapp_free(argv_utf8);
  7444. return 0;
  7445. }
  7446. #endif /* SOKOL_WIN32_FORCE_WINMAIN */
  7447. #endif /* SOKOL_NO_ENTRY */
  7448. #ifdef _MSC_VER
  7449. #pragma warning(pop)
  7450. #endif
  7451. #endif /* _SAPP_WIN32 */
  7452. // █████ ███ ██ ██████ ██████ ██████ ██ ██████
  7453. // ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7454. // ███████ ██ ██ ██ ██ ██ ██████ ██ ██ ██ ██ ██
  7455. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  7456. // ██ ██ ██ ████ ██████ ██ ██ ██████ ██ ██████
  7457. //
  7458. // >>android
  7459. #if defined(_SAPP_ANDROID)
  7460. /* android loop thread */
  7461. _SOKOL_PRIVATE bool _sapp_android_init_egl(void) {
  7462. SOKOL_ASSERT(_sapp.android.display == EGL_NO_DISPLAY);
  7463. SOKOL_ASSERT(_sapp.android.context == EGL_NO_CONTEXT);
  7464. EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
  7465. if (display == EGL_NO_DISPLAY) {
  7466. return false;
  7467. }
  7468. if (eglInitialize(display, NULL, NULL) == EGL_FALSE) {
  7469. return false;
  7470. }
  7471. EGLint alpha_size = _sapp.desc.alpha ? 8 : 0;
  7472. const EGLint cfg_attributes[] = {
  7473. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  7474. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  7475. EGL_RED_SIZE, 8,
  7476. EGL_GREEN_SIZE, 8,
  7477. EGL_BLUE_SIZE, 8,
  7478. EGL_ALPHA_SIZE, alpha_size,
  7479. EGL_DEPTH_SIZE, 16,
  7480. EGL_STENCIL_SIZE, 0,
  7481. EGL_NONE,
  7482. };
  7483. EGLConfig available_cfgs[32];
  7484. EGLint cfg_count;
  7485. eglChooseConfig(display, cfg_attributes, available_cfgs, 32, &cfg_count);
  7486. SOKOL_ASSERT(cfg_count > 0);
  7487. SOKOL_ASSERT(cfg_count <= 32);
  7488. /* find config with 8-bit rgb buffer if available, ndk sample does not trust egl spec */
  7489. EGLConfig config;
  7490. bool exact_cfg_found = false;
  7491. for (int i = 0; i < cfg_count; ++i) {
  7492. EGLConfig c = available_cfgs[i];
  7493. EGLint r, g, b, a, d;
  7494. if (eglGetConfigAttrib(display, c, EGL_RED_SIZE, &r) == EGL_TRUE &&
  7495. eglGetConfigAttrib(display, c, EGL_GREEN_SIZE, &g) == EGL_TRUE &&
  7496. eglGetConfigAttrib(display, c, EGL_BLUE_SIZE, &b) == EGL_TRUE &&
  7497. eglGetConfigAttrib(display, c, EGL_ALPHA_SIZE, &a) == EGL_TRUE &&
  7498. eglGetConfigAttrib(display, c, EGL_DEPTH_SIZE, &d) == EGL_TRUE &&
  7499. r == 8 && g == 8 && b == 8 && (alpha_size == 0 || a == alpha_size) && d == 16) {
  7500. exact_cfg_found = true;
  7501. config = c;
  7502. break;
  7503. }
  7504. }
  7505. if (!exact_cfg_found) {
  7506. config = available_cfgs[0];
  7507. }
  7508. EGLint ctx_attributes[] = {
  7509. EGL_CONTEXT_CLIENT_VERSION, 3,
  7510. EGL_NONE,
  7511. };
  7512. EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, ctx_attributes);
  7513. if (context == EGL_NO_CONTEXT) {
  7514. return false;
  7515. }
  7516. _sapp.android.config = config;
  7517. _sapp.android.display = display;
  7518. _sapp.android.context = context;
  7519. return true;
  7520. }
  7521. _SOKOL_PRIVATE void _sapp_android_cleanup_egl(void) {
  7522. if (_sapp.android.display != EGL_NO_DISPLAY) {
  7523. eglMakeCurrent(_sapp.android.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  7524. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7525. eglDestroySurface(_sapp.android.display, _sapp.android.surface);
  7526. _sapp.android.surface = EGL_NO_SURFACE;
  7527. }
  7528. if (_sapp.android.context != EGL_NO_CONTEXT) {
  7529. eglDestroyContext(_sapp.android.display, _sapp.android.context);
  7530. _sapp.android.context = EGL_NO_CONTEXT;
  7531. }
  7532. eglTerminate(_sapp.android.display);
  7533. _sapp.android.display = EGL_NO_DISPLAY;
  7534. }
  7535. }
  7536. _SOKOL_PRIVATE bool _sapp_android_init_egl_surface(ANativeWindow* window) {
  7537. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7538. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7539. SOKOL_ASSERT(_sapp.android.surface == EGL_NO_SURFACE);
  7540. SOKOL_ASSERT(window);
  7541. /* TODO: set window flags */
  7542. /* ANativeActivity_setWindowFlags(activity, AWINDOW_FLAG_KEEP_SCREEN_ON, 0); */
  7543. /* create egl surface and make it current */
  7544. EGLSurface surface = eglCreateWindowSurface(_sapp.android.display, _sapp.android.config, window, NULL);
  7545. if (surface == EGL_NO_SURFACE) {
  7546. return false;
  7547. }
  7548. if (eglMakeCurrent(_sapp.android.display, surface, surface, _sapp.android.context) == EGL_FALSE) {
  7549. return false;
  7550. }
  7551. _sapp.android.surface = surface;
  7552. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  7553. return true;
  7554. }
  7555. _SOKOL_PRIVATE void _sapp_android_cleanup_egl_surface(void) {
  7556. if (_sapp.android.display == EGL_NO_DISPLAY) {
  7557. return;
  7558. }
  7559. eglMakeCurrent(_sapp.android.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  7560. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7561. eglDestroySurface(_sapp.android.display, _sapp.android.surface);
  7562. _sapp.android.surface = EGL_NO_SURFACE;
  7563. }
  7564. }
  7565. _SOKOL_PRIVATE void _sapp_android_app_event(sapp_event_type type) {
  7566. if (_sapp_events_enabled()) {
  7567. _sapp_init_event(type);
  7568. _sapp_call_event(&_sapp.event);
  7569. }
  7570. }
  7571. _SOKOL_PRIVATE void _sapp_android_update_dimensions(ANativeWindow* window, bool force_update) {
  7572. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7573. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7574. SOKOL_ASSERT(_sapp.android.surface != EGL_NO_SURFACE);
  7575. SOKOL_ASSERT(window);
  7576. const int32_t win_w = ANativeWindow_getWidth(window);
  7577. const int32_t win_h = ANativeWindow_getHeight(window);
  7578. SOKOL_ASSERT(win_w >= 0 && win_h >= 0);
  7579. const bool win_changed = (win_w != _sapp.window_width) || (win_h != _sapp.window_height);
  7580. _sapp.window_width = win_w;
  7581. _sapp.window_height = win_h;
  7582. if (win_changed || force_update) {
  7583. if (!_sapp.desc.high_dpi) {
  7584. const int32_t buf_w = win_w / 2;
  7585. const int32_t buf_h = win_h / 2;
  7586. EGLint format;
  7587. EGLBoolean egl_result = eglGetConfigAttrib(_sapp.android.display, _sapp.android.config, EGL_NATIVE_VISUAL_ID, &format);
  7588. SOKOL_ASSERT(egl_result == EGL_TRUE); _SOKOL_UNUSED(egl_result);
  7589. /* NOTE: calling ANativeWindow_setBuffersGeometry() with the same dimensions
  7590. as the ANativeWindow size results in weird display artefacts, that's
  7591. why it's only called when the buffer geometry is different from
  7592. the window size
  7593. */
  7594. int32_t result = ANativeWindow_setBuffersGeometry(window, buf_w, buf_h, format);
  7595. SOKOL_ASSERT(result == 0); _SOKOL_UNUSED(result);
  7596. }
  7597. }
  7598. /* query surface size */
  7599. EGLint fb_w, fb_h;
  7600. EGLBoolean egl_result_w = eglQuerySurface(_sapp.android.display, _sapp.android.surface, EGL_WIDTH, &fb_w);
  7601. EGLBoolean egl_result_h = eglQuerySurface(_sapp.android.display, _sapp.android.surface, EGL_HEIGHT, &fb_h);
  7602. SOKOL_ASSERT(egl_result_w == EGL_TRUE); _SOKOL_UNUSED(egl_result_w);
  7603. SOKOL_ASSERT(egl_result_h == EGL_TRUE); _SOKOL_UNUSED(egl_result_h);
  7604. const bool fb_changed = (fb_w != _sapp.framebuffer_width) || (fb_h != _sapp.framebuffer_height);
  7605. _sapp.framebuffer_width = fb_w;
  7606. _sapp.framebuffer_height = fb_h;
  7607. _sapp.dpi_scale = (float)_sapp.framebuffer_width / (float)_sapp.window_width;
  7608. if (win_changed || fb_changed || force_update) {
  7609. if (!_sapp.first_frame) {
  7610. _sapp_android_app_event(SAPP_EVENTTYPE_RESIZED);
  7611. }
  7612. }
  7613. }
  7614. _SOKOL_PRIVATE void _sapp_android_cleanup(void) {
  7615. if (_sapp.android.surface != EGL_NO_SURFACE) {
  7616. /* egl context is bound, cleanup gracefully */
  7617. if (_sapp.init_called && !_sapp.cleanup_called) {
  7618. _sapp_call_cleanup();
  7619. }
  7620. }
  7621. /* always try to cleanup by destroying egl context */
  7622. _sapp_android_cleanup_egl();
  7623. }
  7624. _SOKOL_PRIVATE void _sapp_android_shutdown(void) {
  7625. /* try to cleanup while we still have a surface and can call cleanup_cb() */
  7626. _sapp_android_cleanup();
  7627. /* request exit */
  7628. ANativeActivity_finish(_sapp.android.activity);
  7629. }
  7630. _SOKOL_PRIVATE void _sapp_android_frame(void) {
  7631. SOKOL_ASSERT(_sapp.android.display != EGL_NO_DISPLAY);
  7632. SOKOL_ASSERT(_sapp.android.context != EGL_NO_CONTEXT);
  7633. SOKOL_ASSERT(_sapp.android.surface != EGL_NO_SURFACE);
  7634. _sapp_timing_measure(&_sapp.timing);
  7635. _sapp_android_update_dimensions(_sapp.android.current.window, false);
  7636. _sapp_frame();
  7637. eglSwapBuffers(_sapp.android.display, _sapp.android.surface);
  7638. }
  7639. _SOKOL_PRIVATE bool _sapp_android_touch_event(const AInputEvent* e) {
  7640. if (AInputEvent_getType(e) != AINPUT_EVENT_TYPE_MOTION) {
  7641. return false;
  7642. }
  7643. if (!_sapp_events_enabled()) {
  7644. return false;
  7645. }
  7646. int32_t action_idx = AMotionEvent_getAction(e);
  7647. int32_t action = action_idx & AMOTION_EVENT_ACTION_MASK;
  7648. sapp_event_type type = SAPP_EVENTTYPE_INVALID;
  7649. switch (action) {
  7650. case AMOTION_EVENT_ACTION_DOWN:
  7651. case AMOTION_EVENT_ACTION_POINTER_DOWN:
  7652. type = SAPP_EVENTTYPE_TOUCHES_BEGAN;
  7653. break;
  7654. case AMOTION_EVENT_ACTION_MOVE:
  7655. type = SAPP_EVENTTYPE_TOUCHES_MOVED;
  7656. break;
  7657. case AMOTION_EVENT_ACTION_UP:
  7658. case AMOTION_EVENT_ACTION_POINTER_UP:
  7659. type = SAPP_EVENTTYPE_TOUCHES_ENDED;
  7660. break;
  7661. case AMOTION_EVENT_ACTION_CANCEL:
  7662. type = SAPP_EVENTTYPE_TOUCHES_CANCELLED;
  7663. break;
  7664. default:
  7665. break;
  7666. }
  7667. if (type == SAPP_EVENTTYPE_INVALID) {
  7668. return false;
  7669. }
  7670. int32_t idx = action_idx >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
  7671. _sapp_init_event(type);
  7672. _sapp.event.num_touches = (int)AMotionEvent_getPointerCount(e);
  7673. if (_sapp.event.num_touches > SAPP_MAX_TOUCHPOINTS) {
  7674. _sapp.event.num_touches = SAPP_MAX_TOUCHPOINTS;
  7675. }
  7676. for (int32_t i = 0; i < _sapp.event.num_touches; i++) {
  7677. sapp_touchpoint* dst = &_sapp.event.touches[i];
  7678. dst->identifier = (uintptr_t)AMotionEvent_getPointerId(e, (size_t)i);
  7679. dst->pos_x = (AMotionEvent_getX(e, (size_t)i) / _sapp.window_width) * _sapp.framebuffer_width;
  7680. dst->pos_y = (AMotionEvent_getY(e, (size_t)i) / _sapp.window_height) * _sapp.framebuffer_height;
  7681. dst->android_tooltype = (sapp_android_tooltype) AMotionEvent_getToolType(e, (size_t)i);
  7682. if (action == AMOTION_EVENT_ACTION_POINTER_DOWN ||
  7683. action == AMOTION_EVENT_ACTION_POINTER_UP) {
  7684. dst->changed = (i == idx);
  7685. } else {
  7686. dst->changed = true;
  7687. }
  7688. }
  7689. _sapp_call_event(&_sapp.event);
  7690. return true;
  7691. }
  7692. _SOKOL_PRIVATE bool _sapp_android_key_event(const AInputEvent* e) {
  7693. if (AInputEvent_getType(e) != AINPUT_EVENT_TYPE_KEY) {
  7694. return false;
  7695. }
  7696. if (AKeyEvent_getKeyCode(e) == AKEYCODE_BACK) {
  7697. /* FIXME: this should be hooked into a "really quit?" mechanism
  7698. so the app can ask the user for confirmation, this is currently
  7699. generally missing in sokol_app.h
  7700. */
  7701. _sapp_android_shutdown();
  7702. return true;
  7703. }
  7704. return false;
  7705. }
  7706. _SOKOL_PRIVATE int _sapp_android_input_cb(int fd, int events, void* data) {
  7707. _SOKOL_UNUSED(fd);
  7708. _SOKOL_UNUSED(data);
  7709. if ((events & ALOOPER_EVENT_INPUT) == 0) {
  7710. _SAPP_ERROR(ANDROID_UNSUPPORTED_INPUT_EVENT_INPUT_CB);
  7711. return 1;
  7712. }
  7713. SOKOL_ASSERT(_sapp.android.current.input);
  7714. AInputEvent* event = NULL;
  7715. while (AInputQueue_getEvent(_sapp.android.current.input, &event) >= 0) {
  7716. if (AInputQueue_preDispatchEvent(_sapp.android.current.input, event) != 0) {
  7717. continue;
  7718. }
  7719. int32_t handled = 0;
  7720. if (_sapp_android_touch_event(event) || _sapp_android_key_event(event)) {
  7721. handled = 1;
  7722. }
  7723. AInputQueue_finishEvent(_sapp.android.current.input, event, handled);
  7724. }
  7725. return 1;
  7726. }
  7727. _SOKOL_PRIVATE int _sapp_android_main_cb(int fd, int events, void* data) {
  7728. _SOKOL_UNUSED(data);
  7729. if ((events & ALOOPER_EVENT_INPUT) == 0) {
  7730. _SAPP_ERROR(ANDROID_UNSUPPORTED_INPUT_EVENT_MAIN_CB);
  7731. return 1;
  7732. }
  7733. _sapp_android_msg_t msg;
  7734. if (read(fd, &msg, sizeof(msg)) != sizeof(msg)) {
  7735. _SAPP_ERROR(ANDROID_READ_MSG_FAILED);
  7736. return 1;
  7737. }
  7738. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7739. switch (msg) {
  7740. case _SOKOL_ANDROID_MSG_CREATE:
  7741. {
  7742. _SAPP_INFO(ANDROID_MSG_CREATE);
  7743. SOKOL_ASSERT(!_sapp.valid);
  7744. bool result = _sapp_android_init_egl();
  7745. SOKOL_ASSERT(result); _SOKOL_UNUSED(result);
  7746. _sapp.valid = true;
  7747. _sapp.android.has_created = true;
  7748. }
  7749. break;
  7750. case _SOKOL_ANDROID_MSG_RESUME:
  7751. _SAPP_INFO(ANDROID_MSG_RESUME);
  7752. _sapp.android.has_resumed = true;
  7753. _sapp_android_app_event(SAPP_EVENTTYPE_RESUMED);
  7754. break;
  7755. case _SOKOL_ANDROID_MSG_PAUSE:
  7756. _SAPP_INFO(ANDROID_MSG_PAUSE);
  7757. _sapp.android.has_resumed = false;
  7758. _sapp_android_app_event(SAPP_EVENTTYPE_SUSPENDED);
  7759. break;
  7760. case _SOKOL_ANDROID_MSG_FOCUS:
  7761. _SAPP_INFO(ANDROID_MSG_FOCUS);
  7762. _sapp.android.has_focus = true;
  7763. break;
  7764. case _SOKOL_ANDROID_MSG_NO_FOCUS:
  7765. _SAPP_INFO(ANDROID_MSG_NO_FOCUS);
  7766. _sapp.android.has_focus = false;
  7767. break;
  7768. case _SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW:
  7769. _SAPP_INFO(ANDROID_MSG_SET_NATIVE_WINDOW);
  7770. if (_sapp.android.current.window != _sapp.android.pending.window) {
  7771. if (_sapp.android.current.window != NULL) {
  7772. _sapp_android_cleanup_egl_surface();
  7773. }
  7774. if (_sapp.android.pending.window != NULL) {
  7775. if (_sapp_android_init_egl_surface(_sapp.android.pending.window)) {
  7776. _sapp_android_update_dimensions(_sapp.android.pending.window, true);
  7777. } else {
  7778. _sapp_android_shutdown();
  7779. }
  7780. }
  7781. }
  7782. _sapp.android.current.window = _sapp.android.pending.window;
  7783. break;
  7784. case _SOKOL_ANDROID_MSG_SET_INPUT_QUEUE:
  7785. _SAPP_INFO(ANDROID_MSG_SET_INPUT_QUEUE);
  7786. if (_sapp.android.current.input != _sapp.android.pending.input) {
  7787. if (_sapp.android.current.input != NULL) {
  7788. AInputQueue_detachLooper(_sapp.android.current.input);
  7789. }
  7790. if (_sapp.android.pending.input != NULL) {
  7791. AInputQueue_attachLooper(
  7792. _sapp.android.pending.input,
  7793. _sapp.android.looper,
  7794. ALOOPER_POLL_CALLBACK,
  7795. _sapp_android_input_cb,
  7796. NULL); /* data */
  7797. }
  7798. }
  7799. _sapp.android.current.input = _sapp.android.pending.input;
  7800. break;
  7801. case _SOKOL_ANDROID_MSG_DESTROY:
  7802. _SAPP_INFO(ANDROID_MSG_DESTROY);
  7803. _sapp_android_cleanup();
  7804. _sapp.valid = false;
  7805. _sapp.android.is_thread_stopping = true;
  7806. break;
  7807. default:
  7808. _SAPP_WARN(ANDROID_UNKNOWN_MSG);
  7809. break;
  7810. }
  7811. pthread_cond_broadcast(&_sapp.android.pt.cond); /* signal "received" */
  7812. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7813. return 1;
  7814. }
  7815. _SOKOL_PRIVATE bool _sapp_android_should_update(void) {
  7816. bool is_in_front = _sapp.android.has_resumed && _sapp.android.has_focus;
  7817. bool has_surface = _sapp.android.surface != EGL_NO_SURFACE;
  7818. return is_in_front && has_surface;
  7819. }
  7820. _SOKOL_PRIVATE void _sapp_android_show_keyboard(bool shown) {
  7821. SOKOL_ASSERT(_sapp.valid);
  7822. /* This seems to be broken in the NDK, but there is (a very cumbersome) workaround... */
  7823. if (shown) {
  7824. ANativeActivity_showSoftInput(_sapp.android.activity, ANATIVEACTIVITY_SHOW_SOFT_INPUT_FORCED);
  7825. } else {
  7826. ANativeActivity_hideSoftInput(_sapp.android.activity, ANATIVEACTIVITY_HIDE_SOFT_INPUT_NOT_ALWAYS);
  7827. }
  7828. }
  7829. _SOKOL_PRIVATE void* _sapp_android_loop(void* arg) {
  7830. _SOKOL_UNUSED(arg);
  7831. _SAPP_INFO(ANDROID_LOOP_THREAD_STARTED);
  7832. _sapp.android.looper = ALooper_prepare(0 /* or ALOOPER_PREPARE_ALLOW_NON_CALLBACKS*/);
  7833. ALooper_addFd(_sapp.android.looper,
  7834. _sapp.android.pt.read_from_main_fd,
  7835. ALOOPER_POLL_CALLBACK,
  7836. ALOOPER_EVENT_INPUT,
  7837. _sapp_android_main_cb,
  7838. NULL); /* data */
  7839. /* signal start to main thread */
  7840. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7841. _sapp.android.is_thread_started = true;
  7842. pthread_cond_broadcast(&_sapp.android.pt.cond);
  7843. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7844. /* main loop */
  7845. while (!_sapp.android.is_thread_stopping) {
  7846. /* sokol frame */
  7847. if (_sapp_android_should_update()) {
  7848. _sapp_android_frame();
  7849. }
  7850. /* process all events (or stop early if app is requested to quit) */
  7851. bool process_events = true;
  7852. while (process_events && !_sapp.android.is_thread_stopping) {
  7853. bool block_until_event = !_sapp.android.is_thread_stopping && !_sapp_android_should_update();
  7854. process_events = ALooper_pollOnce(block_until_event ? -1 : 0, NULL, NULL, NULL) == ALOOPER_POLL_CALLBACK;
  7855. }
  7856. }
  7857. /* cleanup thread */
  7858. if (_sapp.android.current.input != NULL) {
  7859. AInputQueue_detachLooper(_sapp.android.current.input);
  7860. }
  7861. /* the following causes heap corruption on exit, why??
  7862. ALooper_removeFd(_sapp.android.looper, _sapp.android.pt.read_from_main_fd);
  7863. ALooper_release(_sapp.android.looper);*/
  7864. /* signal "destroyed" */
  7865. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7866. _sapp.android.is_thread_stopped = true;
  7867. pthread_cond_broadcast(&_sapp.android.pt.cond);
  7868. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7869. _SAPP_INFO(ANDROID_LOOP_THREAD_DONE);
  7870. return NULL;
  7871. }
  7872. /* android main/ui thread */
  7873. _SOKOL_PRIVATE void _sapp_android_msg(_sapp_android_msg_t msg) {
  7874. if (write(_sapp.android.pt.write_from_main_fd, &msg, sizeof(msg)) != sizeof(msg)) {
  7875. _SAPP_ERROR(ANDROID_WRITE_MSG_FAILED);
  7876. }
  7877. }
  7878. _SOKOL_PRIVATE void _sapp_android_on_start(ANativeActivity* activity) {
  7879. _SOKOL_UNUSED(activity);
  7880. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSTART);
  7881. }
  7882. _SOKOL_PRIVATE void _sapp_android_on_resume(ANativeActivity* activity) {
  7883. _SOKOL_UNUSED(activity);
  7884. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONRESUME);
  7885. _sapp_android_msg(_SOKOL_ANDROID_MSG_RESUME);
  7886. }
  7887. _SOKOL_PRIVATE void* _sapp_android_on_save_instance_state(ANativeActivity* activity, size_t* out_size) {
  7888. _SOKOL_UNUSED(activity);
  7889. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSAVEINSTANCESTATE);
  7890. *out_size = 0;
  7891. return NULL;
  7892. }
  7893. _SOKOL_PRIVATE void _sapp_android_on_window_focus_changed(ANativeActivity* activity, int has_focus) {
  7894. _SOKOL_UNUSED(activity);
  7895. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONWINDOWFOCUSCHANGED);
  7896. if (has_focus) {
  7897. _sapp_android_msg(_SOKOL_ANDROID_MSG_FOCUS);
  7898. } else {
  7899. _sapp_android_msg(_SOKOL_ANDROID_MSG_NO_FOCUS);
  7900. }
  7901. }
  7902. _SOKOL_PRIVATE void _sapp_android_on_pause(ANativeActivity* activity) {
  7903. _SOKOL_UNUSED(activity);
  7904. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONPAUSE);
  7905. _sapp_android_msg(_SOKOL_ANDROID_MSG_PAUSE);
  7906. }
  7907. _SOKOL_PRIVATE void _sapp_android_on_stop(ANativeActivity* activity) {
  7908. _SOKOL_UNUSED(activity);
  7909. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONSTOP);
  7910. }
  7911. _SOKOL_PRIVATE void _sapp_android_msg_set_native_window(ANativeWindow* window) {
  7912. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7913. _sapp.android.pending.window = window;
  7914. _sapp_android_msg(_SOKOL_ANDROID_MSG_SET_NATIVE_WINDOW);
  7915. while (_sapp.android.current.window != window) {
  7916. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7917. }
  7918. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7919. }
  7920. _SOKOL_PRIVATE void _sapp_android_on_native_window_created(ANativeActivity* activity, ANativeWindow* window) {
  7921. _SOKOL_UNUSED(activity);
  7922. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWCREATED);
  7923. _sapp_android_msg_set_native_window(window);
  7924. }
  7925. _SOKOL_PRIVATE void _sapp_android_on_native_window_destroyed(ANativeActivity* activity, ANativeWindow* window) {
  7926. _SOKOL_UNUSED(activity);
  7927. _SOKOL_UNUSED(window);
  7928. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONNATIVEWINDOWDESTROYED);
  7929. _sapp_android_msg_set_native_window(NULL);
  7930. }
  7931. _SOKOL_PRIVATE void _sapp_android_msg_set_input_queue(AInputQueue* input) {
  7932. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7933. _sapp.android.pending.input = input;
  7934. _sapp_android_msg(_SOKOL_ANDROID_MSG_SET_INPUT_QUEUE);
  7935. while (_sapp.android.current.input != input) {
  7936. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7937. }
  7938. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7939. }
  7940. _SOKOL_PRIVATE void _sapp_android_on_input_queue_created(ANativeActivity* activity, AInputQueue* queue) {
  7941. _SOKOL_UNUSED(activity);
  7942. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUECREATED);
  7943. _sapp_android_msg_set_input_queue(queue);
  7944. }
  7945. _SOKOL_PRIVATE void _sapp_android_on_input_queue_destroyed(ANativeActivity* activity, AInputQueue* queue) {
  7946. _SOKOL_UNUSED(activity);
  7947. _SOKOL_UNUSED(queue);
  7948. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONINPUTQUEUEDESTROYED);
  7949. _sapp_android_msg_set_input_queue(NULL);
  7950. }
  7951. _SOKOL_PRIVATE void _sapp_android_on_config_changed(ANativeActivity* activity) {
  7952. _SOKOL_UNUSED(activity);
  7953. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONCONFIGURATIONCHANGED);
  7954. /* see android:configChanges in manifest */
  7955. }
  7956. _SOKOL_PRIVATE void _sapp_android_on_low_memory(ANativeActivity* activity) {
  7957. _SOKOL_UNUSED(activity);
  7958. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONLOWMEMORY);
  7959. }
  7960. _SOKOL_PRIVATE void _sapp_android_on_destroy(ANativeActivity* activity) {
  7961. /*
  7962. * For some reason even an empty app using nativeactivity.h will crash (WIN DEATH)
  7963. * on my device (Moto X 2nd gen) when the app is removed from the task view
  7964. * (TaskStackView: onTaskViewDismissed).
  7965. *
  7966. * However, if ANativeActivity_finish() is explicitly called from for example
  7967. * _sapp_android_on_stop(), the crash disappears. Is this a bug in NativeActivity?
  7968. */
  7969. _SOKOL_UNUSED(activity);
  7970. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONDESTROY);
  7971. /* send destroy msg */
  7972. pthread_mutex_lock(&_sapp.android.pt.mutex);
  7973. _sapp_android_msg(_SOKOL_ANDROID_MSG_DESTROY);
  7974. while (!_sapp.android.is_thread_stopped) {
  7975. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  7976. }
  7977. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  7978. /* clean up main thread */
  7979. pthread_cond_destroy(&_sapp.android.pt.cond);
  7980. pthread_mutex_destroy(&_sapp.android.pt.mutex);
  7981. close(_sapp.android.pt.read_from_main_fd);
  7982. close(_sapp.android.pt.write_from_main_fd);
  7983. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_DONE);
  7984. /* this is a bit naughty, but causes a clean restart of the app (static globals are reset) */
  7985. exit(0);
  7986. }
  7987. JNIEXPORT
  7988. void ANativeActivity_onCreate(ANativeActivity* activity, void* saved_state, size_t saved_state_size) {
  7989. _SOKOL_UNUSED(saved_state);
  7990. _SOKOL_UNUSED(saved_state_size);
  7991. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_ONCREATE);
  7992. // the NativeActity pointer needs to be available inside sokol_main()
  7993. // (see https://github.com/floooh/sokol/issues/708), however _sapp_init_state()
  7994. // will clear the global _sapp_t struct, so we need to initialize the native
  7995. // activity pointer twice, once before sokol_main() and once after _sapp_init_state()
  7996. _sapp_clear(&_sapp, sizeof(_sapp));
  7997. _sapp.android.activity = activity;
  7998. sapp_desc desc = sokol_main(0, NULL);
  7999. _sapp_init_state(&desc);
  8000. _sapp.android.activity = activity;
  8001. int pipe_fd[2];
  8002. if (pipe(pipe_fd) != 0) {
  8003. _SAPP_ERROR(ANDROID_CREATE_THREAD_PIPE_FAILED);
  8004. return;
  8005. }
  8006. _sapp.android.pt.read_from_main_fd = pipe_fd[0];
  8007. _sapp.android.pt.write_from_main_fd = pipe_fd[1];
  8008. pthread_mutex_init(&_sapp.android.pt.mutex, NULL);
  8009. pthread_cond_init(&_sapp.android.pt.cond, NULL);
  8010. pthread_attr_t attr;
  8011. pthread_attr_init(&attr);
  8012. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  8013. pthread_create(&_sapp.android.pt.thread, &attr, _sapp_android_loop, 0);
  8014. pthread_attr_destroy(&attr);
  8015. /* wait until main loop has started */
  8016. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8017. while (!_sapp.android.is_thread_started) {
  8018. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8019. }
  8020. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8021. /* send create msg */
  8022. pthread_mutex_lock(&_sapp.android.pt.mutex);
  8023. _sapp_android_msg(_SOKOL_ANDROID_MSG_CREATE);
  8024. while (!_sapp.android.has_created) {
  8025. pthread_cond_wait(&_sapp.android.pt.cond, &_sapp.android.pt.mutex);
  8026. }
  8027. pthread_mutex_unlock(&_sapp.android.pt.mutex);
  8028. /* register for callbacks */
  8029. activity->callbacks->onStart = _sapp_android_on_start;
  8030. activity->callbacks->onResume = _sapp_android_on_resume;
  8031. activity->callbacks->onSaveInstanceState = _sapp_android_on_save_instance_state;
  8032. activity->callbacks->onWindowFocusChanged = _sapp_android_on_window_focus_changed;
  8033. activity->callbacks->onPause = _sapp_android_on_pause;
  8034. activity->callbacks->onStop = _sapp_android_on_stop;
  8035. activity->callbacks->onDestroy = _sapp_android_on_destroy;
  8036. activity->callbacks->onNativeWindowCreated = _sapp_android_on_native_window_created;
  8037. /* activity->callbacks->onNativeWindowResized = _sapp_android_on_native_window_resized; */
  8038. /* activity->callbacks->onNativeWindowRedrawNeeded = _sapp_android_on_native_window_redraw_needed; */
  8039. activity->callbacks->onNativeWindowDestroyed = _sapp_android_on_native_window_destroyed;
  8040. activity->callbacks->onInputQueueCreated = _sapp_android_on_input_queue_created;
  8041. activity->callbacks->onInputQueueDestroyed = _sapp_android_on_input_queue_destroyed;
  8042. /* activity->callbacks->onContentRectChanged = _sapp_android_on_content_rect_changed; */
  8043. activity->callbacks->onConfigurationChanged = _sapp_android_on_config_changed;
  8044. activity->callbacks->onLowMemory = _sapp_android_on_low_memory;
  8045. _SAPP_INFO(ANDROID_NATIVE_ACTIVITY_CREATE_SUCCESS);
  8046. /* NOT A BUG: do NOT call sapp_discard_state() */
  8047. }
  8048. #endif /* _SAPP_ANDROID */
  8049. // ██ ██ ███ ██ ██ ██ ██ ██
  8050. // ██ ██ ████ ██ ██ ██ ██ ██
  8051. // ██ ██ ██ ██ ██ ██ ██ ███
  8052. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  8053. // ███████ ██ ██ ████ ██████ ██ ██
  8054. //
  8055. // >>linux
  8056. #if defined(_SAPP_LINUX)
  8057. /* see GLFW's xkb_unicode.c */
  8058. static const struct _sapp_x11_codepair {
  8059. uint16_t keysym;
  8060. uint16_t ucs;
  8061. } _sapp_x11_keysymtab[] = {
  8062. { 0x01a1, 0x0104 },
  8063. { 0x01a2, 0x02d8 },
  8064. { 0x01a3, 0x0141 },
  8065. { 0x01a5, 0x013d },
  8066. { 0x01a6, 0x015a },
  8067. { 0x01a9, 0x0160 },
  8068. { 0x01aa, 0x015e },
  8069. { 0x01ab, 0x0164 },
  8070. { 0x01ac, 0x0179 },
  8071. { 0x01ae, 0x017d },
  8072. { 0x01af, 0x017b },
  8073. { 0x01b1, 0x0105 },
  8074. { 0x01b2, 0x02db },
  8075. { 0x01b3, 0x0142 },
  8076. { 0x01b5, 0x013e },
  8077. { 0x01b6, 0x015b },
  8078. { 0x01b7, 0x02c7 },
  8079. { 0x01b9, 0x0161 },
  8080. { 0x01ba, 0x015f },
  8081. { 0x01bb, 0x0165 },
  8082. { 0x01bc, 0x017a },
  8083. { 0x01bd, 0x02dd },
  8084. { 0x01be, 0x017e },
  8085. { 0x01bf, 0x017c },
  8086. { 0x01c0, 0x0154 },
  8087. { 0x01c3, 0x0102 },
  8088. { 0x01c5, 0x0139 },
  8089. { 0x01c6, 0x0106 },
  8090. { 0x01c8, 0x010c },
  8091. { 0x01ca, 0x0118 },
  8092. { 0x01cc, 0x011a },
  8093. { 0x01cf, 0x010e },
  8094. { 0x01d0, 0x0110 },
  8095. { 0x01d1, 0x0143 },
  8096. { 0x01d2, 0x0147 },
  8097. { 0x01d5, 0x0150 },
  8098. { 0x01d8, 0x0158 },
  8099. { 0x01d9, 0x016e },
  8100. { 0x01db, 0x0170 },
  8101. { 0x01de, 0x0162 },
  8102. { 0x01e0, 0x0155 },
  8103. { 0x01e3, 0x0103 },
  8104. { 0x01e5, 0x013a },
  8105. { 0x01e6, 0x0107 },
  8106. { 0x01e8, 0x010d },
  8107. { 0x01ea, 0x0119 },
  8108. { 0x01ec, 0x011b },
  8109. { 0x01ef, 0x010f },
  8110. { 0x01f0, 0x0111 },
  8111. { 0x01f1, 0x0144 },
  8112. { 0x01f2, 0x0148 },
  8113. { 0x01f5, 0x0151 },
  8114. { 0x01f8, 0x0159 },
  8115. { 0x01f9, 0x016f },
  8116. { 0x01fb, 0x0171 },
  8117. { 0x01fe, 0x0163 },
  8118. { 0x01ff, 0x02d9 },
  8119. { 0x02a1, 0x0126 },
  8120. { 0x02a6, 0x0124 },
  8121. { 0x02a9, 0x0130 },
  8122. { 0x02ab, 0x011e },
  8123. { 0x02ac, 0x0134 },
  8124. { 0x02b1, 0x0127 },
  8125. { 0x02b6, 0x0125 },
  8126. { 0x02b9, 0x0131 },
  8127. { 0x02bb, 0x011f },
  8128. { 0x02bc, 0x0135 },
  8129. { 0x02c5, 0x010a },
  8130. { 0x02c6, 0x0108 },
  8131. { 0x02d5, 0x0120 },
  8132. { 0x02d8, 0x011c },
  8133. { 0x02dd, 0x016c },
  8134. { 0x02de, 0x015c },
  8135. { 0x02e5, 0x010b },
  8136. { 0x02e6, 0x0109 },
  8137. { 0x02f5, 0x0121 },
  8138. { 0x02f8, 0x011d },
  8139. { 0x02fd, 0x016d },
  8140. { 0x02fe, 0x015d },
  8141. { 0x03a2, 0x0138 },
  8142. { 0x03a3, 0x0156 },
  8143. { 0x03a5, 0x0128 },
  8144. { 0x03a6, 0x013b },
  8145. { 0x03aa, 0x0112 },
  8146. { 0x03ab, 0x0122 },
  8147. { 0x03ac, 0x0166 },
  8148. { 0x03b3, 0x0157 },
  8149. { 0x03b5, 0x0129 },
  8150. { 0x03b6, 0x013c },
  8151. { 0x03ba, 0x0113 },
  8152. { 0x03bb, 0x0123 },
  8153. { 0x03bc, 0x0167 },
  8154. { 0x03bd, 0x014a },
  8155. { 0x03bf, 0x014b },
  8156. { 0x03c0, 0x0100 },
  8157. { 0x03c7, 0x012e },
  8158. { 0x03cc, 0x0116 },
  8159. { 0x03cf, 0x012a },
  8160. { 0x03d1, 0x0145 },
  8161. { 0x03d2, 0x014c },
  8162. { 0x03d3, 0x0136 },
  8163. { 0x03d9, 0x0172 },
  8164. { 0x03dd, 0x0168 },
  8165. { 0x03de, 0x016a },
  8166. { 0x03e0, 0x0101 },
  8167. { 0x03e7, 0x012f },
  8168. { 0x03ec, 0x0117 },
  8169. { 0x03ef, 0x012b },
  8170. { 0x03f1, 0x0146 },
  8171. { 0x03f2, 0x014d },
  8172. { 0x03f3, 0x0137 },
  8173. { 0x03f9, 0x0173 },
  8174. { 0x03fd, 0x0169 },
  8175. { 0x03fe, 0x016b },
  8176. { 0x047e, 0x203e },
  8177. { 0x04a1, 0x3002 },
  8178. { 0x04a2, 0x300c },
  8179. { 0x04a3, 0x300d },
  8180. { 0x04a4, 0x3001 },
  8181. { 0x04a5, 0x30fb },
  8182. { 0x04a6, 0x30f2 },
  8183. { 0x04a7, 0x30a1 },
  8184. { 0x04a8, 0x30a3 },
  8185. { 0x04a9, 0x30a5 },
  8186. { 0x04aa, 0x30a7 },
  8187. { 0x04ab, 0x30a9 },
  8188. { 0x04ac, 0x30e3 },
  8189. { 0x04ad, 0x30e5 },
  8190. { 0x04ae, 0x30e7 },
  8191. { 0x04af, 0x30c3 },
  8192. { 0x04b0, 0x30fc },
  8193. { 0x04b1, 0x30a2 },
  8194. { 0x04b2, 0x30a4 },
  8195. { 0x04b3, 0x30a6 },
  8196. { 0x04b4, 0x30a8 },
  8197. { 0x04b5, 0x30aa },
  8198. { 0x04b6, 0x30ab },
  8199. { 0x04b7, 0x30ad },
  8200. { 0x04b8, 0x30af },
  8201. { 0x04b9, 0x30b1 },
  8202. { 0x04ba, 0x30b3 },
  8203. { 0x04bb, 0x30b5 },
  8204. { 0x04bc, 0x30b7 },
  8205. { 0x04bd, 0x30b9 },
  8206. { 0x04be, 0x30bb },
  8207. { 0x04bf, 0x30bd },
  8208. { 0x04c0, 0x30bf },
  8209. { 0x04c1, 0x30c1 },
  8210. { 0x04c2, 0x30c4 },
  8211. { 0x04c3, 0x30c6 },
  8212. { 0x04c4, 0x30c8 },
  8213. { 0x04c5, 0x30ca },
  8214. { 0x04c6, 0x30cb },
  8215. { 0x04c7, 0x30cc },
  8216. { 0x04c8, 0x30cd },
  8217. { 0x04c9, 0x30ce },
  8218. { 0x04ca, 0x30cf },
  8219. { 0x04cb, 0x30d2 },
  8220. { 0x04cc, 0x30d5 },
  8221. { 0x04cd, 0x30d8 },
  8222. { 0x04ce, 0x30db },
  8223. { 0x04cf, 0x30de },
  8224. { 0x04d0, 0x30df },
  8225. { 0x04d1, 0x30e0 },
  8226. { 0x04d2, 0x30e1 },
  8227. { 0x04d3, 0x30e2 },
  8228. { 0x04d4, 0x30e4 },
  8229. { 0x04d5, 0x30e6 },
  8230. { 0x04d6, 0x30e8 },
  8231. { 0x04d7, 0x30e9 },
  8232. { 0x04d8, 0x30ea },
  8233. { 0x04d9, 0x30eb },
  8234. { 0x04da, 0x30ec },
  8235. { 0x04db, 0x30ed },
  8236. { 0x04dc, 0x30ef },
  8237. { 0x04dd, 0x30f3 },
  8238. { 0x04de, 0x309b },
  8239. { 0x04df, 0x309c },
  8240. { 0x05ac, 0x060c },
  8241. { 0x05bb, 0x061b },
  8242. { 0x05bf, 0x061f },
  8243. { 0x05c1, 0x0621 },
  8244. { 0x05c2, 0x0622 },
  8245. { 0x05c3, 0x0623 },
  8246. { 0x05c4, 0x0624 },
  8247. { 0x05c5, 0x0625 },
  8248. { 0x05c6, 0x0626 },
  8249. { 0x05c7, 0x0627 },
  8250. { 0x05c8, 0x0628 },
  8251. { 0x05c9, 0x0629 },
  8252. { 0x05ca, 0x062a },
  8253. { 0x05cb, 0x062b },
  8254. { 0x05cc, 0x062c },
  8255. { 0x05cd, 0x062d },
  8256. { 0x05ce, 0x062e },
  8257. { 0x05cf, 0x062f },
  8258. { 0x05d0, 0x0630 },
  8259. { 0x05d1, 0x0631 },
  8260. { 0x05d2, 0x0632 },
  8261. { 0x05d3, 0x0633 },
  8262. { 0x05d4, 0x0634 },
  8263. { 0x05d5, 0x0635 },
  8264. { 0x05d6, 0x0636 },
  8265. { 0x05d7, 0x0637 },
  8266. { 0x05d8, 0x0638 },
  8267. { 0x05d9, 0x0639 },
  8268. { 0x05da, 0x063a },
  8269. { 0x05e0, 0x0640 },
  8270. { 0x05e1, 0x0641 },
  8271. { 0x05e2, 0x0642 },
  8272. { 0x05e3, 0x0643 },
  8273. { 0x05e4, 0x0644 },
  8274. { 0x05e5, 0x0645 },
  8275. { 0x05e6, 0x0646 },
  8276. { 0x05e7, 0x0647 },
  8277. { 0x05e8, 0x0648 },
  8278. { 0x05e9, 0x0649 },
  8279. { 0x05ea, 0x064a },
  8280. { 0x05eb, 0x064b },
  8281. { 0x05ec, 0x064c },
  8282. { 0x05ed, 0x064d },
  8283. { 0x05ee, 0x064e },
  8284. { 0x05ef, 0x064f },
  8285. { 0x05f0, 0x0650 },
  8286. { 0x05f1, 0x0651 },
  8287. { 0x05f2, 0x0652 },
  8288. { 0x06a1, 0x0452 },
  8289. { 0x06a2, 0x0453 },
  8290. { 0x06a3, 0x0451 },
  8291. { 0x06a4, 0x0454 },
  8292. { 0x06a5, 0x0455 },
  8293. { 0x06a6, 0x0456 },
  8294. { 0x06a7, 0x0457 },
  8295. { 0x06a8, 0x0458 },
  8296. { 0x06a9, 0x0459 },
  8297. { 0x06aa, 0x045a },
  8298. { 0x06ab, 0x045b },
  8299. { 0x06ac, 0x045c },
  8300. { 0x06ae, 0x045e },
  8301. { 0x06af, 0x045f },
  8302. { 0x06b0, 0x2116 },
  8303. { 0x06b1, 0x0402 },
  8304. { 0x06b2, 0x0403 },
  8305. { 0x06b3, 0x0401 },
  8306. { 0x06b4, 0x0404 },
  8307. { 0x06b5, 0x0405 },
  8308. { 0x06b6, 0x0406 },
  8309. { 0x06b7, 0x0407 },
  8310. { 0x06b8, 0x0408 },
  8311. { 0x06b9, 0x0409 },
  8312. { 0x06ba, 0x040a },
  8313. { 0x06bb, 0x040b },
  8314. { 0x06bc, 0x040c },
  8315. { 0x06be, 0x040e },
  8316. { 0x06bf, 0x040f },
  8317. { 0x06c0, 0x044e },
  8318. { 0x06c1, 0x0430 },
  8319. { 0x06c2, 0x0431 },
  8320. { 0x06c3, 0x0446 },
  8321. { 0x06c4, 0x0434 },
  8322. { 0x06c5, 0x0435 },
  8323. { 0x06c6, 0x0444 },
  8324. { 0x06c7, 0x0433 },
  8325. { 0x06c8, 0x0445 },
  8326. { 0x06c9, 0x0438 },
  8327. { 0x06ca, 0x0439 },
  8328. { 0x06cb, 0x043a },
  8329. { 0x06cc, 0x043b },
  8330. { 0x06cd, 0x043c },
  8331. { 0x06ce, 0x043d },
  8332. { 0x06cf, 0x043e },
  8333. { 0x06d0, 0x043f },
  8334. { 0x06d1, 0x044f },
  8335. { 0x06d2, 0x0440 },
  8336. { 0x06d3, 0x0441 },
  8337. { 0x06d4, 0x0442 },
  8338. { 0x06d5, 0x0443 },
  8339. { 0x06d6, 0x0436 },
  8340. { 0x06d7, 0x0432 },
  8341. { 0x06d8, 0x044c },
  8342. { 0x06d9, 0x044b },
  8343. { 0x06da, 0x0437 },
  8344. { 0x06db, 0x0448 },
  8345. { 0x06dc, 0x044d },
  8346. { 0x06dd, 0x0449 },
  8347. { 0x06de, 0x0447 },
  8348. { 0x06df, 0x044a },
  8349. { 0x06e0, 0x042e },
  8350. { 0x06e1, 0x0410 },
  8351. { 0x06e2, 0x0411 },
  8352. { 0x06e3, 0x0426 },
  8353. { 0x06e4, 0x0414 },
  8354. { 0x06e5, 0x0415 },
  8355. { 0x06e6, 0x0424 },
  8356. { 0x06e7, 0x0413 },
  8357. { 0x06e8, 0x0425 },
  8358. { 0x06e9, 0x0418 },
  8359. { 0x06ea, 0x0419 },
  8360. { 0x06eb, 0x041a },
  8361. { 0x06ec, 0x041b },
  8362. { 0x06ed, 0x041c },
  8363. { 0x06ee, 0x041d },
  8364. { 0x06ef, 0x041e },
  8365. { 0x06f0, 0x041f },
  8366. { 0x06f1, 0x042f },
  8367. { 0x06f2, 0x0420 },
  8368. { 0x06f3, 0x0421 },
  8369. { 0x06f4, 0x0422 },
  8370. { 0x06f5, 0x0423 },
  8371. { 0x06f6, 0x0416 },
  8372. { 0x06f7, 0x0412 },
  8373. { 0x06f8, 0x042c },
  8374. { 0x06f9, 0x042b },
  8375. { 0x06fa, 0x0417 },
  8376. { 0x06fb, 0x0428 },
  8377. { 0x06fc, 0x042d },
  8378. { 0x06fd, 0x0429 },
  8379. { 0x06fe, 0x0427 },
  8380. { 0x06ff, 0x042a },
  8381. { 0x07a1, 0x0386 },
  8382. { 0x07a2, 0x0388 },
  8383. { 0x07a3, 0x0389 },
  8384. { 0x07a4, 0x038a },
  8385. { 0x07a5, 0x03aa },
  8386. { 0x07a7, 0x038c },
  8387. { 0x07a8, 0x038e },
  8388. { 0x07a9, 0x03ab },
  8389. { 0x07ab, 0x038f },
  8390. { 0x07ae, 0x0385 },
  8391. { 0x07af, 0x2015 },
  8392. { 0x07b1, 0x03ac },
  8393. { 0x07b2, 0x03ad },
  8394. { 0x07b3, 0x03ae },
  8395. { 0x07b4, 0x03af },
  8396. { 0x07b5, 0x03ca },
  8397. { 0x07b6, 0x0390 },
  8398. { 0x07b7, 0x03cc },
  8399. { 0x07b8, 0x03cd },
  8400. { 0x07b9, 0x03cb },
  8401. { 0x07ba, 0x03b0 },
  8402. { 0x07bb, 0x03ce },
  8403. { 0x07c1, 0x0391 },
  8404. { 0x07c2, 0x0392 },
  8405. { 0x07c3, 0x0393 },
  8406. { 0x07c4, 0x0394 },
  8407. { 0x07c5, 0x0395 },
  8408. { 0x07c6, 0x0396 },
  8409. { 0x07c7, 0x0397 },
  8410. { 0x07c8, 0x0398 },
  8411. { 0x07c9, 0x0399 },
  8412. { 0x07ca, 0x039a },
  8413. { 0x07cb, 0x039b },
  8414. { 0x07cc, 0x039c },
  8415. { 0x07cd, 0x039d },
  8416. { 0x07ce, 0x039e },
  8417. { 0x07cf, 0x039f },
  8418. { 0x07d0, 0x03a0 },
  8419. { 0x07d1, 0x03a1 },
  8420. { 0x07d2, 0x03a3 },
  8421. { 0x07d4, 0x03a4 },
  8422. { 0x07d5, 0x03a5 },
  8423. { 0x07d6, 0x03a6 },
  8424. { 0x07d7, 0x03a7 },
  8425. { 0x07d8, 0x03a8 },
  8426. { 0x07d9, 0x03a9 },
  8427. { 0x07e1, 0x03b1 },
  8428. { 0x07e2, 0x03b2 },
  8429. { 0x07e3, 0x03b3 },
  8430. { 0x07e4, 0x03b4 },
  8431. { 0x07e5, 0x03b5 },
  8432. { 0x07e6, 0x03b6 },
  8433. { 0x07e7, 0x03b7 },
  8434. { 0x07e8, 0x03b8 },
  8435. { 0x07e9, 0x03b9 },
  8436. { 0x07ea, 0x03ba },
  8437. { 0x07eb, 0x03bb },
  8438. { 0x07ec, 0x03bc },
  8439. { 0x07ed, 0x03bd },
  8440. { 0x07ee, 0x03be },
  8441. { 0x07ef, 0x03bf },
  8442. { 0x07f0, 0x03c0 },
  8443. { 0x07f1, 0x03c1 },
  8444. { 0x07f2, 0x03c3 },
  8445. { 0x07f3, 0x03c2 },
  8446. { 0x07f4, 0x03c4 },
  8447. { 0x07f5, 0x03c5 },
  8448. { 0x07f6, 0x03c6 },
  8449. { 0x07f7, 0x03c7 },
  8450. { 0x07f8, 0x03c8 },
  8451. { 0x07f9, 0x03c9 },
  8452. { 0x08a1, 0x23b7 },
  8453. { 0x08a2, 0x250c },
  8454. { 0x08a3, 0x2500 },
  8455. { 0x08a4, 0x2320 },
  8456. { 0x08a5, 0x2321 },
  8457. { 0x08a6, 0x2502 },
  8458. { 0x08a7, 0x23a1 },
  8459. { 0x08a8, 0x23a3 },
  8460. { 0x08a9, 0x23a4 },
  8461. { 0x08aa, 0x23a6 },
  8462. { 0x08ab, 0x239b },
  8463. { 0x08ac, 0x239d },
  8464. { 0x08ad, 0x239e },
  8465. { 0x08ae, 0x23a0 },
  8466. { 0x08af, 0x23a8 },
  8467. { 0x08b0, 0x23ac },
  8468. { 0x08bc, 0x2264 },
  8469. { 0x08bd, 0x2260 },
  8470. { 0x08be, 0x2265 },
  8471. { 0x08bf, 0x222b },
  8472. { 0x08c0, 0x2234 },
  8473. { 0x08c1, 0x221d },
  8474. { 0x08c2, 0x221e },
  8475. { 0x08c5, 0x2207 },
  8476. { 0x08c8, 0x223c },
  8477. { 0x08c9, 0x2243 },
  8478. { 0x08cd, 0x21d4 },
  8479. { 0x08ce, 0x21d2 },
  8480. { 0x08cf, 0x2261 },
  8481. { 0x08d6, 0x221a },
  8482. { 0x08da, 0x2282 },
  8483. { 0x08db, 0x2283 },
  8484. { 0x08dc, 0x2229 },
  8485. { 0x08dd, 0x222a },
  8486. { 0x08de, 0x2227 },
  8487. { 0x08df, 0x2228 },
  8488. { 0x08ef, 0x2202 },
  8489. { 0x08f6, 0x0192 },
  8490. { 0x08fb, 0x2190 },
  8491. { 0x08fc, 0x2191 },
  8492. { 0x08fd, 0x2192 },
  8493. { 0x08fe, 0x2193 },
  8494. { 0x09e0, 0x25c6 },
  8495. { 0x09e1, 0x2592 },
  8496. { 0x09e2, 0x2409 },
  8497. { 0x09e3, 0x240c },
  8498. { 0x09e4, 0x240d },
  8499. { 0x09e5, 0x240a },
  8500. { 0x09e8, 0x2424 },
  8501. { 0x09e9, 0x240b },
  8502. { 0x09ea, 0x2518 },
  8503. { 0x09eb, 0x2510 },
  8504. { 0x09ec, 0x250c },
  8505. { 0x09ed, 0x2514 },
  8506. { 0x09ee, 0x253c },
  8507. { 0x09ef, 0x23ba },
  8508. { 0x09f0, 0x23bb },
  8509. { 0x09f1, 0x2500 },
  8510. { 0x09f2, 0x23bc },
  8511. { 0x09f3, 0x23bd },
  8512. { 0x09f4, 0x251c },
  8513. { 0x09f5, 0x2524 },
  8514. { 0x09f6, 0x2534 },
  8515. { 0x09f7, 0x252c },
  8516. { 0x09f8, 0x2502 },
  8517. { 0x0aa1, 0x2003 },
  8518. { 0x0aa2, 0x2002 },
  8519. { 0x0aa3, 0x2004 },
  8520. { 0x0aa4, 0x2005 },
  8521. { 0x0aa5, 0x2007 },
  8522. { 0x0aa6, 0x2008 },
  8523. { 0x0aa7, 0x2009 },
  8524. { 0x0aa8, 0x200a },
  8525. { 0x0aa9, 0x2014 },
  8526. { 0x0aaa, 0x2013 },
  8527. { 0x0aae, 0x2026 },
  8528. { 0x0aaf, 0x2025 },
  8529. { 0x0ab0, 0x2153 },
  8530. { 0x0ab1, 0x2154 },
  8531. { 0x0ab2, 0x2155 },
  8532. { 0x0ab3, 0x2156 },
  8533. { 0x0ab4, 0x2157 },
  8534. { 0x0ab5, 0x2158 },
  8535. { 0x0ab6, 0x2159 },
  8536. { 0x0ab7, 0x215a },
  8537. { 0x0ab8, 0x2105 },
  8538. { 0x0abb, 0x2012 },
  8539. { 0x0abc, 0x2329 },
  8540. { 0x0abe, 0x232a },
  8541. { 0x0ac3, 0x215b },
  8542. { 0x0ac4, 0x215c },
  8543. { 0x0ac5, 0x215d },
  8544. { 0x0ac6, 0x215e },
  8545. { 0x0ac9, 0x2122 },
  8546. { 0x0aca, 0x2613 },
  8547. { 0x0acc, 0x25c1 },
  8548. { 0x0acd, 0x25b7 },
  8549. { 0x0ace, 0x25cb },
  8550. { 0x0acf, 0x25af },
  8551. { 0x0ad0, 0x2018 },
  8552. { 0x0ad1, 0x2019 },
  8553. { 0x0ad2, 0x201c },
  8554. { 0x0ad3, 0x201d },
  8555. { 0x0ad4, 0x211e },
  8556. { 0x0ad6, 0x2032 },
  8557. { 0x0ad7, 0x2033 },
  8558. { 0x0ad9, 0x271d },
  8559. { 0x0adb, 0x25ac },
  8560. { 0x0adc, 0x25c0 },
  8561. { 0x0add, 0x25b6 },
  8562. { 0x0ade, 0x25cf },
  8563. { 0x0adf, 0x25ae },
  8564. { 0x0ae0, 0x25e6 },
  8565. { 0x0ae1, 0x25ab },
  8566. { 0x0ae2, 0x25ad },
  8567. { 0x0ae3, 0x25b3 },
  8568. { 0x0ae4, 0x25bd },
  8569. { 0x0ae5, 0x2606 },
  8570. { 0x0ae6, 0x2022 },
  8571. { 0x0ae7, 0x25aa },
  8572. { 0x0ae8, 0x25b2 },
  8573. { 0x0ae9, 0x25bc },
  8574. { 0x0aea, 0x261c },
  8575. { 0x0aeb, 0x261e },
  8576. { 0x0aec, 0x2663 },
  8577. { 0x0aed, 0x2666 },
  8578. { 0x0aee, 0x2665 },
  8579. { 0x0af0, 0x2720 },
  8580. { 0x0af1, 0x2020 },
  8581. { 0x0af2, 0x2021 },
  8582. { 0x0af3, 0x2713 },
  8583. { 0x0af4, 0x2717 },
  8584. { 0x0af5, 0x266f },
  8585. { 0x0af6, 0x266d },
  8586. { 0x0af7, 0x2642 },
  8587. { 0x0af8, 0x2640 },
  8588. { 0x0af9, 0x260e },
  8589. { 0x0afa, 0x2315 },
  8590. { 0x0afb, 0x2117 },
  8591. { 0x0afc, 0x2038 },
  8592. { 0x0afd, 0x201a },
  8593. { 0x0afe, 0x201e },
  8594. { 0x0ba3, 0x003c },
  8595. { 0x0ba6, 0x003e },
  8596. { 0x0ba8, 0x2228 },
  8597. { 0x0ba9, 0x2227 },
  8598. { 0x0bc0, 0x00af },
  8599. { 0x0bc2, 0x22a5 },
  8600. { 0x0bc3, 0x2229 },
  8601. { 0x0bc4, 0x230a },
  8602. { 0x0bc6, 0x005f },
  8603. { 0x0bca, 0x2218 },
  8604. { 0x0bcc, 0x2395 },
  8605. { 0x0bce, 0x22a4 },
  8606. { 0x0bcf, 0x25cb },
  8607. { 0x0bd3, 0x2308 },
  8608. { 0x0bd6, 0x222a },
  8609. { 0x0bd8, 0x2283 },
  8610. { 0x0bda, 0x2282 },
  8611. { 0x0bdc, 0x22a2 },
  8612. { 0x0bfc, 0x22a3 },
  8613. { 0x0cdf, 0x2017 },
  8614. { 0x0ce0, 0x05d0 },
  8615. { 0x0ce1, 0x05d1 },
  8616. { 0x0ce2, 0x05d2 },
  8617. { 0x0ce3, 0x05d3 },
  8618. { 0x0ce4, 0x05d4 },
  8619. { 0x0ce5, 0x05d5 },
  8620. { 0x0ce6, 0x05d6 },
  8621. { 0x0ce7, 0x05d7 },
  8622. { 0x0ce8, 0x05d8 },
  8623. { 0x0ce9, 0x05d9 },
  8624. { 0x0cea, 0x05da },
  8625. { 0x0ceb, 0x05db },
  8626. { 0x0cec, 0x05dc },
  8627. { 0x0ced, 0x05dd },
  8628. { 0x0cee, 0x05de },
  8629. { 0x0cef, 0x05df },
  8630. { 0x0cf0, 0x05e0 },
  8631. { 0x0cf1, 0x05e1 },
  8632. { 0x0cf2, 0x05e2 },
  8633. { 0x0cf3, 0x05e3 },
  8634. { 0x0cf4, 0x05e4 },
  8635. { 0x0cf5, 0x05e5 },
  8636. { 0x0cf6, 0x05e6 },
  8637. { 0x0cf7, 0x05e7 },
  8638. { 0x0cf8, 0x05e8 },
  8639. { 0x0cf9, 0x05e9 },
  8640. { 0x0cfa, 0x05ea },
  8641. { 0x0da1, 0x0e01 },
  8642. { 0x0da2, 0x0e02 },
  8643. { 0x0da3, 0x0e03 },
  8644. { 0x0da4, 0x0e04 },
  8645. { 0x0da5, 0x0e05 },
  8646. { 0x0da6, 0x0e06 },
  8647. { 0x0da7, 0x0e07 },
  8648. { 0x0da8, 0x0e08 },
  8649. { 0x0da9, 0x0e09 },
  8650. { 0x0daa, 0x0e0a },
  8651. { 0x0dab, 0x0e0b },
  8652. { 0x0dac, 0x0e0c },
  8653. { 0x0dad, 0x0e0d },
  8654. { 0x0dae, 0x0e0e },
  8655. { 0x0daf, 0x0e0f },
  8656. { 0x0db0, 0x0e10 },
  8657. { 0x0db1, 0x0e11 },
  8658. { 0x0db2, 0x0e12 },
  8659. { 0x0db3, 0x0e13 },
  8660. { 0x0db4, 0x0e14 },
  8661. { 0x0db5, 0x0e15 },
  8662. { 0x0db6, 0x0e16 },
  8663. { 0x0db7, 0x0e17 },
  8664. { 0x0db8, 0x0e18 },
  8665. { 0x0db9, 0x0e19 },
  8666. { 0x0dba, 0x0e1a },
  8667. { 0x0dbb, 0x0e1b },
  8668. { 0x0dbc, 0x0e1c },
  8669. { 0x0dbd, 0x0e1d },
  8670. { 0x0dbe, 0x0e1e },
  8671. { 0x0dbf, 0x0e1f },
  8672. { 0x0dc0, 0x0e20 },
  8673. { 0x0dc1, 0x0e21 },
  8674. { 0x0dc2, 0x0e22 },
  8675. { 0x0dc3, 0x0e23 },
  8676. { 0x0dc4, 0x0e24 },
  8677. { 0x0dc5, 0x0e25 },
  8678. { 0x0dc6, 0x0e26 },
  8679. { 0x0dc7, 0x0e27 },
  8680. { 0x0dc8, 0x0e28 },
  8681. { 0x0dc9, 0x0e29 },
  8682. { 0x0dca, 0x0e2a },
  8683. { 0x0dcb, 0x0e2b },
  8684. { 0x0dcc, 0x0e2c },
  8685. { 0x0dcd, 0x0e2d },
  8686. { 0x0dce, 0x0e2e },
  8687. { 0x0dcf, 0x0e2f },
  8688. { 0x0dd0, 0x0e30 },
  8689. { 0x0dd1, 0x0e31 },
  8690. { 0x0dd2, 0x0e32 },
  8691. { 0x0dd3, 0x0e33 },
  8692. { 0x0dd4, 0x0e34 },
  8693. { 0x0dd5, 0x0e35 },
  8694. { 0x0dd6, 0x0e36 },
  8695. { 0x0dd7, 0x0e37 },
  8696. { 0x0dd8, 0x0e38 },
  8697. { 0x0dd9, 0x0e39 },
  8698. { 0x0dda, 0x0e3a },
  8699. { 0x0ddf, 0x0e3f },
  8700. { 0x0de0, 0x0e40 },
  8701. { 0x0de1, 0x0e41 },
  8702. { 0x0de2, 0x0e42 },
  8703. { 0x0de3, 0x0e43 },
  8704. { 0x0de4, 0x0e44 },
  8705. { 0x0de5, 0x0e45 },
  8706. { 0x0de6, 0x0e46 },
  8707. { 0x0de7, 0x0e47 },
  8708. { 0x0de8, 0x0e48 },
  8709. { 0x0de9, 0x0e49 },
  8710. { 0x0dea, 0x0e4a },
  8711. { 0x0deb, 0x0e4b },
  8712. { 0x0dec, 0x0e4c },
  8713. { 0x0ded, 0x0e4d },
  8714. { 0x0df0, 0x0e50 },
  8715. { 0x0df1, 0x0e51 },
  8716. { 0x0df2, 0x0e52 },
  8717. { 0x0df3, 0x0e53 },
  8718. { 0x0df4, 0x0e54 },
  8719. { 0x0df5, 0x0e55 },
  8720. { 0x0df6, 0x0e56 },
  8721. { 0x0df7, 0x0e57 },
  8722. { 0x0df8, 0x0e58 },
  8723. { 0x0df9, 0x0e59 },
  8724. { 0x0ea1, 0x3131 },
  8725. { 0x0ea2, 0x3132 },
  8726. { 0x0ea3, 0x3133 },
  8727. { 0x0ea4, 0x3134 },
  8728. { 0x0ea5, 0x3135 },
  8729. { 0x0ea6, 0x3136 },
  8730. { 0x0ea7, 0x3137 },
  8731. { 0x0ea8, 0x3138 },
  8732. { 0x0ea9, 0x3139 },
  8733. { 0x0eaa, 0x313a },
  8734. { 0x0eab, 0x313b },
  8735. { 0x0eac, 0x313c },
  8736. { 0x0ead, 0x313d },
  8737. { 0x0eae, 0x313e },
  8738. { 0x0eaf, 0x313f },
  8739. { 0x0eb0, 0x3140 },
  8740. { 0x0eb1, 0x3141 },
  8741. { 0x0eb2, 0x3142 },
  8742. { 0x0eb3, 0x3143 },
  8743. { 0x0eb4, 0x3144 },
  8744. { 0x0eb5, 0x3145 },
  8745. { 0x0eb6, 0x3146 },
  8746. { 0x0eb7, 0x3147 },
  8747. { 0x0eb8, 0x3148 },
  8748. { 0x0eb9, 0x3149 },
  8749. { 0x0eba, 0x314a },
  8750. { 0x0ebb, 0x314b },
  8751. { 0x0ebc, 0x314c },
  8752. { 0x0ebd, 0x314d },
  8753. { 0x0ebe, 0x314e },
  8754. { 0x0ebf, 0x314f },
  8755. { 0x0ec0, 0x3150 },
  8756. { 0x0ec1, 0x3151 },
  8757. { 0x0ec2, 0x3152 },
  8758. { 0x0ec3, 0x3153 },
  8759. { 0x0ec4, 0x3154 },
  8760. { 0x0ec5, 0x3155 },
  8761. { 0x0ec6, 0x3156 },
  8762. { 0x0ec7, 0x3157 },
  8763. { 0x0ec8, 0x3158 },
  8764. { 0x0ec9, 0x3159 },
  8765. { 0x0eca, 0x315a },
  8766. { 0x0ecb, 0x315b },
  8767. { 0x0ecc, 0x315c },
  8768. { 0x0ecd, 0x315d },
  8769. { 0x0ece, 0x315e },
  8770. { 0x0ecf, 0x315f },
  8771. { 0x0ed0, 0x3160 },
  8772. { 0x0ed1, 0x3161 },
  8773. { 0x0ed2, 0x3162 },
  8774. { 0x0ed3, 0x3163 },
  8775. { 0x0ed4, 0x11a8 },
  8776. { 0x0ed5, 0x11a9 },
  8777. { 0x0ed6, 0x11aa },
  8778. { 0x0ed7, 0x11ab },
  8779. { 0x0ed8, 0x11ac },
  8780. { 0x0ed9, 0x11ad },
  8781. { 0x0eda, 0x11ae },
  8782. { 0x0edb, 0x11af },
  8783. { 0x0edc, 0x11b0 },
  8784. { 0x0edd, 0x11b1 },
  8785. { 0x0ede, 0x11b2 },
  8786. { 0x0edf, 0x11b3 },
  8787. { 0x0ee0, 0x11b4 },
  8788. { 0x0ee1, 0x11b5 },
  8789. { 0x0ee2, 0x11b6 },
  8790. { 0x0ee3, 0x11b7 },
  8791. { 0x0ee4, 0x11b8 },
  8792. { 0x0ee5, 0x11b9 },
  8793. { 0x0ee6, 0x11ba },
  8794. { 0x0ee7, 0x11bb },
  8795. { 0x0ee8, 0x11bc },
  8796. { 0x0ee9, 0x11bd },
  8797. { 0x0eea, 0x11be },
  8798. { 0x0eeb, 0x11bf },
  8799. { 0x0eec, 0x11c0 },
  8800. { 0x0eed, 0x11c1 },
  8801. { 0x0eee, 0x11c2 },
  8802. { 0x0eef, 0x316d },
  8803. { 0x0ef0, 0x3171 },
  8804. { 0x0ef1, 0x3178 },
  8805. { 0x0ef2, 0x317f },
  8806. { 0x0ef3, 0x3181 },
  8807. { 0x0ef4, 0x3184 },
  8808. { 0x0ef5, 0x3186 },
  8809. { 0x0ef6, 0x318d },
  8810. { 0x0ef7, 0x318e },
  8811. { 0x0ef8, 0x11eb },
  8812. { 0x0ef9, 0x11f0 },
  8813. { 0x0efa, 0x11f9 },
  8814. { 0x0eff, 0x20a9 },
  8815. { 0x13a4, 0x20ac },
  8816. { 0x13bc, 0x0152 },
  8817. { 0x13bd, 0x0153 },
  8818. { 0x13be, 0x0178 },
  8819. { 0x20ac, 0x20ac },
  8820. { 0xfe50, '`' },
  8821. { 0xfe51, 0x00b4 },
  8822. { 0xfe52, '^' },
  8823. { 0xfe53, '~' },
  8824. { 0xfe54, 0x00af },
  8825. { 0xfe55, 0x02d8 },
  8826. { 0xfe56, 0x02d9 },
  8827. { 0xfe57, 0x00a8 },
  8828. { 0xfe58, 0x02da },
  8829. { 0xfe59, 0x02dd },
  8830. { 0xfe5a, 0x02c7 },
  8831. { 0xfe5b, 0x00b8 },
  8832. { 0xfe5c, 0x02db },
  8833. { 0xfe5d, 0x037a },
  8834. { 0xfe5e, 0x309b },
  8835. { 0xfe5f, 0x309c },
  8836. { 0xfe63, '/' },
  8837. { 0xfe64, 0x02bc },
  8838. { 0xfe65, 0x02bd },
  8839. { 0xfe66, 0x02f5 },
  8840. { 0xfe67, 0x02f3 },
  8841. { 0xfe68, 0x02cd },
  8842. { 0xfe69, 0xa788 },
  8843. { 0xfe6a, 0x02f7 },
  8844. { 0xfe6e, ',' },
  8845. { 0xfe6f, 0x00a4 },
  8846. { 0xfe80, 'a' }, /* XK_dead_a */
  8847. { 0xfe81, 'A' }, /* XK_dead_A */
  8848. { 0xfe82, 'e' }, /* XK_dead_e */
  8849. { 0xfe83, 'E' }, /* XK_dead_E */
  8850. { 0xfe84, 'i' }, /* XK_dead_i */
  8851. { 0xfe85, 'I' }, /* XK_dead_I */
  8852. { 0xfe86, 'o' }, /* XK_dead_o */
  8853. { 0xfe87, 'O' }, /* XK_dead_O */
  8854. { 0xfe88, 'u' }, /* XK_dead_u */
  8855. { 0xfe89, 'U' }, /* XK_dead_U */
  8856. { 0xfe8a, 0x0259 },
  8857. { 0xfe8b, 0x018f },
  8858. { 0xfe8c, 0x00b5 },
  8859. { 0xfe90, '_' },
  8860. { 0xfe91, 0x02c8 },
  8861. { 0xfe92, 0x02cc },
  8862. { 0xff80 /*XKB_KEY_KP_Space*/, ' ' },
  8863. { 0xff95 /*XKB_KEY_KP_7*/, 0x0037 },
  8864. { 0xff96 /*XKB_KEY_KP_4*/, 0x0034 },
  8865. { 0xff97 /*XKB_KEY_KP_8*/, 0x0038 },
  8866. { 0xff98 /*XKB_KEY_KP_6*/, 0x0036 },
  8867. { 0xff99 /*XKB_KEY_KP_2*/, 0x0032 },
  8868. { 0xff9a /*XKB_KEY_KP_9*/, 0x0039 },
  8869. { 0xff9b /*XKB_KEY_KP_3*/, 0x0033 },
  8870. { 0xff9c /*XKB_KEY_KP_1*/, 0x0031 },
  8871. { 0xff9d /*XKB_KEY_KP_5*/, 0x0035 },
  8872. { 0xff9e /*XKB_KEY_KP_0*/, 0x0030 },
  8873. { 0xffaa /*XKB_KEY_KP_Multiply*/, '*' },
  8874. { 0xffab /*XKB_KEY_KP_Add*/, '+' },
  8875. { 0xffac /*XKB_KEY_KP_Separator*/, ',' },
  8876. { 0xffad /*XKB_KEY_KP_Subtract*/, '-' },
  8877. { 0xffae /*XKB_KEY_KP_Decimal*/, '.' },
  8878. { 0xffaf /*XKB_KEY_KP_Divide*/, '/' },
  8879. { 0xffb0 /*XKB_KEY_KP_0*/, 0x0030 },
  8880. { 0xffb1 /*XKB_KEY_KP_1*/, 0x0031 },
  8881. { 0xffb2 /*XKB_KEY_KP_2*/, 0x0032 },
  8882. { 0xffb3 /*XKB_KEY_KP_3*/, 0x0033 },
  8883. { 0xffb4 /*XKB_KEY_KP_4*/, 0x0034 },
  8884. { 0xffb5 /*XKB_KEY_KP_5*/, 0x0035 },
  8885. { 0xffb6 /*XKB_KEY_KP_6*/, 0x0036 },
  8886. { 0xffb7 /*XKB_KEY_KP_7*/, 0x0037 },
  8887. { 0xffb8 /*XKB_KEY_KP_8*/, 0x0038 },
  8888. { 0xffb9 /*XKB_KEY_KP_9*/, 0x0039 },
  8889. { 0xffbd /*XKB_KEY_KP_Equal*/, '=' }
  8890. };
  8891. _SOKOL_PRIVATE int _sapp_x11_error_handler(Display* display, XErrorEvent* event) {
  8892. _SOKOL_UNUSED(display);
  8893. _sapp.x11.error_code = event->error_code;
  8894. return 0;
  8895. }
  8896. _SOKOL_PRIVATE void _sapp_x11_grab_error_handler(void) {
  8897. _sapp.x11.error_code = Success;
  8898. XSetErrorHandler(_sapp_x11_error_handler);
  8899. }
  8900. _SOKOL_PRIVATE void _sapp_x11_release_error_handler(void) {
  8901. XSync(_sapp.x11.display, False);
  8902. XSetErrorHandler(NULL);
  8903. }
  8904. _SOKOL_PRIVATE void _sapp_x11_init_extensions(void) {
  8905. _sapp.x11.UTF8_STRING = XInternAtom(_sapp.x11.display, "UTF8_STRING", False);
  8906. _sapp.x11.WM_PROTOCOLS = XInternAtom(_sapp.x11.display, "WM_PROTOCOLS", False);
  8907. _sapp.x11.WM_DELETE_WINDOW = XInternAtom(_sapp.x11.display, "WM_DELETE_WINDOW", False);
  8908. _sapp.x11.WM_STATE = XInternAtom(_sapp.x11.display, "WM_STATE", False);
  8909. _sapp.x11.NET_WM_NAME = XInternAtom(_sapp.x11.display, "_NET_WM_NAME", False);
  8910. _sapp.x11.NET_WM_ICON_NAME = XInternAtom(_sapp.x11.display, "_NET_WM_ICON_NAME", False);
  8911. _sapp.x11.NET_WM_ICON = XInternAtom(_sapp.x11.display, "_NET_WM_ICON", False);
  8912. _sapp.x11.NET_WM_STATE = XInternAtom(_sapp.x11.display, "_NET_WM_STATE", False);
  8913. _sapp.x11.NET_WM_STATE_FULLSCREEN = XInternAtom(_sapp.x11.display, "_NET_WM_STATE_FULLSCREEN", False);
  8914. _sapp.x11.CLIPBOARD = XInternAtom(_sapp.x11.display, "CLIPBOARD", False);
  8915. _sapp.x11.TARGETS = XInternAtom(_sapp.x11.display, "TARGETS", False);
  8916. if (_sapp.drop.enabled) {
  8917. _sapp.x11.xdnd.XdndAware = XInternAtom(_sapp.x11.display, "XdndAware", False);
  8918. _sapp.x11.xdnd.XdndEnter = XInternAtom(_sapp.x11.display, "XdndEnter", False);
  8919. _sapp.x11.xdnd.XdndPosition = XInternAtom(_sapp.x11.display, "XdndPosition", False);
  8920. _sapp.x11.xdnd.XdndStatus = XInternAtom(_sapp.x11.display, "XdndStatus", False);
  8921. _sapp.x11.xdnd.XdndActionCopy = XInternAtom(_sapp.x11.display, "XdndActionCopy", False);
  8922. _sapp.x11.xdnd.XdndDrop = XInternAtom(_sapp.x11.display, "XdndDrop", False);
  8923. _sapp.x11.xdnd.XdndFinished = XInternAtom(_sapp.x11.display, "XdndFinished", False);
  8924. _sapp.x11.xdnd.XdndSelection = XInternAtom(_sapp.x11.display, "XdndSelection", False);
  8925. _sapp.x11.xdnd.XdndTypeList = XInternAtom(_sapp.x11.display, "XdndTypeList", False);
  8926. _sapp.x11.xdnd.text_uri_list = XInternAtom(_sapp.x11.display, "text/uri-list", False);
  8927. }
  8928. /* check Xi extension for raw mouse input */
  8929. if (XQueryExtension(_sapp.x11.display, "XInputExtension", &_sapp.x11.xi.major_opcode, &_sapp.x11.xi.event_base, &_sapp.x11.xi.error_base)) {
  8930. _sapp.x11.xi.major = 2;
  8931. _sapp.x11.xi.minor = 0;
  8932. if (XIQueryVersion(_sapp.x11.display, &_sapp.x11.xi.major, &_sapp.x11.xi.minor) == Success) {
  8933. _sapp.x11.xi.available = true;
  8934. }
  8935. }
  8936. }
  8937. // translate the X11 KeySyms for a key to sokol-app key code
  8938. // NOTE: this is only used as a fallback, in case the XBK method fails
  8939. // it is layout-dependent and will fail partially on most non-US layouts.
  8940. //
  8941. _SOKOL_PRIVATE sapp_keycode _sapp_x11_translate_keysyms(const KeySym* keysyms, int width) {
  8942. if (width > 1) {
  8943. switch (keysyms[1]) {
  8944. case XK_KP_0: return SAPP_KEYCODE_KP_0;
  8945. case XK_KP_1: return SAPP_KEYCODE_KP_1;
  8946. case XK_KP_2: return SAPP_KEYCODE_KP_2;
  8947. case XK_KP_3: return SAPP_KEYCODE_KP_3;
  8948. case XK_KP_4: return SAPP_KEYCODE_KP_4;
  8949. case XK_KP_5: return SAPP_KEYCODE_KP_5;
  8950. case XK_KP_6: return SAPP_KEYCODE_KP_6;
  8951. case XK_KP_7: return SAPP_KEYCODE_KP_7;
  8952. case XK_KP_8: return SAPP_KEYCODE_KP_8;
  8953. case XK_KP_9: return SAPP_KEYCODE_KP_9;
  8954. case XK_KP_Separator:
  8955. case XK_KP_Decimal: return SAPP_KEYCODE_KP_DECIMAL;
  8956. case XK_KP_Equal: return SAPP_KEYCODE_KP_EQUAL;
  8957. case XK_KP_Enter: return SAPP_KEYCODE_KP_ENTER;
  8958. default: break;
  8959. }
  8960. }
  8961. switch (keysyms[0]) {
  8962. case XK_Escape: return SAPP_KEYCODE_ESCAPE;
  8963. case XK_Tab: return SAPP_KEYCODE_TAB;
  8964. case XK_Shift_L: return SAPP_KEYCODE_LEFT_SHIFT;
  8965. case XK_Shift_R: return SAPP_KEYCODE_RIGHT_SHIFT;
  8966. case XK_Control_L: return SAPP_KEYCODE_LEFT_CONTROL;
  8967. case XK_Control_R: return SAPP_KEYCODE_RIGHT_CONTROL;
  8968. case XK_Meta_L:
  8969. case XK_Alt_L: return SAPP_KEYCODE_LEFT_ALT;
  8970. case XK_Mode_switch: // Mapped to Alt_R on many keyboards
  8971. case XK_ISO_Level3_Shift: // AltGr on at least some machines
  8972. case XK_Meta_R:
  8973. case XK_Alt_R: return SAPP_KEYCODE_RIGHT_ALT;
  8974. case XK_Super_L: return SAPP_KEYCODE_LEFT_SUPER;
  8975. case XK_Super_R: return SAPP_KEYCODE_RIGHT_SUPER;
  8976. case XK_Menu: return SAPP_KEYCODE_MENU;
  8977. case XK_Num_Lock: return SAPP_KEYCODE_NUM_LOCK;
  8978. case XK_Caps_Lock: return SAPP_KEYCODE_CAPS_LOCK;
  8979. case XK_Print: return SAPP_KEYCODE_PRINT_SCREEN;
  8980. case XK_Scroll_Lock: return SAPP_KEYCODE_SCROLL_LOCK;
  8981. case XK_Pause: return SAPP_KEYCODE_PAUSE;
  8982. case XK_Delete: return SAPP_KEYCODE_DELETE;
  8983. case XK_BackSpace: return SAPP_KEYCODE_BACKSPACE;
  8984. case XK_Return: return SAPP_KEYCODE_ENTER;
  8985. case XK_Home: return SAPP_KEYCODE_HOME;
  8986. case XK_End: return SAPP_KEYCODE_END;
  8987. case XK_Page_Up: return SAPP_KEYCODE_PAGE_UP;
  8988. case XK_Page_Down: return SAPP_KEYCODE_PAGE_DOWN;
  8989. case XK_Insert: return SAPP_KEYCODE_INSERT;
  8990. case XK_Left: return SAPP_KEYCODE_LEFT;
  8991. case XK_Right: return SAPP_KEYCODE_RIGHT;
  8992. case XK_Down: return SAPP_KEYCODE_DOWN;
  8993. case XK_Up: return SAPP_KEYCODE_UP;
  8994. case XK_F1: return SAPP_KEYCODE_F1;
  8995. case XK_F2: return SAPP_KEYCODE_F2;
  8996. case XK_F3: return SAPP_KEYCODE_F3;
  8997. case XK_F4: return SAPP_KEYCODE_F4;
  8998. case XK_F5: return SAPP_KEYCODE_F5;
  8999. case XK_F6: return SAPP_KEYCODE_F6;
  9000. case XK_F7: return SAPP_KEYCODE_F7;
  9001. case XK_F8: return SAPP_KEYCODE_F8;
  9002. case XK_F9: return SAPP_KEYCODE_F9;
  9003. case XK_F10: return SAPP_KEYCODE_F10;
  9004. case XK_F11: return SAPP_KEYCODE_F11;
  9005. case XK_F12: return SAPP_KEYCODE_F12;
  9006. case XK_F13: return SAPP_KEYCODE_F13;
  9007. case XK_F14: return SAPP_KEYCODE_F14;
  9008. case XK_F15: return SAPP_KEYCODE_F15;
  9009. case XK_F16: return SAPP_KEYCODE_F16;
  9010. case XK_F17: return SAPP_KEYCODE_F17;
  9011. case XK_F18: return SAPP_KEYCODE_F18;
  9012. case XK_F19: return SAPP_KEYCODE_F19;
  9013. case XK_F20: return SAPP_KEYCODE_F20;
  9014. case XK_F21: return SAPP_KEYCODE_F21;
  9015. case XK_F22: return SAPP_KEYCODE_F22;
  9016. case XK_F23: return SAPP_KEYCODE_F23;
  9017. case XK_F24: return SAPP_KEYCODE_F24;
  9018. case XK_F25: return SAPP_KEYCODE_F25;
  9019. // numeric keypad
  9020. case XK_KP_Divide: return SAPP_KEYCODE_KP_DIVIDE;
  9021. case XK_KP_Multiply: return SAPP_KEYCODE_KP_MULTIPLY;
  9022. case XK_KP_Subtract: return SAPP_KEYCODE_KP_SUBTRACT;
  9023. case XK_KP_Add: return SAPP_KEYCODE_KP_ADD;
  9024. // these should have been detected in secondary keysym test above!
  9025. case XK_KP_Insert: return SAPP_KEYCODE_KP_0;
  9026. case XK_KP_End: return SAPP_KEYCODE_KP_1;
  9027. case XK_KP_Down: return SAPP_KEYCODE_KP_2;
  9028. case XK_KP_Page_Down: return SAPP_KEYCODE_KP_3;
  9029. case XK_KP_Left: return SAPP_KEYCODE_KP_4;
  9030. case XK_KP_Right: return SAPP_KEYCODE_KP_6;
  9031. case XK_KP_Home: return SAPP_KEYCODE_KP_7;
  9032. case XK_KP_Up: return SAPP_KEYCODE_KP_8;
  9033. case XK_KP_Page_Up: return SAPP_KEYCODE_KP_9;
  9034. case XK_KP_Delete: return SAPP_KEYCODE_KP_DECIMAL;
  9035. case XK_KP_Equal: return SAPP_KEYCODE_KP_EQUAL;
  9036. case XK_KP_Enter: return SAPP_KEYCODE_KP_ENTER;
  9037. // last resort: Check for printable keys (should not happen if the XKB
  9038. // extension is available). This will give a layout dependent mapping
  9039. // (which is wrong, and we may miss some keys, especially on non-US
  9040. // keyboards), but it's better than nothing...
  9041. case XK_a: return SAPP_KEYCODE_A;
  9042. case XK_b: return SAPP_KEYCODE_B;
  9043. case XK_c: return SAPP_KEYCODE_C;
  9044. case XK_d: return SAPP_KEYCODE_D;
  9045. case XK_e: return SAPP_KEYCODE_E;
  9046. case XK_f: return SAPP_KEYCODE_F;
  9047. case XK_g: return SAPP_KEYCODE_G;
  9048. case XK_h: return SAPP_KEYCODE_H;
  9049. case XK_i: return SAPP_KEYCODE_I;
  9050. case XK_j: return SAPP_KEYCODE_J;
  9051. case XK_k: return SAPP_KEYCODE_K;
  9052. case XK_l: return SAPP_KEYCODE_L;
  9053. case XK_m: return SAPP_KEYCODE_M;
  9054. case XK_n: return SAPP_KEYCODE_N;
  9055. case XK_o: return SAPP_KEYCODE_O;
  9056. case XK_p: return SAPP_KEYCODE_P;
  9057. case XK_q: return SAPP_KEYCODE_Q;
  9058. case XK_r: return SAPP_KEYCODE_R;
  9059. case XK_s: return SAPP_KEYCODE_S;
  9060. case XK_t: return SAPP_KEYCODE_T;
  9061. case XK_u: return SAPP_KEYCODE_U;
  9062. case XK_v: return SAPP_KEYCODE_V;
  9063. case XK_w: return SAPP_KEYCODE_W;
  9064. case XK_x: return SAPP_KEYCODE_X;
  9065. case XK_y: return SAPP_KEYCODE_Y;
  9066. case XK_z: return SAPP_KEYCODE_Z;
  9067. case XK_1: return SAPP_KEYCODE_1;
  9068. case XK_2: return SAPP_KEYCODE_2;
  9069. case XK_3: return SAPP_KEYCODE_3;
  9070. case XK_4: return SAPP_KEYCODE_4;
  9071. case XK_5: return SAPP_KEYCODE_5;
  9072. case XK_6: return SAPP_KEYCODE_6;
  9073. case XK_7: return SAPP_KEYCODE_7;
  9074. case XK_8: return SAPP_KEYCODE_8;
  9075. case XK_9: return SAPP_KEYCODE_9;
  9076. case XK_0: return SAPP_KEYCODE_0;
  9077. case XK_space: return SAPP_KEYCODE_SPACE;
  9078. case XK_minus: return SAPP_KEYCODE_MINUS;
  9079. case XK_equal: return SAPP_KEYCODE_EQUAL;
  9080. case XK_bracketleft: return SAPP_KEYCODE_LEFT_BRACKET;
  9081. case XK_bracketright: return SAPP_KEYCODE_RIGHT_BRACKET;
  9082. case XK_backslash: return SAPP_KEYCODE_BACKSLASH;
  9083. case XK_semicolon: return SAPP_KEYCODE_SEMICOLON;
  9084. case XK_apostrophe: return SAPP_KEYCODE_APOSTROPHE;
  9085. case XK_grave: return SAPP_KEYCODE_GRAVE_ACCENT;
  9086. case XK_comma: return SAPP_KEYCODE_COMMA;
  9087. case XK_period: return SAPP_KEYCODE_PERIOD;
  9088. case XK_slash: return SAPP_KEYCODE_SLASH;
  9089. case XK_less: return SAPP_KEYCODE_WORLD_1; // At least in some layouts...
  9090. default: break;
  9091. }
  9092. // no matching translation was found
  9093. return SAPP_KEYCODE_INVALID;
  9094. }
  9095. // setup dynamic keycode/scancode mapping tables, this is required
  9096. // for getting layout-independent keycodes on X11.
  9097. //
  9098. // see GLFW x11_init.c/createKeyTables()
  9099. _SOKOL_PRIVATE void _sapp_x11_init_keytable(void) {
  9100. for (int i = 0; i < SAPP_MAX_KEYCODES; i++) {
  9101. _sapp.keycodes[i] = SAPP_KEYCODE_INVALID;
  9102. }
  9103. // use XKB to determine physical key locations independently of the current keyboard layout
  9104. XkbDescPtr desc = XkbGetMap(_sapp.x11.display, 0, XkbUseCoreKbd);
  9105. SOKOL_ASSERT(desc);
  9106. XkbGetNames(_sapp.x11.display, XkbKeyNamesMask | XkbKeyAliasesMask, desc);
  9107. const int scancode_min = desc->min_key_code;
  9108. const int scancode_max = desc->max_key_code;
  9109. const struct { sapp_keycode key; const char* name; } keymap[] = {
  9110. { SAPP_KEYCODE_GRAVE_ACCENT, "TLDE" },
  9111. { SAPP_KEYCODE_1, "AE01" },
  9112. { SAPP_KEYCODE_2, "AE02" },
  9113. { SAPP_KEYCODE_3, "AE03" },
  9114. { SAPP_KEYCODE_4, "AE04" },
  9115. { SAPP_KEYCODE_5, "AE05" },
  9116. { SAPP_KEYCODE_6, "AE06" },
  9117. { SAPP_KEYCODE_7, "AE07" },
  9118. { SAPP_KEYCODE_8, "AE08" },
  9119. { SAPP_KEYCODE_9, "AE09" },
  9120. { SAPP_KEYCODE_0, "AE10" },
  9121. { SAPP_KEYCODE_MINUS, "AE11" },
  9122. { SAPP_KEYCODE_EQUAL, "AE12" },
  9123. { SAPP_KEYCODE_Q, "AD01" },
  9124. { SAPP_KEYCODE_W, "AD02" },
  9125. { SAPP_KEYCODE_E, "AD03" },
  9126. { SAPP_KEYCODE_R, "AD04" },
  9127. { SAPP_KEYCODE_T, "AD05" },
  9128. { SAPP_KEYCODE_Y, "AD06" },
  9129. { SAPP_KEYCODE_U, "AD07" },
  9130. { SAPP_KEYCODE_I, "AD08" },
  9131. { SAPP_KEYCODE_O, "AD09" },
  9132. { SAPP_KEYCODE_P, "AD10" },
  9133. { SAPP_KEYCODE_LEFT_BRACKET, "AD11" },
  9134. { SAPP_KEYCODE_RIGHT_BRACKET, "AD12" },
  9135. { SAPP_KEYCODE_A, "AC01" },
  9136. { SAPP_KEYCODE_S, "AC02" },
  9137. { SAPP_KEYCODE_D, "AC03" },
  9138. { SAPP_KEYCODE_F, "AC04" },
  9139. { SAPP_KEYCODE_G, "AC05" },
  9140. { SAPP_KEYCODE_H, "AC06" },
  9141. { SAPP_KEYCODE_J, "AC07" },
  9142. { SAPP_KEYCODE_K, "AC08" },
  9143. { SAPP_KEYCODE_L, "AC09" },
  9144. { SAPP_KEYCODE_SEMICOLON, "AC10" },
  9145. { SAPP_KEYCODE_APOSTROPHE, "AC11" },
  9146. { SAPP_KEYCODE_Z, "AB01" },
  9147. { SAPP_KEYCODE_X, "AB02" },
  9148. { SAPP_KEYCODE_C, "AB03" },
  9149. { SAPP_KEYCODE_V, "AB04" },
  9150. { SAPP_KEYCODE_B, "AB05" },
  9151. { SAPP_KEYCODE_N, "AB06" },
  9152. { SAPP_KEYCODE_M, "AB07" },
  9153. { SAPP_KEYCODE_COMMA, "AB08" },
  9154. { SAPP_KEYCODE_PERIOD, "AB09" },
  9155. { SAPP_KEYCODE_SLASH, "AB10" },
  9156. { SAPP_KEYCODE_BACKSLASH, "BKSL" },
  9157. { SAPP_KEYCODE_WORLD_1, "LSGT" },
  9158. { SAPP_KEYCODE_SPACE, "SPCE" },
  9159. { SAPP_KEYCODE_ESCAPE, "ESC" },
  9160. { SAPP_KEYCODE_ENTER, "RTRN" },
  9161. { SAPP_KEYCODE_TAB, "TAB" },
  9162. { SAPP_KEYCODE_BACKSPACE, "BKSP" },
  9163. { SAPP_KEYCODE_INSERT, "INS" },
  9164. { SAPP_KEYCODE_DELETE, "DELE" },
  9165. { SAPP_KEYCODE_RIGHT, "RGHT" },
  9166. { SAPP_KEYCODE_LEFT, "LEFT" },
  9167. { SAPP_KEYCODE_DOWN, "DOWN" },
  9168. { SAPP_KEYCODE_UP, "UP" },
  9169. { SAPP_KEYCODE_PAGE_UP, "PGUP" },
  9170. { SAPP_KEYCODE_PAGE_DOWN, "PGDN" },
  9171. { SAPP_KEYCODE_HOME, "HOME" },
  9172. { SAPP_KEYCODE_END, "END" },
  9173. { SAPP_KEYCODE_CAPS_LOCK, "CAPS" },
  9174. { SAPP_KEYCODE_SCROLL_LOCK, "SCLK" },
  9175. { SAPP_KEYCODE_NUM_LOCK, "NMLK" },
  9176. { SAPP_KEYCODE_PRINT_SCREEN, "PRSC" },
  9177. { SAPP_KEYCODE_PAUSE, "PAUS" },
  9178. { SAPP_KEYCODE_F1, "FK01" },
  9179. { SAPP_KEYCODE_F2, "FK02" },
  9180. { SAPP_KEYCODE_F3, "FK03" },
  9181. { SAPP_KEYCODE_F4, "FK04" },
  9182. { SAPP_KEYCODE_F5, "FK05" },
  9183. { SAPP_KEYCODE_F6, "FK06" },
  9184. { SAPP_KEYCODE_F7, "FK07" },
  9185. { SAPP_KEYCODE_F8, "FK08" },
  9186. { SAPP_KEYCODE_F9, "FK09" },
  9187. { SAPP_KEYCODE_F10, "FK10" },
  9188. { SAPP_KEYCODE_F11, "FK11" },
  9189. { SAPP_KEYCODE_F12, "FK12" },
  9190. { SAPP_KEYCODE_F13, "FK13" },
  9191. { SAPP_KEYCODE_F14, "FK14" },
  9192. { SAPP_KEYCODE_F15, "FK15" },
  9193. { SAPP_KEYCODE_F16, "FK16" },
  9194. { SAPP_KEYCODE_F17, "FK17" },
  9195. { SAPP_KEYCODE_F18, "FK18" },
  9196. { SAPP_KEYCODE_F19, "FK19" },
  9197. { SAPP_KEYCODE_F20, "FK20" },
  9198. { SAPP_KEYCODE_F21, "FK21" },
  9199. { SAPP_KEYCODE_F22, "FK22" },
  9200. { SAPP_KEYCODE_F23, "FK23" },
  9201. { SAPP_KEYCODE_F24, "FK24" },
  9202. { SAPP_KEYCODE_F25, "FK25" },
  9203. { SAPP_KEYCODE_KP_0, "KP0" },
  9204. { SAPP_KEYCODE_KP_1, "KP1" },
  9205. { SAPP_KEYCODE_KP_2, "KP2" },
  9206. { SAPP_KEYCODE_KP_3, "KP3" },
  9207. { SAPP_KEYCODE_KP_4, "KP4" },
  9208. { SAPP_KEYCODE_KP_5, "KP5" },
  9209. { SAPP_KEYCODE_KP_6, "KP6" },
  9210. { SAPP_KEYCODE_KP_7, "KP7" },
  9211. { SAPP_KEYCODE_KP_8, "KP8" },
  9212. { SAPP_KEYCODE_KP_9, "KP9" },
  9213. { SAPP_KEYCODE_KP_DECIMAL, "KPDL" },
  9214. { SAPP_KEYCODE_KP_DIVIDE, "KPDV" },
  9215. { SAPP_KEYCODE_KP_MULTIPLY, "KPMU" },
  9216. { SAPP_KEYCODE_KP_SUBTRACT, "KPSU" },
  9217. { SAPP_KEYCODE_KP_ADD, "KPAD" },
  9218. { SAPP_KEYCODE_KP_ENTER, "KPEN" },
  9219. { SAPP_KEYCODE_KP_EQUAL, "KPEQ" },
  9220. { SAPP_KEYCODE_LEFT_SHIFT, "LFSH" },
  9221. { SAPP_KEYCODE_LEFT_CONTROL, "LCTL" },
  9222. { SAPP_KEYCODE_LEFT_ALT, "LALT" },
  9223. { SAPP_KEYCODE_LEFT_SUPER, "LWIN" },
  9224. { SAPP_KEYCODE_RIGHT_SHIFT, "RTSH" },
  9225. { SAPP_KEYCODE_RIGHT_CONTROL, "RCTL" },
  9226. { SAPP_KEYCODE_RIGHT_ALT, "RALT" },
  9227. { SAPP_KEYCODE_RIGHT_ALT, "LVL3" },
  9228. { SAPP_KEYCODE_RIGHT_ALT, "MDSW" },
  9229. { SAPP_KEYCODE_RIGHT_SUPER, "RWIN" },
  9230. { SAPP_KEYCODE_MENU, "MENU" }
  9231. };
  9232. const int num_keymap_items = (int)(sizeof(keymap) / sizeof(keymap[0]));
  9233. // find X11 keycode to sokol-app key code mapping
  9234. for (int scancode = scancode_min; scancode <= scancode_max; scancode++) {
  9235. sapp_keycode key = SAPP_KEYCODE_INVALID;
  9236. for (int i = 0; i < num_keymap_items; i++) {
  9237. if (strncmp(desc->names->keys[scancode].name, keymap[i].name, XkbKeyNameLength) == 0) {
  9238. key = keymap[i].key;
  9239. break;
  9240. }
  9241. }
  9242. // fall back to key aliases in case the key name did not match
  9243. for (int i = 0; i < desc->names->num_key_aliases; i++) {
  9244. if (key != SAPP_KEYCODE_INVALID) {
  9245. break;
  9246. }
  9247. if (strncmp(desc->names->key_aliases[i].real, desc->names->keys[scancode].name, XkbKeyNameLength) != 0) {
  9248. continue;
  9249. }
  9250. for (int j = 0; j < num_keymap_items; j++) {
  9251. if (strncmp(desc->names->key_aliases[i].alias, keymap[i].name, XkbKeyNameLength) == 0) {
  9252. key = keymap[i].key;
  9253. break;
  9254. }
  9255. }
  9256. }
  9257. _sapp.keycodes[scancode] = key;
  9258. }
  9259. XkbFreeNames(desc, XkbKeyNamesMask, True);
  9260. XkbFreeKeyboard(desc, 0, True);
  9261. int width = 0;
  9262. KeySym* keysyms = XGetKeyboardMapping(_sapp.x11.display, scancode_min, scancode_max - scancode_min + 1, &width);
  9263. for (int scancode = scancode_min; scancode <= scancode_max; scancode++) {
  9264. // translate untranslated key codes using the traditional X11 KeySym lookups
  9265. if (_sapp.keycodes[scancode] == SAPP_KEYCODE_INVALID) {
  9266. const size_t base = (size_t)((scancode - scancode_min) * width);
  9267. _sapp.keycodes[scancode] = _sapp_x11_translate_keysyms(&keysyms[base], width);
  9268. }
  9269. }
  9270. XFree(keysyms);
  9271. }
  9272. _SOKOL_PRIVATE void _sapp_x11_query_system_dpi(void) {
  9273. /* from GLFW:
  9274. NOTE: Default to the display-wide DPI as we don't currently have a policy
  9275. for which monitor a window is considered to be on
  9276. _sapp.x11.dpi = DisplayWidth(_sapp.x11.display, _sapp.x11.screen) *
  9277. 25.4f / DisplayWidthMM(_sapp.x11.display, _sapp.x11.screen);
  9278. NOTE: Basing the scale on Xft.dpi where available should provide the most
  9279. consistent user experience (matches Qt, Gtk, etc), although not
  9280. always the most accurate one
  9281. */
  9282. bool dpi_ok = false;
  9283. char* rms = XResourceManagerString(_sapp.x11.display);
  9284. if (rms) {
  9285. XrmDatabase db = XrmGetStringDatabase(rms);
  9286. if (db) {
  9287. XrmValue value;
  9288. char* type = NULL;
  9289. if (XrmGetResource(db, "Xft.dpi", "Xft.Dpi", &type, &value)) {
  9290. if (type && strcmp(type, "String") == 0) {
  9291. _sapp.x11.dpi = atof(value.addr);
  9292. dpi_ok = true;
  9293. }
  9294. }
  9295. XrmDestroyDatabase(db);
  9296. }
  9297. }
  9298. // fallback if querying DPI had failed: assume the standard DPI 96.0f
  9299. if (!dpi_ok) {
  9300. _sapp.x11.dpi = 96.0f;
  9301. _SAPP_WARN(LINUX_X11_QUERY_SYSTEM_DPI_FAILED);
  9302. }
  9303. }
  9304. #if defined(_SAPP_GLX)
  9305. _SOKOL_PRIVATE bool _sapp_glx_has_ext(const char* ext, const char* extensions) {
  9306. SOKOL_ASSERT(ext);
  9307. const char* start = extensions;
  9308. while (true) {
  9309. const char* where = strstr(start, ext);
  9310. if (!where) {
  9311. return false;
  9312. }
  9313. const char* terminator = where + strlen(ext);
  9314. if ((where == start) || (*(where - 1) == ' ')) {
  9315. if (*terminator == ' ' || *terminator == '\0') {
  9316. break;
  9317. }
  9318. }
  9319. start = terminator;
  9320. }
  9321. return true;
  9322. }
  9323. _SOKOL_PRIVATE bool _sapp_glx_extsupported(const char* ext, const char* extensions) {
  9324. if (extensions) {
  9325. return _sapp_glx_has_ext(ext, extensions);
  9326. }
  9327. else {
  9328. return false;
  9329. }
  9330. }
  9331. _SOKOL_PRIVATE void* _sapp_glx_getprocaddr(const char* procname)
  9332. {
  9333. if (_sapp.glx.GetProcAddress) {
  9334. return (void*) _sapp.glx.GetProcAddress(procname);
  9335. }
  9336. else if (_sapp.glx.GetProcAddressARB) {
  9337. return (void*) _sapp.glx.GetProcAddressARB(procname);
  9338. }
  9339. else {
  9340. return dlsym(_sapp.glx.libgl, procname);
  9341. }
  9342. }
  9343. _SOKOL_PRIVATE void _sapp_glx_init(void) {
  9344. const char* sonames[] = { "libGL.so.1", "libGL.so", 0 };
  9345. for (int i = 0; sonames[i]; i++) {
  9346. _sapp.glx.libgl = dlopen(sonames[i], RTLD_LAZY|RTLD_GLOBAL);
  9347. if (_sapp.glx.libgl) {
  9348. break;
  9349. }
  9350. }
  9351. if (!_sapp.glx.libgl) {
  9352. _SAPP_PANIC(LINUX_GLX_LOAD_LIBGL_FAILED);
  9353. }
  9354. _sapp.glx.GetFBConfigs = (PFNGLXGETFBCONFIGSPROC) dlsym(_sapp.glx.libgl, "glXGetFBConfigs");
  9355. _sapp.glx.GetFBConfigAttrib = (PFNGLXGETFBCONFIGATTRIBPROC) dlsym(_sapp.glx.libgl, "glXGetFBConfigAttrib");
  9356. _sapp.glx.GetClientString = (PFNGLXGETCLIENTSTRINGPROC) dlsym(_sapp.glx.libgl, "glXGetClientString");
  9357. _sapp.glx.QueryExtension = (PFNGLXQUERYEXTENSIONPROC) dlsym(_sapp.glx.libgl, "glXQueryExtension");
  9358. _sapp.glx.QueryVersion = (PFNGLXQUERYVERSIONPROC) dlsym(_sapp.glx.libgl, "glXQueryVersion");
  9359. _sapp.glx.DestroyContext = (PFNGLXDESTROYCONTEXTPROC) dlsym(_sapp.glx.libgl, "glXDestroyContext");
  9360. _sapp.glx.MakeCurrent = (PFNGLXMAKECURRENTPROC) dlsym(_sapp.glx.libgl, "glXMakeCurrent");
  9361. _sapp.glx.SwapBuffers = (PFNGLXSWAPBUFFERSPROC) dlsym(_sapp.glx.libgl, "glXSwapBuffers");
  9362. _sapp.glx.QueryExtensionsString = (PFNGLXQUERYEXTENSIONSSTRINGPROC) dlsym(_sapp.glx.libgl, "glXQueryExtensionsString");
  9363. _sapp.glx.CreateWindow = (PFNGLXCREATEWINDOWPROC) dlsym(_sapp.glx.libgl, "glXCreateWindow");
  9364. _sapp.glx.DestroyWindow = (PFNGLXDESTROYWINDOWPROC) dlsym(_sapp.glx.libgl, "glXDestroyWindow");
  9365. _sapp.glx.GetProcAddress = (PFNGLXGETPROCADDRESSPROC) dlsym(_sapp.glx.libgl, "glXGetProcAddress");
  9366. _sapp.glx.GetProcAddressARB = (PFNGLXGETPROCADDRESSPROC) dlsym(_sapp.glx.libgl, "glXGetProcAddressARB");
  9367. _sapp.glx.GetVisualFromFBConfig = (PFNGLXGETVISUALFROMFBCONFIGPROC) dlsym(_sapp.glx.libgl, "glXGetVisualFromFBConfig");
  9368. if (!_sapp.glx.GetFBConfigs ||
  9369. !_sapp.glx.GetFBConfigAttrib ||
  9370. !_sapp.glx.GetClientString ||
  9371. !_sapp.glx.QueryExtension ||
  9372. !_sapp.glx.QueryVersion ||
  9373. !_sapp.glx.DestroyContext ||
  9374. !_sapp.glx.MakeCurrent ||
  9375. !_sapp.glx.SwapBuffers ||
  9376. !_sapp.glx.QueryExtensionsString ||
  9377. !_sapp.glx.CreateWindow ||
  9378. !_sapp.glx.DestroyWindow ||
  9379. !_sapp.glx.GetProcAddress ||
  9380. !_sapp.glx.GetProcAddressARB ||
  9381. !_sapp.glx.GetVisualFromFBConfig)
  9382. {
  9383. _SAPP_PANIC(LINUX_GLX_LOAD_ENTRY_POINTS_FAILED);
  9384. }
  9385. if (!_sapp.glx.QueryExtension(_sapp.x11.display, &_sapp.glx.error_base, &_sapp.glx.event_base)) {
  9386. _SAPP_PANIC(LINUX_GLX_EXTENSION_NOT_FOUND);
  9387. }
  9388. if (!_sapp.glx.QueryVersion(_sapp.x11.display, &_sapp.glx.major, &_sapp.glx.minor)) {
  9389. _SAPP_PANIC(LINUX_GLX_QUERY_VERSION_FAILED);
  9390. }
  9391. if (_sapp.glx.major == 1 && _sapp.glx.minor < 3) {
  9392. _SAPP_PANIC(LINUX_GLX_VERSION_TOO_LOW);
  9393. }
  9394. const char* exts = _sapp.glx.QueryExtensionsString(_sapp.x11.display, _sapp.x11.screen);
  9395. if (_sapp_glx_extsupported("GLX_EXT_swap_control", exts)) {
  9396. _sapp.glx.SwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) _sapp_glx_getprocaddr("glXSwapIntervalEXT");
  9397. _sapp.glx.EXT_swap_control = 0 != _sapp.glx.SwapIntervalEXT;
  9398. }
  9399. if (_sapp_glx_extsupported("GLX_MESA_swap_control", exts)) {
  9400. _sapp.glx.SwapIntervalMESA = (PFNGLXSWAPINTERVALMESAPROC) _sapp_glx_getprocaddr("glXSwapIntervalMESA");
  9401. _sapp.glx.MESA_swap_control = 0 != _sapp.glx.SwapIntervalMESA;
  9402. }
  9403. _sapp.glx.ARB_multisample = _sapp_glx_extsupported("GLX_ARB_multisample", exts);
  9404. if (_sapp_glx_extsupported("GLX_ARB_create_context", exts)) {
  9405. _sapp.glx.CreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC) _sapp_glx_getprocaddr("glXCreateContextAttribsARB");
  9406. _sapp.glx.ARB_create_context = 0 != _sapp.glx.CreateContextAttribsARB;
  9407. }
  9408. _sapp.glx.ARB_create_context_profile = _sapp_glx_extsupported("GLX_ARB_create_context_profile", exts);
  9409. }
  9410. _SOKOL_PRIVATE int _sapp_glx_attrib(GLXFBConfig fbconfig, int attrib) {
  9411. int value;
  9412. _sapp.glx.GetFBConfigAttrib(_sapp.x11.display, fbconfig, attrib, &value);
  9413. return value;
  9414. }
  9415. _SOKOL_PRIVATE GLXFBConfig _sapp_glx_choosefbconfig(void) {
  9416. GLXFBConfig* native_configs;
  9417. _sapp_gl_fbconfig* usable_configs;
  9418. const _sapp_gl_fbconfig* closest;
  9419. int i, native_count, usable_count;
  9420. const char* vendor;
  9421. bool trust_window_bit = true;
  9422. /* HACK: This is a (hopefully temporary) workaround for Chromium
  9423. (VirtualBox GL) not setting the window bit on any GLXFBConfigs
  9424. */
  9425. vendor = _sapp.glx.GetClientString(_sapp.x11.display, GLX_VENDOR);
  9426. if (vendor && strcmp(vendor, "Chromium") == 0) {
  9427. trust_window_bit = false;
  9428. }
  9429. native_configs = _sapp.glx.GetFBConfigs(_sapp.x11.display, _sapp.x11.screen, &native_count);
  9430. if (!native_configs || !native_count) {
  9431. _SAPP_PANIC(LINUX_GLX_NO_GLXFBCONFIGS);
  9432. }
  9433. usable_configs = (_sapp_gl_fbconfig*) _sapp_malloc_clear((size_t)native_count * sizeof(_sapp_gl_fbconfig));
  9434. usable_count = 0;
  9435. for (i = 0; i < native_count; i++) {
  9436. const GLXFBConfig n = native_configs[i];
  9437. _sapp_gl_fbconfig* u = usable_configs + usable_count;
  9438. _sapp_gl_init_fbconfig(u);
  9439. /* Only consider RGBA GLXFBConfigs */
  9440. if (0 == (_sapp_glx_attrib(n, GLX_RENDER_TYPE) & GLX_RGBA_BIT)) {
  9441. continue;
  9442. }
  9443. /* Only consider window GLXFBConfigs */
  9444. if (0 == (_sapp_glx_attrib(n, GLX_DRAWABLE_TYPE) & GLX_WINDOW_BIT)) {
  9445. if (trust_window_bit) {
  9446. continue;
  9447. }
  9448. }
  9449. u->red_bits = _sapp_glx_attrib(n, GLX_RED_SIZE);
  9450. u->green_bits = _sapp_glx_attrib(n, GLX_GREEN_SIZE);
  9451. u->blue_bits = _sapp_glx_attrib(n, GLX_BLUE_SIZE);
  9452. u->alpha_bits = _sapp_glx_attrib(n, GLX_ALPHA_SIZE);
  9453. u->depth_bits = _sapp_glx_attrib(n, GLX_DEPTH_SIZE);
  9454. u->stencil_bits = _sapp_glx_attrib(n, GLX_STENCIL_SIZE);
  9455. if (_sapp_glx_attrib(n, GLX_DOUBLEBUFFER)) {
  9456. u->doublebuffer = true;
  9457. }
  9458. if (_sapp.glx.ARB_multisample) {
  9459. u->samples = _sapp_glx_attrib(n, GLX_SAMPLES);
  9460. }
  9461. u->handle = (uintptr_t) n;
  9462. usable_count++;
  9463. }
  9464. _sapp_gl_fbconfig desired;
  9465. _sapp_gl_init_fbconfig(&desired);
  9466. desired.red_bits = 8;
  9467. desired.green_bits = 8;
  9468. desired.blue_bits = 8;
  9469. desired.alpha_bits = 8;
  9470. desired.depth_bits = 24;
  9471. desired.stencil_bits = 8;
  9472. desired.doublebuffer = true;
  9473. desired.samples = _sapp.sample_count > 1 ? _sapp.sample_count : 0;
  9474. closest = _sapp_gl_choose_fbconfig(&desired, usable_configs, usable_count);
  9475. GLXFBConfig result = 0;
  9476. if (closest) {
  9477. result = (GLXFBConfig) closest->handle;
  9478. }
  9479. XFree(native_configs);
  9480. _sapp_free(usable_configs);
  9481. return result;
  9482. }
  9483. _SOKOL_PRIVATE void _sapp_glx_choose_visual(Visual** visual, int* depth) {
  9484. GLXFBConfig native = _sapp_glx_choosefbconfig();
  9485. if (0 == native) {
  9486. _SAPP_PANIC(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG);
  9487. }
  9488. XVisualInfo* result = _sapp.glx.GetVisualFromFBConfig(_sapp.x11.display, native);
  9489. if (!result) {
  9490. _SAPP_PANIC(LINUX_GLX_GET_VISUAL_FROM_FBCONFIG_FAILED);
  9491. }
  9492. *visual = result->visual;
  9493. *depth = result->depth;
  9494. XFree(result);
  9495. }
  9496. _SOKOL_PRIVATE void _sapp_glx_make_current(void) {
  9497. _sapp.glx.MakeCurrent(_sapp.x11.display, _sapp.glx.window, _sapp.glx.ctx);
  9498. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  9499. }
  9500. _SOKOL_PRIVATE void _sapp_glx_create_context(void) {
  9501. GLXFBConfig native = _sapp_glx_choosefbconfig();
  9502. if (0 == native){
  9503. _SAPP_PANIC(LINUX_GLX_NO_SUITABLE_GLXFBCONFIG);
  9504. }
  9505. if (!(_sapp.glx.ARB_create_context && _sapp.glx.ARB_create_context_profile)) {
  9506. _SAPP_PANIC(LINUX_GLX_REQUIRED_EXTENSIONS_MISSING);
  9507. }
  9508. _sapp_x11_grab_error_handler();
  9509. const int attribs[] = {
  9510. GLX_CONTEXT_MAJOR_VERSION_ARB, _sapp.desc.gl_major_version,
  9511. GLX_CONTEXT_MINOR_VERSION_ARB, _sapp.desc.gl_minor_version,
  9512. GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
  9513. GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
  9514. 0, 0
  9515. };
  9516. _sapp.glx.ctx = _sapp.glx.CreateContextAttribsARB(_sapp.x11.display, native, NULL, True, attribs);
  9517. if (!_sapp.glx.ctx) {
  9518. _SAPP_PANIC(LINUX_GLX_CREATE_CONTEXT_FAILED);
  9519. }
  9520. _sapp_x11_release_error_handler();
  9521. _sapp.glx.window = _sapp.glx.CreateWindow(_sapp.x11.display, native, _sapp.x11.window, NULL);
  9522. if (!_sapp.glx.window) {
  9523. _SAPP_PANIC(LINUX_GLX_CREATE_WINDOW_FAILED);
  9524. }
  9525. _sapp_glx_make_current();
  9526. }
  9527. _SOKOL_PRIVATE void _sapp_glx_destroy_context(void) {
  9528. if (_sapp.glx.window) {
  9529. _sapp.glx.DestroyWindow(_sapp.x11.display, _sapp.glx.window);
  9530. _sapp.glx.window = 0;
  9531. }
  9532. if (_sapp.glx.ctx) {
  9533. _sapp.glx.DestroyContext(_sapp.x11.display, _sapp.glx.ctx);
  9534. _sapp.glx.ctx = 0;
  9535. }
  9536. }
  9537. _SOKOL_PRIVATE void _sapp_glx_swap_buffers(void) {
  9538. _sapp.glx.SwapBuffers(_sapp.x11.display, _sapp.glx.window);
  9539. }
  9540. _SOKOL_PRIVATE void _sapp_glx_swapinterval(int interval) {
  9541. if (_sapp.glx.EXT_swap_control) {
  9542. _sapp.glx.SwapIntervalEXT(_sapp.x11.display, _sapp.glx.window, interval);
  9543. }
  9544. else if (_sapp.glx.MESA_swap_control) {
  9545. _sapp.glx.SwapIntervalMESA(interval);
  9546. }
  9547. }
  9548. #endif /* _SAPP_GLX */
  9549. _SOKOL_PRIVATE void _sapp_x11_send_event(Atom type, int a, int b, int c, int d, int e) {
  9550. XEvent event;
  9551. _sapp_clear(&event, sizeof(event));
  9552. event.type = ClientMessage;
  9553. event.xclient.window = _sapp.x11.window;
  9554. event.xclient.format = 32;
  9555. event.xclient.message_type = type;
  9556. event.xclient.data.l[0] = a;
  9557. event.xclient.data.l[1] = b;
  9558. event.xclient.data.l[2] = c;
  9559. event.xclient.data.l[3] = d;
  9560. event.xclient.data.l[4] = e;
  9561. XSendEvent(_sapp.x11.display, _sapp.x11.root,
  9562. False,
  9563. SubstructureNotifyMask | SubstructureRedirectMask,
  9564. &event);
  9565. }
  9566. _SOKOL_PRIVATE void _sapp_x11_query_window_size(void) {
  9567. XWindowAttributes attribs;
  9568. XGetWindowAttributes(_sapp.x11.display, _sapp.x11.window, &attribs);
  9569. _sapp.window_width = attribs.width;
  9570. _sapp.window_height = attribs.height;
  9571. _sapp.framebuffer_width = _sapp.window_width;
  9572. _sapp.framebuffer_height = _sapp.window_height;
  9573. }
  9574. _SOKOL_PRIVATE void _sapp_x11_set_fullscreen(bool enable) {
  9575. /* NOTE: this function must be called after XMapWindow (which happens in _sapp_x11_show_window()) */
  9576. if (_sapp.x11.NET_WM_STATE && _sapp.x11.NET_WM_STATE_FULLSCREEN) {
  9577. if (enable) {
  9578. const int _NET_WM_STATE_ADD = 1;
  9579. _sapp_x11_send_event(_sapp.x11.NET_WM_STATE,
  9580. _NET_WM_STATE_ADD,
  9581. _sapp.x11.NET_WM_STATE_FULLSCREEN,
  9582. 0, 1, 0);
  9583. }
  9584. else {
  9585. const int _NET_WM_STATE_REMOVE = 0;
  9586. _sapp_x11_send_event(_sapp.x11.NET_WM_STATE,
  9587. _NET_WM_STATE_REMOVE,
  9588. _sapp.x11.NET_WM_STATE_FULLSCREEN,
  9589. 0, 1, 0);
  9590. }
  9591. }
  9592. XFlush(_sapp.x11.display);
  9593. }
  9594. _SOKOL_PRIVATE void _sapp_x11_create_hidden_cursor(void) {
  9595. SOKOL_ASSERT(0 == _sapp.x11.hidden_cursor);
  9596. const int w = 16;
  9597. const int h = 16;
  9598. XcursorImage* img = XcursorImageCreate(w, h);
  9599. SOKOL_ASSERT(img && (img->width == 16) && (img->height == 16) && img->pixels);
  9600. img->xhot = 0;
  9601. img->yhot = 0;
  9602. const size_t num_bytes = (size_t)(w * h) * sizeof(XcursorPixel);
  9603. _sapp_clear(img->pixels, num_bytes);
  9604. _sapp.x11.hidden_cursor = XcursorImageLoadCursor(_sapp.x11.display, img);
  9605. XcursorImageDestroy(img);
  9606. }
  9607. _SOKOL_PRIVATE void _sapp_x11_create_standard_cursor(sapp_mouse_cursor cursor, const char* name, const char* theme, int size, uint32_t fallback_native) {
  9608. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  9609. SOKOL_ASSERT(_sapp.x11.display);
  9610. if (theme) {
  9611. XcursorImage* img = XcursorLibraryLoadImage(name, theme, size);
  9612. if (img) {
  9613. _sapp.x11.cursors[cursor] = XcursorImageLoadCursor(_sapp.x11.display, img);
  9614. XcursorImageDestroy(img);
  9615. }
  9616. }
  9617. if (0 == _sapp.x11.cursors[cursor]) {
  9618. _sapp.x11.cursors[cursor] = XCreateFontCursor(_sapp.x11.display, fallback_native);
  9619. }
  9620. }
  9621. _SOKOL_PRIVATE void _sapp_x11_create_cursors(void) {
  9622. SOKOL_ASSERT(_sapp.x11.display);
  9623. const char* cursor_theme = XcursorGetTheme(_sapp.x11.display);
  9624. const int size = XcursorGetDefaultSize(_sapp.x11.display);
  9625. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_ARROW, "default", cursor_theme, size, XC_left_ptr);
  9626. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_IBEAM, "text", cursor_theme, size, XC_xterm);
  9627. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_CROSSHAIR, "crosshair", cursor_theme, size, XC_crosshair);
  9628. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_POINTING_HAND, "pointer", cursor_theme, size, XC_hand2);
  9629. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_EW, "ew-resize", cursor_theme, size, XC_sb_h_double_arrow);
  9630. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NS, "ns-resize", cursor_theme, size, XC_sb_v_double_arrow);
  9631. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NWSE, "nwse-resize", cursor_theme, size, 0);
  9632. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_NESW, "nesw-resize", cursor_theme, size, 0);
  9633. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_RESIZE_ALL, "all-scroll", cursor_theme, size, XC_fleur);
  9634. _sapp_x11_create_standard_cursor(SAPP_MOUSECURSOR_NOT_ALLOWED, "no-allowed", cursor_theme, size, 0);
  9635. _sapp_x11_create_hidden_cursor();
  9636. }
  9637. _SOKOL_PRIVATE void _sapp_x11_destroy_cursors(void) {
  9638. SOKOL_ASSERT(_sapp.x11.display);
  9639. if (_sapp.x11.hidden_cursor) {
  9640. XFreeCursor(_sapp.x11.display, _sapp.x11.hidden_cursor);
  9641. _sapp.x11.hidden_cursor = 0;
  9642. }
  9643. for (int i = 0; i < _SAPP_MOUSECURSOR_NUM; i++) {
  9644. if (_sapp.x11.cursors[i]) {
  9645. XFreeCursor(_sapp.x11.display, _sapp.x11.cursors[i]);
  9646. _sapp.x11.cursors[i] = 0;
  9647. }
  9648. }
  9649. }
  9650. _SOKOL_PRIVATE void _sapp_x11_toggle_fullscreen(void) {
  9651. _sapp.fullscreen = !_sapp.fullscreen;
  9652. _sapp_x11_set_fullscreen(_sapp.fullscreen);
  9653. _sapp_x11_query_window_size();
  9654. }
  9655. _SOKOL_PRIVATE void _sapp_x11_update_cursor(sapp_mouse_cursor cursor, bool shown) {
  9656. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  9657. if (shown) {
  9658. if (_sapp.x11.cursors[cursor]) {
  9659. XDefineCursor(_sapp.x11.display, _sapp.x11.window, _sapp.x11.cursors[cursor]);
  9660. }
  9661. else {
  9662. XUndefineCursor(_sapp.x11.display, _sapp.x11.window);
  9663. }
  9664. }
  9665. else {
  9666. XDefineCursor(_sapp.x11.display, _sapp.x11.window, _sapp.x11.hidden_cursor);
  9667. }
  9668. XFlush(_sapp.x11.display);
  9669. }
  9670. _SOKOL_PRIVATE void _sapp_x11_lock_mouse(bool lock) {
  9671. if (lock == _sapp.mouse.locked) {
  9672. return;
  9673. }
  9674. _sapp.mouse.dx = 0.0f;
  9675. _sapp.mouse.dy = 0.0f;
  9676. _sapp.mouse.locked = lock;
  9677. if (_sapp.mouse.locked) {
  9678. if (_sapp.x11.xi.available) {
  9679. XIEventMask em;
  9680. unsigned char mask[XIMaskLen(XI_RawMotion)] = { 0 }; // XIMaskLen is a macro
  9681. em.deviceid = XIAllMasterDevices;
  9682. em.mask_len = sizeof(mask);
  9683. em.mask = mask;
  9684. XISetMask(mask, XI_RawMotion);
  9685. XISelectEvents(_sapp.x11.display, _sapp.x11.root, &em, 1);
  9686. }
  9687. XGrabPointer(_sapp.x11.display, // display
  9688. _sapp.x11.window, // grab_window
  9689. True, // owner_events
  9690. ButtonPressMask | ButtonReleaseMask | PointerMotionMask, // event_mask
  9691. GrabModeAsync, // pointer_mode
  9692. GrabModeAsync, // keyboard_mode
  9693. _sapp.x11.window, // confine_to
  9694. _sapp.x11.hidden_cursor, // cursor
  9695. CurrentTime); // time
  9696. }
  9697. else {
  9698. if (_sapp.x11.xi.available) {
  9699. XIEventMask em;
  9700. unsigned char mask[] = { 0 };
  9701. em.deviceid = XIAllMasterDevices;
  9702. em.mask_len = sizeof(mask);
  9703. em.mask = mask;
  9704. XISelectEvents(_sapp.x11.display, _sapp.x11.root, &em, 1);
  9705. }
  9706. XWarpPointer(_sapp.x11.display, None, _sapp.x11.window, 0, 0, 0, 0, (int) _sapp.mouse.x, _sapp.mouse.y);
  9707. XUngrabPointer(_sapp.x11.display, CurrentTime);
  9708. }
  9709. XFlush(_sapp.x11.display);
  9710. }
  9711. _SOKOL_PRIVATE void _sapp_x11_set_clipboard_string(const char* str) {
  9712. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  9713. if (strlen(str) >= (size_t)_sapp.clipboard.buf_size) {
  9714. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  9715. }
  9716. XSetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD, _sapp.x11.window, CurrentTime);
  9717. if (XGetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD) != _sapp.x11.window) {
  9718. _SAPP_ERROR(LINUX_X11_FAILED_TO_BECOME_OWNER_OF_CLIPBOARD);
  9719. }
  9720. }
  9721. _SOKOL_PRIVATE const char* _sapp_x11_get_clipboard_string(void) {
  9722. SOKOL_ASSERT(_sapp.clipboard.enabled && _sapp.clipboard.buffer);
  9723. Atom none = XInternAtom(_sapp.x11.display, "SAPP_SELECTION", False);
  9724. Atom incremental = XInternAtom(_sapp.x11.display, "INCR", False);
  9725. if (XGetSelectionOwner(_sapp.x11.display, _sapp.x11.CLIPBOARD) == _sapp.x11.window) {
  9726. // Instead of doing a large number of X round-trips just to put this
  9727. // string into a window property and then read it back, just return it
  9728. return _sapp.clipboard.buffer;
  9729. }
  9730. XConvertSelection(_sapp.x11.display,
  9731. _sapp.x11.CLIPBOARD,
  9732. _sapp.x11.UTF8_STRING,
  9733. none,
  9734. _sapp.x11.window,
  9735. CurrentTime);
  9736. XEvent event;
  9737. while (!XCheckTypedWindowEvent(_sapp.x11.display, _sapp.x11.window, SelectionNotify, &event)) {
  9738. // Wait for event data to arrive on the X11 display socket
  9739. struct pollfd fd = { ConnectionNumber(_sapp.x11.display), POLLIN };
  9740. while (!XPending(_sapp.x11.display)) {
  9741. poll(&fd, 1, -1);
  9742. }
  9743. }
  9744. if (event.xselection.property == None) {
  9745. return NULL;
  9746. }
  9747. char* data = NULL;
  9748. Atom actualType;
  9749. int actualFormat;
  9750. unsigned long itemCount, bytesAfter;
  9751. const bool ret = XGetWindowProperty(_sapp.x11.display,
  9752. event.xselection.requestor,
  9753. event.xselection.property,
  9754. 0,
  9755. LONG_MAX,
  9756. True,
  9757. _sapp.x11.UTF8_STRING,
  9758. &actualType,
  9759. &actualFormat,
  9760. &itemCount,
  9761. &bytesAfter,
  9762. (unsigned char**) &data);
  9763. if (ret != Success || data == NULL) {
  9764. if (data != NULL) {
  9765. XFree(data);
  9766. }
  9767. return NULL;
  9768. }
  9769. if ((actualType == incremental) || (itemCount >= (size_t)_sapp.clipboard.buf_size)) {
  9770. _SAPP_ERROR(CLIPBOARD_STRING_TOO_BIG);
  9771. XFree(data);
  9772. return NULL;
  9773. }
  9774. _sapp_strcpy(data, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  9775. XFree(data);
  9776. return _sapp.clipboard.buffer;
  9777. }
  9778. _SOKOL_PRIVATE void _sapp_x11_update_window_title(void) {
  9779. Xutf8SetWMProperties(_sapp.x11.display,
  9780. _sapp.x11.window,
  9781. _sapp.window_title, _sapp.window_title,
  9782. NULL, 0, NULL, NULL, NULL);
  9783. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9784. _sapp.x11.NET_WM_NAME, _sapp.x11.UTF8_STRING, 8,
  9785. PropModeReplace,
  9786. (unsigned char*)_sapp.window_title,
  9787. strlen(_sapp.window_title));
  9788. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9789. _sapp.x11.NET_WM_ICON_NAME, _sapp.x11.UTF8_STRING, 8,
  9790. PropModeReplace,
  9791. (unsigned char*)_sapp.window_title,
  9792. strlen(_sapp.window_title));
  9793. XFlush(_sapp.x11.display);
  9794. }
  9795. _SOKOL_PRIVATE void _sapp_x11_set_icon(const sapp_icon_desc* icon_desc, int num_images) {
  9796. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  9797. int long_count = 0;
  9798. for (int i = 0; i < num_images; i++) {
  9799. const sapp_image_desc* img_desc = &icon_desc->images[i];
  9800. long_count += 2 + (img_desc->width * img_desc->height);
  9801. }
  9802. long* icon_data = (long*) _sapp_malloc_clear((size_t)long_count * sizeof(long));
  9803. SOKOL_ASSERT(icon_data);
  9804. long* dst = icon_data;
  9805. for (int img_index = 0; img_index < num_images; img_index++) {
  9806. const sapp_image_desc* img_desc = &icon_desc->images[img_index];
  9807. const uint8_t* src = (const uint8_t*) img_desc->pixels.ptr;
  9808. *dst++ = img_desc->width;
  9809. *dst++ = img_desc->height;
  9810. const int num_pixels = img_desc->width * img_desc->height;
  9811. for (int pixel_index = 0; pixel_index < num_pixels; pixel_index++) {
  9812. *dst++ = ((long)(src[pixel_index * 4 + 0]) << 16) |
  9813. ((long)(src[pixel_index * 4 + 1]) << 8) |
  9814. ((long)(src[pixel_index * 4 + 2]) << 0) |
  9815. ((long)(src[pixel_index * 4 + 3]) << 24);
  9816. }
  9817. }
  9818. XChangeProperty(_sapp.x11.display, _sapp.x11.window,
  9819. _sapp.x11.NET_WM_ICON,
  9820. XA_CARDINAL, 32,
  9821. PropModeReplace,
  9822. (unsigned char*)icon_data,
  9823. long_count);
  9824. _sapp_free(icon_data);
  9825. XFlush(_sapp.x11.display);
  9826. }
  9827. _SOKOL_PRIVATE void _sapp_x11_create_window(Visual* visual, int depth) {
  9828. _sapp.x11.colormap = XCreateColormap(_sapp.x11.display, _sapp.x11.root, visual, AllocNone);
  9829. XSetWindowAttributes wa;
  9830. _sapp_clear(&wa, sizeof(wa));
  9831. const uint32_t wamask = CWBorderPixel | CWColormap | CWEventMask;
  9832. wa.colormap = _sapp.x11.colormap;
  9833. wa.border_pixel = 0;
  9834. wa.event_mask = StructureNotifyMask | KeyPressMask | KeyReleaseMask |
  9835. PointerMotionMask | ButtonPressMask | ButtonReleaseMask |
  9836. ExposureMask | FocusChangeMask | VisibilityChangeMask |
  9837. EnterWindowMask | LeaveWindowMask | PropertyChangeMask;
  9838. int display_width = DisplayWidth(_sapp.x11.display, _sapp.x11.screen);
  9839. int display_height = DisplayHeight(_sapp.x11.display, _sapp.x11.screen);
  9840. int window_width = _sapp.window_width;
  9841. int window_height = _sapp.window_height;
  9842. if (0 == window_width) {
  9843. window_width = (display_width * 4) / 5;
  9844. }
  9845. if (0 == window_height) {
  9846. window_height = (display_height * 4) / 5;
  9847. }
  9848. int window_xpos = (display_width - window_width) / 2;
  9849. int window_ypos = (display_height - window_height) / 2;
  9850. if (window_xpos < 0) {
  9851. window_xpos = 0;
  9852. }
  9853. if (window_ypos < 0) {
  9854. window_ypos = 0;
  9855. }
  9856. _sapp_x11_grab_error_handler();
  9857. _sapp.x11.window = XCreateWindow(_sapp.x11.display,
  9858. _sapp.x11.root,
  9859. window_xpos,
  9860. window_ypos,
  9861. (uint32_t)window_width,
  9862. (uint32_t)window_height,
  9863. 0, /* border width */
  9864. depth, /* color depth */
  9865. InputOutput,
  9866. visual,
  9867. wamask,
  9868. &wa);
  9869. _sapp_x11_release_error_handler();
  9870. if (!_sapp.x11.window) {
  9871. _SAPP_PANIC(LINUX_X11_CREATE_WINDOW_FAILED);
  9872. }
  9873. Atom protocols[] = {
  9874. _sapp.x11.WM_DELETE_WINDOW
  9875. };
  9876. XSetWMProtocols(_sapp.x11.display, _sapp.x11.window, protocols, 1);
  9877. XSizeHints* hints = XAllocSizeHints();
  9878. hints->flags = (PWinGravity | PPosition | PSize);
  9879. hints->win_gravity = StaticGravity;
  9880. hints->x = window_xpos;
  9881. hints->y = window_ypos;
  9882. hints->width = window_width;
  9883. hints->height = window_height;
  9884. XSetWMNormalHints(_sapp.x11.display, _sapp.x11.window, hints);
  9885. XFree(hints);
  9886. /* announce support for drag'n'drop */
  9887. if (_sapp.drop.enabled) {
  9888. const Atom version = _SAPP_X11_XDND_VERSION;
  9889. XChangeProperty(_sapp.x11.display, _sapp.x11.window, _sapp.x11.xdnd.XdndAware, XA_ATOM, 32, PropModeReplace, (unsigned char*) &version, 1);
  9890. }
  9891. _sapp_x11_update_window_title();
  9892. _sapp_x11_query_window_size();
  9893. }
  9894. _SOKOL_PRIVATE void _sapp_x11_destroy_window(void) {
  9895. if (_sapp.x11.window) {
  9896. XUnmapWindow(_sapp.x11.display, _sapp.x11.window);
  9897. XDestroyWindow(_sapp.x11.display, _sapp.x11.window);
  9898. _sapp.x11.window = 0;
  9899. }
  9900. if (_sapp.x11.colormap) {
  9901. XFreeColormap(_sapp.x11.display, _sapp.x11.colormap);
  9902. _sapp.x11.colormap = 0;
  9903. }
  9904. XFlush(_sapp.x11.display);
  9905. }
  9906. _SOKOL_PRIVATE bool _sapp_x11_window_visible(void) {
  9907. XWindowAttributes wa;
  9908. XGetWindowAttributes(_sapp.x11.display, _sapp.x11.window, &wa);
  9909. return wa.map_state == IsViewable;
  9910. }
  9911. _SOKOL_PRIVATE void _sapp_x11_show_window(void) {
  9912. if (!_sapp_x11_window_visible()) {
  9913. XMapWindow(_sapp.x11.display, _sapp.x11.window);
  9914. XRaiseWindow(_sapp.x11.display, _sapp.x11.window);
  9915. XFlush(_sapp.x11.display);
  9916. }
  9917. }
  9918. _SOKOL_PRIVATE void _sapp_x11_hide_window(void) {
  9919. XUnmapWindow(_sapp.x11.display, _sapp.x11.window);
  9920. XFlush(_sapp.x11.display);
  9921. }
  9922. _SOKOL_PRIVATE unsigned long _sapp_x11_get_window_property(Window window, Atom property, Atom type, unsigned char** value) {
  9923. Atom actualType;
  9924. int actualFormat;
  9925. unsigned long itemCount, bytesAfter;
  9926. XGetWindowProperty(_sapp.x11.display,
  9927. window,
  9928. property,
  9929. 0,
  9930. LONG_MAX,
  9931. False,
  9932. type,
  9933. &actualType,
  9934. &actualFormat,
  9935. &itemCount,
  9936. &bytesAfter,
  9937. value);
  9938. return itemCount;
  9939. }
  9940. _SOKOL_PRIVATE int _sapp_x11_get_window_state(void) {
  9941. int result = WithdrawnState;
  9942. struct {
  9943. CARD32 state;
  9944. Window icon;
  9945. } *state = NULL;
  9946. if (_sapp_x11_get_window_property(_sapp.x11.window, _sapp.x11.WM_STATE, _sapp.x11.WM_STATE, (unsigned char**)&state) >= 2) {
  9947. result = (int)state->state;
  9948. }
  9949. if (state) {
  9950. XFree(state);
  9951. }
  9952. return result;
  9953. }
  9954. _SOKOL_PRIVATE uint32_t _sapp_x11_key_modifier_bit(sapp_keycode key) {
  9955. switch (key) {
  9956. case SAPP_KEYCODE_LEFT_SHIFT:
  9957. case SAPP_KEYCODE_RIGHT_SHIFT:
  9958. return SAPP_MODIFIER_SHIFT;
  9959. case SAPP_KEYCODE_LEFT_CONTROL:
  9960. case SAPP_KEYCODE_RIGHT_CONTROL:
  9961. return SAPP_MODIFIER_CTRL;
  9962. case SAPP_KEYCODE_LEFT_ALT:
  9963. case SAPP_KEYCODE_RIGHT_ALT:
  9964. return SAPP_MODIFIER_ALT;
  9965. case SAPP_KEYCODE_LEFT_SUPER:
  9966. case SAPP_KEYCODE_RIGHT_SUPER:
  9967. return SAPP_MODIFIER_SUPER;
  9968. default:
  9969. return 0;
  9970. }
  9971. }
  9972. _SOKOL_PRIVATE uint32_t _sapp_x11_button_modifier_bit(sapp_mousebutton btn) {
  9973. switch (btn) {
  9974. case SAPP_MOUSEBUTTON_LEFT: return SAPP_MODIFIER_LMB;
  9975. case SAPP_MOUSEBUTTON_RIGHT: return SAPP_MODIFIER_RMB;
  9976. case SAPP_MOUSEBUTTON_MIDDLE: return SAPP_MODIFIER_MMB;
  9977. default: return 0;
  9978. }
  9979. }
  9980. _SOKOL_PRIVATE uint32_t _sapp_x11_mods(uint32_t x11_mods) {
  9981. uint32_t mods = 0;
  9982. if (x11_mods & ShiftMask) {
  9983. mods |= SAPP_MODIFIER_SHIFT;
  9984. }
  9985. if (x11_mods & ControlMask) {
  9986. mods |= SAPP_MODIFIER_CTRL;
  9987. }
  9988. if (x11_mods & Mod1Mask) {
  9989. mods |= SAPP_MODIFIER_ALT;
  9990. }
  9991. if (x11_mods & Mod4Mask) {
  9992. mods |= SAPP_MODIFIER_SUPER;
  9993. }
  9994. if (x11_mods & Button1Mask) {
  9995. mods |= SAPP_MODIFIER_LMB;
  9996. }
  9997. if (x11_mods & Button2Mask) {
  9998. mods |= SAPP_MODIFIER_MMB;
  9999. }
  10000. if (x11_mods & Button3Mask) {
  10001. mods |= SAPP_MODIFIER_RMB;
  10002. }
  10003. return mods;
  10004. }
  10005. _SOKOL_PRIVATE void _sapp_x11_app_event(sapp_event_type type) {
  10006. if (_sapp_events_enabled()) {
  10007. _sapp_init_event(type);
  10008. _sapp_call_event(&_sapp.event);
  10009. }
  10010. }
  10011. _SOKOL_PRIVATE sapp_mousebutton _sapp_x11_translate_button(const XEvent* event) {
  10012. switch (event->xbutton.button) {
  10013. case Button1: return SAPP_MOUSEBUTTON_LEFT;
  10014. case Button2: return SAPP_MOUSEBUTTON_MIDDLE;
  10015. case Button3: return SAPP_MOUSEBUTTON_RIGHT;
  10016. default: return SAPP_MOUSEBUTTON_INVALID;
  10017. }
  10018. }
  10019. _SOKOL_PRIVATE void _sapp_x11_mouse_update(int x, int y, bool clear_dxdy) {
  10020. if (!_sapp.mouse.locked) {
  10021. const float new_x = (float) x;
  10022. const float new_y = (float) y;
  10023. if (clear_dxdy) {
  10024. _sapp.mouse.dx = 0.0f;
  10025. _sapp.mouse.dy = 0.0f;
  10026. } else if (_sapp.mouse.pos_valid) {
  10027. _sapp.mouse.dx = new_x - _sapp.mouse.x;
  10028. _sapp.mouse.dy = new_y - _sapp.mouse.y;
  10029. }
  10030. _sapp.mouse.x = new_x;
  10031. _sapp.mouse.y = new_y;
  10032. _sapp.mouse.pos_valid = true;
  10033. }
  10034. }
  10035. _SOKOL_PRIVATE void _sapp_x11_mouse_event(sapp_event_type type, sapp_mousebutton btn, uint32_t mods) {
  10036. if (_sapp_events_enabled()) {
  10037. _sapp_init_event(type);
  10038. _sapp.event.mouse_button = btn;
  10039. _sapp.event.modifiers = mods;
  10040. _sapp_call_event(&_sapp.event);
  10041. }
  10042. }
  10043. _SOKOL_PRIVATE void _sapp_x11_scroll_event(float x, float y, uint32_t mods) {
  10044. if (_sapp_events_enabled()) {
  10045. _sapp_init_event(SAPP_EVENTTYPE_MOUSE_SCROLL);
  10046. _sapp.event.modifiers = mods;
  10047. _sapp.event.scroll_x = x;
  10048. _sapp.event.scroll_y = y;
  10049. _sapp_call_event(&_sapp.event);
  10050. }
  10051. }
  10052. _SOKOL_PRIVATE void _sapp_x11_key_event(sapp_event_type type, sapp_keycode key, bool repeat, uint32_t mods) {
  10053. if (_sapp_events_enabled()) {
  10054. _sapp_init_event(type);
  10055. _sapp.event.key_code = key;
  10056. _sapp.event.key_repeat = repeat;
  10057. _sapp.event.modifiers = mods;
  10058. _sapp_call_event(&_sapp.event);
  10059. /* check if a CLIPBOARD_PASTED event must be sent too */
  10060. if (_sapp.clipboard.enabled &&
  10061. (type == SAPP_EVENTTYPE_KEY_DOWN) &&
  10062. (_sapp.event.modifiers == SAPP_MODIFIER_CTRL) &&
  10063. (_sapp.event.key_code == SAPP_KEYCODE_V))
  10064. {
  10065. _sapp_init_event(SAPP_EVENTTYPE_CLIPBOARD_PASTED);
  10066. _sapp_call_event(&_sapp.event);
  10067. }
  10068. }
  10069. }
  10070. _SOKOL_PRIVATE void _sapp_x11_char_event(uint32_t chr, bool repeat, uint32_t mods) {
  10071. if (_sapp_events_enabled()) {
  10072. _sapp_init_event(SAPP_EVENTTYPE_CHAR);
  10073. _sapp.event.char_code = chr;
  10074. _sapp.event.key_repeat = repeat;
  10075. _sapp.event.modifiers = mods;
  10076. _sapp_call_event(&_sapp.event);
  10077. }
  10078. }
  10079. _SOKOL_PRIVATE sapp_keycode _sapp_x11_translate_key(int scancode) {
  10080. if ((scancode >= 0) && (scancode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10081. return _sapp.keycodes[scancode];
  10082. } else {
  10083. return SAPP_KEYCODE_INVALID;
  10084. }
  10085. }
  10086. _SOKOL_PRIVATE int32_t _sapp_x11_keysym_to_unicode(KeySym keysym) {
  10087. int min = 0;
  10088. int max = sizeof(_sapp_x11_keysymtab) / sizeof(struct _sapp_x11_codepair) - 1;
  10089. int mid;
  10090. /* First check for Latin-1 characters (1:1 mapping) */
  10091. if ((keysym >= 0x0020 && keysym <= 0x007e) ||
  10092. (keysym >= 0x00a0 && keysym <= 0x00ff))
  10093. {
  10094. return keysym;
  10095. }
  10096. /* Also check for directly encoded 24-bit UCS characters */
  10097. if ((keysym & 0xff000000) == 0x01000000) {
  10098. return keysym & 0x00ffffff;
  10099. }
  10100. /* Binary search in table */
  10101. while (max >= min) {
  10102. mid = (min + max) / 2;
  10103. if (_sapp_x11_keysymtab[mid].keysym < keysym) {
  10104. min = mid + 1;
  10105. }
  10106. else if (_sapp_x11_keysymtab[mid].keysym > keysym) {
  10107. max = mid - 1;
  10108. }
  10109. else {
  10110. return _sapp_x11_keysymtab[mid].ucs;
  10111. }
  10112. }
  10113. /* No matching Unicode value found */
  10114. return -1;
  10115. }
  10116. _SOKOL_PRIVATE bool _sapp_x11_keypress_repeat(int keycode) {
  10117. bool repeat = false;
  10118. if ((keycode >= 0) && (keycode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10119. repeat = _sapp.x11.key_repeat[keycode];
  10120. _sapp.x11.key_repeat[keycode] = true;
  10121. }
  10122. return repeat;
  10123. }
  10124. _SOKOL_PRIVATE void _sapp_x11_keyrelease_repeat(int keycode) {
  10125. if ((keycode >= 0) && (keycode < _SAPP_X11_MAX_X11_KEYCODES)) {
  10126. _sapp.x11.key_repeat[keycode] = false;
  10127. }
  10128. }
  10129. _SOKOL_PRIVATE bool _sapp_x11_parse_dropped_files_list(const char* src) {
  10130. SOKOL_ASSERT(src);
  10131. SOKOL_ASSERT(_sapp.drop.buffer);
  10132. _sapp_clear_drop_buffer();
  10133. _sapp.drop.num_files = 0;
  10134. /*
  10135. src is (potentially percent-encoded) string made of one or multiple paths
  10136. separated by \r\n, each path starting with 'file://'
  10137. */
  10138. bool err = false;
  10139. int src_count = 0;
  10140. char src_chr = 0;
  10141. char* dst_ptr = _sapp.drop.buffer;
  10142. const char* dst_end_ptr = dst_ptr + (_sapp.drop.max_path_length - 1); // room for terminating 0
  10143. while (0 != (src_chr = *src++)) {
  10144. src_count++;
  10145. char dst_chr = 0;
  10146. /* check leading 'file://' */
  10147. if (src_count <= 7) {
  10148. if (((src_count == 1) && (src_chr != 'f')) ||
  10149. ((src_count == 2) && (src_chr != 'i')) ||
  10150. ((src_count == 3) && (src_chr != 'l')) ||
  10151. ((src_count == 4) && (src_chr != 'e')) ||
  10152. ((src_count == 5) && (src_chr != ':')) ||
  10153. ((src_count == 6) && (src_chr != '/')) ||
  10154. ((src_count == 7) && (src_chr != '/')))
  10155. {
  10156. _SAPP_ERROR(LINUX_X11_DROPPED_FILE_URI_WRONG_SCHEME);
  10157. err = true;
  10158. break;
  10159. }
  10160. }
  10161. else if (src_chr == '\r') {
  10162. // skip
  10163. }
  10164. else if (src_chr == '\n') {
  10165. src_count = 0;
  10166. _sapp.drop.num_files++;
  10167. // too many files is not an error
  10168. if (_sapp.drop.num_files >= _sapp.drop.max_files) {
  10169. break;
  10170. }
  10171. dst_ptr = _sapp.drop.buffer + _sapp.drop.num_files * _sapp.drop.max_path_length;
  10172. dst_end_ptr = dst_ptr + (_sapp.drop.max_path_length - 1);
  10173. }
  10174. else if ((src_chr == '%') && src[0] && src[1]) {
  10175. // a percent-encoded byte (most likely UTF-8 multibyte sequence)
  10176. const char digits[3] = { src[0], src[1], 0 };
  10177. src += 2;
  10178. dst_chr = (char) strtol(digits, 0, 16);
  10179. }
  10180. else {
  10181. dst_chr = src_chr;
  10182. }
  10183. if (dst_chr) {
  10184. // dst_end_ptr already has adjustment for terminating zero
  10185. if (dst_ptr < dst_end_ptr) {
  10186. *dst_ptr++ = dst_chr;
  10187. }
  10188. else {
  10189. _SAPP_ERROR(DROPPED_FILE_PATH_TOO_LONG);
  10190. err = true;
  10191. break;
  10192. }
  10193. }
  10194. }
  10195. if (err) {
  10196. _sapp_clear_drop_buffer();
  10197. _sapp.drop.num_files = 0;
  10198. return false;
  10199. }
  10200. else {
  10201. return true;
  10202. }
  10203. }
  10204. _SOKOL_PRIVATE void _sapp_x11_on_genericevent(XEvent* event) {
  10205. if (_sapp.mouse.locked && _sapp.x11.xi.available) {
  10206. if (event->xcookie.extension == _sapp.x11.xi.major_opcode) {
  10207. if (XGetEventData(_sapp.x11.display, &event->xcookie)) {
  10208. if (event->xcookie.evtype == XI_RawMotion) {
  10209. XIRawEvent* re = (XIRawEvent*) event->xcookie.data;
  10210. if (re->valuators.mask_len) {
  10211. const double* values = re->raw_values;
  10212. if (XIMaskIsSet(re->valuators.mask, 0)) {
  10213. _sapp.mouse.dx = (float) *values;
  10214. values++;
  10215. }
  10216. if (XIMaskIsSet(re->valuators.mask, 1)) {
  10217. _sapp.mouse.dy = (float) *values;
  10218. }
  10219. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xmotion.state));
  10220. }
  10221. }
  10222. XFreeEventData(_sapp.x11.display, &event->xcookie);
  10223. }
  10224. }
  10225. }
  10226. }
  10227. _SOKOL_PRIVATE void _sapp_x11_on_focusin(XEvent* event) {
  10228. // NOTE: ignoring NotifyGrab and NotifyUngrab is same behaviour as GLFW
  10229. if ((event->xfocus.mode != NotifyGrab) && (event->xfocus.mode != NotifyUngrab)) {
  10230. _sapp_x11_app_event(SAPP_EVENTTYPE_FOCUSED);
  10231. }
  10232. }
  10233. _SOKOL_PRIVATE void _sapp_x11_on_focusout(XEvent* event) {
  10234. // if focus is lost for any reason, and we're in mouse locked mode, disable mouse lock
  10235. if (_sapp.mouse.locked) {
  10236. _sapp_x11_lock_mouse(false);
  10237. }
  10238. // NOTE: ignoring NotifyGrab and NotifyUngrab is same behaviour as GLFW
  10239. if ((event->xfocus.mode != NotifyGrab) && (event->xfocus.mode != NotifyUngrab)) {
  10240. _sapp_x11_app_event(SAPP_EVENTTYPE_UNFOCUSED);
  10241. }
  10242. }
  10243. _SOKOL_PRIVATE void _sapp_x11_on_keypress(XEvent* event) {
  10244. int keycode = (int)event->xkey.keycode;
  10245. const sapp_keycode key = _sapp_x11_translate_key(keycode);
  10246. const bool repeat = _sapp_x11_keypress_repeat(keycode);
  10247. uint32_t mods = _sapp_x11_mods(event->xkey.state);
  10248. // X11 doesn't set modifier bit on key down, so emulate that
  10249. mods |= _sapp_x11_key_modifier_bit(key);
  10250. if (key != SAPP_KEYCODE_INVALID) {
  10251. _sapp_x11_key_event(SAPP_EVENTTYPE_KEY_DOWN, key, repeat, mods);
  10252. }
  10253. KeySym keysym;
  10254. XLookupString(&event->xkey, NULL, 0, &keysym, NULL);
  10255. int32_t chr = _sapp_x11_keysym_to_unicode(keysym);
  10256. if (chr > 0) {
  10257. _sapp_x11_char_event((uint32_t)chr, repeat, mods);
  10258. }
  10259. }
  10260. _SOKOL_PRIVATE void _sapp_x11_on_keyrelease(XEvent* event) {
  10261. int keycode = (int)event->xkey.keycode;
  10262. const sapp_keycode key = _sapp_x11_translate_key(keycode);
  10263. _sapp_x11_keyrelease_repeat(keycode);
  10264. if (key != SAPP_KEYCODE_INVALID) {
  10265. uint32_t mods = _sapp_x11_mods(event->xkey.state);
  10266. // X11 doesn't clear modifier bit on key up, so emulate that
  10267. mods &= ~_sapp_x11_key_modifier_bit(key);
  10268. _sapp_x11_key_event(SAPP_EVENTTYPE_KEY_UP, key, false, mods);
  10269. }
  10270. }
  10271. _SOKOL_PRIVATE void _sapp_x11_on_buttonpress(XEvent* event) {
  10272. _sapp_x11_mouse_update(event->xbutton.x, event->xbutton.y, false);
  10273. const sapp_mousebutton btn = _sapp_x11_translate_button(event);
  10274. uint32_t mods = _sapp_x11_mods(event->xbutton.state);
  10275. // X11 doesn't set modifier bit on button down, so emulate that
  10276. mods |= _sapp_x11_button_modifier_bit(btn);
  10277. if (btn != SAPP_MOUSEBUTTON_INVALID) {
  10278. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_DOWN, btn, mods);
  10279. _sapp.x11.mouse_buttons |= (1 << btn);
  10280. }
  10281. else {
  10282. // might be a scroll event
  10283. switch (event->xbutton.button) {
  10284. case 4: _sapp_x11_scroll_event(0.0f, 1.0f, mods); break;
  10285. case 5: _sapp_x11_scroll_event(0.0f, -1.0f, mods); break;
  10286. case 6: _sapp_x11_scroll_event(1.0f, 0.0f, mods); break;
  10287. case 7: _sapp_x11_scroll_event(-1.0f, 0.0f, mods); break;
  10288. }
  10289. }
  10290. }
  10291. _SOKOL_PRIVATE void _sapp_x11_on_buttonrelease(XEvent* event) {
  10292. _sapp_x11_mouse_update(event->xbutton.x, event->xbutton.y, false);
  10293. const sapp_mousebutton btn = _sapp_x11_translate_button(event);
  10294. if (btn != SAPP_MOUSEBUTTON_INVALID) {
  10295. uint32_t mods = _sapp_x11_mods(event->xbutton.state);
  10296. // X11 doesn't clear modifier bit on button up, so emulate that
  10297. mods &= ~_sapp_x11_button_modifier_bit(btn);
  10298. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_UP, btn, mods);
  10299. _sapp.x11.mouse_buttons &= ~(1 << btn);
  10300. }
  10301. }
  10302. _SOKOL_PRIVATE void _sapp_x11_on_enternotify(XEvent* event) {
  10303. // don't send enter/leave events while mouse button held down
  10304. if (0 == _sapp.x11.mouse_buttons) {
  10305. _sapp_x11_mouse_update(event->xcrossing.x, event->xcrossing.y, true);
  10306. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_ENTER, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xcrossing.state));
  10307. }
  10308. }
  10309. _SOKOL_PRIVATE void _sapp_x11_on_leavenotify(XEvent* event) {
  10310. if (0 == _sapp.x11.mouse_buttons) {
  10311. _sapp_x11_mouse_update(event->xcrossing.x, event->xcrossing.y, true);
  10312. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_LEAVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xcrossing.state));
  10313. }
  10314. }
  10315. _SOKOL_PRIVATE void _sapp_x11_on_motionnotify(XEvent* event) {
  10316. if (!_sapp.mouse.locked) {
  10317. _sapp_x11_mouse_update(event->xmotion.x, event->xmotion.y, false);
  10318. _sapp_x11_mouse_event(SAPP_EVENTTYPE_MOUSE_MOVE, SAPP_MOUSEBUTTON_INVALID, _sapp_x11_mods(event->xmotion.state));
  10319. }
  10320. }
  10321. _SOKOL_PRIVATE void _sapp_x11_on_configurenotify(XEvent* event) {
  10322. if ((event->xconfigure.width != _sapp.window_width) || (event->xconfigure.height != _sapp.window_height)) {
  10323. _sapp.window_width = event->xconfigure.width;
  10324. _sapp.window_height = event->xconfigure.height;
  10325. _sapp.framebuffer_width = _sapp.window_width;
  10326. _sapp.framebuffer_height = _sapp.window_height;
  10327. _sapp_x11_app_event(SAPP_EVENTTYPE_RESIZED);
  10328. }
  10329. }
  10330. _SOKOL_PRIVATE void _sapp_x11_on_propertynotify(XEvent* event) {
  10331. if (event->xproperty.state == PropertyNewValue) {
  10332. if (event->xproperty.atom == _sapp.x11.WM_STATE) {
  10333. const int state = _sapp_x11_get_window_state();
  10334. if (state != _sapp.x11.window_state) {
  10335. _sapp.x11.window_state = state;
  10336. if (state == IconicState) {
  10337. _sapp_x11_app_event(SAPP_EVENTTYPE_ICONIFIED);
  10338. }
  10339. else if (state == NormalState) {
  10340. _sapp_x11_app_event(SAPP_EVENTTYPE_RESTORED);
  10341. }
  10342. }
  10343. }
  10344. }
  10345. }
  10346. _SOKOL_PRIVATE void _sapp_x11_on_selectionnotify(XEvent* event) {
  10347. if (event->xselection.property == _sapp.x11.xdnd.XdndSelection) {
  10348. char* data = 0;
  10349. uint32_t result = _sapp_x11_get_window_property(event->xselection.requestor,
  10350. event->xselection.property,
  10351. event->xselection.target,
  10352. (unsigned char**) &data);
  10353. if (_sapp.drop.enabled && result) {
  10354. if (_sapp_x11_parse_dropped_files_list(data)) {
  10355. _sapp.mouse.dx = 0.0f;
  10356. _sapp.mouse.dy = 0.0f;
  10357. if (_sapp_events_enabled()) {
  10358. // FIXME: Figure out how to get modifier key state here.
  10359. // The XSelection event has no 'state' item, and
  10360. // XQueryKeymap() always returns a zeroed array.
  10361. _sapp_init_event(SAPP_EVENTTYPE_FILES_DROPPED);
  10362. _sapp_call_event(&_sapp.event);
  10363. }
  10364. }
  10365. }
  10366. if (_sapp.x11.xdnd.version >= 2) {
  10367. XEvent reply;
  10368. _sapp_clear(&reply, sizeof(reply));
  10369. reply.type = ClientMessage;
  10370. reply.xclient.window = _sapp.x11.xdnd.source;
  10371. reply.xclient.message_type = _sapp.x11.xdnd.XdndFinished;
  10372. reply.xclient.format = 32;
  10373. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10374. reply.xclient.data.l[1] = result;
  10375. reply.xclient.data.l[2] = (long)_sapp.x11.xdnd.XdndActionCopy;
  10376. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10377. XFlush(_sapp.x11.display);
  10378. }
  10379. }
  10380. }
  10381. _SOKOL_PRIVATE void _sapp_x11_on_clientmessage(XEvent* event) {
  10382. if (XFilterEvent(event, None)) {
  10383. return;
  10384. }
  10385. if (event->xclient.message_type == _sapp.x11.WM_PROTOCOLS) {
  10386. const Atom protocol = (Atom)event->xclient.data.l[0];
  10387. if (protocol == _sapp.x11.WM_DELETE_WINDOW) {
  10388. _sapp.quit_requested = true;
  10389. }
  10390. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndEnter) {
  10391. const bool is_list = 0 != (event->xclient.data.l[1] & 1);
  10392. _sapp.x11.xdnd.source = (Window)event->xclient.data.l[0];
  10393. _sapp.x11.xdnd.version = event->xclient.data.l[1] >> 24;
  10394. _sapp.x11.xdnd.format = None;
  10395. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10396. return;
  10397. }
  10398. uint32_t count = 0;
  10399. Atom* formats = 0;
  10400. if (is_list) {
  10401. count = _sapp_x11_get_window_property(_sapp.x11.xdnd.source, _sapp.x11.xdnd.XdndTypeList, XA_ATOM, (unsigned char**)&formats);
  10402. } else {
  10403. count = 3;
  10404. formats = (Atom*) event->xclient.data.l + 2;
  10405. }
  10406. for (uint32_t i = 0; i < count; i++) {
  10407. if (formats[i] == _sapp.x11.xdnd.text_uri_list) {
  10408. _sapp.x11.xdnd.format = _sapp.x11.xdnd.text_uri_list;
  10409. break;
  10410. }
  10411. }
  10412. if (is_list && formats) {
  10413. XFree(formats);
  10414. }
  10415. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndDrop) {
  10416. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10417. return;
  10418. }
  10419. Time time = CurrentTime;
  10420. if (_sapp.x11.xdnd.format) {
  10421. if (_sapp.x11.xdnd.version >= 1) {
  10422. time = (Time)event->xclient.data.l[2];
  10423. }
  10424. XConvertSelection(_sapp.x11.display,
  10425. _sapp.x11.xdnd.XdndSelection,
  10426. _sapp.x11.xdnd.format,
  10427. _sapp.x11.xdnd.XdndSelection,
  10428. _sapp.x11.window,
  10429. time);
  10430. } else if (_sapp.x11.xdnd.version >= 2) {
  10431. XEvent reply;
  10432. _sapp_clear(&reply, sizeof(reply));
  10433. reply.type = ClientMessage;
  10434. reply.xclient.window = _sapp.x11.xdnd.source;
  10435. reply.xclient.message_type = _sapp.x11.xdnd.XdndFinished;
  10436. reply.xclient.format = 32;
  10437. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10438. reply.xclient.data.l[1] = 0; // drag was rejected
  10439. reply.xclient.data.l[2] = None;
  10440. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10441. XFlush(_sapp.x11.display);
  10442. }
  10443. } else if (event->xclient.message_type == _sapp.x11.xdnd.XdndPosition) {
  10444. // drag operation has moved over the window
  10445. // FIXME: we could track the mouse position here, but
  10446. // this isn't implemented on other platforms either so far
  10447. if (_sapp.x11.xdnd.version > _SAPP_X11_XDND_VERSION) {
  10448. return;
  10449. }
  10450. XEvent reply;
  10451. _sapp_clear(&reply, sizeof(reply));
  10452. reply.type = ClientMessage;
  10453. reply.xclient.window = _sapp.x11.xdnd.source;
  10454. reply.xclient.message_type = _sapp.x11.xdnd.XdndStatus;
  10455. reply.xclient.format = 32;
  10456. reply.xclient.data.l[0] = (long)_sapp.x11.window;
  10457. if (_sapp.x11.xdnd.format) {
  10458. /* reply that we are ready to copy the dragged data */
  10459. reply.xclient.data.l[1] = 1; // accept with no rectangle
  10460. if (_sapp.x11.xdnd.version >= 2) {
  10461. reply.xclient.data.l[4] = (long)_sapp.x11.xdnd.XdndActionCopy;
  10462. }
  10463. }
  10464. XSendEvent(_sapp.x11.display, _sapp.x11.xdnd.source, False, NoEventMask, &reply);
  10465. XFlush(_sapp.x11.display);
  10466. }
  10467. }
  10468. _SOKOL_PRIVATE void _sapp_x11_on_selectionrequest(XEvent* event) {
  10469. XSelectionRequestEvent* req = &event->xselectionrequest;
  10470. if (req->selection != _sapp.x11.CLIPBOARD) {
  10471. return;
  10472. }
  10473. if (!_sapp.clipboard.enabled) {
  10474. return;
  10475. }
  10476. SOKOL_ASSERT(_sapp.clipboard.buffer);
  10477. XSelectionEvent reply;
  10478. _sapp_clear(&reply, sizeof(reply));
  10479. reply.type = SelectionNotify;
  10480. reply.display = req->display;
  10481. reply.requestor = req->requestor;
  10482. reply.selection = req->selection;
  10483. reply.target = req->target;
  10484. reply.property = req->property;
  10485. reply.time = req->time;
  10486. if (req->target == _sapp.x11.UTF8_STRING) {
  10487. XChangeProperty(_sapp.x11.display,
  10488. req->requestor,
  10489. req->property,
  10490. _sapp.x11.UTF8_STRING,
  10491. 8,
  10492. PropModeReplace,
  10493. (unsigned char*) _sapp.clipboard.buffer,
  10494. strlen(_sapp.clipboard.buffer));
  10495. } else if (req->target == _sapp.x11.TARGETS) {
  10496. XChangeProperty(_sapp.x11.display,
  10497. req->requestor,
  10498. req->property,
  10499. XA_ATOM,
  10500. 32,
  10501. PropModeReplace,
  10502. (unsigned char*) &_sapp.x11.UTF8_STRING,
  10503. 1);
  10504. } else {
  10505. reply.property = None;
  10506. }
  10507. XSendEvent(_sapp.x11.display, req->requestor, False, 0, (XEvent*) &reply);
  10508. }
  10509. _SOKOL_PRIVATE void _sapp_x11_process_event(XEvent* event) {
  10510. switch (event->type) {
  10511. case GenericEvent:
  10512. _sapp_x11_on_genericevent(event);
  10513. break;
  10514. case FocusIn:
  10515. _sapp_x11_on_focusin(event);
  10516. break;
  10517. case FocusOut:
  10518. _sapp_x11_on_focusout(event);
  10519. break;
  10520. case KeyPress:
  10521. _sapp_x11_on_keypress(event);
  10522. break;
  10523. case KeyRelease:
  10524. _sapp_x11_on_keyrelease(event);
  10525. break;
  10526. case ButtonPress:
  10527. _sapp_x11_on_buttonpress(event);
  10528. break;
  10529. case ButtonRelease:
  10530. _sapp_x11_on_buttonrelease(event);
  10531. break;
  10532. case EnterNotify:
  10533. _sapp_x11_on_enternotify(event);
  10534. break;
  10535. case LeaveNotify:
  10536. _sapp_x11_on_leavenotify(event);
  10537. break;
  10538. case MotionNotify:
  10539. _sapp_x11_on_motionnotify(event);
  10540. break;
  10541. case ConfigureNotify:
  10542. _sapp_x11_on_configurenotify(event);
  10543. break;
  10544. case PropertyNotify:
  10545. _sapp_x11_on_propertynotify(event);
  10546. break;
  10547. case SelectionNotify:
  10548. _sapp_x11_on_selectionnotify(event);
  10549. break;
  10550. case SelectionRequest:
  10551. _sapp_x11_on_selectionrequest(event);
  10552. break;
  10553. case DestroyNotify:
  10554. // not a bug
  10555. break;
  10556. case ClientMessage:
  10557. _sapp_x11_on_clientmessage(event);
  10558. break;
  10559. }
  10560. }
  10561. #if !defined(_SAPP_GLX)
  10562. _SOKOL_PRIVATE void _sapp_egl_init(void) {
  10563. #if defined(SOKOL_GLCORE)
  10564. if (!eglBindAPI(EGL_OPENGL_API)) {
  10565. _SAPP_PANIC(LINUX_EGL_BIND_OPENGL_API_FAILED);
  10566. }
  10567. #else
  10568. if (!eglBindAPI(EGL_OPENGL_ES_API)) {
  10569. _SAPP_PANIC(LINUX_EGL_BIND_OPENGL_ES_API_FAILED);
  10570. }
  10571. #endif
  10572. _sapp.egl.display = eglGetDisplay((EGLNativeDisplayType)_sapp.x11.display);
  10573. if (EGL_NO_DISPLAY == _sapp.egl.display) {
  10574. _SAPP_PANIC(LINUX_EGL_GET_DISPLAY_FAILED);
  10575. }
  10576. EGLint major, minor;
  10577. if (!eglInitialize(_sapp.egl.display, &major, &minor)) {
  10578. _SAPP_PANIC(LINUX_EGL_INITIALIZE_FAILED);
  10579. }
  10580. EGLint sample_count = _sapp.desc.sample_count > 1 ? _sapp.desc.sample_count : 0;
  10581. EGLint alpha_size = _sapp.desc.alpha ? 8 : 0;
  10582. const EGLint config_attrs[] = {
  10583. EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
  10584. #if defined(SOKOL_GLCORE)
  10585. EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
  10586. #elif defined(SOKOL_GLES3)
  10587. EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
  10588. #endif
  10589. EGL_RED_SIZE, 8,
  10590. EGL_GREEN_SIZE, 8,
  10591. EGL_BLUE_SIZE, 8,
  10592. EGL_ALPHA_SIZE, alpha_size,
  10593. EGL_DEPTH_SIZE, 24,
  10594. EGL_STENCIL_SIZE, 8,
  10595. EGL_SAMPLE_BUFFERS, _sapp.desc.sample_count > 1 ? 1 : 0,
  10596. EGL_SAMPLES, sample_count,
  10597. EGL_NONE,
  10598. };
  10599. EGLConfig egl_configs[32];
  10600. EGLint config_count;
  10601. if (!eglChooseConfig(_sapp.egl.display, config_attrs, egl_configs, 32, &config_count) || config_count == 0) {
  10602. _SAPP_PANIC(LINUX_EGL_NO_CONFIGS);
  10603. }
  10604. EGLConfig config = egl_configs[0];
  10605. for (int i = 0; i < config_count; ++i) {
  10606. EGLConfig c = egl_configs[i];
  10607. EGLint r, g, b, a, d, s, n;
  10608. if (eglGetConfigAttrib(_sapp.egl.display, c, EGL_RED_SIZE, &r) &&
  10609. eglGetConfigAttrib(_sapp.egl.display, c, EGL_GREEN_SIZE, &g) &&
  10610. eglGetConfigAttrib(_sapp.egl.display, c, EGL_BLUE_SIZE, &b) &&
  10611. eglGetConfigAttrib(_sapp.egl.display, c, EGL_ALPHA_SIZE, &a) &&
  10612. eglGetConfigAttrib(_sapp.egl.display, c, EGL_DEPTH_SIZE, &d) &&
  10613. eglGetConfigAttrib(_sapp.egl.display, c, EGL_STENCIL_SIZE, &s) &&
  10614. eglGetConfigAttrib(_sapp.egl.display, c, EGL_SAMPLES, &n) &&
  10615. (r == 8) && (g == 8) && (b == 8) && (a == alpha_size) && (d == 24) && (s == 8) && (n == sample_count)) {
  10616. config = c;
  10617. break;
  10618. }
  10619. }
  10620. EGLint visual_id;
  10621. if (!eglGetConfigAttrib(_sapp.egl.display, config, EGL_NATIVE_VISUAL_ID, &visual_id)) {
  10622. _SAPP_PANIC(LINUX_EGL_NO_NATIVE_VISUAL);
  10623. }
  10624. XVisualInfo visual_info_template;
  10625. _sapp_clear(&visual_info_template, sizeof(visual_info_template));
  10626. visual_info_template.visualid = (VisualID)visual_id;
  10627. int num_visuals;
  10628. XVisualInfo* visual_info = XGetVisualInfo(_sapp.x11.display, VisualIDMask, &visual_info_template, &num_visuals);
  10629. if (!visual_info) {
  10630. _SAPP_PANIC(LINUX_EGL_GET_VISUAL_INFO_FAILED);
  10631. }
  10632. _sapp_x11_create_window(visual_info->visual, visual_info->depth);
  10633. XFree(visual_info);
  10634. _sapp.egl.surface = eglCreateWindowSurface(_sapp.egl.display, config, (EGLNativeWindowType)_sapp.x11.window, NULL);
  10635. if (EGL_NO_SURFACE == _sapp.egl.surface) {
  10636. _SAPP_PANIC(LINUX_EGL_CREATE_WINDOW_SURFACE_FAILED);
  10637. }
  10638. EGLint ctx_attrs[] = {
  10639. #if defined(SOKOL_GLCORE)
  10640. EGL_CONTEXT_MAJOR_VERSION, _sapp.desc.gl_major_version,
  10641. EGL_CONTEXT_MINOR_VERSION, _sapp.desc.gl_minor_version,
  10642. EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT,
  10643. #elif defined(SOKOL_GLES3)
  10644. EGL_CONTEXT_CLIENT_VERSION, 3,
  10645. #endif
  10646. EGL_NONE,
  10647. };
  10648. _sapp.egl.context = eglCreateContext(_sapp.egl.display, config, EGL_NO_CONTEXT, ctx_attrs);
  10649. if (EGL_NO_CONTEXT == _sapp.egl.context) {
  10650. _SAPP_PANIC(LINUX_EGL_CREATE_CONTEXT_FAILED);
  10651. }
  10652. if (!eglMakeCurrent(_sapp.egl.display, _sapp.egl.surface, _sapp.egl.surface, _sapp.egl.context)) {
  10653. _SAPP_PANIC(LINUX_EGL_MAKE_CURRENT_FAILED);
  10654. }
  10655. glGetIntegerv(GL_FRAMEBUFFER_BINDING, (GLint*)&_sapp.gl.framebuffer);
  10656. eglSwapInterval(_sapp.egl.display, _sapp.swap_interval);
  10657. }
  10658. _SOKOL_PRIVATE void _sapp_egl_destroy(void) {
  10659. if (_sapp.egl.display != EGL_NO_DISPLAY) {
  10660. eglMakeCurrent(_sapp.egl.display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
  10661. if (_sapp.egl.context != EGL_NO_CONTEXT) {
  10662. eglDestroyContext(_sapp.egl.display, _sapp.egl.context);
  10663. _sapp.egl.context = EGL_NO_CONTEXT;
  10664. }
  10665. if (_sapp.egl.surface != EGL_NO_SURFACE) {
  10666. eglDestroySurface(_sapp.egl.display, _sapp.egl.surface);
  10667. _sapp.egl.surface = EGL_NO_SURFACE;
  10668. }
  10669. eglTerminate(_sapp.egl.display);
  10670. _sapp.egl.display = EGL_NO_DISPLAY;
  10671. }
  10672. }
  10673. #endif /* _SAPP_GLX */
  10674. _SOKOL_PRIVATE void _sapp_linux_run(const sapp_desc* desc) {
  10675. /* The following lines are here to trigger a linker error instead of an
  10676. obscure runtime error if the user has forgotten to add -pthread to
  10677. the compiler or linker options. They have no other purpose.
  10678. */
  10679. pthread_attr_t pthread_attr;
  10680. pthread_attr_init(&pthread_attr);
  10681. pthread_attr_destroy(&pthread_attr);
  10682. _sapp_init_state(desc);
  10683. _sapp.x11.window_state = NormalState;
  10684. XInitThreads();
  10685. XrmInitialize();
  10686. _sapp.x11.display = XOpenDisplay(NULL);
  10687. if (!_sapp.x11.display) {
  10688. _SAPP_PANIC(LINUX_X11_OPEN_DISPLAY_FAILED);
  10689. }
  10690. _sapp.x11.screen = DefaultScreen(_sapp.x11.display);
  10691. _sapp.x11.root = DefaultRootWindow(_sapp.x11.display);
  10692. _sapp_x11_query_system_dpi();
  10693. _sapp.dpi_scale = _sapp.x11.dpi / 96.0f;
  10694. _sapp_x11_init_extensions();
  10695. _sapp_x11_create_cursors();
  10696. XkbSetDetectableAutoRepeat(_sapp.x11.display, true, NULL);
  10697. _sapp_x11_init_keytable();
  10698. #if defined(_SAPP_GLX)
  10699. _sapp_glx_init();
  10700. Visual* visual = 0;
  10701. int depth = 0;
  10702. _sapp_glx_choose_visual(&visual, &depth);
  10703. _sapp_x11_create_window(visual, depth);
  10704. _sapp_glx_create_context();
  10705. _sapp_glx_swapinterval(_sapp.swap_interval);
  10706. #else
  10707. _sapp_egl_init();
  10708. #endif
  10709. sapp_set_icon(&desc->icon);
  10710. _sapp.valid = true;
  10711. _sapp_x11_show_window();
  10712. if (_sapp.fullscreen) {
  10713. _sapp_x11_set_fullscreen(true);
  10714. }
  10715. XFlush(_sapp.x11.display);
  10716. while (!_sapp.quit_ordered) {
  10717. _sapp_timing_measure(&_sapp.timing);
  10718. int count = XPending(_sapp.x11.display);
  10719. while (count--) {
  10720. XEvent event;
  10721. XNextEvent(_sapp.x11.display, &event);
  10722. _sapp_x11_process_event(&event);
  10723. }
  10724. _sapp_frame();
  10725. #if defined(_SAPP_GLX)
  10726. _sapp_glx_swap_buffers();
  10727. #else
  10728. eglSwapBuffers(_sapp.egl.display, _sapp.egl.surface);
  10729. #endif
  10730. XFlush(_sapp.x11.display);
  10731. /* handle quit-requested, either from window or from sapp_request_quit() */
  10732. if (_sapp.quit_requested && !_sapp.quit_ordered) {
  10733. /* give user code a chance to intervene */
  10734. _sapp_x11_app_event(SAPP_EVENTTYPE_QUIT_REQUESTED);
  10735. /* if user code hasn't intervened, quit the app */
  10736. if (_sapp.quit_requested) {
  10737. _sapp.quit_ordered = true;
  10738. }
  10739. }
  10740. }
  10741. _sapp_call_cleanup();
  10742. #if defined(_SAPP_GLX)
  10743. _sapp_glx_destroy_context();
  10744. #else
  10745. _sapp_egl_destroy();
  10746. #endif
  10747. _sapp_x11_destroy_window();
  10748. _sapp_x11_destroy_cursors();
  10749. XCloseDisplay(_sapp.x11.display);
  10750. _sapp_discard_state();
  10751. }
  10752. #if !defined(SOKOL_NO_ENTRY)
  10753. int main(int argc, char* argv[]) {
  10754. sapp_desc desc = sokol_main(argc, argv);
  10755. _sapp_linux_run(&desc);
  10756. return 0;
  10757. }
  10758. #endif /* SOKOL_NO_ENTRY */
  10759. #endif /* _SAPP_LINUX */
  10760. // ██████ ██ ██ ██████ ██ ██ ██████
  10761. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  10762. // ██████ ██ ██ ██████ ██ ██ ██
  10763. // ██ ██ ██ ██ ██ ██ ██ ██
  10764. // ██ ██████ ██████ ███████ ██ ██████
  10765. //
  10766. // >>public
  10767. #if defined(SOKOL_NO_ENTRY)
  10768. SOKOL_API_IMPL void sapp_run(const sapp_desc* desc) {
  10769. SOKOL_ASSERT(desc);
  10770. #if defined(_SAPP_MACOS)
  10771. _sapp_macos_run(desc);
  10772. #elif defined(_SAPP_IOS)
  10773. _sapp_ios_run(desc);
  10774. #elif defined(_SAPP_EMSCRIPTEN)
  10775. _sapp_emsc_run(desc);
  10776. #elif defined(_SAPP_WIN32)
  10777. _sapp_win32_run(desc);
  10778. #elif defined(_SAPP_LINUX)
  10779. _sapp_linux_run(desc);
  10780. #else
  10781. #error "sapp_run() not supported on this platform"
  10782. #endif
  10783. }
  10784. /* this is just a stub so the linker doesn't complain */
  10785. sapp_desc sokol_main(int argc, char* argv[]) {
  10786. _SOKOL_UNUSED(argc);
  10787. _SOKOL_UNUSED(argv);
  10788. sapp_desc desc;
  10789. _sapp_clear(&desc, sizeof(desc));
  10790. return desc;
  10791. }
  10792. #else
  10793. /* likewise, in normal mode, sapp_run() is just an empty stub */
  10794. SOKOL_API_IMPL void sapp_run(const sapp_desc* desc) {
  10795. _SOKOL_UNUSED(desc);
  10796. }
  10797. #endif
  10798. SOKOL_API_IMPL bool sapp_isvalid(void) {
  10799. return _sapp.valid;
  10800. }
  10801. SOKOL_API_IMPL void* sapp_userdata(void) {
  10802. return _sapp.desc.user_data;
  10803. }
  10804. SOKOL_API_IMPL sapp_desc sapp_query_desc(void) {
  10805. return _sapp.desc;
  10806. }
  10807. SOKOL_API_IMPL uint64_t sapp_frame_count(void) {
  10808. return _sapp.frame_count;
  10809. }
  10810. SOKOL_API_IMPL double sapp_frame_duration(void) {
  10811. return _sapp_timing_get_avg(&_sapp.timing);
  10812. }
  10813. SOKOL_API_IMPL int sapp_width(void) {
  10814. return (_sapp.framebuffer_width > 0) ? _sapp.framebuffer_width : 1;
  10815. }
  10816. SOKOL_API_IMPL float sapp_widthf(void) {
  10817. return (float)sapp_width();
  10818. }
  10819. SOKOL_API_IMPL int sapp_height(void) {
  10820. return (_sapp.framebuffer_height > 0) ? _sapp.framebuffer_height : 1;
  10821. }
  10822. SOKOL_API_IMPL float sapp_heightf(void) {
  10823. return (float)sapp_height();
  10824. }
  10825. SOKOL_API_IMPL int sapp_color_format(void) {
  10826. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  10827. switch (_sapp.wgpu.render_format) {
  10828. case WGPUTextureFormat_RGBA8Unorm:
  10829. return _SAPP_PIXELFORMAT_RGBA8;
  10830. case WGPUTextureFormat_BGRA8Unorm:
  10831. return _SAPP_PIXELFORMAT_BGRA8;
  10832. default:
  10833. SOKOL_UNREACHABLE;
  10834. return 0;
  10835. }
  10836. #elif defined(SOKOL_METAL) || defined(SOKOL_D3D11)
  10837. return _SAPP_PIXELFORMAT_BGRA8;
  10838. #else
  10839. return _SAPP_PIXELFORMAT_RGBA8;
  10840. #endif
  10841. }
  10842. SOKOL_API_IMPL int sapp_depth_format(void) {
  10843. return _SAPP_PIXELFORMAT_DEPTH_STENCIL;
  10844. }
  10845. SOKOL_API_IMPL int sapp_sample_count(void) {
  10846. return _sapp.sample_count;
  10847. }
  10848. SOKOL_API_IMPL bool sapp_high_dpi(void) {
  10849. return _sapp.desc.high_dpi && (_sapp.dpi_scale >= 1.5f);
  10850. }
  10851. SOKOL_API_IMPL float sapp_dpi_scale(void) {
  10852. return _sapp.dpi_scale;
  10853. }
  10854. SOKOL_API_IMPL const void* sapp_egl_get_display(void) {
  10855. SOKOL_ASSERT(_sapp.valid);
  10856. #if defined(_SAPP_ANDROID)
  10857. return _sapp.android.display;
  10858. #elif defined(_SAPP_LINUX) && !defined(_SAPP_GLX)
  10859. return _sapp.egl.display;
  10860. #else
  10861. return 0;
  10862. #endif
  10863. }
  10864. SOKOL_API_IMPL const void* sapp_egl_get_context(void) {
  10865. SOKOL_ASSERT(_sapp.valid);
  10866. #if defined(_SAPP_ANDROID)
  10867. return _sapp.android.context;
  10868. #elif defined(_SAPP_LINUX) && !defined(_SAPP_GLX)
  10869. return _sapp.egl.context;
  10870. #else
  10871. return 0;
  10872. #endif
  10873. }
  10874. SOKOL_API_IMPL void sapp_show_keyboard(bool show) {
  10875. #if defined(_SAPP_IOS)
  10876. _sapp_ios_show_keyboard(show);
  10877. #elif defined(_SAPP_ANDROID)
  10878. _sapp_android_show_keyboard(show);
  10879. #else
  10880. _SOKOL_UNUSED(show);
  10881. #endif
  10882. }
  10883. SOKOL_API_IMPL bool sapp_keyboard_shown(void) {
  10884. return _sapp.onscreen_keyboard_shown;
  10885. }
  10886. SOKOL_API_IMPL bool sapp_is_fullscreen(void) {
  10887. return _sapp.fullscreen;
  10888. }
  10889. SOKOL_API_IMPL void sapp_toggle_fullscreen(void) {
  10890. #if defined(_SAPP_MACOS)
  10891. _sapp_macos_toggle_fullscreen();
  10892. #elif defined(_SAPP_WIN32)
  10893. _sapp_win32_toggle_fullscreen();
  10894. #elif defined(_SAPP_LINUX)
  10895. _sapp_x11_toggle_fullscreen();
  10896. #endif
  10897. }
  10898. /* NOTE that sapp_show_mouse() does not "stack" like the Win32 or macOS API functions! */
  10899. SOKOL_API_IMPL void sapp_show_mouse(bool show) {
  10900. if (_sapp.mouse.shown != show) {
  10901. #if defined(_SAPP_MACOS)
  10902. _sapp_macos_update_cursor(_sapp.mouse.current_cursor, show);
  10903. #elif defined(_SAPP_WIN32)
  10904. _sapp_win32_update_cursor(_sapp.mouse.current_cursor, show, false);
  10905. #elif defined(_SAPP_LINUX)
  10906. _sapp_x11_update_cursor(_sapp.mouse.current_cursor, show);
  10907. #elif defined(_SAPP_EMSCRIPTEN)
  10908. _sapp_emsc_update_cursor(_sapp.mouse.current_cursor, show);
  10909. #endif
  10910. _sapp.mouse.shown = show;
  10911. }
  10912. }
  10913. SOKOL_API_IMPL bool sapp_mouse_shown(void) {
  10914. return _sapp.mouse.shown;
  10915. }
  10916. SOKOL_API_IMPL void sapp_lock_mouse(bool lock) {
  10917. #if defined(_SAPP_MACOS)
  10918. _sapp_macos_lock_mouse(lock);
  10919. #elif defined(_SAPP_EMSCRIPTEN)
  10920. _sapp_emsc_lock_mouse(lock);
  10921. #elif defined(_SAPP_WIN32)
  10922. _sapp_win32_lock_mouse(lock);
  10923. #elif defined(_SAPP_LINUX)
  10924. _sapp_x11_lock_mouse(lock);
  10925. #else
  10926. _sapp.mouse.locked = lock;
  10927. #endif
  10928. }
  10929. SOKOL_API_IMPL bool sapp_mouse_locked(void) {
  10930. return _sapp.mouse.locked;
  10931. }
  10932. SOKOL_API_IMPL void sapp_set_mouse_cursor(sapp_mouse_cursor cursor) {
  10933. SOKOL_ASSERT((cursor >= 0) && (cursor < _SAPP_MOUSECURSOR_NUM));
  10934. if (_sapp.mouse.current_cursor != cursor) {
  10935. #if defined(_SAPP_MACOS)
  10936. _sapp_macos_update_cursor(cursor, _sapp.mouse.shown);
  10937. #elif defined(_SAPP_WIN32)
  10938. _sapp_win32_update_cursor(cursor, _sapp.mouse.shown, false);
  10939. #elif defined(_SAPP_LINUX)
  10940. _sapp_x11_update_cursor(cursor, _sapp.mouse.shown);
  10941. #elif defined(_SAPP_EMSCRIPTEN)
  10942. _sapp_emsc_update_cursor(cursor, _sapp.mouse.shown);
  10943. #endif
  10944. _sapp.mouse.current_cursor = cursor;
  10945. }
  10946. }
  10947. SOKOL_API_IMPL sapp_mouse_cursor sapp_get_mouse_cursor(void) {
  10948. return _sapp.mouse.current_cursor;
  10949. }
  10950. SOKOL_API_IMPL void sapp_request_quit(void) {
  10951. _sapp.quit_requested = true;
  10952. }
  10953. SOKOL_API_IMPL void sapp_cancel_quit(void) {
  10954. _sapp.quit_requested = false;
  10955. }
  10956. SOKOL_API_IMPL void sapp_quit(void) {
  10957. _sapp.quit_ordered = true;
  10958. }
  10959. SOKOL_API_IMPL void sapp_consume_event(void) {
  10960. _sapp.event_consumed = true;
  10961. }
  10962. /* NOTE: on HTML5, sapp_set_clipboard_string() must be called from within event handler! */
  10963. SOKOL_API_IMPL void sapp_set_clipboard_string(const char* str) {
  10964. if (!_sapp.clipboard.enabled) {
  10965. return;
  10966. }
  10967. SOKOL_ASSERT(str);
  10968. #if defined(_SAPP_MACOS)
  10969. _sapp_macos_set_clipboard_string(str);
  10970. #elif defined(_SAPP_EMSCRIPTEN)
  10971. _sapp_emsc_set_clipboard_string(str);
  10972. #elif defined(_SAPP_WIN32)
  10973. _sapp_win32_set_clipboard_string(str);
  10974. #elif defined(_SAPP_LINUX)
  10975. _sapp_x11_set_clipboard_string(str);
  10976. #else
  10977. /* not implemented */
  10978. #endif
  10979. _sapp_strcpy(str, _sapp.clipboard.buffer, _sapp.clipboard.buf_size);
  10980. }
  10981. SOKOL_API_IMPL const char* sapp_get_clipboard_string(void) {
  10982. if (!_sapp.clipboard.enabled) {
  10983. return "";
  10984. }
  10985. #if defined(_SAPP_MACOS)
  10986. return _sapp_macos_get_clipboard_string();
  10987. #elif defined(_SAPP_EMSCRIPTEN)
  10988. return _sapp.clipboard.buffer;
  10989. #elif defined(_SAPP_WIN32)
  10990. return _sapp_win32_get_clipboard_string();
  10991. #elif defined(_SAPP_LINUX)
  10992. return _sapp_x11_get_clipboard_string();
  10993. #else
  10994. /* not implemented */
  10995. return _sapp.clipboard.buffer;
  10996. #endif
  10997. }
  10998. SOKOL_API_IMPL void sapp_set_window_title(const char* title) {
  10999. SOKOL_ASSERT(title);
  11000. _sapp_strcpy(title, _sapp.window_title, sizeof(_sapp.window_title));
  11001. #if defined(_SAPP_MACOS)
  11002. _sapp_macos_update_window_title();
  11003. #elif defined(_SAPP_WIN32)
  11004. _sapp_win32_update_window_title();
  11005. #elif defined(_SAPP_LINUX)
  11006. _sapp_x11_update_window_title();
  11007. #endif
  11008. }
  11009. SOKOL_API_IMPL void sapp_set_icon(const sapp_icon_desc* desc) {
  11010. SOKOL_ASSERT(desc);
  11011. if (desc->sokol_default) {
  11012. if (0 == _sapp.default_icon_pixels) {
  11013. _sapp_setup_default_icon();
  11014. }
  11015. SOKOL_ASSERT(0 != _sapp.default_icon_pixels);
  11016. desc = &_sapp.default_icon_desc;
  11017. }
  11018. const int num_images = _sapp_icon_num_images(desc);
  11019. if (num_images == 0) {
  11020. return;
  11021. }
  11022. SOKOL_ASSERT((num_images > 0) && (num_images <= SAPP_MAX_ICONIMAGES));
  11023. if (!_sapp_validate_icon_desc(desc, num_images)) {
  11024. return;
  11025. }
  11026. #if defined(_SAPP_MACOS)
  11027. _sapp_macos_set_icon(desc, num_images);
  11028. #elif defined(_SAPP_WIN32)
  11029. _sapp_win32_set_icon(desc, num_images);
  11030. #elif defined(_SAPP_LINUX)
  11031. _sapp_x11_set_icon(desc, num_images);
  11032. #elif defined(_SAPP_EMSCRIPTEN)
  11033. _sapp_emsc_set_icon(desc, num_images);
  11034. #endif
  11035. }
  11036. SOKOL_API_IMPL int sapp_get_num_dropped_files(void) {
  11037. SOKOL_ASSERT(_sapp.drop.enabled);
  11038. return _sapp.drop.num_files;
  11039. }
  11040. SOKOL_API_IMPL const char* sapp_get_dropped_file_path(int index) {
  11041. SOKOL_ASSERT(_sapp.drop.enabled);
  11042. SOKOL_ASSERT((index >= 0) && (index < _sapp.drop.num_files));
  11043. SOKOL_ASSERT(_sapp.drop.buffer);
  11044. if (!_sapp.drop.enabled) {
  11045. return "";
  11046. }
  11047. if ((index < 0) || (index >= _sapp.drop.max_files)) {
  11048. return "";
  11049. }
  11050. return (const char*) _sapp_dropped_file_path_ptr(index);
  11051. }
  11052. SOKOL_API_IMPL uint32_t sapp_html5_get_dropped_file_size(int index) {
  11053. SOKOL_ASSERT(_sapp.drop.enabled);
  11054. SOKOL_ASSERT((index >= 0) && (index < _sapp.drop.num_files));
  11055. #if defined(_SAPP_EMSCRIPTEN)
  11056. if (!_sapp.drop.enabled) {
  11057. return 0;
  11058. }
  11059. return sapp_js_dropped_file_size(index);
  11060. #else
  11061. (void)index;
  11062. return 0;
  11063. #endif
  11064. }
  11065. SOKOL_API_IMPL void sapp_html5_fetch_dropped_file(const sapp_html5_fetch_request* request) {
  11066. SOKOL_ASSERT(_sapp.drop.enabled);
  11067. SOKOL_ASSERT(request);
  11068. SOKOL_ASSERT(request->callback);
  11069. SOKOL_ASSERT(request->buffer.ptr);
  11070. SOKOL_ASSERT(request->buffer.size > 0);
  11071. #if defined(_SAPP_EMSCRIPTEN)
  11072. const int index = request->dropped_file_index;
  11073. sapp_html5_fetch_error error_code = SAPP_HTML5_FETCH_ERROR_NO_ERROR;
  11074. if ((index < 0) || (index >= _sapp.drop.num_files)) {
  11075. error_code = SAPP_HTML5_FETCH_ERROR_OTHER;
  11076. }
  11077. if (sapp_html5_get_dropped_file_size(index) > request->buffer.size) {
  11078. error_code = SAPP_HTML5_FETCH_ERROR_BUFFER_TOO_SMALL;
  11079. }
  11080. if (SAPP_HTML5_FETCH_ERROR_NO_ERROR != error_code) {
  11081. _sapp_emsc_invoke_fetch_cb(index,
  11082. false, // success
  11083. (int)error_code,
  11084. request->callback,
  11085. 0, // fetched_size
  11086. (void*)request->buffer.ptr,
  11087. request->buffer.size,
  11088. request->user_data);
  11089. }
  11090. else {
  11091. sapp_js_fetch_dropped_file(index,
  11092. request->callback,
  11093. (void*)request->buffer.ptr,
  11094. request->buffer.size,
  11095. request->user_data);
  11096. }
  11097. #else
  11098. (void)request;
  11099. #endif
  11100. }
  11101. SOKOL_API_IMPL const void* sapp_metal_get_device(void) {
  11102. SOKOL_ASSERT(_sapp.valid);
  11103. #if defined(SOKOL_METAL)
  11104. #if defined(_SAPP_MACOS)
  11105. const void* obj = (__bridge const void*) _sapp.macos.mtl_device;
  11106. #else
  11107. const void* obj = (__bridge const void*) _sapp.ios.mtl_device;
  11108. #endif
  11109. SOKOL_ASSERT(obj);
  11110. return obj;
  11111. #else
  11112. return 0;
  11113. #endif
  11114. }
  11115. SOKOL_API_IMPL const void* sapp_metal_get_current_drawable(void) {
  11116. SOKOL_ASSERT(_sapp.valid);
  11117. #if defined(SOKOL_METAL)
  11118. #if defined(_SAPP_MACOS)
  11119. const void* obj = (__bridge const void*) [_sapp.macos.view currentDrawable];
  11120. #else
  11121. const void* obj = (__bridge const void*) [_sapp.ios.view currentDrawable];
  11122. #endif
  11123. SOKOL_ASSERT(obj);
  11124. return obj;
  11125. #else
  11126. return 0;
  11127. #endif
  11128. }
  11129. SOKOL_API_IMPL const void* sapp_metal_get_depth_stencil_texture(void) {
  11130. SOKOL_ASSERT(_sapp.valid);
  11131. #if defined(SOKOL_METAL)
  11132. #if defined(_SAPP_MACOS)
  11133. const void* obj = (__bridge const void*) [_sapp.macos.view depthStencilTexture];
  11134. #else
  11135. const void* obj = (__bridge const void*) [_sapp.ios.view depthStencilTexture];
  11136. #endif
  11137. return obj;
  11138. #else
  11139. return 0;
  11140. #endif
  11141. }
  11142. SOKOL_API_IMPL const void* sapp_metal_get_msaa_color_texture(void) {
  11143. SOKOL_ASSERT(_sapp.valid);
  11144. #if defined(SOKOL_METAL)
  11145. #if defined(_SAPP_MACOS)
  11146. const void* obj = (__bridge const void*) [_sapp.macos.view multisampleColorTexture];
  11147. #else
  11148. const void* obj = (__bridge const void*) [_sapp.ios.view multisampleColorTexture];
  11149. #endif
  11150. return obj;
  11151. #else
  11152. return 0;
  11153. #endif
  11154. }
  11155. SOKOL_API_IMPL const void* sapp_macos_get_window(void) {
  11156. #if defined(_SAPP_MACOS)
  11157. const void* obj = (__bridge const void*) _sapp.macos.window;
  11158. SOKOL_ASSERT(obj);
  11159. return obj;
  11160. #else
  11161. return 0;
  11162. #endif
  11163. }
  11164. SOKOL_API_IMPL const void* sapp_ios_get_window(void) {
  11165. #if defined(_SAPP_IOS)
  11166. const void* obj = (__bridge const void*) _sapp.ios.window;
  11167. SOKOL_ASSERT(obj);
  11168. return obj;
  11169. #else
  11170. return 0;
  11171. #endif
  11172. }
  11173. SOKOL_API_IMPL const void* sapp_d3d11_get_device(void) {
  11174. SOKOL_ASSERT(_sapp.valid);
  11175. #if defined(SOKOL_D3D11)
  11176. return _sapp.d3d11.device;
  11177. #else
  11178. return 0;
  11179. #endif
  11180. }
  11181. SOKOL_API_IMPL const void* sapp_d3d11_get_device_context(void) {
  11182. SOKOL_ASSERT(_sapp.valid);
  11183. #if defined(SOKOL_D3D11)
  11184. return _sapp.d3d11.device_context;
  11185. #else
  11186. return 0;
  11187. #endif
  11188. }
  11189. SOKOL_API_IMPL const void* sapp_d3d11_get_swap_chain(void) {
  11190. SOKOL_ASSERT(_sapp.valid);
  11191. #if defined(SOKOL_D3D11)
  11192. return _sapp.d3d11.swap_chain;
  11193. #else
  11194. return 0;
  11195. #endif
  11196. }
  11197. SOKOL_API_IMPL const void* sapp_d3d11_get_render_view(void) {
  11198. SOKOL_ASSERT(_sapp.valid);
  11199. #if defined(SOKOL_D3D11)
  11200. if (_sapp.sample_count > 1) {
  11201. SOKOL_ASSERT(_sapp.d3d11.msaa_rtv);
  11202. return _sapp.d3d11.msaa_rtv;
  11203. } else {
  11204. SOKOL_ASSERT(_sapp.d3d11.rtv);
  11205. return _sapp.d3d11.rtv;
  11206. }
  11207. #else
  11208. return 0;
  11209. #endif
  11210. }
  11211. SOKOL_API_IMPL const void* sapp_d3d11_get_resolve_view(void) {
  11212. SOKOL_ASSERT(_sapp.valid);
  11213. #if defined(SOKOL_D3D11)
  11214. if (_sapp.sample_count > 1) {
  11215. SOKOL_ASSERT(_sapp.d3d11.rtv);
  11216. return _sapp.d3d11.rtv;
  11217. } else {
  11218. return 0;
  11219. }
  11220. #else
  11221. return 0;
  11222. #endif
  11223. }
  11224. SOKOL_API_IMPL const void* sapp_d3d11_get_depth_stencil_view(void) {
  11225. SOKOL_ASSERT(_sapp.valid);
  11226. #if defined(SOKOL_D3D11)
  11227. return _sapp.d3d11.dsv;
  11228. #else
  11229. return 0;
  11230. #endif
  11231. }
  11232. SOKOL_API_IMPL const void* sapp_win32_get_hwnd(void) {
  11233. SOKOL_ASSERT(_sapp.valid);
  11234. #if defined(_SAPP_WIN32)
  11235. return _sapp.win32.hwnd;
  11236. #else
  11237. return 0;
  11238. #endif
  11239. }
  11240. SOKOL_API_IMPL const void* sapp_wgpu_get_device(void) {
  11241. SOKOL_ASSERT(_sapp.valid);
  11242. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11243. return (const void*) _sapp.wgpu.device;
  11244. #else
  11245. return 0;
  11246. #endif
  11247. }
  11248. SOKOL_API_IMPL const void* sapp_wgpu_get_render_view(void) {
  11249. SOKOL_ASSERT(_sapp.valid);
  11250. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11251. if (_sapp.sample_count > 1) {
  11252. SOKOL_ASSERT(_sapp.wgpu.msaa_view);
  11253. return (const void*) _sapp.wgpu.msaa_view;
  11254. } else {
  11255. SOKOL_ASSERT(_sapp.wgpu.swapchain_view);
  11256. return (const void*) _sapp.wgpu.swapchain_view;
  11257. }
  11258. #else
  11259. return 0;
  11260. #endif
  11261. }
  11262. SOKOL_API_IMPL const void* sapp_wgpu_get_resolve_view(void) {
  11263. SOKOL_ASSERT(_sapp.valid);
  11264. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11265. if (_sapp.sample_count > 1) {
  11266. SOKOL_ASSERT(_sapp.wgpu.swapchain_view);
  11267. return (const void*) _sapp.wgpu.swapchain_view;
  11268. } else {
  11269. return 0;
  11270. }
  11271. #else
  11272. return 0;
  11273. #endif
  11274. }
  11275. SOKOL_API_IMPL const void* sapp_wgpu_get_depth_stencil_view(void) {
  11276. SOKOL_ASSERT(_sapp.valid);
  11277. #if defined(_SAPP_EMSCRIPTEN) && defined(SOKOL_WGPU)
  11278. return (const void*) _sapp.wgpu.depth_stencil_view;
  11279. #else
  11280. return 0;
  11281. #endif
  11282. }
  11283. SOKOL_API_IMPL uint32_t sapp_gl_get_framebuffer(void) {
  11284. SOKOL_ASSERT(_sapp.valid);
  11285. #if defined(_SAPP_ANY_GL)
  11286. return _sapp.gl.framebuffer;
  11287. #else
  11288. return 0;
  11289. #endif
  11290. }
  11291. SOKOL_API_IMPL int sapp_gl_get_major_version(void) {
  11292. SOKOL_ASSERT(_sapp.valid);
  11293. #if defined(SOKOL_GLCORE)
  11294. return _sapp.desc.gl_major_version;
  11295. #else
  11296. return 0;
  11297. #endif
  11298. }
  11299. SOKOL_API_IMPL int sapp_gl_get_minor_version(void) {
  11300. SOKOL_ASSERT(_sapp.valid);
  11301. #if defined(SOKOL_GLCORE)
  11302. return _sapp.desc.gl_minor_version;
  11303. #else
  11304. return 0;
  11305. #endif
  11306. }
  11307. SOKOL_API_IMPL const void* sapp_android_get_native_activity(void) {
  11308. // NOTE: _sapp.valid is not asserted here because sapp_android_get_native_activity()
  11309. // needs to be callable from within sokol_main() (see: https://github.com/floooh/sokol/issues/708)
  11310. #if defined(_SAPP_ANDROID)
  11311. return (void*)_sapp.android.activity;
  11312. #else
  11313. return 0;
  11314. #endif
  11315. }
  11316. SOKOL_API_IMPL void sapp_html5_ask_leave_site(bool ask) {
  11317. _sapp.html5_ask_leave_site = ask;
  11318. }
  11319. #endif /* SOKOL_APP_IMPL */