SDL_android.c 120 KB

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