SDL_android.c 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_PLATFORM_ANDROID
  20. #include "SDL_android.h"
  21. #include "../../events/SDL_events_c.h"
  22. #include "../../video/android/SDL_androidkeyboard.h"
  23. #include "../../video/android/SDL_androidmouse.h"
  24. #include "../../video/android/SDL_androidtouch.h"
  25. #include "../../video/android/SDL_androidpen.h"
  26. #include "../../video/android/SDL_androidvideo.h"
  27. #include "../../video/android/SDL_androidwindow.h"
  28. #include "../../joystick/android/SDL_sysjoystick_c.h"
  29. #include "../../haptic/android/SDL_syshaptic_c.h"
  30. #include "../../hidapi/android/hid.h"
  31. #include "../../SDL_hints_c.h"
  32. #include <android/log.h>
  33. #include <android/configuration.h>
  34. #include <android/asset_manager_jni.h>
  35. #include <sys/system_properties.h>
  36. #include <pthread.h>
  37. #include <sys/types.h>
  38. #include <unistd.h>
  39. #include <dlfcn.h>
  40. #include <time.h>
  41. #define SDL_JAVA_PREFIX org_libsdl_app
  42. #define CONCAT1(prefix, class, function) CONCAT2(prefix, class, function)
  43. #define CONCAT2(prefix, class, function) Java_##prefix##_##class##_##function
  44. #define SDL_JAVA_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLActivity, function)
  45. #define SDL_JAVA_AUDIO_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLAudioManager, function)
  46. #define SDL_JAVA_CONTROLLER_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLControllerManager, function)
  47. #define SDL_JAVA_INTERFACE_INPUT_CONNECTION(function) CONCAT1(SDL_JAVA_PREFIX, SDLInputConnection, function)
  48. // Audio encoding definitions
  49. #define ENCODING_PCM_8BIT 3
  50. #define ENCODING_PCM_16BIT 2
  51. #define ENCODING_PCM_FLOAT 4
  52. // Java class SDLActivity
  53. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetVersion)(
  54. JNIEnv *env, jclass cls);
  55. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(
  56. JNIEnv *env, jclass cls);
  57. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeInitMainThread)(
  58. JNIEnv *env, jclass cls);
  59. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeCleanupMainThread)(
  60. JNIEnv *env, jclass cls);
  61. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(
  62. JNIEnv *env, jclass cls,
  63. jstring library, jstring function, jobject array);
  64. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
  65. JNIEnv *env, jclass jcls,
  66. jstring filename);
  67. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetScreenResolution)(
  68. JNIEnv *env, jclass jcls,
  69. jint surfaceWidth, jint surfaceHeight,
  70. jint deviceWidth, jint deviceHeight, jfloat density, jfloat rate);
  71. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
  72. JNIEnv *env, jclass cls);
  73. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceCreated)(
  74. JNIEnv *env, jclass jcls);
  75. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(
  76. JNIEnv *env, jclass jcls);
  77. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(
  78. JNIEnv *env, jclass jcls);
  79. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeScreenKeyboardShown)(
  80. JNIEnv *env, jclass jcls);
  81. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeScreenKeyboardHidden)(
  82. JNIEnv *env, jclass jcls);
  83. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
  84. JNIEnv *env, jclass jcls,
  85. jint keycode);
  86. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
  87. JNIEnv *env, jclass jcls,
  88. jint keycode);
  89. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(onNativeSoftReturnKey)(
  90. JNIEnv *env, jclass jcls);
  91. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
  92. JNIEnv *env, jclass jcls);
  93. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
  94. JNIEnv *env, jclass jcls,
  95. jint touch_device_id_in, jint pointer_finger_id_in,
  96. jint action, jfloat x, jfloat y, jfloat p);
  97. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePinchStart)(
  98. JNIEnv *env, jclass jcls);
  99. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePinchUpdate)(
  100. JNIEnv *env, jclass jcls,
  101. jfloat scale);
  102. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePinchEnd)(
  103. JNIEnv *env, jclass jcls);
  104. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
  105. JNIEnv *env, jclass jcls,
  106. jint button, jint action, jfloat x, jfloat y, jboolean relative);
  107. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePen)(
  108. JNIEnv *env, jclass jcls,
  109. jint pen_id_in, jint device_type, jint button, jint action, jfloat x, jfloat y, jfloat p);
  110. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeClipboardChanged)(
  111. JNIEnv *env, jclass jcls);
  112. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
  113. JNIEnv *env, jclass cls);
  114. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeLocaleChanged)(
  115. JNIEnv *env, jclass cls);
  116. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDarkModeChanged)(
  117. JNIEnv *env, jclass cls, jboolean enabled);
  118. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSendQuit)(
  119. JNIEnv *env, jclass cls);
  120. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
  121. JNIEnv *env, jclass cls);
  122. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
  123. JNIEnv *env, jclass cls);
  124. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
  125. JNIEnv *env, jclass cls);
  126. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeFocusChanged)(
  127. JNIEnv *env, jclass cls, jboolean hasFocus);
  128. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
  129. JNIEnv *env, jclass cls,
  130. jstring name);
  131. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeGetHintBoolean)(
  132. JNIEnv *env, jclass cls,
  133. jstring name, jboolean default_value);
  134. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
  135. JNIEnv *env, jclass cls,
  136. jstring name, jstring value);
  137. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetNaturalOrientation)(
  138. JNIEnv *env, jclass cls,
  139. jint orientation);
  140. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeRotationChanged)(
  141. JNIEnv *env, jclass cls,
  142. jint rotation);
  143. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeInsetsChanged)(
  144. JNIEnv *env, jclass cls,
  145. jint left, jint right, jint top, jint bottom);
  146. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)(
  147. JNIEnv *env, jclass cls,
  148. jint touchId, jstring name);
  149. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)(
  150. JNIEnv *env, jclass cls,
  151. jint requestCode, jboolean result);
  152. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeAllowRecreateActivity)(
  153. JNIEnv *env, jclass jcls);
  154. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeCheckSDLThreadCounter)(
  155. JNIEnv *env, jclass jcls);
  156. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeFileDialog)(
  157. JNIEnv *env, jclass jcls,
  158. jint requestCode, jobjectArray fileList, jint filter);
  159. static JNINativeMethod SDLActivity_tab[] = {
  160. { "nativeGetVersion", "()Ljava/lang/String;", SDL_JAVA_INTERFACE(nativeGetVersion) },
  161. { "nativeSetupJNI", "()V", SDL_JAVA_INTERFACE(nativeSetupJNI) },
  162. { "nativeInitMainThread", "()V", SDL_JAVA_INTERFACE(nativeInitMainThread) },
  163. { "nativeCleanupMainThread", "()V", SDL_JAVA_INTERFACE(nativeCleanupMainThread) },
  164. { "nativeRunMain", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)I", SDL_JAVA_INTERFACE(nativeRunMain) },
  165. { "onNativeDropFile", "(Ljava/lang/String;)V", SDL_JAVA_INTERFACE(onNativeDropFile) },
  166. { "nativeSetScreenResolution", "(IIIIFF)V", SDL_JAVA_INTERFACE(nativeSetScreenResolution) },
  167. { "onNativeResize", "()V", SDL_JAVA_INTERFACE(onNativeResize) },
  168. { "onNativeSurfaceCreated", "()V", SDL_JAVA_INTERFACE(onNativeSurfaceCreated) },
  169. { "onNativeSurfaceChanged", "()V", SDL_JAVA_INTERFACE(onNativeSurfaceChanged) },
  170. { "onNativeSurfaceDestroyed", "()V", SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed) },
  171. { "onNativeScreenKeyboardShown", "()V", SDL_JAVA_INTERFACE(onNativeScreenKeyboardShown) },
  172. { "onNativeScreenKeyboardHidden", "()V", SDL_JAVA_INTERFACE(onNativeScreenKeyboardHidden) },
  173. { "onNativeKeyDown", "(I)V", SDL_JAVA_INTERFACE(onNativeKeyDown) },
  174. { "onNativeKeyUp", "(I)V", SDL_JAVA_INTERFACE(onNativeKeyUp) },
  175. { "onNativeSoftReturnKey", "()Z", SDL_JAVA_INTERFACE(onNativeSoftReturnKey) },
  176. { "onNativeKeyboardFocusLost", "()V", SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost) },
  177. { "onNativeTouch", "(IIIFFF)V", SDL_JAVA_INTERFACE(onNativeTouch) },
  178. { "onNativePinchStart", "()V", SDL_JAVA_INTERFACE(onNativePinchStart) },
  179. { "onNativePinchUpdate", "(F)V", SDL_JAVA_INTERFACE(onNativePinchUpdate) },
  180. { "onNativePinchEnd", "()V", SDL_JAVA_INTERFACE(onNativePinchEnd) },
  181. { "onNativeMouse", "(IIFFZ)V", SDL_JAVA_INTERFACE(onNativeMouse) },
  182. { "onNativePen", "(IIIIFFF)V", SDL_JAVA_INTERFACE(onNativePen) },
  183. { "onNativeClipboardChanged", "()V", SDL_JAVA_INTERFACE(onNativeClipboardChanged) },
  184. { "nativeLowMemory", "()V", SDL_JAVA_INTERFACE(nativeLowMemory) },
  185. { "onNativeLocaleChanged", "()V", SDL_JAVA_INTERFACE(onNativeLocaleChanged) },
  186. { "onNativeDarkModeChanged", "(Z)V", SDL_JAVA_INTERFACE(onNativeDarkModeChanged) },
  187. { "nativeSendQuit", "()V", SDL_JAVA_INTERFACE(nativeSendQuit) },
  188. { "nativeQuit", "()V", SDL_JAVA_INTERFACE(nativeQuit) },
  189. { "nativePause", "()V", SDL_JAVA_INTERFACE(nativePause) },
  190. { "nativeResume", "()V", SDL_JAVA_INTERFACE(nativeResume) },
  191. { "nativeFocusChanged", "(Z)V", SDL_JAVA_INTERFACE(nativeFocusChanged) },
  192. { "nativeGetHint", "(Ljava/lang/String;)Ljava/lang/String;", SDL_JAVA_INTERFACE(nativeGetHint) },
  193. { "nativeGetHintBoolean", "(Ljava/lang/String;Z)Z", SDL_JAVA_INTERFACE(nativeGetHintBoolean) },
  194. { "nativeSetenv", "(Ljava/lang/String;Ljava/lang/String;)V", SDL_JAVA_INTERFACE(nativeSetenv) },
  195. { "nativeSetNaturalOrientation", "(I)V", SDL_JAVA_INTERFACE(nativeSetNaturalOrientation) },
  196. { "onNativeRotationChanged", "(I)V", SDL_JAVA_INTERFACE(onNativeRotationChanged) },
  197. { "onNativeInsetsChanged", "(IIII)V", SDL_JAVA_INTERFACE(onNativeInsetsChanged) },
  198. { "nativeAddTouch", "(ILjava/lang/String;)V", SDL_JAVA_INTERFACE(nativeAddTouch) },
  199. { "nativePermissionResult", "(IZ)V", SDL_JAVA_INTERFACE(nativePermissionResult) },
  200. { "nativeAllowRecreateActivity", "()Z", SDL_JAVA_INTERFACE(nativeAllowRecreateActivity) },
  201. { "nativeCheckSDLThreadCounter", "()I", SDL_JAVA_INTERFACE(nativeCheckSDLThreadCounter) },
  202. { "onNativeFileDialog", "(I[Ljava/lang/String;I)V", SDL_JAVA_INTERFACE(onNativeFileDialog) }
  203. };
  204. // Java class SDLInputConnection
  205. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
  206. JNIEnv *env, jclass cls,
  207. jstring text, jint newCursorPosition);
  208. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar)(
  209. JNIEnv *env, jclass cls,
  210. jchar chUnicode);
  211. static JNINativeMethod SDLInputConnection_tab[] = {
  212. { "nativeCommitText", "(Ljava/lang/String;I)V", SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText) },
  213. { "nativeGenerateScancodeForUnichar", "(C)V", SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar) }
  214. };
  215. // Java class SDLAudioManager
  216. JNIEXPORT void JNICALL SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI)(
  217. JNIEnv *env, jclass jcls);
  218. JNIEXPORT void JNICALL
  219. SDL_JAVA_AUDIO_INTERFACE(nativeAddAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording, jstring name,
  220. jint device_id);
  221. JNIEXPORT void JNICALL
  222. SDL_JAVA_AUDIO_INTERFACE(nativeRemoveAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording,
  223. jint device_id);
  224. static JNINativeMethod SDLAudioManager_tab[] = {
  225. { "nativeSetupJNI", "()V", SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI) },
  226. { "nativeAddAudioDevice", "(ZLjava/lang/String;I)V", SDL_JAVA_AUDIO_INTERFACE(nativeAddAudioDevice) },
  227. { "nativeRemoveAudioDevice", "(ZI)V", SDL_JAVA_AUDIO_INTERFACE(nativeRemoveAudioDevice) }
  228. };
  229. // Java class SDLControllerManager
  230. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI)(
  231. JNIEnv *env, jclass jcls);
  232. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadDown)(
  233. JNIEnv *env, jclass jcls,
  234. jint device_id, jint keycode, jint scancode);
  235. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadUp)(
  236. JNIEnv *env, jclass jcls,
  237. jint device_id, jint keycode, jint scancode);
  238. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoy)(
  239. JNIEnv *env, jclass jcls,
  240. jint device_id, jint axis, jfloat value);
  241. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
  242. JNIEnv *env, jclass jcls,
  243. jint device_id, jint hat_id, jint x, jint y);
  244. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoySensor)(
  245. JNIEnv *env, jclass jcls,
  246. jint device_id, jint sensor_type, jlong sensor_timestamp, jfloat x, jfloat y, jfloat z);
  247. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
  248. JNIEnv *env, jclass jcls,
  249. jint device_id, jstring device_name, jstring device_desc, jint vendor_id, jint product_id,
  250. jint button_mask, jint naxes, jint axis_mask, jint nhats,
  251. jboolean can_rumble, jboolean has_rgb_led, jboolean has_accelerometer, jboolean has_gyroscope);
  252. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick)(
  253. JNIEnv *env, jclass jcls,
  254. jint device_id);
  255. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddHaptic)(
  256. JNIEnv *env, jclass jcls,
  257. jint device_id, jstring device_name);
  258. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic)(
  259. JNIEnv *env, jclass jcls,
  260. jint device_id);
  261. static JNINativeMethod SDLControllerManager_tab[] = {
  262. { "nativeSetupJNI", "()V", SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI) },
  263. { "onNativePadDown", "(III)Z", SDL_JAVA_CONTROLLER_INTERFACE(onNativePadDown) },
  264. { "onNativePadUp", "(III)Z", SDL_JAVA_CONTROLLER_INTERFACE(onNativePadUp) },
  265. { "onNativeJoy", "(IIF)V", SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoy) },
  266. { "onNativeHat", "(IIII)V", SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat) },
  267. { "onNativeJoySensor", "(IIJFFF)V", SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoySensor) },
  268. { "nativeAddJoystick", "(ILjava/lang/String;Ljava/lang/String;IIIIIIZZZZ)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick) },
  269. { "nativeRemoveJoystick", "(I)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick) },
  270. { "nativeAddHaptic", "(ILjava/lang/String;)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeAddHaptic) },
  271. { "nativeRemoveHaptic", "(I)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic) }
  272. };
  273. // Uncomment this to log messages entering and exiting methods in this file
  274. // #define DEBUG_JNI
  275. static void checkJNIReady(void);
  276. /*******************************************************************************
  277. This file links the Java side of Android with libsdl
  278. *******************************************************************************/
  279. #include <jni.h>
  280. /*******************************************************************************
  281. Globals
  282. *******************************************************************************/
  283. static pthread_key_t mThreadKey;
  284. static pthread_once_t key_once = PTHREAD_ONCE_INIT;
  285. static JavaVM *mJavaVM = NULL;
  286. // Main activity
  287. static jclass mActivityClass;
  288. // method signatures
  289. static jmethodID midClipboardGetText;
  290. static jmethodID midClipboardHasText;
  291. static jmethodID midClipboardSetText;
  292. static jmethodID midCreateCustomCursor;
  293. static jmethodID midDestroyCustomCursor;
  294. static jmethodID midGetContext;
  295. static jmethodID midGetManifestEnvironmentVariables;
  296. static jmethodID midGetNativeSurface;
  297. static jmethodID midInitTouch;
  298. static jmethodID midIsAndroidTV;
  299. static jmethodID midIsChromebook;
  300. static jmethodID midIsDeXMode;
  301. static jmethodID midIsTablet;
  302. static jmethodID midManualBackButton;
  303. static jmethodID midMinimizeWindow;
  304. static jmethodID midOpenURL;
  305. static jmethodID midRequestPermission;
  306. static jmethodID midShowToast;
  307. static jmethodID midSendMessage;
  308. static jmethodID midSetActivityTitle;
  309. static jmethodID midSetCustomCursor;
  310. static jmethodID midSetOrientation;
  311. static jmethodID midSetRelativeMouseEnabled;
  312. static jmethodID midSetSystemCursor;
  313. static jmethodID midSetWindowStyle;
  314. static jmethodID midShouldMinimizeOnFocusLoss;
  315. static jmethodID midShowTextInput;
  316. static jmethodID midSupportsRelativeMouse;
  317. static jmethodID midOpenFileDescriptor;
  318. static jmethodID midShowFileDialog;
  319. static jmethodID midGetPreferredLocales;
  320. // audio manager
  321. static jclass mAudioManagerClass;
  322. // method signatures
  323. static jmethodID midRegisterAudioDeviceCallback;
  324. static jmethodID midUnregisterAudioDeviceCallback;
  325. static jmethodID midAudioSetThreadPriority;
  326. // controller manager
  327. static jclass mControllerManagerClass;
  328. // method signatures
  329. static jmethodID midDetectDevices;
  330. static jmethodID midJoystickSetLED;
  331. static jmethodID midJoystickSetSensorsEnabled;
  332. static jmethodID midDetectHapticDevices;
  333. static jmethodID midHapticRun;
  334. static jmethodID midHapticRumble;
  335. static jmethodID midHapticStop;
  336. // display orientation
  337. static SDL_DisplayOrientation displayNaturalOrientation;
  338. static SDL_DisplayOrientation displayCurrentOrientation;
  339. static bool bHasEnvironmentVariables;
  340. // Android AssetManager
  341. static void Internal_Android_Create_AssetManager(void);
  342. static void Internal_Android_Destroy_AssetManager(void);
  343. static AAssetManager *asset_manager = NULL;
  344. static jobject javaAssetManagerRef = 0;
  345. static SDL_Mutex *Android_ActivityMutex = NULL;
  346. static SDL_Mutex *Android_LifecycleMutex = NULL;
  347. static SDL_Semaphore *Android_LifecycleEventSem = NULL;
  348. static SDL_AndroidLifecycleEvent Android_LifecycleEvents[SDL_NUM_ANDROID_LIFECYCLE_EVENTS];
  349. static int Android_NumLifecycleEvents;
  350. /*******************************************************************************
  351. Functions called by JNI
  352. *******************************************************************************/
  353. /* From http://developer.android.com/guide/practices/jni.html
  354. * All threads are Linux threads, scheduled by the kernel.
  355. * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
  356. * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
  357. * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
  358. * and cannot make JNI calls.
  359. * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
  360. * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
  361. * is a no-op.
  362. * Note: You can call this function any number of times for the same thread, there's no harm in it
  363. */
  364. /* From http://developer.android.com/guide/practices/jni.html
  365. * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
  366. * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
  367. * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
  368. * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
  369. * Note: The destructor is not called unless the stored value is != NULL
  370. * Note: You can call this function any number of times for the same thread, there's no harm in it
  371. * (except for some lost CPU cycles)
  372. */
  373. // Set local storage value
  374. static bool Android_JNI_SetEnv(JNIEnv *env)
  375. {
  376. int status = pthread_setspecific(mThreadKey, env);
  377. if (status < 0) {
  378. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed pthread_setspecific() in Android_JNI_SetEnv() (err=%d)", status);
  379. return false;
  380. }
  381. return true;
  382. }
  383. // Get local storage value
  384. JNIEnv *Android_JNI_GetEnv(void)
  385. {
  386. // Get JNIEnv from the Thread local storage
  387. JNIEnv *env = pthread_getspecific(mThreadKey);
  388. if (!env) {
  389. // If it fails, try to attach ! (e.g the thread isn't created with SDL_CreateThread()
  390. int status;
  391. // There should be a JVM
  392. if (!mJavaVM) {
  393. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed, there is no JavaVM");
  394. return NULL;
  395. }
  396. /* Attach the current thread to the JVM and get a JNIEnv.
  397. * It will be detached by pthread_create destructor 'Android_JNI_ThreadDestroyed' */
  398. status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
  399. if (status < 0) {
  400. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to attach current thread (err=%d)", status);
  401. return NULL;
  402. }
  403. // Save JNIEnv into the Thread local storage
  404. if (!Android_JNI_SetEnv(env)) {
  405. return NULL;
  406. }
  407. }
  408. return env;
  409. }
  410. // Set up an external thread for using JNI with Android_JNI_GetEnv()
  411. bool Android_JNI_SetupThread(void)
  412. {
  413. JNIEnv *env;
  414. int status;
  415. // There should be a JVM
  416. if (!mJavaVM) {
  417. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed, there is no JavaVM");
  418. return false;
  419. }
  420. /* Attach the current thread to the JVM and get a JNIEnv.
  421. * It will be detached by pthread_create destructor 'Android_JNI_ThreadDestroyed' */
  422. status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
  423. if (status < 0) {
  424. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to attach current thread (err=%d)", status);
  425. return false;
  426. }
  427. // Save JNIEnv into the Thread local storage
  428. if (!Android_JNI_SetEnv(env)) {
  429. return false;
  430. }
  431. return true;
  432. }
  433. // Destructor called for each thread where mThreadKey is not NULL
  434. static void Android_JNI_ThreadDestroyed(void *value)
  435. {
  436. // The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required
  437. JNIEnv *env = (JNIEnv *)value;
  438. if (env) {
  439. (*mJavaVM)->DetachCurrentThread(mJavaVM);
  440. Android_JNI_SetEnv(NULL);
  441. }
  442. }
  443. // Creation of local storage mThreadKey
  444. static void Android_JNI_CreateKey(void)
  445. {
  446. int status = pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed);
  447. if (status < 0) {
  448. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing mThreadKey with pthread_key_create() (err=%d)", status);
  449. }
  450. }
  451. static void Android_JNI_CreateKey_once(void)
  452. {
  453. int status = pthread_once(&key_once, Android_JNI_CreateKey);
  454. if (status < 0) {
  455. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing mThreadKey with pthread_once() (err=%d)", status);
  456. }
  457. }
  458. static void register_methods(JNIEnv *env, const char *classname, JNINativeMethod *methods, int nb)
  459. {
  460. jclass clazz = (*env)->FindClass(env, classname);
  461. if (!clazz || (*env)->RegisterNatives(env, clazz, methods, nb) < 0) {
  462. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to register methods of %s", classname);
  463. return;
  464. }
  465. }
  466. // Library init
  467. JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
  468. {
  469. JNIEnv *env = NULL;
  470. mJavaVM = vm;
  471. if ((*mJavaVM)->GetEnv(mJavaVM, (void **)&env, JNI_VERSION_1_4) != JNI_OK) {
  472. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to get JNI Env");
  473. return JNI_VERSION_1_4;
  474. }
  475. register_methods(env, "org/libsdl/app/SDLActivity", SDLActivity_tab, SDL_arraysize(SDLActivity_tab));
  476. register_methods(env, "org/libsdl/app/SDLInputConnection", SDLInputConnection_tab, SDL_arraysize(SDLInputConnection_tab));
  477. register_methods(env, "org/libsdl/app/SDLAudioManager", SDLAudioManager_tab, SDL_arraysize(SDLAudioManager_tab));
  478. register_methods(env, "org/libsdl/app/SDLControllerManager", SDLControllerManager_tab, SDL_arraysize(SDLControllerManager_tab));
  479. register_methods(env, "org/libsdl/app/HIDDeviceManager", HIDDeviceManager_tab, SDL_arraysize(HIDDeviceManager_tab));
  480. return JNI_VERSION_1_4;
  481. }
  482. void checkJNIReady(void)
  483. {
  484. if (!mActivityClass || !mAudioManagerClass || !mControllerManagerClass) {
  485. // We aren't fully initialized, let's just return.
  486. return;
  487. }
  488. SDL_SetMainReady();
  489. }
  490. // Get SDL version -- called before SDL_main() to verify JNI bindings
  491. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetVersion)(JNIEnv *env, jclass cls)
  492. {
  493. char version[128];
  494. SDL_snprintf(version, sizeof(version), "%d.%d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION);
  495. return (*env)->NewStringUTF(env, version);
  496. }
  497. // Activity initialization -- called before SDL_main() to initialize JNI bindings
  498. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cls)
  499. {
  500. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeSetupJNI()");
  501. // Start with a clean slate
  502. SDL_ClearError();
  503. /*
  504. * Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
  505. * Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
  506. */
  507. Android_JNI_CreateKey_once();
  508. // Save JNIEnv of SDLActivity
  509. Android_JNI_SetEnv(env);
  510. if (!mJavaVM) {
  511. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to found a JavaVM");
  512. }
  513. /* Use a mutex to prevent concurrency issues between Java Activity and Native thread code, when using 'Android_Window'.
  514. * (Eg. Java sending Touch events, while native code is destroying the main SDL_Window. )
  515. */
  516. if (!Android_ActivityMutex) {
  517. Android_ActivityMutex = SDL_CreateMutex(); // Could this be created twice if onCreate() is called a second time ?
  518. }
  519. if (!Android_ActivityMutex) {
  520. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_ActivityMutex mutex");
  521. }
  522. Android_LifecycleMutex = SDL_CreateMutex();
  523. if (!Android_LifecycleMutex) {
  524. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_LifecycleMutex mutex");
  525. }
  526. Android_LifecycleEventSem = SDL_CreateSemaphore(0);
  527. if (!Android_LifecycleEventSem) {
  528. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_LifecycleEventSem semaphore");
  529. }
  530. mActivityClass = (jclass)((*env)->NewGlobalRef(env, cls));
  531. midClipboardGetText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardGetText", "()Ljava/lang/String;");
  532. midClipboardHasText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardHasText", "()Z");
  533. midClipboardSetText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardSetText", "(Ljava/lang/String;)V");
  534. midCreateCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "createCustomCursor", "([IIIII)I");
  535. midDestroyCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "destroyCustomCursor", "(I)V");
  536. midGetContext = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/app/Activity;");
  537. midGetManifestEnvironmentVariables = (*env)->GetStaticMethodID(env, mActivityClass, "getManifestEnvironmentVariables", "()Z");
  538. midGetNativeSurface = (*env)->GetStaticMethodID(env, mActivityClass, "getNativeSurface", "()Landroid/view/Surface;");
  539. midInitTouch = (*env)->GetStaticMethodID(env, mActivityClass, "initTouch", "()V");
  540. midIsAndroidTV = (*env)->GetStaticMethodID(env, mActivityClass, "isAndroidTV", "()Z");
  541. midIsChromebook = (*env)->GetStaticMethodID(env, mActivityClass, "isChromebook", "()Z");
  542. midIsDeXMode = (*env)->GetStaticMethodID(env, mActivityClass, "isDeXMode", "()Z");
  543. midIsTablet = (*env)->GetStaticMethodID(env, mActivityClass, "isTablet", "()Z");
  544. midManualBackButton = (*env)->GetStaticMethodID(env, mActivityClass, "manualBackButton", "()V");
  545. midMinimizeWindow = (*env)->GetStaticMethodID(env, mActivityClass, "minimizeWindow", "()V");
  546. midOpenURL = (*env)->GetStaticMethodID(env, mActivityClass, "openURL", "(Ljava/lang/String;)Z");
  547. midRequestPermission = (*env)->GetStaticMethodID(env, mActivityClass, "requestPermission", "(Ljava/lang/String;I)V");
  548. midShowToast = (*env)->GetStaticMethodID(env, mActivityClass, "showToast", "(Ljava/lang/String;IIII)Z");
  549. midSendMessage = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
  550. midSetActivityTitle = (*env)->GetStaticMethodID(env, mActivityClass, "setActivityTitle", "(Ljava/lang/String;)Z");
  551. midSetCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setCustomCursor", "(I)Z");
  552. midSetOrientation = (*env)->GetStaticMethodID(env, mActivityClass, "setOrientation", "(IIZLjava/lang/String;)V");
  553. midSetRelativeMouseEnabled = (*env)->GetStaticMethodID(env, mActivityClass, "setRelativeMouseEnabled", "(Z)Z");
  554. midSetSystemCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setSystemCursor", "(I)Z");
  555. midSetWindowStyle = (*env)->GetStaticMethodID(env, mActivityClass, "setWindowStyle", "(Z)V");
  556. midShouldMinimizeOnFocusLoss = (*env)->GetStaticMethodID(env, mActivityClass, "shouldMinimizeOnFocusLoss", "()Z");
  557. midShowTextInput = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIIII)Z");
  558. midSupportsRelativeMouse = (*env)->GetStaticMethodID(env, mActivityClass, "supportsRelativeMouse", "()Z");
  559. midOpenFileDescriptor = (*env)->GetStaticMethodID(env, mActivityClass, "openFileDescriptor", "(Ljava/lang/String;Ljava/lang/String;)I");
  560. midShowFileDialog = (*env)->GetStaticMethodID(env, mActivityClass, "showFileDialog", "([Ljava/lang/String;ZILjava/lang/String;I)Z");
  561. midGetPreferredLocales = (*env)->GetStaticMethodID(env, mActivityClass, "getPreferredLocales", "()Ljava/lang/String;");
  562. if (!midClipboardGetText ||
  563. !midClipboardHasText ||
  564. !midClipboardSetText ||
  565. !midCreateCustomCursor ||
  566. !midDestroyCustomCursor ||
  567. !midGetContext ||
  568. !midGetManifestEnvironmentVariables ||
  569. !midGetNativeSurface ||
  570. !midInitTouch ||
  571. !midIsAndroidTV ||
  572. !midIsChromebook ||
  573. !midIsDeXMode ||
  574. !midIsTablet ||
  575. !midManualBackButton ||
  576. !midMinimizeWindow ||
  577. !midOpenURL ||
  578. !midRequestPermission ||
  579. !midShowToast ||
  580. !midSendMessage ||
  581. !midSetActivityTitle ||
  582. !midSetCustomCursor ||
  583. !midSetOrientation ||
  584. !midSetRelativeMouseEnabled ||
  585. !midSetSystemCursor ||
  586. !midSetWindowStyle ||
  587. !midShouldMinimizeOnFocusLoss ||
  588. !midShowTextInput ||
  589. !midSupportsRelativeMouse ||
  590. !midOpenFileDescriptor ||
  591. !midShowFileDialog ||
  592. !midGetPreferredLocales) {
  593. __android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLActivity.java?");
  594. }
  595. checkJNIReady();
  596. }
  597. // Audio initialization -- called before SDL_main() to initialize JNI bindings
  598. JNIEXPORT void JNICALL SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cls)
  599. {
  600. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "AUDIO nativeSetupJNI()");
  601. mAudioManagerClass = (jclass)((*env)->NewGlobalRef(env, cls));
  602. midRegisterAudioDeviceCallback = (*env)->GetStaticMethodID(env, mAudioManagerClass,
  603. "registerAudioDeviceCallback",
  604. "()V");
  605. midUnregisterAudioDeviceCallback = (*env)->GetStaticMethodID(env, mAudioManagerClass,
  606. "unregisterAudioDeviceCallback",
  607. "()V");
  608. midAudioSetThreadPriority = (*env)->GetStaticMethodID(env, mAudioManagerClass,
  609. "audioSetThreadPriority", "(ZI)V");
  610. if (!midRegisterAudioDeviceCallback || !midUnregisterAudioDeviceCallback || !midAudioSetThreadPriority) {
  611. __android_log_print(ANDROID_LOG_WARN, "SDL",
  612. "Missing some Java callbacks, do you have the latest version of SDLAudioManager.java?");
  613. }
  614. checkJNIReady();
  615. }
  616. // Controller initialization -- called before SDL_main() to initialize JNI bindings
  617. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cls)
  618. {
  619. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "CONTROLLER nativeSetupJNI()");
  620. mControllerManagerClass = (jclass)((*env)->NewGlobalRef(env, cls));
  621. midDetectDevices = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  622. "detectDevices", "()V");
  623. midJoystickSetLED = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  624. "joystickSetLED", "(IIII)V");
  625. midJoystickSetSensorsEnabled = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  626. "joystickSetSensorsEnabled", "(IZ)V");
  627. midDetectHapticDevices = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  628. "detectHapticDevices", "()V");
  629. midHapticRun = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  630. "hapticRun", "(IFI)V");
  631. midHapticRumble = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  632. "hapticRumble", "(IFFI)V");
  633. midHapticStop = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  634. "hapticStop", "(I)V");
  635. if (!midDetectDevices || !midJoystickSetLED || !midJoystickSetSensorsEnabled || !midDetectHapticDevices || !midHapticRun || !midHapticRumble || !midHapticStop) {
  636. __android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLControllerManager.java?");
  637. }
  638. checkJNIReady();
  639. }
  640. static int run_count = 0;
  641. static bool allow_recreate_activity;
  642. static bool allow_recreate_activity_set;
  643. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeCheckSDLThreadCounter)(
  644. JNIEnv *env, jclass jcls)
  645. {
  646. int tmp = run_count;
  647. run_count += 1;
  648. return tmp;
  649. }
  650. void Android_SetAllowRecreateActivity(bool enabled)
  651. {
  652. allow_recreate_activity = enabled;
  653. allow_recreate_activity_set = true;
  654. }
  655. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeAllowRecreateActivity)(
  656. JNIEnv *env, jclass jcls)
  657. {
  658. return allow_recreate_activity;
  659. }
  660. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeInitMainThread)(
  661. JNIEnv *env, jclass jcls)
  662. {
  663. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeInitSDLThread() %d time", run_count);
  664. run_count += 1;
  665. // Save JNIEnv of SDLThread
  666. Android_JNI_SetEnv(env);
  667. }
  668. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeCleanupMainThread)(
  669. JNIEnv *env, jclass jcls)
  670. {
  671. /* This is a Java thread, it doesn't need to be Detached from the JVM.
  672. * Set to mThreadKey value to NULL not to call pthread_create destructor 'Android_JNI_ThreadDestroyed' */
  673. Android_JNI_SetEnv(NULL);
  674. }
  675. // Start up the SDL app
  676. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(JNIEnv *env, jclass cls, jstring library, jstring function, jobject array)
  677. {
  678. int status = -1;
  679. const char *library_file;
  680. void *library_handle;
  681. library_file = (*env)->GetStringUTFChars(env, library, NULL);
  682. library_handle = dlopen(library_file, RTLD_GLOBAL);
  683. if (library_handle == NULL) {
  684. /* When deploying android app bundle format uncompressed native libs may not extract from apk to filesystem.
  685. In this case we should use lib name without path. https://bugzilla.libsdl.org/show_bug.cgi?id=4739 */
  686. const char *library_name = SDL_strrchr(library_file, '/');
  687. if (library_name && *library_name) {
  688. library_name += 1;
  689. library_handle = dlopen(library_name, RTLD_GLOBAL);
  690. }
  691. }
  692. if (library_handle) {
  693. const char *function_name;
  694. SDL_main_func SDL_main;
  695. function_name = (*env)->GetStringUTFChars(env, function, NULL);
  696. SDL_main = (SDL_main_func)dlsym(library_handle, function_name);
  697. if (SDL_main) {
  698. // Use the name "app_process" for argv[0] so PHYSFS_platformCalcBaseDir() works.
  699. // https://github.com/love2d/love-android/issues/24
  700. // (note that PhysicsFS hasn't used argv on Android in a long time, but we'll keep this for compat at least for SDL3's lifetime. --ryan.)
  701. const char *argv0 = "app_process";
  702. const int len = (*env)->GetArrayLength(env, array); // argv elements, not counting argv[0].
  703. size_t total_alloc_len = (SDL_strlen(argv0) + 1) + ((len + 2) * sizeof (char *)); // len+2 to allocate an array that also holds argv0 and a NULL terminator.
  704. for (int i = 0; i < len; ++i) {
  705. total_alloc_len++; // null terminator.
  706. jstring string = (*env)->GetObjectArrayElement(env, array, i);
  707. if (string) {
  708. const char *utf = (*env)->GetStringUTFChars(env, string, 0);
  709. if (utf) {
  710. total_alloc_len += SDL_strlen(utf) + 1;
  711. (*env)->ReleaseStringUTFChars(env, string, utf);
  712. }
  713. (*env)->DeleteLocalRef(env, string);
  714. }
  715. }
  716. void *args = malloc(total_alloc_len); // This should NOT be SDL_malloc()
  717. if (!args) { // uhoh.
  718. __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Out of memory parsing command line!");
  719. } else {
  720. size_t remain = total_alloc_len - (sizeof (char *) * (len + 2));
  721. int argc = 0;
  722. char **argv = (char **) args;
  723. char *ptr = (char *) &argv[len + 2];
  724. size_t cpy = SDL_strlcpy(ptr, argv0, remain) + 1;
  725. argv[argc++] = ptr;
  726. SDL_assert(cpy <= remain); remain -= cpy; ptr += cpy;
  727. for (int i = 0; i < len; ++i) {
  728. jstring string = (*env)->GetObjectArrayElement(env, array, i);
  729. const char *utf = string ? (*env)->GetStringUTFChars(env, string, 0) : NULL;
  730. cpy = SDL_strlcpy(ptr, utf ? utf : "", remain) + 1;
  731. if (cpy < remain) {
  732. argv[argc++] = ptr;
  733. remain -= cpy;
  734. ptr += cpy;
  735. }
  736. if (utf) {
  737. (*env)->ReleaseStringUTFChars(env, string, utf);
  738. }
  739. if (string) {
  740. (*env)->DeleteLocalRef(env, string);
  741. }
  742. }
  743. argv[argc] = NULL;
  744. // Run the application.
  745. status = SDL_RunApp(argc, argv, SDL_main, NULL);
  746. // Release the arguments.
  747. free(args); // This should NOT be SDL_free()
  748. }
  749. } else {
  750. __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Couldn't find function %s in library %s", function_name, library_file);
  751. }
  752. (*env)->ReleaseStringUTFChars(env, function, function_name);
  753. dlclose(library_handle);
  754. } else {
  755. __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Couldn't load library %s", library_file);
  756. }
  757. (*env)->ReleaseStringUTFChars(env, library, library_file);
  758. // Do not issue an exit or the whole application will terminate instead of just the SDL thread
  759. // exit(status);
  760. return status;
  761. }
  762. static int FindLifecycleEvent(SDL_AndroidLifecycleEvent event)
  763. {
  764. for (int index = 0; index < Android_NumLifecycleEvents; ++index) {
  765. if (Android_LifecycleEvents[index] == event) {
  766. return index;
  767. }
  768. }
  769. return -1;
  770. }
  771. static void RemoveLifecycleEvent(int index)
  772. {
  773. if (index < Android_NumLifecycleEvents - 1) {
  774. SDL_memmove(&Android_LifecycleEvents[index], &Android_LifecycleEvents[index+1], (Android_NumLifecycleEvents - index - 1) * sizeof(Android_LifecycleEvents[index]));
  775. }
  776. --Android_NumLifecycleEvents;
  777. }
  778. void Android_SendLifecycleEvent(SDL_AndroidLifecycleEvent event)
  779. {
  780. SDL_LockMutex(Android_LifecycleMutex);
  781. {
  782. int index;
  783. bool add_event = true;
  784. switch (event) {
  785. case SDL_ANDROID_LIFECYCLE_WAKE:
  786. // We don't need more than one wake queued
  787. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_WAKE);
  788. if (index >= 0) {
  789. add_event = false;
  790. }
  791. break;
  792. case SDL_ANDROID_LIFECYCLE_PAUSE:
  793. // If we have a resume queued, just stay in the paused state
  794. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_RESUME);
  795. if (index >= 0) {
  796. RemoveLifecycleEvent(index);
  797. add_event = false;
  798. }
  799. break;
  800. case SDL_ANDROID_LIFECYCLE_RESUME:
  801. // If we have a pause queued, just stay in the resumed state
  802. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_PAUSE);
  803. if (index >= 0) {
  804. RemoveLifecycleEvent(index);
  805. add_event = false;
  806. }
  807. break;
  808. case SDL_ANDROID_LIFECYCLE_LOWMEMORY:
  809. // We don't need more than one low memory event queued
  810. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_LOWMEMORY);
  811. if (index >= 0) {
  812. add_event = false;
  813. }
  814. break;
  815. case SDL_ANDROID_LIFECYCLE_DESTROY:
  816. // Remove all other events, we're done!
  817. while (Android_NumLifecycleEvents > 0) {
  818. RemoveLifecycleEvent(0);
  819. }
  820. break;
  821. default:
  822. SDL_assert(!"Sending unexpected lifecycle event");
  823. add_event = false;
  824. break;
  825. }
  826. if (add_event) {
  827. SDL_assert(Android_NumLifecycleEvents < SDL_arraysize(Android_LifecycleEvents));
  828. Android_LifecycleEvents[Android_NumLifecycleEvents++] = event;
  829. SDL_SignalSemaphore(Android_LifecycleEventSem);
  830. }
  831. }
  832. SDL_UnlockMutex(Android_LifecycleMutex);
  833. }
  834. bool Android_WaitLifecycleEvent(SDL_AndroidLifecycleEvent *event, Sint64 timeoutNS)
  835. {
  836. bool got_event = false;
  837. while (!got_event && SDL_WaitSemaphoreTimeoutNS(Android_LifecycleEventSem, timeoutNS)) {
  838. SDL_LockMutex(Android_LifecycleMutex);
  839. {
  840. if (Android_NumLifecycleEvents > 0) {
  841. *event = Android_LifecycleEvents[0];
  842. RemoveLifecycleEvent(0);
  843. got_event = true;
  844. }
  845. }
  846. SDL_UnlockMutex(Android_LifecycleMutex);
  847. }
  848. return got_event;
  849. }
  850. void Android_LockActivityMutex(void)
  851. {
  852. SDL_LockMutex(Android_ActivityMutex);
  853. }
  854. void Android_UnlockActivityMutex(void)
  855. {
  856. SDL_UnlockMutex(Android_ActivityMutex);
  857. }
  858. // Drop file
  859. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
  860. JNIEnv *env, jclass jcls,
  861. jstring filename)
  862. {
  863. const char *path = (*env)->GetStringUTFChars(env, filename, NULL);
  864. SDL_SendDropFile(NULL, NULL, path);
  865. (*env)->ReleaseStringUTFChars(env, filename, path);
  866. SDL_SendDropComplete(NULL);
  867. }
  868. // Set screen resolution
  869. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetScreenResolution)(
  870. JNIEnv *env, jclass jcls,
  871. jint surfaceWidth, jint surfaceHeight,
  872. jint deviceWidth, jint deviceHeight, jfloat density, jfloat rate)
  873. {
  874. SDL_LockMutex(Android_ActivityMutex);
  875. Android_SetScreenResolution(surfaceWidth, surfaceHeight, deviceWidth, deviceHeight, density, rate);
  876. SDL_UnlockMutex(Android_ActivityMutex);
  877. }
  878. // Resize
  879. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
  880. JNIEnv *env, jclass jcls)
  881. {
  882. SDL_LockMutex(Android_ActivityMutex);
  883. if (Android_Window) {
  884. Android_SendResize(Android_Window);
  885. }
  886. SDL_UnlockMutex(Android_ActivityMutex);
  887. }
  888. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetNaturalOrientation)(
  889. JNIEnv *env, jclass jcls,
  890. jint orientation)
  891. {
  892. displayNaturalOrientation = (SDL_DisplayOrientation)orientation;
  893. }
  894. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeRotationChanged)(
  895. JNIEnv *env, jclass jcls,
  896. jint rotation)
  897. {
  898. SDL_LockMutex(Android_ActivityMutex);
  899. if (displayNaturalOrientation == SDL_ORIENTATION_LANDSCAPE) {
  900. rotation += 90;
  901. }
  902. switch (rotation % 360) {
  903. case 0:
  904. displayCurrentOrientation = SDL_ORIENTATION_PORTRAIT;
  905. break;
  906. case 90:
  907. displayCurrentOrientation = SDL_ORIENTATION_LANDSCAPE;
  908. break;
  909. case 180:
  910. displayCurrentOrientation = SDL_ORIENTATION_PORTRAIT_FLIPPED;
  911. break;
  912. case 270:
  913. displayCurrentOrientation = SDL_ORIENTATION_LANDSCAPE_FLIPPED;
  914. break;
  915. default:
  916. displayCurrentOrientation = SDL_ORIENTATION_UNKNOWN;
  917. break;
  918. }
  919. Android_SetOrientation(displayCurrentOrientation);
  920. SDL_UnlockMutex(Android_ActivityMutex);
  921. }
  922. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeInsetsChanged)(
  923. JNIEnv *env, jclass jcls,
  924. jint left, jint right, jint top, jint bottom)
  925. {
  926. SDL_LockMutex(Android_ActivityMutex);
  927. Android_SetWindowSafeAreaInsets(left, right, top, bottom);
  928. SDL_UnlockMutex(Android_ActivityMutex);
  929. }
  930. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)(
  931. JNIEnv *env, jclass cls,
  932. jint touchId, jstring name)
  933. {
  934. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  935. SDL_AddTouch(Android_ConvertJavaTouchID(touchId),
  936. SDL_TOUCH_DEVICE_DIRECT, utfname);
  937. (*env)->ReleaseStringUTFChars(env, name, utfname);
  938. }
  939. JNIEXPORT void JNICALL
  940. SDL_JAVA_AUDIO_INTERFACE(nativeAddAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording,
  941. jstring name, jint device_id)
  942. {
  943. #if ALLOW_MULTIPLE_ANDROID_AUDIO_DEVICES
  944. if (SDL_GetCurrentAudioDriver() != NULL) {
  945. void *handle = (void *)((size_t)device_id);
  946. if (!SDL_FindPhysicalAudioDeviceByHandle(handle)) {
  947. const char *utf8name = (*env)->GetStringUTFChars(env, name, NULL);
  948. SDL_AddAudioDevice(recording, SDL_strdup(utf8name), NULL, handle);
  949. (*env)->ReleaseStringUTFChars(env, name, utf8name);
  950. }
  951. }
  952. #endif
  953. }
  954. JNIEXPORT void JNICALL
  955. SDL_JAVA_AUDIO_INTERFACE(nativeRemoveAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording,
  956. jint device_id)
  957. {
  958. #if ALLOW_MULTIPLE_ANDROID_AUDIO_DEVICES
  959. if (SDL_GetCurrentAudioDriver() != NULL) {
  960. SDL_Log("Removing device with handle %d, recording %d", device_id, recording);
  961. SDL_AudioDeviceDisconnected(SDL_FindPhysicalAudioDeviceByHandle((void *)((size_t)device_id)));
  962. }
  963. #endif
  964. }
  965. // Paddown
  966. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadDown)(
  967. JNIEnv *env, jclass jcls,
  968. jint device_id, jint keycode, jint scancode)
  969. {
  970. #ifdef SDL_JOYSTICK_ANDROID
  971. return Android_OnPadDown(device_id, keycode, scancode);
  972. #else
  973. return false;
  974. #endif // SDL_JOYSTICK_ANDROID
  975. }
  976. // Padup
  977. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadUp)(
  978. JNIEnv *env, jclass jcls,
  979. jint device_id, jint keycode, jint scancode)
  980. {
  981. #ifdef SDL_JOYSTICK_ANDROID
  982. return Android_OnPadUp(device_id, keycode, scancode);
  983. #else
  984. return false;
  985. #endif // SDL_JOYSTICK_ANDROID
  986. }
  987. // Joy
  988. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoy)(
  989. JNIEnv *env, jclass jcls,
  990. jint device_id, jint axis, jfloat value)
  991. {
  992. #ifdef SDL_JOYSTICK_ANDROID
  993. Android_OnJoy(device_id, axis, value);
  994. #endif // SDL_JOYSTICK_ANDROID
  995. }
  996. // POV Hat
  997. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
  998. JNIEnv *env, jclass jcls,
  999. jint device_id, jint hat_id, jint x, jint y)
  1000. {
  1001. #ifdef SDL_JOYSTICK_ANDROID
  1002. Android_OnHat(device_id, hat_id, x, y);
  1003. #endif // SDL_JOYSTICK_ANDROID
  1004. }
  1005. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoySensor)(
  1006. JNIEnv *env, jclass jcls,
  1007. jint device_id, jint sensor_type, jlong sensor_timestamp, jfloat x, jfloat y, jfloat z)
  1008. {
  1009. #ifdef SDL_JOYSTICK_ANDROID
  1010. // In Java there's no Uint64 type, so pass Sint64 as if it was Uint64.
  1011. Android_OnJoySensor(device_id, sensor_type, sensor_timestamp, x, y, z);
  1012. #endif // SDL_JOYSTICK_ANDROID
  1013. }
  1014. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
  1015. JNIEnv *env, jclass jcls,
  1016. jint device_id, jstring device_name, jstring device_desc,
  1017. jint vendor_id, jint product_id,
  1018. jint button_mask, jint naxes, jint axis_mask, jint nhats, jboolean can_rumble, jboolean has_rgb_led,
  1019. jboolean has_accelerometer, jboolean has_gyroscope)
  1020. {
  1021. #ifdef SDL_JOYSTICK_ANDROID
  1022. const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
  1023. const char *desc = (*env)->GetStringUTFChars(env, device_desc, NULL);
  1024. Android_AddJoystick(device_id, name, desc, vendor_id, product_id, button_mask, naxes, axis_mask, nhats,
  1025. can_rumble, has_rgb_led, has_accelerometer, has_gyroscope);
  1026. (*env)->ReleaseStringUTFChars(env, device_name, name);
  1027. (*env)->ReleaseStringUTFChars(env, device_desc, desc);
  1028. #endif // SDL_JOYSTICK_ANDROID
  1029. }
  1030. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick)(
  1031. JNIEnv *env, jclass jcls,
  1032. jint device_id)
  1033. {
  1034. #ifdef SDL_JOYSTICK_ANDROID
  1035. Android_RemoveJoystick(device_id);
  1036. #endif // SDL_JOYSTICK_ANDROID
  1037. }
  1038. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddHaptic)(
  1039. JNIEnv *env, jclass jcls, jint device_id, jstring device_name)
  1040. {
  1041. #ifdef SDL_HAPTIC_ANDROID
  1042. const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
  1043. Android_AddHaptic(device_id, name);
  1044. (*env)->ReleaseStringUTFChars(env, device_name, name);
  1045. #endif // SDL_HAPTIC_ANDROID
  1046. }
  1047. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic)(
  1048. JNIEnv *env, jclass jcls, jint device_id)
  1049. {
  1050. #ifdef SDL_HAPTIC_ANDROID
  1051. Android_RemoveHaptic(device_id);
  1052. #endif
  1053. }
  1054. // Called from surfaceCreated()
  1055. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceCreated)(JNIEnv *env, jclass jcls)
  1056. {
  1057. SDL_LockMutex(Android_ActivityMutex);
  1058. if (Android_Window) {
  1059. SDL_WindowData *data = Android_Window->internal;
  1060. data->native_window = Android_JNI_GetNativeWindow();
  1061. SDL_SetPointerProperty(SDL_GetWindowProperties(Android_Window), SDL_PROP_WINDOW_ANDROID_WINDOW_POINTER, data->native_window);
  1062. if (data->native_window == NULL) {
  1063. SDL_SetError("Could not fetch native window from UI thread");
  1064. }
  1065. }
  1066. SDL_UnlockMutex(Android_ActivityMutex);
  1067. }
  1068. // Called from surfaceChanged()
  1069. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(JNIEnv *env, jclass jcls)
  1070. {
  1071. SDL_LockMutex(Android_ActivityMutex);
  1072. #ifdef SDL_VIDEO_OPENGL_EGL
  1073. if (Android_Window && (Android_Window->flags & SDL_WINDOW_OPENGL)) {
  1074. SDL_VideoDevice *_this = SDL_GetVideoDevice();
  1075. SDL_WindowData *data = Android_Window->internal;
  1076. // If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here
  1077. if (data->egl_surface == EGL_NO_SURFACE) {
  1078. data->egl_surface = SDL_EGL_CreateSurface(_this, Android_Window, (NativeWindowType)data->native_window);
  1079. SDL_SetPointerProperty(SDL_GetWindowProperties(Android_Window), SDL_PROP_WINDOW_ANDROID_SURFACE_POINTER, data->egl_surface);
  1080. }
  1081. // GL Context handling is done in the event loop because this function is run from the Java thread
  1082. }
  1083. #endif
  1084. if (Android_Window) {
  1085. Android_RestoreScreenKeyboard(SDL_GetVideoDevice(), Android_Window);
  1086. }
  1087. SDL_UnlockMutex(Android_ActivityMutex);
  1088. }
  1089. // Called from surfaceDestroyed()
  1090. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(JNIEnv *env, jclass jcls)
  1091. {
  1092. int nb_attempt = 50;
  1093. retry:
  1094. SDL_LockMutex(Android_ActivityMutex);
  1095. if (Android_Window) {
  1096. SDL_WindowData *data = Android_Window->internal;
  1097. // Wait for Main thread being paused and context un-activated to release 'egl_surface'
  1098. if ((Android_Window->flags & SDL_WINDOW_OPENGL) && !data->backup_done) {
  1099. nb_attempt -= 1;
  1100. if (nb_attempt == 0) {
  1101. SDL_SetError("Try to release egl_surface with context probably still active");
  1102. } else {
  1103. SDL_UnlockMutex(Android_ActivityMutex);
  1104. SDL_Delay(10);
  1105. goto retry;
  1106. }
  1107. }
  1108. #ifdef SDL_VIDEO_OPENGL_EGL
  1109. if (data->egl_surface != EGL_NO_SURFACE) {
  1110. SDL_EGL_DestroySurface(SDL_GetVideoDevice(), data->egl_surface);
  1111. data->egl_surface = EGL_NO_SURFACE;
  1112. }
  1113. #endif
  1114. if (data->native_window) {
  1115. ANativeWindow_release(data->native_window);
  1116. data->native_window = NULL;
  1117. }
  1118. // GL Context handling is done in the event loop because this function is run from the Java thread
  1119. }
  1120. SDL_UnlockMutex(Android_ActivityMutex);
  1121. }
  1122. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeScreenKeyboardShown)(JNIEnv *env, jclass jcls)
  1123. {
  1124. SDL_SendScreenKeyboardShown();
  1125. }
  1126. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeScreenKeyboardHidden)(JNIEnv *env, jclass jcls)
  1127. {
  1128. SDL_SendScreenKeyboardHidden();
  1129. }
  1130. // Keydown
  1131. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
  1132. JNIEnv *env, jclass jcls,
  1133. jint keycode)
  1134. {
  1135. SDL_LockMutex(Android_ActivityMutex);
  1136. if (Android_Window) {
  1137. Android_OnKeyDown(keycode);
  1138. }
  1139. SDL_UnlockMutex(Android_ActivityMutex);
  1140. }
  1141. // Keyup
  1142. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
  1143. JNIEnv *env, jclass jcls,
  1144. jint keycode)
  1145. {
  1146. SDL_LockMutex(Android_ActivityMutex);
  1147. if (Android_Window) {
  1148. Android_OnKeyUp(keycode);
  1149. }
  1150. SDL_UnlockMutex(Android_ActivityMutex);
  1151. }
  1152. // Virtual keyboard return key might stop text input
  1153. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(onNativeSoftReturnKey)(
  1154. JNIEnv *env, jclass jcls)
  1155. {
  1156. if (SDL_GetHintBoolean(SDL_HINT_RETURN_KEY_HIDES_IME, false)) {
  1157. SDL_StopTextInput(Android_Window);
  1158. return JNI_TRUE;
  1159. }
  1160. return JNI_FALSE;
  1161. }
  1162. // Keyboard Focus Lost
  1163. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
  1164. JNIEnv *env, jclass jcls)
  1165. {
  1166. // Calling SDL_StopTextInput will take care of hiding the keyboard and cleaning up the DummyText widget
  1167. SDL_StopTextInput(Android_Window);
  1168. }
  1169. // Touch
  1170. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
  1171. JNIEnv *env, jclass jcls,
  1172. jint touch_device_id_in, jint pointer_finger_id_in,
  1173. jint action, jfloat x, jfloat y, jfloat p)
  1174. {
  1175. SDL_LockMutex(Android_ActivityMutex);
  1176. Android_OnTouch(Android_Window, touch_device_id_in, pointer_finger_id_in, action, x, y, p);
  1177. SDL_UnlockMutex(Android_ActivityMutex);
  1178. }
  1179. // Pinch
  1180. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePinchStart)(
  1181. JNIEnv *env, jclass jcls)
  1182. {
  1183. SDL_LockMutex(Android_ActivityMutex);
  1184. if (Android_Window) {
  1185. SDL_SendPinch(SDL_EVENT_PINCH_BEGIN, 0, Android_Window, 0);
  1186. }
  1187. SDL_UnlockMutex(Android_ActivityMutex);
  1188. }
  1189. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePinchUpdate)(
  1190. JNIEnv *env, jclass jcls, jfloat scale)
  1191. {
  1192. SDL_LockMutex(Android_ActivityMutex);
  1193. if (Android_Window) {
  1194. SDL_SendPinch(SDL_EVENT_PINCH_UPDATE, 0, Android_Window, scale);
  1195. }
  1196. SDL_UnlockMutex(Android_ActivityMutex);
  1197. }
  1198. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePinchEnd)(
  1199. JNIEnv *env, jclass jcls)
  1200. {
  1201. SDL_LockMutex(Android_ActivityMutex);
  1202. if (Android_Window) {
  1203. SDL_SendPinch(SDL_EVENT_PINCH_END, 0, Android_Window, 0);
  1204. }
  1205. SDL_UnlockMutex(Android_ActivityMutex);
  1206. }
  1207. // Mouse
  1208. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
  1209. JNIEnv *env, jclass jcls,
  1210. jint button, jint action, jfloat x, jfloat y, jboolean relative)
  1211. {
  1212. SDL_LockMutex(Android_ActivityMutex);
  1213. Android_OnMouse(Android_Window, button, action, x, y, relative);
  1214. SDL_UnlockMutex(Android_ActivityMutex);
  1215. }
  1216. // Pen
  1217. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePen)(
  1218. JNIEnv *env, jclass jcls,
  1219. jint pen_id_in, jint device_type, jint button, jint action, jfloat x, jfloat y, jfloat p)
  1220. {
  1221. SDL_LockMutex(Android_ActivityMutex);
  1222. Android_OnPen(Android_Window, pen_id_in, device_type, button, action, x, y, p);
  1223. SDL_UnlockMutex(Android_ActivityMutex);
  1224. }
  1225. // Clipboard
  1226. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeClipboardChanged)(
  1227. JNIEnv *env, jclass jcls)
  1228. {
  1229. // TODO: compute new mime types
  1230. SDL_SendClipboardUpdate(false, NULL, 0);
  1231. }
  1232. // Low memory
  1233. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
  1234. JNIEnv *env, jclass cls)
  1235. {
  1236. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_LOWMEMORY);
  1237. }
  1238. /* Locale
  1239. * requires android:configChanges="layoutDirection|locale" in AndroidManifest.xml */
  1240. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeLocaleChanged)(
  1241. JNIEnv *env, jclass cls)
  1242. {
  1243. SDL_SendAppEvent(SDL_EVENT_LOCALE_CHANGED);
  1244. }
  1245. // Dark mode
  1246. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDarkModeChanged)(
  1247. JNIEnv *env, jclass cls, jboolean enabled)
  1248. {
  1249. Android_SetDarkMode(enabled);
  1250. }
  1251. // Send Quit event to "SDLThread" thread
  1252. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSendQuit)(
  1253. JNIEnv *env, jclass cls)
  1254. {
  1255. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_DESTROY);
  1256. }
  1257. // Activity ends
  1258. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
  1259. JNIEnv *env, jclass cls)
  1260. {
  1261. const char *str;
  1262. if (Android_ActivityMutex) {
  1263. SDL_DestroyMutex(Android_ActivityMutex);
  1264. Android_ActivityMutex = NULL;
  1265. }
  1266. if (Android_LifecycleMutex) {
  1267. SDL_DestroyMutex(Android_LifecycleMutex);
  1268. Android_LifecycleMutex = NULL;
  1269. }
  1270. if (Android_LifecycleEventSem) {
  1271. SDL_DestroySemaphore(Android_LifecycleEventSem);
  1272. Android_LifecycleEventSem = NULL;
  1273. }
  1274. Android_NumLifecycleEvents = 0;
  1275. Internal_Android_Destroy_AssetManager();
  1276. str = SDL_GetError();
  1277. if (str && str[0]) {
  1278. __android_log_print(ANDROID_LOG_ERROR, "SDL", "SDLActivity thread ends (error=%s)", str);
  1279. } else {
  1280. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDLActivity thread ends");
  1281. }
  1282. }
  1283. // Pause
  1284. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
  1285. JNIEnv *env, jclass cls)
  1286. {
  1287. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativePause()");
  1288. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_PAUSE);
  1289. }
  1290. // Resume
  1291. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
  1292. JNIEnv *env, jclass cls)
  1293. {
  1294. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeResume()");
  1295. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_RESUME);
  1296. }
  1297. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeFocusChanged)(
  1298. JNIEnv *env, jclass cls, jboolean hasFocus)
  1299. {
  1300. SDL_LockMutex(Android_ActivityMutex);
  1301. if (Android_Window) {
  1302. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeFocusChanged()");
  1303. SDL_SendWindowEvent(Android_Window, (hasFocus ? SDL_EVENT_WINDOW_FOCUS_GAINED : SDL_EVENT_WINDOW_FOCUS_LOST), 0, 0);
  1304. }
  1305. SDL_UnlockMutex(Android_ActivityMutex);
  1306. }
  1307. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
  1308. JNIEnv *env, jclass cls,
  1309. jstring text, jint newCursorPosition)
  1310. {
  1311. const char *utftext = (*env)->GetStringUTFChars(env, text, NULL);
  1312. SDL_SendKeyboardText(utftext);
  1313. (*env)->ReleaseStringUTFChars(env, text, utftext);
  1314. }
  1315. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar)(
  1316. JNIEnv *env, jclass cls,
  1317. jchar chUnicode)
  1318. {
  1319. SDL_SendKeyboardUnicodeKey(0, chUnicode);
  1320. }
  1321. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
  1322. JNIEnv *env, jclass cls,
  1323. jstring name)
  1324. {
  1325. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  1326. const char *hint = SDL_GetHint(utfname);
  1327. jstring result = (*env)->NewStringUTF(env, hint);
  1328. (*env)->ReleaseStringUTFChars(env, name, utfname);
  1329. return result;
  1330. }
  1331. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeGetHintBoolean)(
  1332. JNIEnv *env, jclass cls,
  1333. jstring name, jboolean default_value)
  1334. {
  1335. jboolean result;
  1336. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  1337. result = SDL_GetHintBoolean(utfname, default_value);
  1338. (*env)->ReleaseStringUTFChars(env, name, utfname);
  1339. return result;
  1340. }
  1341. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
  1342. JNIEnv *env, jclass cls,
  1343. jstring name, jstring value)
  1344. {
  1345. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  1346. const char *utfvalue = (*env)->GetStringUTFChars(env, value, NULL);
  1347. // This is only called at startup, to initialize the environment
  1348. // Note that we call setenv() directly to avoid affecting SDL environments
  1349. setenv(utfname, utfvalue, 1); // This should NOT be SDL_setenv()
  1350. if (SDL_strcmp(utfname, SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY) == 0) {
  1351. // Special handling for this hint, which needs to persist outside the normal application flow
  1352. // Only set this the first time we run, in case it's been set by the application via SDL_SetHint()
  1353. if (!allow_recreate_activity_set) {
  1354. Android_SetAllowRecreateActivity(SDL_GetStringBoolean(utfvalue, false));
  1355. }
  1356. }
  1357. (*env)->ReleaseStringUTFChars(env, name, utfname);
  1358. (*env)->ReleaseStringUTFChars(env, value, utfvalue);
  1359. }
  1360. /*******************************************************************************
  1361. Functions called by SDL into Java
  1362. *******************************************************************************/
  1363. static SDL_AtomicInt s_active;
  1364. struct LocalReferenceHolder
  1365. {
  1366. JNIEnv *m_env;
  1367. const char *m_func;
  1368. };
  1369. static struct LocalReferenceHolder LocalReferenceHolder_Setup(const char *func)
  1370. {
  1371. struct LocalReferenceHolder refholder;
  1372. refholder.m_env = NULL;
  1373. refholder.m_func = func;
  1374. #ifdef DEBUG_JNI
  1375. SDL_Log("Entering function %s", func);
  1376. #endif
  1377. return refholder;
  1378. }
  1379. static bool LocalReferenceHolder_Init(struct LocalReferenceHolder *refholder, JNIEnv *env)
  1380. {
  1381. const int capacity = 16;
  1382. if ((*env)->PushLocalFrame(env, capacity) < 0) {
  1383. SDL_SetError("Failed to allocate enough JVM local references");
  1384. return false;
  1385. }
  1386. SDL_AtomicIncRef(&s_active);
  1387. refholder->m_env = env;
  1388. return true;
  1389. }
  1390. static void LocalReferenceHolder_Cleanup(struct LocalReferenceHolder *refholder)
  1391. {
  1392. #ifdef DEBUG_JNI
  1393. SDL_Log("Leaving function %s", refholder->m_func);
  1394. #endif
  1395. if (refholder->m_env) {
  1396. JNIEnv *env = refholder->m_env;
  1397. (*env)->PopLocalFrame(env, NULL);
  1398. SDL_AtomicDecRef(&s_active);
  1399. }
  1400. }
  1401. ANativeWindow *Android_JNI_GetNativeWindow(void)
  1402. {
  1403. ANativeWindow *anw = NULL;
  1404. jobject s;
  1405. JNIEnv *env = Android_JNI_GetEnv();
  1406. s = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetNativeSurface);
  1407. if (s) {
  1408. anw = ANativeWindow_fromSurface(env, s);
  1409. (*env)->DeleteLocalRef(env, s);
  1410. }
  1411. return anw;
  1412. }
  1413. void Android_JNI_SetActivityTitle(const char *title)
  1414. {
  1415. JNIEnv *env = Android_JNI_GetEnv();
  1416. jstring jtitle = (*env)->NewStringUTF(env, title);
  1417. (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetActivityTitle, jtitle);
  1418. (*env)->DeleteLocalRef(env, jtitle);
  1419. }
  1420. void Android_JNI_SetWindowStyle(bool fullscreen)
  1421. {
  1422. JNIEnv *env = Android_JNI_GetEnv();
  1423. (*env)->CallStaticVoidMethod(env, mActivityClass, midSetWindowStyle, fullscreen ? 1 : 0);
  1424. }
  1425. void Android_JNI_SetOrientation(int w, int h, int resizable, const char *hint)
  1426. {
  1427. JNIEnv *env = Android_JNI_GetEnv();
  1428. jstring jhint = (*env)->NewStringUTF(env, (hint ? hint : ""));
  1429. (*env)->CallStaticVoidMethod(env, mActivityClass, midSetOrientation, w, h, (resizable ? 1 : 0), jhint);
  1430. (*env)->DeleteLocalRef(env, jhint);
  1431. }
  1432. SDL_DisplayOrientation Android_JNI_GetDisplayNaturalOrientation(void)
  1433. {
  1434. return displayNaturalOrientation;
  1435. }
  1436. SDL_DisplayOrientation Android_JNI_GetDisplayCurrentOrientation(void)
  1437. {
  1438. return displayCurrentOrientation;
  1439. }
  1440. void Android_JNI_MinimizeWindow(void)
  1441. {
  1442. JNIEnv *env = Android_JNI_GetEnv();
  1443. (*env)->CallStaticVoidMethod(env, mActivityClass, midMinimizeWindow);
  1444. }
  1445. bool Android_JNI_ShouldMinimizeOnFocusLoss(void)
  1446. {
  1447. JNIEnv *env = Android_JNI_GetEnv();
  1448. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midShouldMinimizeOnFocusLoss);
  1449. }
  1450. /*
  1451. * Audio support
  1452. */
  1453. void Android_StartAudioHotplug(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording)
  1454. {
  1455. JNIEnv *env = Android_JNI_GetEnv();
  1456. // this will fire the callback for each existing device right away (which will eventually SDL_AddAudioDevice), and again later when things change.
  1457. (*env)->CallStaticVoidMethod(env, mAudioManagerClass, midRegisterAudioDeviceCallback);
  1458. *default_playback = *default_recording = NULL; // !!! FIXME: how do you decide the default device id?
  1459. }
  1460. void Android_StopAudioHotplug(void)
  1461. {
  1462. JNIEnv *env = Android_JNI_GetEnv();
  1463. (*env)->CallStaticVoidMethod(env, mAudioManagerClass, midUnregisterAudioDeviceCallback);
  1464. }
  1465. static void Android_JNI_AudioSetThreadPriority(int recording, int device_id)
  1466. {
  1467. JNIEnv *env = Android_JNI_GetEnv();
  1468. (*env)->CallStaticVoidMethod(env, mAudioManagerClass, midAudioSetThreadPriority, recording, device_id);
  1469. }
  1470. void Android_AudioThreadInit(SDL_AudioDevice *device)
  1471. {
  1472. Android_JNI_AudioSetThreadPriority((int) device->recording, (int)device->instance_id);
  1473. }
  1474. // Test for an exception and call SDL_SetError with its detail if one occurs
  1475. // If the parameter silent is truthy then SDL_SetError() will not be called.
  1476. static bool Android_JNI_ExceptionOccurred(bool silent)
  1477. {
  1478. JNIEnv *env = Android_JNI_GetEnv();
  1479. jthrowable exception;
  1480. // Detect mismatch LocalReferenceHolder_Init/Cleanup
  1481. SDL_assert(SDL_GetAtomicInt(&s_active) > 0);
  1482. exception = (*env)->ExceptionOccurred(env);
  1483. if (exception != NULL) {
  1484. jmethodID mid;
  1485. // Until this happens most JNI operations have undefined behaviour
  1486. (*env)->ExceptionClear(env);
  1487. if (!silent) {
  1488. jclass exceptionClass = (*env)->GetObjectClass(env, exception);
  1489. jclass classClass = (*env)->FindClass(env, "java/lang/Class");
  1490. jstring exceptionName;
  1491. const char *exceptionNameUTF8;
  1492. jstring exceptionMessage;
  1493. mid = (*env)->GetMethodID(env, classClass, "getName", "()Ljava/lang/String;");
  1494. exceptionName = (jstring)(*env)->CallObjectMethod(env, exceptionClass, mid);
  1495. exceptionNameUTF8 = (*env)->GetStringUTFChars(env, exceptionName, 0);
  1496. (*env)->DeleteLocalRef(env, classClass);
  1497. mid = (*env)->GetMethodID(env, exceptionClass, "getMessage", "()Ljava/lang/String;");
  1498. exceptionMessage = (jstring)(*env)->CallObjectMethod(env, exception, mid);
  1499. (*env)->DeleteLocalRef(env, exceptionClass);
  1500. if (exceptionMessage != NULL) {
  1501. const char *exceptionMessageUTF8 = (*env)->GetStringUTFChars(env, exceptionMessage, 0);
  1502. SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
  1503. (*env)->ReleaseStringUTFChars(env, exceptionMessage, exceptionMessageUTF8);
  1504. (*env)->DeleteLocalRef(env, exceptionMessage);
  1505. } else {
  1506. SDL_SetError("%s", exceptionNameUTF8);
  1507. }
  1508. (*env)->ReleaseStringUTFChars(env, exceptionName, exceptionNameUTF8);
  1509. (*env)->DeleteLocalRef(env, exceptionName);
  1510. }
  1511. return true;
  1512. }
  1513. return false;
  1514. }
  1515. // APK file tree discovery...
  1516. // APK files are just .zip files, so try to find parse out the file tree from it. We'll still
  1517. // use Android's system APIs to actually access data, but those APIs aren't reliable for
  1518. // enumerating the tree for various reasons.
  1519. // we only care about the directories; Android's AAssetManager can enumerate all files in any
  1520. // known directory, but it won't enumerate subdirectories, so we track that by ourselves.
  1521. typedef struct APKNode
  1522. {
  1523. char *name;
  1524. SDL_PathInfo info;
  1525. struct APKNode *parent;
  1526. struct APKNode *children;
  1527. struct APKNode *children_tail;
  1528. struct APKNode *next_sibling;
  1529. } APKNode;
  1530. static APKNode *APKRootNode = NULL;
  1531. static void FreeAPKNode(APKNode *node)
  1532. {
  1533. if (node) {
  1534. FreeAPKNode(node->next_sibling);
  1535. FreeAPKNode(node->children);
  1536. SDL_free(node->name);
  1537. SDL_free(node);
  1538. }
  1539. }
  1540. static APKNode *FindAPKChildNode(APKNode *parent, const char *child)
  1541. {
  1542. if ((child[0] == '.') && (child[1] == '\0')) { // "." paths just return the current dir.
  1543. return parent;
  1544. } else if ((child[0] == '.') && (child[1] == '.') && (child[2] == '\0')) { // ".." paths return the parent dir (or the current dir if at the root).
  1545. return parent->parent ? parent->parent : parent;
  1546. }
  1547. for (APKNode *node = parent->children; node != NULL; node = node->next_sibling) {
  1548. if (SDL_strcmp(child, node->name) == 0) {
  1549. return node;
  1550. }
  1551. }
  1552. return NULL;
  1553. }
  1554. static const APKNode *FindAPKNode(const char *constpath)
  1555. {
  1556. //SDL_Log("FindAPKNode('%s') ...", constpath);
  1557. if (SDL_strncmp(constpath, "assets://", 9) == 0) {
  1558. constpath += 9;
  1559. }
  1560. APKNode *parent = APKRootNode;
  1561. if (!parent) {
  1562. return NULL;
  1563. } else if (*constpath == '\0') {
  1564. return parent;
  1565. }
  1566. const size_t pathlen = SDL_strlen(constpath);
  1567. bool isstack = false;
  1568. char *alloc_path = SDL_small_alloc(char, pathlen + 1, &isstack);
  1569. if (!alloc_path) {
  1570. return NULL;
  1571. }
  1572. char *path = alloc_path;
  1573. SDL_strlcpy(path, constpath, pathlen + 1);
  1574. while (parent) {
  1575. while (*path == '/') {
  1576. path++; // just in case there are absolute paths or double-slashes, drop them.
  1577. }
  1578. if (*path == '\0') { // ended with a '/'? We're done.
  1579. break;
  1580. }
  1581. char *ptr = SDL_strchr(path, '/');
  1582. if (ptr) {
  1583. *ptr = '\0'; // terminate on the end of this subdir's name.
  1584. }
  1585. APKNode *node = FindAPKChildNode(parent, path);
  1586. if (!node) {
  1587. SDL_SetError("No such file or directory");
  1588. parent = NULL;
  1589. } else if ((node->info.type == SDL_PATHTYPE_FILE) && ptr) { // file where we want a directory?
  1590. SDL_SetError("%s is not a directory", alloc_path);
  1591. parent = NULL;
  1592. } else {
  1593. parent = node;
  1594. if (!ptr) {
  1595. break;
  1596. }
  1597. *ptr = '/';
  1598. path = ptr + 1;
  1599. }
  1600. }
  1601. SDL_small_free(alloc_path, isstack);
  1602. return parent;
  1603. }
  1604. static APKNode *AddAPKChildNode(APKNode *parent, const char *child)
  1605. {
  1606. APKNode *node = FindAPKChildNode(parent, child);
  1607. if (!node) { // don't have this one yet, make a new node.
  1608. node = (APKNode *) SDL_calloc(1, sizeof (*node));
  1609. if (!node) {
  1610. return NULL; // uhoh.
  1611. }
  1612. node->name = SDL_strdup(child);
  1613. if (!node->name) {
  1614. SDL_free(node);
  1615. return NULL; // uhoh.
  1616. }
  1617. SDL_copyp(&node->info, &parent->info); // you probably need to update this afterwards.
  1618. node->parent = parent;
  1619. if (parent->children_tail) { // APKs tend to be sorted alphabetically, so insert new nodes at the end of the list to maintain this order.
  1620. parent->children_tail->next_sibling = node;
  1621. } else {
  1622. parent->children = node;
  1623. }
  1624. parent->children_tail = node;
  1625. }
  1626. return node;
  1627. }
  1628. static APKNode *AddAPKDirs(char *path, APKNode *parent)
  1629. {
  1630. // zip files specify explicit directories by just having a path that ends with a dir separator,
  1631. // which works nicely for our needs here; if the last segment of the path doesn't end with a
  1632. // '/', it's a file and we can drop it, or we filled in the final subdirectory and the '/' at
  1633. // the end will put us at an empty string to be dropped.
  1634. //
  1635. // directories do not need to be explicitly specified if something uses some deeper path, they
  1636. // may need to be inferred from those references, so we build out the tree by looking at all
  1637. // files and filling in nodes they mention.
  1638. SDL_assert(parent->info.type == SDL_PATHTYPE_DIRECTORY);
  1639. SDL_assert(parent->info.size == 0);
  1640. while (true) { // while still subdirectories to handle...
  1641. while (*path == '/') {
  1642. path++; // just in case there are absolute paths or double-slashes, drop them.
  1643. }
  1644. char *ptr = SDL_strchr(path, '/');
  1645. if (!ptr) {
  1646. break; // last thing is either an empty string (we ended with a '/'), or an actual file's name, so drop it.
  1647. }
  1648. if ((path[0] == '.') && ((path[1] == '\0') || ((path[1] == '.') ||(path[2] == '\0')))) {
  1649. // whoa, there's a "." or ".." subdir in a zip entry's path? Fail!
  1650. SDL_SetError("bogus file path in APK file entry");
  1651. return NULL;
  1652. }
  1653. *ptr = '\0'; // terminate on the end of this subdir's name.
  1654. APKNode *node = AddAPKChildNode(parent, path);
  1655. *ptr = '/';
  1656. if (!node) {
  1657. return NULL; // uhoh.
  1658. }
  1659. parent = node;
  1660. path = ptr + 1; // point to start of next section.
  1661. }
  1662. return parent;
  1663. }
  1664. static SDL_Time ZipDosTimeToSDLTime(Uint32 dostime)
  1665. {
  1666. // Note that DOS-style datetimes in a zip don't have timezone info, etc,
  1667. // so these are treated as UTC for lack of a better option. Also, they have
  1668. // 2-second precision and the year bits are going to roll over in 2108.
  1669. // There are possibly better timestamps in extended fields (!!! FIXME: add
  1670. // support for those), but this field is guaranteed to exist with all its
  1671. // flaws and is probably Good Enough anyhow.
  1672. const Uint32 dosdate = (Uint32) ((dostime >> 16) & 0xFFFF);
  1673. const Uint32 dostime16 = dostime & 0xFFFF;
  1674. const int m = (int) ((dosdate >> 5) & 0x0F);
  1675. const int d = (int) ((dosdate >> 0) & 0x1F) + 1;
  1676. const int y = (int) (((dosdate >> 9) & 0x7F) + 1980) - (m <= 2 ? 1 : 0);
  1677. const int hour = (int) ((dostime16 >> 11) & 0x1F);
  1678. const int minute = (int) ((dostime16 >> 5) & 0x3F);
  1679. const int sec = (int) ((dostime16 << 1) & 0x3E);
  1680. // days since 1/1/1970: https://howardhinnant.github.io/date_algorithms.html#days_from_civil
  1681. const int era = ((y >= 0) ? y : (y - 399)) / 400;
  1682. const unsigned int yoe = (unsigned int) (y - era * 400); // [0, 399]
  1683. const unsigned int doy = (((153 * ((m > 2) ? (m - 3) : (m + 9))) + 2) / 5) + (d - 1); // [0, 365]
  1684. const unsigned int doe = (yoe * 365) + (yoe / 4) - (yoe / 100) + doy; // [0, 146096]
  1685. const int days = (era * 146097) + ((int) doe) - 719468;
  1686. const int seconds = (hour * (60 * 60)) + (minute * 60) + (sec);
  1687. return (SDL_Time) (((Sint64) days) * 86400) + seconds;
  1688. }
  1689. #define ZIP_CENTRAL_DIR_SIG 0x02014b50
  1690. #define ZIP_END_OF_CENTRAL_DIR_SIG 0x06054b50
  1691. #define ZIP64_END_OF_CENTRAL_DIR_SIG 0x06064b50
  1692. #define ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIG 0x07064b50
  1693. #define ZIP64_EXTENDED_INFO_EXTRA_FIELD_SIG 0x0001
  1694. static bool ProcessZip(SDL_IOStream *io, APKNode *root)
  1695. {
  1696. // There is a record at the end of a .zip file we can use to find the central directory;
  1697. // unfortunately it's before the variable-length comment field, so we might need to read
  1698. // from the end of the file until we see a magic signature. For now, we assume APKs don't
  1699. // have a comment, so we don't have to search backwards for the signature and it's always
  1700. // 22 bytes from EOF.
  1701. const Sint64 eocd = SDL_GetIOSize(io) - 22;
  1702. if (eocd < 0) {
  1703. SDL_Log("ANDROID: Couldn't find End Of Central Directory in APK (%s). Filesystem enumeration will fail.", SDL_GetError());
  1704. return false;
  1705. }
  1706. bool zip64 = false;
  1707. Sint64 centraldir = -1;
  1708. Uint64 num_entries = 0;
  1709. Uint16 val16 = 0;
  1710. Uint32 val32 = 0;
  1711. Uint64 val64 = 0;
  1712. // First, check if this is actually zip64 format instead. The zip64 magic is 20 bytes back.
  1713. if (eocd < 20) { // presumably we always _are_ > 20, but let's be defensive here.
  1714. goto corrupterr;
  1715. } else if (SDL_SeekIO(io, eocd - 20, SDL_IO_SEEK_SET) < 0) {
  1716. goto ioerr;
  1717. } else if (!SDL_ReadU32LE(io, &val32)) {
  1718. goto ioerr;
  1719. } else if (val32 == ZIP64_END_OF_CENTRAL_DIRECTORY_LOCATOR_SIG) { // this is a zip64 archive?
  1720. if (!SDL_ReadU32LE(io, &val32)) { // disk number with start of central directory.
  1721. goto ioerr;
  1722. } else if (val32 != 0) {
  1723. goto corrupterr;
  1724. } else if (!SDL_ReadU64LE(io, &val64)) { // file offset of zip64 end-of-central-dir record
  1725. goto ioerr;
  1726. // note that this gets significantly more complex if there is data prepended to the .zip file
  1727. // (like a self-extracting .exe, etc), but until that happens, we're keeping this as simple
  1728. // as possible and assuming the file offset in val64 is correct.
  1729. } else if (SDL_SeekIO(io, (Sint64) val64, SDL_IO_SEEK_SET) < 0) {
  1730. goto ioerr;
  1731. } else if (!SDL_ReadU32LE(io, &val32)) { // zip64 end-of-central-dir signature.
  1732. goto ioerr;
  1733. } else if (val32 != ZIP64_END_OF_CENTRAL_DIR_SIG) {
  1734. goto corrupterr;
  1735. } else if (SDL_SeekIO(io, 28, SDL_IO_SEEK_CUR) < 0) { // we don't care about several of the fields, skip over them.
  1736. goto ioerr;
  1737. } else if (!SDL_ReadU64LE(io, &num_entries)) { // total entries in the central dir.
  1738. goto ioerr;
  1739. } else if (!SDL_ReadU64LE(io, &val64)) { // size of the central dir.
  1740. goto ioerr;
  1741. } else if (!SDL_ReadU64LE(io, &val64)) { // offset of the central dir.
  1742. goto ioerr;
  1743. }
  1744. zip64 = true;
  1745. centraldir = (Sint64) val64;
  1746. } else if (SDL_SeekIO(io, eocd + 4 + 6, SDL_IO_SEEK_SET) < 0) { // skip back to where we were, plus skip some fields we don't care about.
  1747. goto ioerr;
  1748. } else if (!SDL_ReadU16LE(io, &val16)) {
  1749. goto ioerr;
  1750. } else if (!SDL_ReadU32LE(io, &val32)) { // size of the central dir.
  1751. goto ioerr;
  1752. } else if (!SDL_ReadU32LE(io, &val32)) { // offset of the central dir.
  1753. goto ioerr;
  1754. } else {
  1755. num_entries = (Uint64) val16;
  1756. centraldir = (Sint64) val32;
  1757. }
  1758. // okay, we know where the central dir is now, go there and start reading entries.
  1759. SDL_assert(centraldir > 0); // negative means we failed, zero is impossible since there should be something else there.
  1760. for (Uint64 i = 0; i < num_entries; i++) {
  1761. Uint16 fnamelen = 0;
  1762. Uint16 extralen = 0;
  1763. Uint16 commentlen = 0;
  1764. Uint32 dosmodtime = 0;
  1765. Uint32 uncompressed32 = 0;
  1766. Uint64 uncompressed64 = 0;
  1767. // we don't care about most of this information, just parse through it to get what we need.
  1768. if (SDL_SeekIO(io, centraldir, SDL_IO_SEEK_SET) < 0) {
  1769. goto ioerr;
  1770. } else if (!SDL_ReadU32LE(io, &val32)) { // central dir item signature.
  1771. goto ioerr;
  1772. } else if (val32 != ZIP_CENTRAL_DIR_SIG) {
  1773. goto corrupterr;
  1774. } else if (!SDL_ReadU16LE(io, &val16)) { // version made by
  1775. goto ioerr;
  1776. } else if (!SDL_ReadU16LE(io, &val16)) { // version needed
  1777. goto ioerr;
  1778. } else if (!SDL_ReadU16LE(io, &val16)) { // general bits
  1779. goto ioerr;
  1780. } else if (!SDL_ReadU16LE(io, &val16)) { // compression method
  1781. goto ioerr;
  1782. } else if (!SDL_ReadU32LE(io, &dosmodtime)) { // last mod date/time
  1783. goto ioerr;
  1784. } else if (!SDL_ReadU32LE(io, &val32)) { // CRC-32
  1785. goto ioerr;
  1786. } else if (!SDL_ReadU32LE(io, &val32)) { // compressed size
  1787. goto ioerr;
  1788. } else if (!SDL_ReadU32LE(io, &uncompressed32)) { // uncompressed size
  1789. goto ioerr;
  1790. } else if (!SDL_ReadU16LE(io, &fnamelen)) { // filename length
  1791. goto ioerr;
  1792. } else if (!SDL_ReadU16LE(io, &extralen)) { // extra length
  1793. goto ioerr;
  1794. } else if (!SDL_ReadU16LE(io, &commentlen)) { // comment length
  1795. goto ioerr;
  1796. } else if (!SDL_ReadU16LE(io, &val16)) { // disk number start
  1797. goto ioerr;
  1798. } else if (!SDL_ReadU16LE(io, &val16)) { // internal file attributes
  1799. goto ioerr;
  1800. } else if (!SDL_ReadU32LE(io, &val32)) { // external file attributes
  1801. goto ioerr;
  1802. } else if (!SDL_ReadU32LE(io, &val32)) { // relative offset of local header
  1803. goto ioerr;
  1804. }
  1805. char fnamebuf[0xFFFF+1]; // just eat 64k of stack like a boss until someone complains.
  1806. if (SDL_ReadIO(io, fnamebuf, (size_t) fnamelen) != ((size_t) fnamelen)) {
  1807. goto ioerr;
  1808. }
  1809. // technically zip files might have '\\' dir separators, but these were mostly old DOS files and not Android APKs, I think. Revisit if necessary.
  1810. fnamebuf[fnamelen] = '\0'; // make sure the string is null-terminated.
  1811. //SDL_Log("ANDROID: Saw ZIP entry '%s'", fnamebuf);
  1812. uncompressed64 = (Uint64) uncompressed32;
  1813. if (zip64 && (uncompressed32 == 0xFFFFFFFF)) { // file is larger than 4gig, find the zip64 extended info field in the extra section.
  1814. bool found = false;
  1815. Uint16 remaining = extralen;
  1816. while (remaining > 4) { // Two 16-bit values at a minimum, tag and len.
  1817. Uint16 tag, len;
  1818. if (!SDL_ReadU16LE(io, &tag) || !SDL_ReadU16LE(io, &len)) {
  1819. goto ioerr;
  1820. } else if (remaining < (len + 4)) {
  1821. goto corrupterr;
  1822. } else if (tag != ZIP64_EXTENDED_INFO_EXTRA_FIELD_SIG) { // not the field we need, skip over it.
  1823. if (SDL_SeekIO(io, (Sint64) len, SDL_IO_SEEK_CUR) < 0) {
  1824. goto ioerr;
  1825. }
  1826. } else if (len < 8) {
  1827. goto corrupterr;
  1828. } else if ((uncompressed32 == 0xFFFFFFFF) && !SDL_ReadU64LE(io, &uncompressed64)) {
  1829. goto ioerr;
  1830. // there are other values in here, but we don't care about them and we're done, so don't try to skip over them.
  1831. } else {
  1832. found = true;
  1833. break; // got what we need, drop out.
  1834. }
  1835. remaining -= len + 4;
  1836. }
  1837. if (!found) {
  1838. goto corrupterr;
  1839. }
  1840. }
  1841. char *ptr = fnamebuf;
  1842. while (*ptr == '/') { // drop absolute paths.
  1843. ptr++;
  1844. }
  1845. if (SDL_strncmp(ptr, "assets/", 7) == 0) { // we only care about things under 'assets' for now. Drop everything else.
  1846. ptr += 6; // keep the '/' so strrchr never returns NULL.
  1847. APKNode *node = AddAPKDirs(ptr, root); // this builds out any missing subdirs, returns parent dir's node.
  1848. if (!node) {
  1849. goto ioerr; // (probably out of memory.)
  1850. }
  1851. const SDL_Time modtime = ZipDosTimeToSDLTime(dosmodtime);
  1852. ptr = SDL_strrchr(ptr, '/');
  1853. SDL_assert(ptr != NULL);
  1854. if (*(++ptr) == '\0') { // explicit directory entry paths end with '/' ...`node` is the new node.
  1855. node->info.type = SDL_PATHTYPE_DIRECTORY;
  1856. node->info.size = 0;
  1857. } else {
  1858. node = AddAPKChildNode(node, ptr);
  1859. if (!node) {
  1860. goto ioerr; // (probably out of memory.)
  1861. }
  1862. node->info.type = SDL_PATHTYPE_FILE;
  1863. node->info.size = uncompressed64;
  1864. }
  1865. node->info.create_time = node->info.modify_time = node->info.access_time = modtime;
  1866. }
  1867. centraldir += (Sint64) (46 + fnamelen + extralen + commentlen); // will seek to next file entry.
  1868. }
  1869. return true;
  1870. corrupterr:
  1871. SDL_Log("ANDROID: Unexpected or corrupt data in APK. Filesystem enumeration will fail.");
  1872. return false;
  1873. ioerr:
  1874. SDL_Log("ANDROID: i/o error in APK (%s). Filesystem enumeration will fail.", SDL_GetError());
  1875. return false;
  1876. }
  1877. static bool CreateAPKNodes(const char *path)
  1878. {
  1879. //SDL_Log("ANDROID: Parsing APK file '%s' ...", path);
  1880. SDL_IOStream *io = SDL_IOFromFile(path, "rb");
  1881. if (!io) {
  1882. SDL_Log("ANDROID: Can't open APK '%s' for reading (%s). Filesystem enumeration will fail.", path, SDL_GetError());
  1883. } else {
  1884. ProcessZip(io, APKRootNode);
  1885. SDL_CloseIO(io);
  1886. }
  1887. return true;
  1888. }
  1889. static bool PrepareAPK(void)
  1890. {
  1891. // the assetmanager isn't useful for enumerating directories, so parse the APK directly for that info upfront.
  1892. bool retval = (APKRootNode != NULL);
  1893. if (!retval) {
  1894. // allocate this upfront, so if there's a failure, we'll not try again and just have an empty file tree.
  1895. APKRootNode = (APKNode *) SDL_calloc(1, sizeof (*APKRootNode));
  1896. if (!APKRootNode) {
  1897. return false; // oh well.
  1898. }
  1899. APKRootNode->info.type = SDL_PATHTYPE_DIRECTORY;
  1900. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  1901. JNIEnv *env = Android_JNI_GetEnv();
  1902. if (LocalReferenceHolder_Init(&refs, env)) {
  1903. jobject context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1904. jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context), "getPackageResourcePath", "()Ljava/lang/String;");
  1905. jstring jstr = (jstring)(*env)->CallObjectMethod(env, context, mid);
  1906. jthrowable jexception = (*env)->ExceptionOccurred(env);
  1907. if (jexception != NULL) {
  1908. (*env)->ExceptionClear(env); // oh well
  1909. } else {
  1910. const char *apkpath = (*env)->GetStringUTFChars(env, jstr, NULL);
  1911. SDL_PathInfo apkinfo;
  1912. SDL_assert(apkpath[0] == '/'); // So SDL_GetPathInfo goes through the `stat` path and doesn't try to dig into the APK.
  1913. if (SDL_GetPathInfo(apkpath, &apkinfo)) { // we just want the file times here, so oh well if it fails.
  1914. APKRootNode->info.create_time = apkinfo.create_time;
  1915. APKRootNode->info.modify_time = apkinfo.modify_time;
  1916. APKRootNode->info.access_time = apkinfo.access_time;
  1917. }
  1918. CreateAPKNodes(apkpath);
  1919. (*env)->ReleaseStringUTFChars(env, jstr, apkpath);
  1920. retval = true;
  1921. }
  1922. }
  1923. LocalReferenceHolder_Cleanup(&refs);
  1924. }
  1925. return retval; // even on failure, leave an empty root node so we have zero files and don't try to load the .zip again.
  1926. }
  1927. static void Internal_Android_Create_AssetManager(void)
  1928. {
  1929. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  1930. JNIEnv *env = Android_JNI_GetEnv();
  1931. jmethodID mid;
  1932. jobject context;
  1933. jobject javaAssetManager;
  1934. if (!LocalReferenceHolder_Init(&refs, env)) {
  1935. LocalReferenceHolder_Cleanup(&refs);
  1936. return;
  1937. }
  1938. // context = SDLActivity.getContext();
  1939. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1940. // javaAssetManager = context.getAssets();
  1941. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  1942. "getAssets", "()Landroid/content/res/AssetManager;");
  1943. javaAssetManager = (*env)->CallObjectMethod(env, context, mid);
  1944. /**
  1945. * Given a Dalvik AssetManager object, obtain the corresponding native AAssetManager
  1946. * object. Note that the caller is responsible for obtaining and holding a VM reference
  1947. * to the jobject to prevent its being garbage collected while the native object is
  1948. * in use.
  1949. */
  1950. javaAssetManagerRef = (*env)->NewGlobalRef(env, javaAssetManager);
  1951. asset_manager = AAssetManager_fromJava(env, javaAssetManagerRef);
  1952. if (!asset_manager) {
  1953. (*env)->DeleteGlobalRef(env, javaAssetManagerRef);
  1954. Android_JNI_ExceptionOccurred(true);
  1955. }
  1956. LocalReferenceHolder_Cleanup(&refs);
  1957. }
  1958. static void Internal_Android_Destroy_AssetManager(void)
  1959. {
  1960. JNIEnv *env = Android_JNI_GetEnv();
  1961. if (asset_manager) {
  1962. (*env)->DeleteGlobalRef(env, javaAssetManagerRef);
  1963. asset_manager = NULL;
  1964. }
  1965. if (APKRootNode) {
  1966. FreeAPKNode(APKRootNode);
  1967. APKRootNode = NULL;
  1968. }
  1969. }
  1970. static const char *GetAssetPath(const char *path)
  1971. {
  1972. if (!path) {
  1973. return NULL;
  1974. }
  1975. if (path[0] == '.' && ((path[1] == '/') || (path[1] == '\0'))) {
  1976. path++;
  1977. } else if (SDL_strncmp(path, "assets://", 9) == 0) {
  1978. path += 9;
  1979. }
  1980. while (*path == '/') {
  1981. ++path;
  1982. }
  1983. return path;
  1984. }
  1985. bool Android_JNI_FileOpen(void **puserdata, const char *fileName, const char *mode)
  1986. {
  1987. SDL_assert(puserdata != NULL);
  1988. AAsset *asset = NULL;
  1989. *puserdata = NULL;
  1990. if (!asset_manager) {
  1991. Internal_Android_Create_AssetManager();
  1992. if (!asset_manager) {
  1993. return SDL_SetError("Couldn't create asset manager");
  1994. }
  1995. }
  1996. fileName = GetAssetPath(fileName);
  1997. asset = AAssetManager_open(asset_manager, fileName, AASSET_MODE_UNKNOWN);
  1998. if (!asset) {
  1999. return SDL_SetError("Couldn't open asset '%s'", fileName);
  2000. }
  2001. *puserdata = (void *)asset;
  2002. return true;
  2003. }
  2004. size_t Android_JNI_FileRead(void *userdata, void *buffer, size_t size, SDL_IOStatus *status)
  2005. {
  2006. const int bytes = AAsset_read((AAsset *)userdata, buffer, size);
  2007. if (bytes < 0) {
  2008. SDL_SetError("AAsset_read() failed");
  2009. *status = SDL_IO_STATUS_ERROR;
  2010. return 0;
  2011. } else if (bytes < size) {
  2012. *status = SDL_IO_STATUS_EOF;
  2013. }
  2014. return (size_t)bytes;
  2015. }
  2016. size_t Android_JNI_FileWrite(void *userdata, const void *buffer, size_t size, SDL_IOStatus *status)
  2017. {
  2018. SDL_SetError("Cannot write to Android package filesystem");
  2019. *status = SDL_IO_STATUS_ERROR;
  2020. return 0;
  2021. }
  2022. Sint64 Android_JNI_FileSize(void *userdata)
  2023. {
  2024. return (Sint64) AAsset_getLength64((AAsset *)userdata);
  2025. }
  2026. Sint64 Android_JNI_FileSeek(void *userdata, Sint64 offset, SDL_IOWhence whence)
  2027. {
  2028. return (Sint64) AAsset_seek64((AAsset *)userdata, offset, (int)whence);
  2029. }
  2030. bool Android_JNI_FileClose(void *userdata)
  2031. {
  2032. AAsset_close((AAsset *)userdata);
  2033. return true;
  2034. }
  2035. bool Android_JNI_EnumerateAssetDirectory(const char *path, SDL_EnumerateDirectoryCallback cb, void *userdata)
  2036. {
  2037. SDL_assert(path != NULL);
  2038. if (!PrepareAPK()) {
  2039. return false;
  2040. }
  2041. SDL_EnumerationResult result = SDL_ENUM_CONTINUE;
  2042. const char *asset_path = GetAssetPath(path);
  2043. const APKNode *apknode = FindAPKNode(asset_path);
  2044. if (!apknode) {
  2045. return SDL_SetError("No such directory");
  2046. } else if (apknode->info.type != SDL_PATHTYPE_DIRECTORY) {
  2047. return SDL_SetError("Not a directory");
  2048. } else {
  2049. for (const APKNode *node = apknode->children; node && (result == SDL_ENUM_CONTINUE); node = node->next_sibling) {
  2050. result = cb(userdata, path, node->name);
  2051. }
  2052. }
  2053. return (result != SDL_ENUM_FAILURE);
  2054. }
  2055. bool Android_JNI_GetAssetPathInfo(const char *path, SDL_PathInfo *info)
  2056. {
  2057. SDL_assert(path != NULL);
  2058. if (!PrepareAPK()) {
  2059. return false;
  2060. }
  2061. path = GetAssetPath(path);
  2062. const APKNode *apknode = FindAPKNode(path);
  2063. if (!apknode) {
  2064. return SDL_SetError("No such file or directory");
  2065. }
  2066. SDL_copyp(info, &apknode->info);
  2067. return true;
  2068. }
  2069. bool Android_JNI_SetClipboardText(const char *text)
  2070. {
  2071. JNIEnv *env = Android_JNI_GetEnv();
  2072. jstring string = (*env)->NewStringUTF(env, text);
  2073. (*env)->CallStaticVoidMethod(env, mActivityClass, midClipboardSetText, string);
  2074. (*env)->DeleteLocalRef(env, string);
  2075. return true;
  2076. }
  2077. char *Android_JNI_GetClipboardText(void)
  2078. {
  2079. JNIEnv *env = Android_JNI_GetEnv();
  2080. char *text = NULL;
  2081. jstring string;
  2082. string = (*env)->CallStaticObjectMethod(env, mActivityClass, midClipboardGetText);
  2083. if (string) {
  2084. const char *utf = (*env)->GetStringUTFChars(env, string, 0);
  2085. if (utf) {
  2086. text = SDL_strdup(utf);
  2087. (*env)->ReleaseStringUTFChars(env, string, utf);
  2088. }
  2089. (*env)->DeleteLocalRef(env, string);
  2090. }
  2091. return (!text) ? SDL_strdup("") : text;
  2092. }
  2093. bool Android_JNI_HasClipboardText(void)
  2094. {
  2095. JNIEnv *env = Android_JNI_GetEnv();
  2096. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midClipboardHasText);
  2097. }
  2098. /* returns 0 on success or -1 on error (others undefined then)
  2099. * returns truthy or falsy value in plugged, charged and battery
  2100. * returns the value in seconds and percent or -1 if not available
  2101. */
  2102. int Android_JNI_GetPowerInfo(int *plugged, int *charged, int *battery, int *seconds, int *percent)
  2103. {
  2104. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  2105. JNIEnv *env = Android_JNI_GetEnv();
  2106. jmethodID mid;
  2107. jobject context;
  2108. jstring action;
  2109. jclass cls;
  2110. jobject filter;
  2111. jobject intent;
  2112. jstring iname;
  2113. jmethodID imid;
  2114. jstring bname;
  2115. jmethodID bmid;
  2116. if (!LocalReferenceHolder_Init(&refs, env)) {
  2117. LocalReferenceHolder_Cleanup(&refs);
  2118. return -1;
  2119. }
  2120. // context = SDLActivity.getContext();
  2121. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2122. action = (*env)->NewStringUTF(env, "android.intent.action.BATTERY_CHANGED");
  2123. cls = (*env)->FindClass(env, "android/content/IntentFilter");
  2124. mid = (*env)->GetMethodID(env, cls, "<init>", "(Ljava/lang/String;)V");
  2125. filter = (*env)->NewObject(env, cls, mid, action);
  2126. (*env)->DeleteLocalRef(env, action);
  2127. mid = (*env)->GetMethodID(env, mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
  2128. intent = (*env)->CallObjectMethod(env, context, mid, NULL, filter);
  2129. (*env)->DeleteLocalRef(env, filter);
  2130. cls = (*env)->GetObjectClass(env, intent);
  2131. imid = (*env)->GetMethodID(env, cls, "getIntExtra", "(Ljava/lang/String;I)I");
  2132. // Watch out for C89 scoping rules because of the macro
  2133. #define GET_INT_EXTRA(var, key) \
  2134. int var; \
  2135. iname = (*env)->NewStringUTF(env, key); \
  2136. (var) = (*env)->CallIntMethod(env, intent, imid, iname, -1); \
  2137. (*env)->DeleteLocalRef(env, iname);
  2138. bmid = (*env)->GetMethodID(env, cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
  2139. // Watch out for C89 scoping rules because of the macro
  2140. #define GET_BOOL_EXTRA(var, key) \
  2141. int var; \
  2142. bname = (*env)->NewStringUTF(env, key); \
  2143. (var) = (*env)->CallBooleanMethod(env, intent, bmid, bname, JNI_FALSE); \
  2144. (*env)->DeleteLocalRef(env, bname);
  2145. if (plugged) {
  2146. // Watch out for C89 scoping rules because of the macro
  2147. GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
  2148. if (plug == -1) {
  2149. LocalReferenceHolder_Cleanup(&refs);
  2150. return -1;
  2151. }
  2152. // 1 == BatteryManager.BATTERY_PLUGGED_AC
  2153. // 2 == BatteryManager.BATTERY_PLUGGED_USB
  2154. *plugged = (0 < plug) ? 1 : 0;
  2155. }
  2156. if (charged) {
  2157. // Watch out for C89 scoping rules because of the macro
  2158. GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
  2159. if (status == -1) {
  2160. LocalReferenceHolder_Cleanup(&refs);
  2161. return -1;
  2162. }
  2163. // 5 == BatteryManager.BATTERY_STATUS_FULL
  2164. *charged = (status == 5) ? 1 : 0;
  2165. }
  2166. if (battery) {
  2167. GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
  2168. *battery = present ? 1 : 0;
  2169. }
  2170. if (seconds) {
  2171. *seconds = -1; // not possible
  2172. }
  2173. if (percent) {
  2174. int level;
  2175. int scale;
  2176. // Watch out for C89 scoping rules because of the macro
  2177. {
  2178. GET_INT_EXTRA(level_temp, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
  2179. level = level_temp;
  2180. }
  2181. // Watch out for C89 scoping rules because of the macro
  2182. {
  2183. GET_INT_EXTRA(scale_temp, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
  2184. scale = scale_temp;
  2185. }
  2186. if ((level == -1) || (scale == -1)) {
  2187. LocalReferenceHolder_Cleanup(&refs);
  2188. return -1;
  2189. }
  2190. *percent = level * 100 / scale;
  2191. }
  2192. (*env)->DeleteLocalRef(env, intent);
  2193. LocalReferenceHolder_Cleanup(&refs);
  2194. return 0;
  2195. }
  2196. // Add all touch devices
  2197. void Android_JNI_InitTouch(void)
  2198. {
  2199. JNIEnv *env = Android_JNI_GetEnv();
  2200. (*env)->CallStaticVoidMethod(env, mActivityClass, midInitTouch);
  2201. }
  2202. void Android_JNI_DetectDevices(void)
  2203. {
  2204. JNIEnv *env = Android_JNI_GetEnv();
  2205. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midDetectDevices);
  2206. }
  2207. void Android_JNI_JoystickSetLED(int device_id, int red, int green, int blue)
  2208. {
  2209. JNIEnv *env = Android_JNI_GetEnv();
  2210. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midJoystickSetLED, device_id, red, green, blue);
  2211. }
  2212. void Android_JNI_JoystickSetSensorsEnabled(int device_id, bool enabled)
  2213. {
  2214. JNIEnv *env = Android_JNI_GetEnv();
  2215. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midJoystickSetSensorsEnabled, device_id, (enabled == 1));
  2216. }
  2217. void Android_JNI_DetectHapticDevices(void)
  2218. {
  2219. JNIEnv *env = Android_JNI_GetEnv();
  2220. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midDetectHapticDevices);
  2221. }
  2222. void Android_JNI_HapticRun(int device_id, float intensity, int length)
  2223. {
  2224. JNIEnv *env = Android_JNI_GetEnv();
  2225. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticRun, device_id, intensity, length);
  2226. }
  2227. void Android_JNI_HapticRumble(int device_id, float low_frequency_intensity, float high_frequency_intensity, int length)
  2228. {
  2229. JNIEnv *env = Android_JNI_GetEnv();
  2230. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticRumble, device_id, low_frequency_intensity, high_frequency_intensity, length);
  2231. }
  2232. void Android_JNI_HapticStop(int device_id)
  2233. {
  2234. JNIEnv *env = Android_JNI_GetEnv();
  2235. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticStop, device_id);
  2236. }
  2237. // See SDLActivity.java for constants.
  2238. #define COMMAND_SET_KEEP_SCREEN_ON 5
  2239. bool SDL_SendAndroidMessage(Uint32 command, int param)
  2240. {
  2241. CHECK_PARAM(command < 0x8000) {
  2242. return SDL_InvalidParamError("command");
  2243. }
  2244. return Android_JNI_SendMessage(command, param);
  2245. }
  2246. // sends message to be handled on the UI event dispatch thread
  2247. bool Android_JNI_SendMessage(int command, int param)
  2248. {
  2249. JNIEnv *env = Android_JNI_GetEnv();
  2250. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSendMessage, command, param);
  2251. }
  2252. bool Android_JNI_SuspendScreenSaver(bool suspend)
  2253. {
  2254. return Android_JNI_SendMessage(COMMAND_SET_KEEP_SCREEN_ON, (suspend == false) ? 0 : 1);
  2255. }
  2256. void Android_JNI_ShowScreenKeyboard(int input_type, SDL_Rect *inputRect)
  2257. {
  2258. JNIEnv *env = Android_JNI_GetEnv();
  2259. (*env)->CallStaticBooleanMethod(env, mActivityClass, midShowTextInput,
  2260. input_type,
  2261. inputRect->x,
  2262. inputRect->y,
  2263. inputRect->w,
  2264. inputRect->h);
  2265. }
  2266. void Android_JNI_HideScreenKeyboard(void)
  2267. {
  2268. // has to match Activity constant
  2269. const int COMMAND_TEXTEDIT_HIDE = 3;
  2270. Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
  2271. }
  2272. bool Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonID)
  2273. {
  2274. JNIEnv *env;
  2275. jclass clazz;
  2276. jmethodID mid;
  2277. jobject context;
  2278. jstring title;
  2279. jstring message;
  2280. jintArray button_flags;
  2281. jintArray button_ids;
  2282. jobjectArray button_texts;
  2283. jintArray colors;
  2284. jobject text;
  2285. jint temp;
  2286. int i;
  2287. env = Android_JNI_GetEnv();
  2288. // convert parameters
  2289. clazz = (*env)->FindClass(env, "java/lang/String");
  2290. title = (*env)->NewStringUTF(env, messageboxdata->title);
  2291. message = (*env)->NewStringUTF(env, messageboxdata->message);
  2292. button_flags = (*env)->NewIntArray(env, messageboxdata->numbuttons);
  2293. button_ids = (*env)->NewIntArray(env, messageboxdata->numbuttons);
  2294. button_texts = (*env)->NewObjectArray(env, messageboxdata->numbuttons,
  2295. clazz, NULL);
  2296. for (i = 0; i < messageboxdata->numbuttons; ++i) {
  2297. const SDL_MessageBoxButtonData *sdlButton;
  2298. if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) {
  2299. sdlButton = &messageboxdata->buttons[messageboxdata->numbuttons - 1 - i];
  2300. } else {
  2301. sdlButton = &messageboxdata->buttons[i];
  2302. }
  2303. temp = sdlButton->flags;
  2304. (*env)->SetIntArrayRegion(env, button_flags, i, 1, &temp);
  2305. temp = sdlButton->buttonID;
  2306. (*env)->SetIntArrayRegion(env, button_ids, i, 1, &temp);
  2307. text = (*env)->NewStringUTF(env, sdlButton->text);
  2308. (*env)->SetObjectArrayElement(env, button_texts, i, text);
  2309. (*env)->DeleteLocalRef(env, text);
  2310. }
  2311. if (messageboxdata->colorScheme) {
  2312. colors = (*env)->NewIntArray(env, SDL_MESSAGEBOX_COLOR_COUNT);
  2313. for (i = 0; i < SDL_MESSAGEBOX_COLOR_COUNT; ++i) {
  2314. temp = (0xFFU << 24) |
  2315. (messageboxdata->colorScheme->colors[i].r << 16) |
  2316. (messageboxdata->colorScheme->colors[i].g << 8) |
  2317. (messageboxdata->colorScheme->colors[i].b << 0);
  2318. (*env)->SetIntArrayRegion(env, colors, i, 1, &temp);
  2319. }
  2320. } else {
  2321. colors = NULL;
  2322. }
  2323. (*env)->DeleteLocalRef(env, clazz);
  2324. // context = SDLActivity.getContext();
  2325. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2326. clazz = (*env)->GetObjectClass(env, context);
  2327. mid = (*env)->GetMethodID(env, clazz,
  2328. "messageboxShowMessageBox", "(ILjava/lang/String;Ljava/lang/String;[I[I[Ljava/lang/String;[I)I");
  2329. *buttonID = (*env)->CallIntMethod(env, context, mid,
  2330. (jint)messageboxdata->flags,
  2331. title,
  2332. message,
  2333. button_flags,
  2334. button_ids,
  2335. button_texts,
  2336. colors);
  2337. (*env)->DeleteLocalRef(env, context);
  2338. (*env)->DeleteLocalRef(env, clazz);
  2339. // delete parameters
  2340. (*env)->DeleteLocalRef(env, title);
  2341. (*env)->DeleteLocalRef(env, message);
  2342. (*env)->DeleteLocalRef(env, button_flags);
  2343. (*env)->DeleteLocalRef(env, button_ids);
  2344. (*env)->DeleteLocalRef(env, button_texts);
  2345. (*env)->DeleteLocalRef(env, colors);
  2346. return true;
  2347. }
  2348. /*
  2349. //////////////////////////////////////////////////////////////////////////////
  2350. //
  2351. // Functions exposed to SDL applications in SDL_system.h
  2352. //////////////////////////////////////////////////////////////////////////////
  2353. */
  2354. void *SDL_GetAndroidJNIEnv(void)
  2355. {
  2356. return Android_JNI_GetEnv();
  2357. }
  2358. void *SDL_GetAndroidActivity(void)
  2359. {
  2360. // See SDL_system.h for caveats on using this function.
  2361. JNIEnv *env = Android_JNI_GetEnv();
  2362. if (!env) {
  2363. return NULL;
  2364. }
  2365. // return SDLActivity.getContext();
  2366. return (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2367. }
  2368. int SDL_GetAndroidSDKVersion(void)
  2369. {
  2370. static int sdk_version;
  2371. if (!sdk_version) {
  2372. char sdk[PROP_VALUE_MAX] = { 0 };
  2373. if (__system_property_get("ro.build.version.sdk", sdk) != 0) {
  2374. sdk_version = SDL_atoi(sdk);
  2375. }
  2376. }
  2377. return sdk_version;
  2378. }
  2379. char *SDL_GetAndroidPackageName(void)
  2380. {
  2381. // this doesn't currently cache this, because it's only used by SDL_GetExeName, which _does_ cache it.
  2382. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  2383. JNIEnv *env = Android_JNI_GetEnv();
  2384. if (!LocalReferenceHolder_Init(&refs, env)) {
  2385. LocalReferenceHolder_Cleanup(&refs);
  2386. return NULL;
  2387. }
  2388. // context = SDLActivity.getContext();
  2389. jobject context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2390. if (!context) {
  2391. SDL_SetError("Couldn't get Android context!");
  2392. LocalReferenceHolder_Cleanup(&refs);
  2393. return NULL;
  2394. }
  2395. // fileObj = context.getFilesDir();
  2396. jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context), "getPackageName", "()Ljava/lang/String;");
  2397. jstring jstr = (jstring)(*env)->CallObjectMethod(env, context, mid);
  2398. if (Android_JNI_ExceptionOccurred(false)) {
  2399. LocalReferenceHolder_Cleanup(&refs);
  2400. return NULL;
  2401. }
  2402. const char *cstr = (*env)->GetStringUTFChars(env, jstr, NULL);
  2403. char *retval = cstr ? SDL_strdup(cstr) : NULL;
  2404. (*env)->ReleaseStringUTFChars(env, jstr, cstr);
  2405. LocalReferenceHolder_Cleanup(&refs);
  2406. return retval;
  2407. }
  2408. bool SDL_IsAndroidTablet(void)
  2409. {
  2410. JNIEnv *env = Android_JNI_GetEnv();
  2411. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsTablet);
  2412. }
  2413. bool SDL_IsAndroidTV(void)
  2414. {
  2415. JNIEnv *env = Android_JNI_GetEnv();
  2416. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsAndroidTV);
  2417. }
  2418. bool SDL_IsChromebook(void)
  2419. {
  2420. JNIEnv *env = Android_JNI_GetEnv();
  2421. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsChromebook);
  2422. }
  2423. bool SDL_IsDeXMode(void)
  2424. {
  2425. JNIEnv *env = Android_JNI_GetEnv();
  2426. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsDeXMode);
  2427. }
  2428. void SDL_SendAndroidBackButton(void)
  2429. {
  2430. JNIEnv *env = Android_JNI_GetEnv();
  2431. (*env)->CallStaticVoidMethod(env, mActivityClass, midManualBackButton);
  2432. }
  2433. const char *SDL_GetAndroidInternalStoragePath(void)
  2434. {
  2435. static char *s_AndroidInternalFilesPath = NULL;
  2436. if (!s_AndroidInternalFilesPath) {
  2437. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  2438. jmethodID mid;
  2439. jobject context;
  2440. jobject fileObject;
  2441. jstring pathString;
  2442. const char *path;
  2443. JNIEnv *env = Android_JNI_GetEnv();
  2444. if (!LocalReferenceHolder_Init(&refs, env)) {
  2445. LocalReferenceHolder_Cleanup(&refs);
  2446. return NULL;
  2447. }
  2448. // context = SDLActivity.getContext();
  2449. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2450. if (!context) {
  2451. SDL_SetError("Couldn't get Android context!");
  2452. LocalReferenceHolder_Cleanup(&refs);
  2453. return NULL;
  2454. }
  2455. // fileObj = context.getFilesDir();
  2456. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  2457. "getFilesDir", "()Ljava/io/File;");
  2458. fileObject = (*env)->CallObjectMethod(env, context, mid);
  2459. if (!fileObject) {
  2460. SDL_SetError("Couldn't get internal directory");
  2461. LocalReferenceHolder_Cleanup(&refs);
  2462. return NULL;
  2463. }
  2464. // path = fileObject.getCanonicalPath();
  2465. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  2466. "getCanonicalPath", "()Ljava/lang/String;");
  2467. pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  2468. if (Android_JNI_ExceptionOccurred(false)) {
  2469. LocalReferenceHolder_Cleanup(&refs);
  2470. return NULL;
  2471. }
  2472. path = (*env)->GetStringUTFChars(env, pathString, NULL);
  2473. s_AndroidInternalFilesPath = SDL_strdup(path);
  2474. (*env)->ReleaseStringUTFChars(env, pathString, path);
  2475. LocalReferenceHolder_Cleanup(&refs);
  2476. }
  2477. return s_AndroidInternalFilesPath;
  2478. }
  2479. Uint32 SDL_GetAndroidExternalStorageState(void)
  2480. {
  2481. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  2482. jmethodID mid;
  2483. jclass cls;
  2484. jstring stateString;
  2485. const char *state_string;
  2486. Uint32 stateFlags;
  2487. JNIEnv *env = Android_JNI_GetEnv();
  2488. if (!LocalReferenceHolder_Init(&refs, env)) {
  2489. LocalReferenceHolder_Cleanup(&refs);
  2490. return 0;
  2491. }
  2492. cls = (*env)->FindClass(env, "android/os/Environment");
  2493. mid = (*env)->GetStaticMethodID(env, cls,
  2494. "getExternalStorageState", "()Ljava/lang/String;");
  2495. stateString = (jstring)(*env)->CallStaticObjectMethod(env, cls, mid);
  2496. state_string = (*env)->GetStringUTFChars(env, stateString, NULL);
  2497. // Print an info message so people debugging know the storage state
  2498. __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state_string);
  2499. if (SDL_strcmp(state_string, "mounted") == 0) {
  2500. stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
  2501. SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
  2502. } else if (SDL_strcmp(state_string, "mounted_ro") == 0) {
  2503. stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
  2504. } else {
  2505. stateFlags = 0;
  2506. }
  2507. (*env)->ReleaseStringUTFChars(env, stateString, state_string);
  2508. LocalReferenceHolder_Cleanup(&refs);
  2509. return stateFlags;
  2510. }
  2511. const char *SDL_GetAndroidExternalStoragePath(void)
  2512. {
  2513. static char *s_AndroidExternalFilesPath = NULL;
  2514. if (!s_AndroidExternalFilesPath) {
  2515. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  2516. jmethodID mid;
  2517. jobject context;
  2518. jobject fileObject;
  2519. jstring pathString;
  2520. const char *path;
  2521. JNIEnv *env = Android_JNI_GetEnv();
  2522. if (!LocalReferenceHolder_Init(&refs, env)) {
  2523. LocalReferenceHolder_Cleanup(&refs);
  2524. return NULL;
  2525. }
  2526. // context = SDLActivity.getContext();
  2527. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2528. // fileObj = context.getExternalFilesDir();
  2529. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  2530. "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
  2531. fileObject = (*env)->CallObjectMethod(env, context, mid, NULL);
  2532. if (!fileObject) {
  2533. SDL_SetError("Couldn't get external directory");
  2534. LocalReferenceHolder_Cleanup(&refs);
  2535. return NULL;
  2536. }
  2537. // path = fileObject.getAbsolutePath();
  2538. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  2539. "getAbsolutePath", "()Ljava/lang/String;");
  2540. pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  2541. path = (*env)->GetStringUTFChars(env, pathString, NULL);
  2542. s_AndroidExternalFilesPath = SDL_strdup(path);
  2543. (*env)->ReleaseStringUTFChars(env, pathString, path);
  2544. LocalReferenceHolder_Cleanup(&refs);
  2545. }
  2546. return s_AndroidExternalFilesPath;
  2547. }
  2548. const char *SDL_GetAndroidCachePath(void)
  2549. {
  2550. // !!! FIXME: lots of duplication with SDL_GetAndroidExternalStoragePath and SDL_GetAndroidInternalStoragePath; consolidate these functions!
  2551. static char *s_AndroidCachePath = NULL;
  2552. if (!s_AndroidCachePath) {
  2553. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(SDL_FUNCTION);
  2554. jmethodID mid;
  2555. jobject context;
  2556. jobject fileObject;
  2557. jstring pathString;
  2558. const char *path;
  2559. JNIEnv *env = Android_JNI_GetEnv();
  2560. if (!LocalReferenceHolder_Init(&refs, env)) {
  2561. LocalReferenceHolder_Cleanup(&refs);
  2562. return NULL;
  2563. }
  2564. // context = SDLActivity.getContext();
  2565. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2566. // fileObj = context.getExternalFilesDir();
  2567. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  2568. "getCacheDir", "()Ljava/io/File;");
  2569. fileObject = (*env)->CallObjectMethod(env, context, mid);
  2570. if (!fileObject) {
  2571. SDL_SetError("Couldn't get cache directory");
  2572. LocalReferenceHolder_Cleanup(&refs);
  2573. return NULL;
  2574. }
  2575. // path = fileObject.getAbsolutePath();
  2576. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  2577. "getAbsolutePath", "()Ljava/lang/String;");
  2578. pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  2579. path = (*env)->GetStringUTFChars(env, pathString, NULL);
  2580. s_AndroidCachePath = SDL_strdup(path);
  2581. (*env)->ReleaseStringUTFChars(env, pathString, path);
  2582. LocalReferenceHolder_Cleanup(&refs);
  2583. }
  2584. return s_AndroidCachePath;
  2585. }
  2586. bool SDL_ShowAndroidToast(const char *message, int duration, int gravity, int xOffset, int yOffset)
  2587. {
  2588. return Android_JNI_ShowToast(message, duration, gravity, xOffset, yOffset);
  2589. }
  2590. void Android_JNI_GetManifestEnvironmentVariables(void)
  2591. {
  2592. if (!mActivityClass || !midGetManifestEnvironmentVariables) {
  2593. __android_log_print(ANDROID_LOG_WARN, "SDL", "Request to get environment variables before JNI is ready");
  2594. return;
  2595. }
  2596. if (!bHasEnvironmentVariables) {
  2597. JNIEnv *env = Android_JNI_GetEnv();
  2598. bool ret = (*env)->CallStaticBooleanMethod(env, mActivityClass, midGetManifestEnvironmentVariables);
  2599. if (ret) {
  2600. bHasEnvironmentVariables = true;
  2601. }
  2602. }
  2603. }
  2604. int Android_JNI_CreateCustomCursor(SDL_Surface *surface, int hot_x, int hot_y)
  2605. {
  2606. JNIEnv *env = Android_JNI_GetEnv();
  2607. int custom_cursor = 0;
  2608. jintArray pixels;
  2609. pixels = (*env)->NewIntArray(env, surface->w * surface->h);
  2610. if (pixels) {
  2611. (*env)->SetIntArrayRegion(env, pixels, 0, surface->w * surface->h, (int *)surface->pixels);
  2612. custom_cursor = (*env)->CallStaticIntMethod(env, mActivityClass, midCreateCustomCursor, pixels, surface->w, surface->h, hot_x, hot_y);
  2613. (*env)->DeleteLocalRef(env, pixels);
  2614. } else {
  2615. SDL_OutOfMemory();
  2616. }
  2617. return custom_cursor;
  2618. }
  2619. void Android_JNI_DestroyCustomCursor(int cursorID)
  2620. {
  2621. JNIEnv *env = Android_JNI_GetEnv();
  2622. (*env)->CallStaticVoidMethod(env, mActivityClass, midDestroyCustomCursor, cursorID);
  2623. }
  2624. bool Android_JNI_SetCustomCursor(int cursorID)
  2625. {
  2626. JNIEnv *env = Android_JNI_GetEnv();
  2627. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetCustomCursor, cursorID);
  2628. }
  2629. bool Android_JNI_SetSystemCursor(int cursorID)
  2630. {
  2631. JNIEnv *env = Android_JNI_GetEnv();
  2632. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetSystemCursor, cursorID);
  2633. }
  2634. bool Android_JNI_SupportsRelativeMouse(void)
  2635. {
  2636. JNIEnv *env = Android_JNI_GetEnv();
  2637. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSupportsRelativeMouse);
  2638. }
  2639. bool Android_JNI_SetRelativeMouseEnabled(bool enabled)
  2640. {
  2641. JNIEnv *env = Android_JNI_GetEnv();
  2642. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetRelativeMouseEnabled, (enabled == 1));
  2643. }
  2644. typedef struct NativePermissionRequestInfo
  2645. {
  2646. int request_code;
  2647. char *permission;
  2648. SDL_RequestAndroidPermissionCallback callback;
  2649. void *userdata;
  2650. struct NativePermissionRequestInfo *next;
  2651. } NativePermissionRequestInfo;
  2652. static NativePermissionRequestInfo pending_permissions;
  2653. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)(
  2654. JNIEnv *env, jclass cls,
  2655. jint requestCode, jboolean result)
  2656. {
  2657. SDL_LockMutex(SDL_event_lock);
  2658. NativePermissionRequestInfo *prev = &pending_permissions;
  2659. for (NativePermissionRequestInfo *info = prev->next; info != NULL; info = info->next) {
  2660. if (info->request_code == (int) requestCode) {
  2661. prev->next = info->next;
  2662. SDL_UnlockMutex(SDL_event_lock);
  2663. info->callback(info->userdata, info->permission, result ? true : false);
  2664. SDL_free(info->permission);
  2665. SDL_free(info);
  2666. return;
  2667. }
  2668. prev = info;
  2669. }
  2670. SDL_UnlockMutex(SDL_event_lock);
  2671. }
  2672. bool SDL_RequestAndroidPermission(const char *permission, SDL_RequestAndroidPermissionCallback cb, void *userdata)
  2673. {
  2674. if (!permission) {
  2675. return SDL_InvalidParamError("permission");
  2676. } else if (!cb) {
  2677. return SDL_InvalidParamError("cb");
  2678. }
  2679. NativePermissionRequestInfo *info = (NativePermissionRequestInfo *) SDL_calloc(1, sizeof (NativePermissionRequestInfo));
  2680. if (!info) {
  2681. return false;
  2682. }
  2683. info->permission = SDL_strdup(permission);
  2684. if (!info->permission) {
  2685. SDL_free(info);
  2686. return false;
  2687. }
  2688. static SDL_AtomicInt next_request_code;
  2689. info->request_code = SDL_AddAtomicInt(&next_request_code, 1);
  2690. info->callback = cb;
  2691. info->userdata = userdata;
  2692. SDL_LockMutex(SDL_event_lock);
  2693. info->next = pending_permissions.next;
  2694. pending_permissions.next = info;
  2695. SDL_UnlockMutex(SDL_event_lock);
  2696. JNIEnv *env = Android_JNI_GetEnv();
  2697. jstring jpermission = (*env)->NewStringUTF(env, permission);
  2698. (*env)->CallStaticVoidMethod(env, mActivityClass, midRequestPermission, jpermission, info->request_code);
  2699. (*env)->DeleteLocalRef(env, jpermission);
  2700. return true;
  2701. }
  2702. // Show toast notification
  2703. bool Android_JNI_ShowToast(const char *message, int duration, int gravity, int xOffset, int yOffset)
  2704. {
  2705. bool result;
  2706. JNIEnv *env = Android_JNI_GetEnv();
  2707. jstring jmessage = (*env)->NewStringUTF(env, message);
  2708. result = (*env)->CallStaticBooleanMethod(env, mActivityClass, midShowToast, jmessage, duration, gravity, xOffset, yOffset);
  2709. (*env)->DeleteLocalRef(env, jmessage);
  2710. return result;
  2711. }
  2712. bool Android_JNI_GetLocale(char *buf, size_t buflen)
  2713. {
  2714. bool result = false;
  2715. if (buf && buflen > 0) {
  2716. *buf = '\0';
  2717. JNIEnv *env = Android_JNI_GetEnv();
  2718. jstring string = (jstring)(*env)->CallStaticObjectMethod(env, mActivityClass, midGetPreferredLocales);
  2719. if (string) {
  2720. const char *utf8string = (*env)->GetStringUTFChars(env, string, NULL);
  2721. if (utf8string) {
  2722. result = true;
  2723. SDL_strlcpy(buf, utf8string, buflen);
  2724. (*env)->ReleaseStringUTFChars(env, string, utf8string);
  2725. }
  2726. (*env)->DeleteLocalRef(env, string);
  2727. }
  2728. }
  2729. return result;
  2730. }
  2731. bool Android_JNI_OpenURL(const char *url)
  2732. {
  2733. bool result;
  2734. JNIEnv *env = Android_JNI_GetEnv();
  2735. jstring jurl = (*env)->NewStringUTF(env, url);
  2736. result = (*env)->CallStaticBooleanMethod(env, mActivityClass, midOpenURL, jurl);
  2737. (*env)->DeleteLocalRef(env, jurl);
  2738. return result;
  2739. }
  2740. int Android_JNI_OpenFileDescriptor(const char *uri, const char *mode)
  2741. {
  2742. // Get fopen-style modes
  2743. int moderead = 0, modewrite = 0, modeappend = 0, modeupdate = 0;
  2744. for (const char *cmode = mode; *cmode; cmode++) {
  2745. switch (*cmode) {
  2746. case 'a':
  2747. modeappend = 1;
  2748. break;
  2749. case 'r':
  2750. moderead = 1;
  2751. break;
  2752. case 'w':
  2753. modewrite = 1;
  2754. break;
  2755. case '+':
  2756. modeupdate = 1;
  2757. break;
  2758. default:
  2759. break;
  2760. }
  2761. }
  2762. // Translate fopen-style modes to ContentResolver modes.
  2763. // Android only allows "r", "w", "wt", "wa", "rw" or "rwt".
  2764. const char *contentResolverMode = "r";
  2765. if (moderead) {
  2766. if (modewrite) {
  2767. contentResolverMode = "rwt";
  2768. } else {
  2769. contentResolverMode = modeupdate ? "rw" : "r";
  2770. }
  2771. } else if (modewrite) {
  2772. contentResolverMode = modeupdate ? "rwt" : "wt";
  2773. } else if (modeappend) {
  2774. contentResolverMode = modeupdate ? "rw" : "wa";
  2775. }
  2776. JNIEnv *env = Android_JNI_GetEnv();
  2777. jstring jstringUri = (*env)->NewStringUTF(env, uri);
  2778. jstring jstringMode = (*env)->NewStringUTF(env, contentResolverMode);
  2779. jint fd = (*env)->CallStaticIntMethod(env, mActivityClass, midOpenFileDescriptor, jstringUri, jstringMode);
  2780. (*env)->DeleteLocalRef(env, jstringUri);
  2781. (*env)->DeleteLocalRef(env, jstringMode);
  2782. if (fd == -1) {
  2783. SDL_SetError("Unspecified error in JNI");
  2784. }
  2785. return fd;
  2786. }
  2787. static struct AndroidFileDialog
  2788. {
  2789. int request_code;
  2790. SDL_DialogFileCallback callback;
  2791. void *userdata;
  2792. } mAndroidFileDialogData;
  2793. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeFileDialog)(
  2794. JNIEnv *env, jclass jcls,
  2795. jint requestCode, jobjectArray fileList, jint filter)
  2796. {
  2797. if (mAndroidFileDialogData.callback != NULL && mAndroidFileDialogData.request_code == requestCode) {
  2798. if (fileList == NULL) {
  2799. SDL_SetError("Unspecified error in JNI");
  2800. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, NULL, -1);
  2801. mAndroidFileDialogData.callback = NULL;
  2802. return;
  2803. }
  2804. // Convert fileList to string
  2805. size_t count = (*env)->GetArrayLength(env, fileList);
  2806. char **charFileList = SDL_calloc(count + 1, sizeof(char *));
  2807. if (charFileList == NULL) {
  2808. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, NULL, -1);
  2809. mAndroidFileDialogData.callback = NULL;
  2810. return;
  2811. }
  2812. // Convert to UTF-8
  2813. // TODO: Fix modified UTF-8 to classic UTF-8
  2814. for (int i = 0; i < count; i++) {
  2815. jstring string = (*env)->GetObjectArrayElement(env, fileList, i);
  2816. if (!string) {
  2817. continue;
  2818. }
  2819. const char *utf8string = (*env)->GetStringUTFChars(env, string, NULL);
  2820. if (!utf8string) {
  2821. (*env)->DeleteLocalRef(env, string);
  2822. continue;
  2823. }
  2824. char *newFile = SDL_strdup(utf8string);
  2825. if (!newFile) {
  2826. (*env)->ReleaseStringUTFChars(env, string, utf8string);
  2827. (*env)->DeleteLocalRef(env, string);
  2828. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, NULL, -1);
  2829. mAndroidFileDialogData.callback = NULL;
  2830. // Cleanup memory
  2831. for (int j = 0; j < i; j++) {
  2832. SDL_free(charFileList[j]);
  2833. }
  2834. SDL_free(charFileList);
  2835. return;
  2836. }
  2837. charFileList[i] = newFile;
  2838. (*env)->ReleaseStringUTFChars(env, string, utf8string);
  2839. (*env)->DeleteLocalRef(env, string);
  2840. }
  2841. // Call user-provided callback
  2842. SDL_ClearError();
  2843. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, (const char *const *) charFileList, filter);
  2844. mAndroidFileDialogData.callback = NULL;
  2845. // Cleanup memory
  2846. for (int i = 0; i < count; i++) {
  2847. SDL_free(charFileList[i]);
  2848. }
  2849. SDL_free(charFileList);
  2850. }
  2851. }
  2852. bool Android_JNI_ShowFileDialog(
  2853. SDL_DialogFileCallback callback, void *userdata,
  2854. const SDL_DialogFileFilter *filters, int nfilters, SDL_FileDialogType type,
  2855. bool multiple, const char *initialPath)
  2856. {
  2857. if (mAndroidFileDialogData.callback != NULL) {
  2858. SDL_SetError("Only one file dialog can be run at a time.");
  2859. return false;
  2860. }
  2861. // Setup type
  2862. int dialogType = 0;
  2863. switch (type) {
  2864. case SDL_FILEDIALOG_OPENFILE:
  2865. dialogType = 0;
  2866. break;
  2867. case SDL_FILEDIALOG_SAVEFILE:
  2868. multiple = false;
  2869. dialogType = 1;
  2870. break;
  2871. case SDL_FILEDIALOG_OPENFOLDER:
  2872. multiple = false;
  2873. dialogType = 2;
  2874. break;
  2875. default:
  2876. SDL_SetError("Invalid file dialog type");
  2877. return false;
  2878. }
  2879. JNIEnv *env = Android_JNI_GetEnv();
  2880. // Setup filters
  2881. jobjectArray filtersArray = NULL;
  2882. if (filters) {
  2883. jclass stringClass = (*env)->FindClass(env, "java/lang/String");
  2884. filtersArray = (*env)->NewObjectArray(env, nfilters, stringClass, NULL);
  2885. (*env)->DeleteLocalRef(env, stringClass);
  2886. // Convert to string
  2887. for (int i = 0; i < nfilters; i++) {
  2888. jstring str = (*env)->NewStringUTF(env, filters[i].pattern);
  2889. (*env)->SetObjectArrayElement(env, filtersArray, i, str);
  2890. (*env)->DeleteLocalRef(env, str);
  2891. }
  2892. }
  2893. // Setup initial path
  2894. jstring initialPathString = NULL;
  2895. if (initialPath && *initialPath) {
  2896. initialPathString = (*env)->NewStringUTF(env, initialPath);
  2897. }
  2898. // Setup data
  2899. static SDL_AtomicInt next_request_code;
  2900. mAndroidFileDialogData.request_code = SDL_AddAtomicInt(&next_request_code, 1);
  2901. mAndroidFileDialogData.userdata = userdata;
  2902. mAndroidFileDialogData.callback = callback;
  2903. // Invoke JNI
  2904. jboolean success = (*env)->CallStaticBooleanMethod(env, mActivityClass,
  2905. midShowFileDialog, filtersArray, (jboolean) multiple,
  2906. dialogType, initialPathString, mAndroidFileDialogData.request_code);
  2907. (*env)->DeleteLocalRef(env, filtersArray);
  2908. (*env)->DeleteLocalRef(env, initialPathString);
  2909. if (!success) {
  2910. mAndroidFileDialogData.callback = NULL;
  2911. SDL_AddAtomicInt(&next_request_code, -1);
  2912. SDL_SetError("Unspecified error in JNI");
  2913. return false;
  2914. }
  2915. return true;
  2916. }
  2917. #endif // SDL_PLATFORM_ANDROID