SDL_android.c 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 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. #define SDL_JAVA_PREFIX org_libsdl_app
  41. #define CONCAT1(prefix, class, function) CONCAT2(prefix, class, function)
  42. #define CONCAT2(prefix, class, function) Java_##prefix##_##class##_##function
  43. #define SDL_JAVA_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLActivity, function)
  44. #define SDL_JAVA_AUDIO_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLAudioManager, function)
  45. #define SDL_JAVA_CONTROLLER_INTERFACE(function) CONCAT1(SDL_JAVA_PREFIX, SDLControllerManager, function)
  46. #define SDL_JAVA_INTERFACE_INPUT_CONNECTION(function) CONCAT1(SDL_JAVA_PREFIX, SDLInputConnection, function)
  47. // Audio encoding definitions
  48. #define ENCODING_PCM_8BIT 3
  49. #define ENCODING_PCM_16BIT 2
  50. #define ENCODING_PCM_FLOAT 4
  51. // Java class SDLActivity
  52. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetVersion)(
  53. JNIEnv *env, jclass cls);
  54. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(
  55. JNIEnv *env, jclass cls);
  56. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeInitMainThread)(
  57. JNIEnv *env, jclass cls);
  58. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeCleanupMainThread)(
  59. JNIEnv *env, jclass cls);
  60. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(
  61. JNIEnv *env, jclass cls,
  62. jstring library, jstring function, jobject array);
  63. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
  64. JNIEnv *env, jclass jcls,
  65. jstring filename);
  66. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetScreenResolution)(
  67. JNIEnv *env, jclass jcls,
  68. jint surfaceWidth, jint surfaceHeight,
  69. jint deviceWidth, jint deviceHeight, jfloat density, jfloat rate);
  70. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
  71. JNIEnv *env, jclass cls);
  72. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceCreated)(
  73. JNIEnv *env, jclass jcls);
  74. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(
  75. JNIEnv *env, jclass jcls);
  76. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(
  77. JNIEnv *env, jclass jcls);
  78. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
  79. JNIEnv *env, jclass jcls,
  80. jint keycode);
  81. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
  82. JNIEnv *env, jclass jcls,
  83. jint keycode);
  84. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(onNativeSoftReturnKey)(
  85. JNIEnv *env, jclass jcls);
  86. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
  87. JNIEnv *env, jclass jcls);
  88. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
  89. JNIEnv *env, jclass jcls,
  90. jint touch_device_id_in, jint pointer_finger_id_in,
  91. jint action, jfloat x, jfloat y, jfloat p);
  92. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
  93. JNIEnv *env, jclass jcls,
  94. jint button, jint action, jfloat x, jfloat y, jboolean relative);
  95. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePen)(
  96. JNIEnv *env, jclass jcls,
  97. jint pen_id_in, jint button, jint action, jfloat x, jfloat y, jfloat p);
  98. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
  99. JNIEnv *env, jclass jcls,
  100. jfloat x, jfloat y, jfloat z);
  101. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeClipboardChanged)(
  102. JNIEnv *env, jclass jcls);
  103. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
  104. JNIEnv *env, jclass cls);
  105. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeLocaleChanged)(
  106. JNIEnv *env, jclass cls);
  107. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDarkModeChanged)(
  108. JNIEnv *env, jclass cls, jboolean enabled);
  109. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSendQuit)(
  110. JNIEnv *env, jclass cls);
  111. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
  112. JNIEnv *env, jclass cls);
  113. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
  114. JNIEnv *env, jclass cls);
  115. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
  116. JNIEnv *env, jclass cls);
  117. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeFocusChanged)(
  118. JNIEnv *env, jclass cls, jboolean hasFocus);
  119. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
  120. JNIEnv *env, jclass cls,
  121. jstring name);
  122. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeGetHintBoolean)(
  123. JNIEnv *env, jclass cls,
  124. jstring name, jboolean default_value);
  125. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
  126. JNIEnv *env, jclass cls,
  127. jstring name, jstring value);
  128. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetNaturalOrientation)(
  129. JNIEnv *env, jclass cls,
  130. jint orientation);
  131. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeRotationChanged)(
  132. JNIEnv *env, jclass cls,
  133. jint rotation);
  134. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeInsetsChanged)(
  135. JNIEnv *env, jclass cls,
  136. jint left, jint right, jint top, jint bottom);
  137. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)(
  138. JNIEnv *env, jclass cls,
  139. jint touchId, jstring name);
  140. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)(
  141. JNIEnv *env, jclass cls,
  142. jint requestCode, jboolean result);
  143. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeAllowRecreateActivity)(
  144. JNIEnv *env, jclass jcls);
  145. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeCheckSDLThreadCounter)(
  146. JNIEnv *env, jclass jcls);
  147. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeFileDialog)(
  148. JNIEnv *env, jclass jcls,
  149. jint requestCode, jobjectArray fileList, jint filter);
  150. static JNINativeMethod SDLActivity_tab[] = {
  151. { "nativeGetVersion", "()Ljava/lang/String;", SDL_JAVA_INTERFACE(nativeGetVersion) },
  152. { "nativeSetupJNI", "()I", SDL_JAVA_INTERFACE(nativeSetupJNI) },
  153. { "nativeInitMainThread", "()V", SDL_JAVA_INTERFACE(nativeInitMainThread) },
  154. { "nativeCleanupMainThread", "()V", SDL_JAVA_INTERFACE(nativeCleanupMainThread) },
  155. { "nativeRunMain", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Object;)I", SDL_JAVA_INTERFACE(nativeRunMain) },
  156. { "onNativeDropFile", "(Ljava/lang/String;)V", SDL_JAVA_INTERFACE(onNativeDropFile) },
  157. { "nativeSetScreenResolution", "(IIIIFF)V", SDL_JAVA_INTERFACE(nativeSetScreenResolution) },
  158. { "onNativeResize", "()V", SDL_JAVA_INTERFACE(onNativeResize) },
  159. { "onNativeSurfaceCreated", "()V", SDL_JAVA_INTERFACE(onNativeSurfaceCreated) },
  160. { "onNativeSurfaceChanged", "()V", SDL_JAVA_INTERFACE(onNativeSurfaceChanged) },
  161. { "onNativeSurfaceDestroyed", "()V", SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed) },
  162. { "onNativeKeyDown", "(I)V", SDL_JAVA_INTERFACE(onNativeKeyDown) },
  163. { "onNativeKeyUp", "(I)V", SDL_JAVA_INTERFACE(onNativeKeyUp) },
  164. { "onNativeSoftReturnKey", "()Z", SDL_JAVA_INTERFACE(onNativeSoftReturnKey) },
  165. { "onNativeKeyboardFocusLost", "()V", SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost) },
  166. { "onNativeTouch", "(IIIFFF)V", SDL_JAVA_INTERFACE(onNativeTouch) },
  167. { "onNativeMouse", "(IIFFZ)V", SDL_JAVA_INTERFACE(onNativeMouse) },
  168. { "onNativePen", "(IIIFFF)V", SDL_JAVA_INTERFACE(onNativePen) },
  169. { "onNativeAccel", "(FFF)V", SDL_JAVA_INTERFACE(onNativeAccel) },
  170. { "onNativeClipboardChanged", "()V", SDL_JAVA_INTERFACE(onNativeClipboardChanged) },
  171. { "nativeLowMemory", "()V", SDL_JAVA_INTERFACE(nativeLowMemory) },
  172. { "onNativeLocaleChanged", "()V", SDL_JAVA_INTERFACE(onNativeLocaleChanged) },
  173. { "onNativeDarkModeChanged", "(Z)V", SDL_JAVA_INTERFACE(onNativeDarkModeChanged) },
  174. { "nativeSendQuit", "()V", SDL_JAVA_INTERFACE(nativeSendQuit) },
  175. { "nativeQuit", "()V", SDL_JAVA_INTERFACE(nativeQuit) },
  176. { "nativePause", "()V", SDL_JAVA_INTERFACE(nativePause) },
  177. { "nativeResume", "()V", SDL_JAVA_INTERFACE(nativeResume) },
  178. { "nativeFocusChanged", "(Z)V", SDL_JAVA_INTERFACE(nativeFocusChanged) },
  179. { "nativeGetHint", "(Ljava/lang/String;)Ljava/lang/String;", SDL_JAVA_INTERFACE(nativeGetHint) },
  180. { "nativeGetHintBoolean", "(Ljava/lang/String;Z)Z", SDL_JAVA_INTERFACE(nativeGetHintBoolean) },
  181. { "nativeSetenv", "(Ljava/lang/String;Ljava/lang/String;)V", SDL_JAVA_INTERFACE(nativeSetenv) },
  182. { "nativeSetNaturalOrientation", "(I)V", SDL_JAVA_INTERFACE(nativeSetNaturalOrientation) },
  183. { "onNativeRotationChanged", "(I)V", SDL_JAVA_INTERFACE(onNativeRotationChanged) },
  184. { "onNativeInsetsChanged", "(IIII)V", SDL_JAVA_INTERFACE(onNativeInsetsChanged) },
  185. { "nativeAddTouch", "(ILjava/lang/String;)V", SDL_JAVA_INTERFACE(nativeAddTouch) },
  186. { "nativePermissionResult", "(IZ)V", SDL_JAVA_INTERFACE(nativePermissionResult) },
  187. { "nativeAllowRecreateActivity", "()Z", SDL_JAVA_INTERFACE(nativeAllowRecreateActivity) },
  188. { "nativeCheckSDLThreadCounter", "()I", SDL_JAVA_INTERFACE(nativeCheckSDLThreadCounter) },
  189. { "onNativeFileDialog", "(I[Ljava/lang/String;I)V", SDL_JAVA_INTERFACE(onNativeFileDialog) }
  190. };
  191. // Java class SDLInputConnection
  192. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
  193. JNIEnv *env, jclass cls,
  194. jstring text, jint newCursorPosition);
  195. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar)(
  196. JNIEnv *env, jclass cls,
  197. jchar chUnicode);
  198. static JNINativeMethod SDLInputConnection_tab[] = {
  199. { "nativeCommitText", "(Ljava/lang/String;I)V", SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText) },
  200. { "nativeGenerateScancodeForUnichar", "(C)V", SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar) }
  201. };
  202. // Java class SDLAudioManager
  203. JNIEXPORT void JNICALL SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI)(
  204. JNIEnv *env, jclass jcls);
  205. JNIEXPORT void JNICALL
  206. SDL_JAVA_AUDIO_INTERFACE(addAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording, jstring name,
  207. jint device_id);
  208. JNIEXPORT void JNICALL
  209. SDL_JAVA_AUDIO_INTERFACE(removeAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording,
  210. jint device_id);
  211. static JNINativeMethod SDLAudioManager_tab[] = {
  212. { "nativeSetupJNI", "()I", SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI) },
  213. { "addAudioDevice", "(ZLjava/lang/String;I)V", SDL_JAVA_AUDIO_INTERFACE(addAudioDevice) },
  214. { "removeAudioDevice", "(ZI)V", SDL_JAVA_AUDIO_INTERFACE(removeAudioDevice) }
  215. };
  216. // Java class SDLControllerManager
  217. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI)(
  218. JNIEnv *env, jclass jcls);
  219. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadDown)(
  220. JNIEnv *env, jclass jcls,
  221. jint device_id, jint keycode);
  222. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadUp)(
  223. JNIEnv *env, jclass jcls,
  224. jint device_id, jint keycode);
  225. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoy)(
  226. JNIEnv *env, jclass jcls,
  227. jint device_id, jint axis, jfloat value);
  228. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
  229. JNIEnv *env, jclass jcls,
  230. jint device_id, jint hat_id, jint x, jint y);
  231. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
  232. JNIEnv *env, jclass jcls,
  233. jint device_id, jstring device_name, jstring device_desc, jint vendor_id, jint product_id,
  234. jint button_mask, jint naxes, jint axis_mask, jint nhats, jboolean can_rumble);
  235. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick)(
  236. JNIEnv *env, jclass jcls,
  237. jint device_id);
  238. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddHaptic)(
  239. JNIEnv *env, jclass jcls,
  240. jint device_id, jstring device_name);
  241. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic)(
  242. JNIEnv *env, jclass jcls,
  243. jint device_id);
  244. static JNINativeMethod SDLControllerManager_tab[] = {
  245. { "nativeSetupJNI", "()I", SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI) },
  246. { "onNativePadDown", "(II)Z", SDL_JAVA_CONTROLLER_INTERFACE(onNativePadDown) },
  247. { "onNativePadUp", "(II)Z", SDL_JAVA_CONTROLLER_INTERFACE(onNativePadUp) },
  248. { "onNativeJoy", "(IIF)V", SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoy) },
  249. { "onNativeHat", "(IIII)V", SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat) },
  250. { "nativeAddJoystick", "(ILjava/lang/String;Ljava/lang/String;IIIIIIZ)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick) },
  251. { "nativeRemoveJoystick", "(I)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick) },
  252. { "nativeAddHaptic", "(ILjava/lang/String;)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeAddHaptic) },
  253. { "nativeRemoveHaptic", "(I)V", SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic) }
  254. };
  255. // Uncomment this to log messages entering and exiting methods in this file
  256. // #define DEBUG_JNI
  257. static void checkJNIReady(void);
  258. /*******************************************************************************
  259. This file links the Java side of Android with libsdl
  260. *******************************************************************************/
  261. #include <jni.h>
  262. /*******************************************************************************
  263. Globals
  264. *******************************************************************************/
  265. static pthread_key_t mThreadKey;
  266. static pthread_once_t key_once = PTHREAD_ONCE_INIT;
  267. static JavaVM *mJavaVM = NULL;
  268. // Main activity
  269. static jclass mActivityClass;
  270. // method signatures
  271. static jmethodID midClipboardGetText;
  272. static jmethodID midClipboardHasText;
  273. static jmethodID midClipboardSetText;
  274. static jmethodID midCreateCustomCursor;
  275. static jmethodID midDestroyCustomCursor;
  276. static jmethodID midGetContext;
  277. static jmethodID midGetManifestEnvironmentVariables;
  278. static jmethodID midGetNativeSurface;
  279. static jmethodID midInitTouch;
  280. static jmethodID midIsAndroidTV;
  281. static jmethodID midIsChromebook;
  282. static jmethodID midIsDeXMode;
  283. static jmethodID midIsScreenKeyboardShown;
  284. static jmethodID midIsTablet;
  285. static jmethodID midManualBackButton;
  286. static jmethodID midMinimizeWindow;
  287. static jmethodID midOpenURL;
  288. static jmethodID midRequestPermission;
  289. static jmethodID midShowToast;
  290. static jmethodID midSendMessage;
  291. static jmethodID midSetActivityTitle;
  292. static jmethodID midSetCustomCursor;
  293. static jmethodID midSetOrientation;
  294. static jmethodID midSetRelativeMouseEnabled;
  295. static jmethodID midSetSystemCursor;
  296. static jmethodID midSetWindowStyle;
  297. static jmethodID midShouldMinimizeOnFocusLoss;
  298. static jmethodID midShowTextInput;
  299. static jmethodID midSupportsRelativeMouse;
  300. static jmethodID midOpenFileDescriptor;
  301. static jmethodID midShowFileDialog;
  302. static jmethodID midGetPreferredLocales;
  303. // audio manager
  304. static jclass mAudioManagerClass;
  305. // method signatures
  306. static jmethodID midRegisterAudioDeviceCallback;
  307. static jmethodID midUnregisterAudioDeviceCallback;
  308. static jmethodID midAudioSetThreadPriority;
  309. // controller manager
  310. static jclass mControllerManagerClass;
  311. // method signatures
  312. static jmethodID midPollInputDevices;
  313. static jmethodID midPollHapticDevices;
  314. static jmethodID midHapticRun;
  315. static jmethodID midHapticRumble;
  316. static jmethodID midHapticStop;
  317. // Accelerometer data storage
  318. static SDL_DisplayOrientation displayNaturalOrientation;
  319. static SDL_DisplayOrientation displayCurrentOrientation;
  320. static float fLastAccelerometer[3];
  321. static bool bHasNewData;
  322. static bool bHasEnvironmentVariables;
  323. // Android AssetManager
  324. static void Internal_Android_Create_AssetManager(void);
  325. static void Internal_Android_Destroy_AssetManager(void);
  326. static AAssetManager *asset_manager = NULL;
  327. static jobject javaAssetManagerRef = 0;
  328. static SDL_Mutex *Android_ActivityMutex = NULL;
  329. static SDL_Mutex *Android_LifecycleMutex = NULL;
  330. static SDL_Semaphore *Android_LifecycleEventSem = NULL;
  331. static SDL_AndroidLifecycleEvent Android_LifecycleEvents[SDL_NUM_ANDROID_LIFECYCLE_EVENTS];
  332. static int Android_NumLifecycleEvents;
  333. /*******************************************************************************
  334. Functions called by JNI
  335. *******************************************************************************/
  336. /* From http://developer.android.com/guide/practices/jni.html
  337. * All threads are Linux threads, scheduled by the kernel.
  338. * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
  339. * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
  340. * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
  341. * and cannot make JNI calls.
  342. * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
  343. * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
  344. * is a no-op.
  345. * Note: You can call this function any number of times for the same thread, there's no harm in it
  346. */
  347. /* From http://developer.android.com/guide/practices/jni.html
  348. * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
  349. * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
  350. * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
  351. * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
  352. * Note: The destructor is not called unless the stored value is != NULL
  353. * Note: You can call this function any number of times for the same thread, there's no harm in it
  354. * (except for some lost CPU cycles)
  355. */
  356. // Set local storage value
  357. static bool Android_JNI_SetEnv(JNIEnv *env)
  358. {
  359. int status = pthread_setspecific(mThreadKey, env);
  360. if (status < 0) {
  361. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed pthread_setspecific() in Android_JNI_SetEnv() (err=%d)", status);
  362. return false;
  363. }
  364. return true;
  365. }
  366. // Get local storage value
  367. JNIEnv *Android_JNI_GetEnv(void)
  368. {
  369. // Get JNIEnv from the Thread local storage
  370. JNIEnv *env = pthread_getspecific(mThreadKey);
  371. if (!env) {
  372. // If it fails, try to attach ! (e.g the thread isn't created with SDL_CreateThread()
  373. int status;
  374. // There should be a JVM
  375. if (!mJavaVM) {
  376. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed, there is no JavaVM");
  377. return NULL;
  378. }
  379. /* Attach the current thread to the JVM and get a JNIEnv.
  380. * It will be detached by pthread_create destructor 'Android_JNI_ThreadDestroyed' */
  381. status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
  382. if (status < 0) {
  383. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to attach current thread (err=%d)", status);
  384. return NULL;
  385. }
  386. // Save JNIEnv into the Thread local storage
  387. if (!Android_JNI_SetEnv(env)) {
  388. return NULL;
  389. }
  390. }
  391. return env;
  392. }
  393. // Set up an external thread for using JNI with Android_JNI_GetEnv()
  394. bool Android_JNI_SetupThread(void)
  395. {
  396. JNIEnv *env;
  397. int status;
  398. // There should be a JVM
  399. if (!mJavaVM) {
  400. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed, there is no JavaVM");
  401. return false;
  402. }
  403. /* Attach the current thread to the JVM and get a JNIEnv.
  404. * It will be detached by pthread_create destructor 'Android_JNI_ThreadDestroyed' */
  405. status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
  406. if (status < 0) {
  407. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to attach current thread (err=%d)", status);
  408. return false;
  409. }
  410. // Save JNIEnv into the Thread local storage
  411. if (!Android_JNI_SetEnv(env)) {
  412. return false;
  413. }
  414. return true;
  415. }
  416. // Destructor called for each thread where mThreadKey is not NULL
  417. static void Android_JNI_ThreadDestroyed(void *value)
  418. {
  419. // The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required
  420. JNIEnv *env = (JNIEnv *)value;
  421. if (env) {
  422. (*mJavaVM)->DetachCurrentThread(mJavaVM);
  423. Android_JNI_SetEnv(NULL);
  424. }
  425. }
  426. // Creation of local storage mThreadKey
  427. static void Android_JNI_CreateKey(void)
  428. {
  429. int status = pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed);
  430. if (status < 0) {
  431. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing mThreadKey with pthread_key_create() (err=%d)", status);
  432. }
  433. }
  434. static void Android_JNI_CreateKey_once(void)
  435. {
  436. int status = pthread_once(&key_once, Android_JNI_CreateKey);
  437. if (status < 0) {
  438. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing mThreadKey with pthread_once() (err=%d)", status);
  439. }
  440. }
  441. static void register_methods(JNIEnv *env, const char *classname, JNINativeMethod *methods, int nb)
  442. {
  443. jclass clazz = (*env)->FindClass(env, classname);
  444. if (!clazz || (*env)->RegisterNatives(env, clazz, methods, nb) < 0) {
  445. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to register methods of %s", classname);
  446. return;
  447. }
  448. }
  449. // Library init
  450. JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
  451. {
  452. JNIEnv *env = NULL;
  453. mJavaVM = vm;
  454. if ((*mJavaVM)->GetEnv(mJavaVM, (void **)&env, JNI_VERSION_1_4) != JNI_OK) {
  455. __android_log_print(ANDROID_LOG_ERROR, "SDL", "Failed to get JNI Env");
  456. return JNI_VERSION_1_4;
  457. }
  458. register_methods(env, "org/libsdl/app/SDLActivity", SDLActivity_tab, SDL_arraysize(SDLActivity_tab));
  459. register_methods(env, "org/libsdl/app/SDLInputConnection", SDLInputConnection_tab, SDL_arraysize(SDLInputConnection_tab));
  460. register_methods(env, "org/libsdl/app/SDLAudioManager", SDLAudioManager_tab, SDL_arraysize(SDLAudioManager_tab));
  461. register_methods(env, "org/libsdl/app/SDLControllerManager", SDLControllerManager_tab, SDL_arraysize(SDLControllerManager_tab));
  462. register_methods(env, "org/libsdl/app/HIDDeviceManager", HIDDeviceManager_tab, SDL_arraysize(HIDDeviceManager_tab));
  463. return JNI_VERSION_1_4;
  464. }
  465. void checkJNIReady(void)
  466. {
  467. if (!mActivityClass || !mAudioManagerClass || !mControllerManagerClass) {
  468. // We aren't fully initialized, let's just return.
  469. return;
  470. }
  471. SDL_SetMainReady();
  472. }
  473. // Get SDL version -- called before SDL_main() to verify JNI bindings
  474. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetVersion)(JNIEnv *env, jclass cls)
  475. {
  476. char version[128];
  477. SDL_snprintf(version, sizeof(version), "%d.%d.%d", SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_MICRO_VERSION);
  478. return (*env)->NewStringUTF(env, version);
  479. }
  480. // Activity initialization -- called before SDL_main() to initialize JNI bindings
  481. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cls)
  482. {
  483. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeSetupJNI()");
  484. // Start with a clean slate
  485. SDL_ClearError();
  486. /*
  487. * Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
  488. * Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
  489. */
  490. Android_JNI_CreateKey_once();
  491. // Save JNIEnv of SDLActivity
  492. Android_JNI_SetEnv(env);
  493. if (!mJavaVM) {
  494. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to found a JavaVM");
  495. }
  496. /* Use a mutex to prevent concurrency issues between Java Activity and Native thread code, when using 'Android_Window'.
  497. * (Eg. Java sending Touch events, while native code is destroying the main SDL_Window. )
  498. */
  499. if (!Android_ActivityMutex) {
  500. Android_ActivityMutex = SDL_CreateMutex(); // Could this be created twice if onCreate() is called a second time ?
  501. }
  502. if (!Android_ActivityMutex) {
  503. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_ActivityMutex mutex");
  504. }
  505. Android_LifecycleMutex = SDL_CreateMutex();
  506. if (!Android_LifecycleMutex) {
  507. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_LifecycleMutex mutex");
  508. }
  509. Android_LifecycleEventSem = SDL_CreateSemaphore(0);
  510. if (!Android_LifecycleEventSem) {
  511. __android_log_print(ANDROID_LOG_ERROR, "SDL", "failed to create Android_LifecycleEventSem semaphore");
  512. }
  513. mActivityClass = (jclass)((*env)->NewGlobalRef(env, cls));
  514. midClipboardGetText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardGetText", "()Ljava/lang/String;");
  515. midClipboardHasText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardHasText", "()Z");
  516. midClipboardSetText = (*env)->GetStaticMethodID(env, mActivityClass, "clipboardSetText", "(Ljava/lang/String;)V");
  517. midCreateCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "createCustomCursor", "([IIIII)I");
  518. midDestroyCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "destroyCustomCursor", "(I)V");
  519. midGetContext = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
  520. midGetManifestEnvironmentVariables = (*env)->GetStaticMethodID(env, mActivityClass, "getManifestEnvironmentVariables", "()Z");
  521. midGetNativeSurface = (*env)->GetStaticMethodID(env, mActivityClass, "getNativeSurface", "()Landroid/view/Surface;");
  522. midInitTouch = (*env)->GetStaticMethodID(env, mActivityClass, "initTouch", "()V");
  523. midIsAndroidTV = (*env)->GetStaticMethodID(env, mActivityClass, "isAndroidTV", "()Z");
  524. midIsChromebook = (*env)->GetStaticMethodID(env, mActivityClass, "isChromebook", "()Z");
  525. midIsDeXMode = (*env)->GetStaticMethodID(env, mActivityClass, "isDeXMode", "()Z");
  526. midIsScreenKeyboardShown = (*env)->GetStaticMethodID(env, mActivityClass, "isScreenKeyboardShown", "()Z");
  527. midIsTablet = (*env)->GetStaticMethodID(env, mActivityClass, "isTablet", "()Z");
  528. midManualBackButton = (*env)->GetStaticMethodID(env, mActivityClass, "manualBackButton", "()V");
  529. midMinimizeWindow = (*env)->GetStaticMethodID(env, mActivityClass, "minimizeWindow", "()V");
  530. midOpenURL = (*env)->GetStaticMethodID(env, mActivityClass, "openURL", "(Ljava/lang/String;)Z");
  531. midRequestPermission = (*env)->GetStaticMethodID(env, mActivityClass, "requestPermission", "(Ljava/lang/String;I)V");
  532. midShowToast = (*env)->GetStaticMethodID(env, mActivityClass, "showToast", "(Ljava/lang/String;IIII)Z");
  533. midSendMessage = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
  534. midSetActivityTitle = (*env)->GetStaticMethodID(env, mActivityClass, "setActivityTitle", "(Ljava/lang/String;)Z");
  535. midSetCustomCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setCustomCursor", "(I)Z");
  536. midSetOrientation = (*env)->GetStaticMethodID(env, mActivityClass, "setOrientation", "(IIZLjava/lang/String;)V");
  537. midSetRelativeMouseEnabled = (*env)->GetStaticMethodID(env, mActivityClass, "setRelativeMouseEnabled", "(Z)Z");
  538. midSetSystemCursor = (*env)->GetStaticMethodID(env, mActivityClass, "setSystemCursor", "(I)Z");
  539. midSetWindowStyle = (*env)->GetStaticMethodID(env, mActivityClass, "setWindowStyle", "(Z)V");
  540. midShouldMinimizeOnFocusLoss = (*env)->GetStaticMethodID(env, mActivityClass, "shouldMinimizeOnFocusLoss", "()Z");
  541. midShowTextInput = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIIII)Z");
  542. midSupportsRelativeMouse = (*env)->GetStaticMethodID(env, mActivityClass, "supportsRelativeMouse", "()Z");
  543. midOpenFileDescriptor = (*env)->GetStaticMethodID(env, mActivityClass, "openFileDescriptor", "(Ljava/lang/String;Ljava/lang/String;)I");
  544. midShowFileDialog = (*env)->GetStaticMethodID(env, mActivityClass, "showFileDialog", "([Ljava/lang/String;ZZI)Z");
  545. midGetPreferredLocales = (*env)->GetStaticMethodID(env, mActivityClass, "getPreferredLocales", "()Ljava/lang/String;");
  546. if (!midClipboardGetText ||
  547. !midClipboardHasText ||
  548. !midClipboardSetText ||
  549. !midCreateCustomCursor ||
  550. !midDestroyCustomCursor ||
  551. !midGetContext ||
  552. !midGetManifestEnvironmentVariables ||
  553. !midGetNativeSurface ||
  554. !midInitTouch ||
  555. !midIsAndroidTV ||
  556. !midIsChromebook ||
  557. !midIsDeXMode ||
  558. !midIsScreenKeyboardShown ||
  559. !midIsTablet ||
  560. !midManualBackButton ||
  561. !midMinimizeWindow ||
  562. !midOpenURL ||
  563. !midRequestPermission ||
  564. !midShowToast ||
  565. !midSendMessage ||
  566. !midSetActivityTitle ||
  567. !midSetCustomCursor ||
  568. !midSetOrientation ||
  569. !midSetRelativeMouseEnabled ||
  570. !midSetSystemCursor ||
  571. !midSetWindowStyle ||
  572. !midShouldMinimizeOnFocusLoss ||
  573. !midShowTextInput ||
  574. !midSupportsRelativeMouse ||
  575. !midOpenFileDescriptor ||
  576. !midShowFileDialog ||
  577. !midGetPreferredLocales) {
  578. __android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLActivity.java?");
  579. }
  580. checkJNIReady();
  581. }
  582. // Audio initialization -- called before SDL_main() to initialize JNI bindings
  583. JNIEXPORT void JNICALL SDL_JAVA_AUDIO_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cls)
  584. {
  585. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "AUDIO nativeSetupJNI()");
  586. mAudioManagerClass = (jclass)((*env)->NewGlobalRef(env, cls));
  587. midRegisterAudioDeviceCallback = (*env)->GetStaticMethodID(env, mAudioManagerClass,
  588. "registerAudioDeviceCallback",
  589. "()V");
  590. midUnregisterAudioDeviceCallback = (*env)->GetStaticMethodID(env, mAudioManagerClass,
  591. "unregisterAudioDeviceCallback",
  592. "()V");
  593. midAudioSetThreadPriority = (*env)->GetStaticMethodID(env, mAudioManagerClass,
  594. "audioSetThreadPriority", "(ZI)V");
  595. if (!midRegisterAudioDeviceCallback || !midUnregisterAudioDeviceCallback || !midAudioSetThreadPriority) {
  596. __android_log_print(ANDROID_LOG_WARN, "SDL",
  597. "Missing some Java callbacks, do you have the latest version of SDLAudioManager.java?");
  598. }
  599. checkJNIReady();
  600. }
  601. // Controller initialization -- called before SDL_main() to initialize JNI bindings
  602. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeSetupJNI)(JNIEnv *env, jclass cls)
  603. {
  604. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "CONTROLLER nativeSetupJNI()");
  605. mControllerManagerClass = (jclass)((*env)->NewGlobalRef(env, cls));
  606. midPollInputDevices = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  607. "pollInputDevices", "()V");
  608. midPollHapticDevices = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  609. "pollHapticDevices", "()V");
  610. midHapticRun = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  611. "hapticRun", "(IFI)V");
  612. midHapticRumble = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  613. "hapticRumble", "(IFFI)V");
  614. midHapticStop = (*env)->GetStaticMethodID(env, mControllerManagerClass,
  615. "hapticStop", "(I)V");
  616. if (!midPollInputDevices || !midPollHapticDevices || !midHapticRun || !midHapticRumble || !midHapticStop) {
  617. __android_log_print(ANDROID_LOG_WARN, "SDL", "Missing some Java callbacks, do you have the latest version of SDLControllerManager.java?");
  618. }
  619. checkJNIReady();
  620. }
  621. // SDL main function prototype
  622. typedef int (*SDL_main_func)(int argc, char *argv[]);
  623. static int run_count = 0;
  624. static bool allow_recreate_activity;
  625. static bool allow_recreate_activity_set;
  626. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeCheckSDLThreadCounter)(
  627. JNIEnv *env, jclass jcls)
  628. {
  629. int tmp = run_count;
  630. run_count += 1;
  631. return tmp;
  632. }
  633. void Android_SetAllowRecreateActivity(bool enabled)
  634. {
  635. allow_recreate_activity = enabled;
  636. allow_recreate_activity_set = true;
  637. }
  638. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeAllowRecreateActivity)(
  639. JNIEnv *env, jclass jcls)
  640. {
  641. return allow_recreate_activity;
  642. }
  643. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeInitMainThread)(
  644. JNIEnv *env, jclass jcls)
  645. {
  646. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeInitSDLThread() %d time", run_count);
  647. run_count += 1;
  648. // Save JNIEnv of SDLThread
  649. Android_JNI_SetEnv(env);
  650. }
  651. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeCleanupMainThread)(
  652. JNIEnv *env, jclass jcls)
  653. {
  654. /* This is a Java thread, it doesn't need to be Detached from the JVM.
  655. * Set to mThreadKey value to NULL not to call pthread_create destructor 'Android_JNI_ThreadDestroyed' */
  656. Android_JNI_SetEnv(NULL);
  657. }
  658. // Start up the SDL app
  659. JNIEXPORT int JNICALL SDL_JAVA_INTERFACE(nativeRunMain)(JNIEnv *env, jclass cls, jstring library, jstring function, jobject array)
  660. {
  661. int status = -1;
  662. const char *library_file;
  663. void *library_handle;
  664. library_file = (*env)->GetStringUTFChars(env, library, NULL);
  665. library_handle = dlopen(library_file, RTLD_GLOBAL);
  666. if (library_handle == NULL) {
  667. /* When deploying android app bundle format uncompressed native libs may not extract from apk to filesystem.
  668. In this case we should use lib name without path. https://bugzilla.libsdl.org/show_bug.cgi?id=4739 */
  669. const char *library_name = SDL_strrchr(library_file, '/');
  670. if (library_name && *library_name) {
  671. library_name += 1;
  672. library_handle = dlopen(library_name, RTLD_GLOBAL);
  673. }
  674. }
  675. if (library_handle) {
  676. const char *function_name;
  677. SDL_main_func SDL_main;
  678. function_name = (*env)->GetStringUTFChars(env, function, NULL);
  679. SDL_main = (SDL_main_func)dlsym(library_handle, function_name);
  680. if (SDL_main) {
  681. int i;
  682. int argc;
  683. int len;
  684. char **argv;
  685. bool isstack;
  686. // Prepare the arguments.
  687. len = (*env)->GetArrayLength(env, array);
  688. argv = SDL_small_alloc(char *, 1 + len + 1, &isstack); // !!! FIXME: check for NULL
  689. argc = 0;
  690. /* Use the name "app_process" so PHYSFS_platformCalcBaseDir() works.
  691. https://github.com/love2d/love-android/issues/24
  692. */
  693. argv[argc++] = SDL_strdup("app_process");
  694. for (i = 0; i < len; ++i) {
  695. char *arg = NULL;
  696. jstring string = (*env)->GetObjectArrayElement(env, array, i);
  697. if (string) {
  698. const char *utf = (*env)->GetStringUTFChars(env, string, 0);
  699. if (utf) {
  700. arg = SDL_strdup(utf);
  701. (*env)->ReleaseStringUTFChars(env, string, utf);
  702. }
  703. (*env)->DeleteLocalRef(env, string);
  704. }
  705. if (arg == NULL) {
  706. arg = SDL_strdup("");
  707. }
  708. argv[argc++] = arg;
  709. }
  710. argv[argc] = NULL;
  711. // Run the application.
  712. status = SDL_main(argc, argv);
  713. // Release the arguments.
  714. for (i = 0; i < argc; ++i) {
  715. SDL_free(argv[i]);
  716. }
  717. SDL_small_free(argv, isstack);
  718. } else {
  719. __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Couldn't find function %s in library %s", function_name, library_file);
  720. }
  721. (*env)->ReleaseStringUTFChars(env, function, function_name);
  722. dlclose(library_handle);
  723. } else {
  724. __android_log_print(ANDROID_LOG_ERROR, "SDL", "nativeRunMain(): Couldn't load library %s", library_file);
  725. }
  726. (*env)->ReleaseStringUTFChars(env, library, library_file);
  727. // Do not issue an exit or the whole application will terminate instead of just the SDL thread
  728. // exit(status);
  729. return status;
  730. }
  731. static int FindLifecycleEvent(SDL_AndroidLifecycleEvent event)
  732. {
  733. for (int index = 0; index < Android_NumLifecycleEvents; ++index) {
  734. if (Android_LifecycleEvents[index] == event) {
  735. return index;
  736. }
  737. }
  738. return -1;
  739. }
  740. static void RemoveLifecycleEvent(int index)
  741. {
  742. if (index < Android_NumLifecycleEvents - 1) {
  743. SDL_memmove(&Android_LifecycleEvents[index], &Android_LifecycleEvents[index+1], (Android_NumLifecycleEvents - index - 1) * sizeof(Android_LifecycleEvents[index]));
  744. }
  745. --Android_NumLifecycleEvents;
  746. }
  747. void Android_SendLifecycleEvent(SDL_AndroidLifecycleEvent event)
  748. {
  749. SDL_LockMutex(Android_LifecycleMutex);
  750. {
  751. int index;
  752. bool add_event = true;
  753. switch (event) {
  754. case SDL_ANDROID_LIFECYCLE_WAKE:
  755. // We don't need more than one wake queued
  756. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_WAKE);
  757. if (index >= 0) {
  758. add_event = false;
  759. }
  760. break;
  761. case SDL_ANDROID_LIFECYCLE_PAUSE:
  762. // If we have a resume queued, just stay in the paused state
  763. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_RESUME);
  764. if (index >= 0) {
  765. RemoveLifecycleEvent(index);
  766. add_event = false;
  767. }
  768. break;
  769. case SDL_ANDROID_LIFECYCLE_RESUME:
  770. // If we have a pause queued, just stay in the resumed state
  771. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_PAUSE);
  772. if (index >= 0) {
  773. RemoveLifecycleEvent(index);
  774. add_event = false;
  775. }
  776. break;
  777. case SDL_ANDROID_LIFECYCLE_LOWMEMORY:
  778. // We don't need more than one low memory event queued
  779. index = FindLifecycleEvent(SDL_ANDROID_LIFECYCLE_LOWMEMORY);
  780. if (index >= 0) {
  781. add_event = false;
  782. }
  783. break;
  784. case SDL_ANDROID_LIFECYCLE_DESTROY:
  785. // Remove all other events, we're done!
  786. while (Android_NumLifecycleEvents > 0) {
  787. RemoveLifecycleEvent(0);
  788. }
  789. break;
  790. default:
  791. SDL_assert(!"Sending unexpected lifecycle event");
  792. add_event = false;
  793. break;
  794. }
  795. if (add_event) {
  796. SDL_assert(Android_NumLifecycleEvents < SDL_arraysize(Android_LifecycleEvents));
  797. Android_LifecycleEvents[Android_NumLifecycleEvents++] = event;
  798. SDL_SignalSemaphore(Android_LifecycleEventSem);
  799. }
  800. }
  801. SDL_UnlockMutex(Android_LifecycleMutex);
  802. }
  803. bool Android_WaitLifecycleEvent(SDL_AndroidLifecycleEvent *event, Sint64 timeoutNS)
  804. {
  805. bool got_event = false;
  806. while (!got_event && SDL_WaitSemaphoreTimeoutNS(Android_LifecycleEventSem, timeoutNS)) {
  807. SDL_LockMutex(Android_LifecycleMutex);
  808. {
  809. if (Android_NumLifecycleEvents > 0) {
  810. *event = Android_LifecycleEvents[0];
  811. RemoveLifecycleEvent(0);
  812. got_event = true;
  813. }
  814. }
  815. SDL_UnlockMutex(Android_LifecycleMutex);
  816. }
  817. return got_event;
  818. }
  819. void Android_LockActivityMutex(void)
  820. {
  821. SDL_LockMutex(Android_ActivityMutex);
  822. }
  823. void Android_UnlockActivityMutex(void)
  824. {
  825. SDL_UnlockMutex(Android_ActivityMutex);
  826. }
  827. // Drop file
  828. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
  829. JNIEnv *env, jclass jcls,
  830. jstring filename)
  831. {
  832. const char *path = (*env)->GetStringUTFChars(env, filename, NULL);
  833. SDL_SendDropFile(NULL, NULL, path);
  834. (*env)->ReleaseStringUTFChars(env, filename, path);
  835. SDL_SendDropComplete(NULL);
  836. }
  837. // Set screen resolution
  838. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetScreenResolution)(
  839. JNIEnv *env, jclass jcls,
  840. jint surfaceWidth, jint surfaceHeight,
  841. jint deviceWidth, jint deviceHeight, jfloat density, jfloat rate)
  842. {
  843. SDL_LockMutex(Android_ActivityMutex);
  844. Android_SetScreenResolution(surfaceWidth, surfaceHeight, deviceWidth, deviceHeight, density, rate);
  845. SDL_UnlockMutex(Android_ActivityMutex);
  846. }
  847. // Resize
  848. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
  849. JNIEnv *env, jclass jcls)
  850. {
  851. SDL_LockMutex(Android_ActivityMutex);
  852. if (Android_Window) {
  853. Android_SendResize(Android_Window);
  854. }
  855. SDL_UnlockMutex(Android_ActivityMutex);
  856. }
  857. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetNaturalOrientation)(
  858. JNIEnv *env, jclass jcls,
  859. jint orientation)
  860. {
  861. displayNaturalOrientation = (SDL_DisplayOrientation)orientation;
  862. }
  863. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeRotationChanged)(
  864. JNIEnv *env, jclass jcls,
  865. jint rotation)
  866. {
  867. SDL_LockMutex(Android_ActivityMutex);
  868. if (displayNaturalOrientation == SDL_ORIENTATION_LANDSCAPE) {
  869. rotation += 90;
  870. }
  871. switch (rotation % 360) {
  872. case 0:
  873. displayCurrentOrientation = SDL_ORIENTATION_PORTRAIT;
  874. break;
  875. case 90:
  876. displayCurrentOrientation = SDL_ORIENTATION_LANDSCAPE;
  877. break;
  878. case 180:
  879. displayCurrentOrientation = SDL_ORIENTATION_PORTRAIT_FLIPPED;
  880. break;
  881. case 270:
  882. displayCurrentOrientation = SDL_ORIENTATION_LANDSCAPE_FLIPPED;
  883. break;
  884. default:
  885. displayCurrentOrientation = SDL_ORIENTATION_UNKNOWN;
  886. break;
  887. }
  888. Android_SetOrientation(displayCurrentOrientation);
  889. SDL_UnlockMutex(Android_ActivityMutex);
  890. }
  891. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeInsetsChanged)(
  892. JNIEnv *env, jclass jcls,
  893. jint left, jint right, jint top, jint bottom)
  894. {
  895. SDL_LockMutex(Android_ActivityMutex);
  896. Android_SetWindowSafeAreaInsets(left, right, top, bottom);
  897. SDL_UnlockMutex(Android_ActivityMutex);
  898. }
  899. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeAddTouch)(
  900. JNIEnv *env, jclass cls,
  901. jint touchId, jstring name)
  902. {
  903. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  904. SDL_AddTouch(Android_ConvertJavaTouchID(touchId),
  905. SDL_TOUCH_DEVICE_DIRECT, utfname);
  906. (*env)->ReleaseStringUTFChars(env, name, utfname);
  907. }
  908. JNIEXPORT void JNICALL
  909. SDL_JAVA_AUDIO_INTERFACE(addAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording,
  910. jstring name, jint device_id)
  911. {
  912. #if ALLOW_MULTIPLE_ANDROID_AUDIO_DEVICES
  913. if (SDL_GetCurrentAudioDriver() != NULL) {
  914. void *handle = (void *)((size_t)device_id);
  915. if (!SDL_FindPhysicalAudioDeviceByHandle(handle)) {
  916. const char *utf8name = (*env)->GetStringUTFChars(env, name, NULL);
  917. SDL_AddAudioDevice(recording, SDL_strdup(utf8name), NULL, handle);
  918. (*env)->ReleaseStringUTFChars(env, name, utf8name);
  919. }
  920. }
  921. #endif
  922. }
  923. JNIEXPORT void JNICALL
  924. SDL_JAVA_AUDIO_INTERFACE(removeAudioDevice)(JNIEnv *env, jclass jcls, jboolean recording,
  925. jint device_id)
  926. {
  927. #if ALLOW_MULTIPLE_ANDROID_AUDIO_DEVICES
  928. if (SDL_GetCurrentAudioDriver() != NULL) {
  929. SDL_Log("Removing device with handle %d, recording %d", device_id, recording);
  930. SDL_AudioDeviceDisconnected(SDL_FindPhysicalAudioDeviceByHandle((void *)((size_t)device_id)));
  931. }
  932. #endif
  933. }
  934. // Paddown
  935. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadDown)(
  936. JNIEnv *env, jclass jcls,
  937. jint device_id, jint keycode)
  938. {
  939. #ifdef SDL_JOYSTICK_ANDROID
  940. return Android_OnPadDown(device_id, keycode);
  941. #else
  942. return false;
  943. #endif // SDL_JOYSTICK_ANDROID
  944. }
  945. // Padup
  946. JNIEXPORT jboolean JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativePadUp)(
  947. JNIEnv *env, jclass jcls,
  948. jint device_id, jint keycode)
  949. {
  950. #ifdef SDL_JOYSTICK_ANDROID
  951. return Android_OnPadUp(device_id, keycode);
  952. #else
  953. return false;
  954. #endif // SDL_JOYSTICK_ANDROID
  955. }
  956. // Joy
  957. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeJoy)(
  958. JNIEnv *env, jclass jcls,
  959. jint device_id, jint axis, jfloat value)
  960. {
  961. #ifdef SDL_JOYSTICK_ANDROID
  962. Android_OnJoy(device_id, axis, value);
  963. #endif // SDL_JOYSTICK_ANDROID
  964. }
  965. // POV Hat
  966. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(onNativeHat)(
  967. JNIEnv *env, jclass jcls,
  968. jint device_id, jint hat_id, jint x, jint y)
  969. {
  970. #ifdef SDL_JOYSTICK_ANDROID
  971. Android_OnHat(device_id, hat_id, x, y);
  972. #endif // SDL_JOYSTICK_ANDROID
  973. }
  974. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddJoystick)(
  975. JNIEnv *env, jclass jcls,
  976. jint device_id, jstring device_name, jstring device_desc,
  977. jint vendor_id, jint product_id,
  978. jint button_mask, jint naxes, jint axis_mask, jint nhats, jboolean can_rumble)
  979. {
  980. #ifdef SDL_JOYSTICK_ANDROID
  981. const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
  982. const char *desc = (*env)->GetStringUTFChars(env, device_desc, NULL);
  983. Android_AddJoystick(device_id, name, desc, vendor_id, product_id, button_mask, naxes, axis_mask, nhats, can_rumble);
  984. (*env)->ReleaseStringUTFChars(env, device_name, name);
  985. (*env)->ReleaseStringUTFChars(env, device_desc, desc);
  986. #endif // SDL_JOYSTICK_ANDROID
  987. }
  988. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveJoystick)(
  989. JNIEnv *env, jclass jcls,
  990. jint device_id)
  991. {
  992. #ifdef SDL_JOYSTICK_ANDROID
  993. Android_RemoveJoystick(device_id);
  994. #endif // SDL_JOYSTICK_ANDROID
  995. }
  996. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeAddHaptic)(
  997. JNIEnv *env, jclass jcls, jint device_id, jstring device_name)
  998. {
  999. #ifdef SDL_HAPTIC_ANDROID
  1000. const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
  1001. Android_AddHaptic(device_id, name);
  1002. (*env)->ReleaseStringUTFChars(env, device_name, name);
  1003. #endif // SDL_HAPTIC_ANDROID
  1004. }
  1005. JNIEXPORT void JNICALL SDL_JAVA_CONTROLLER_INTERFACE(nativeRemoveHaptic)(
  1006. JNIEnv *env, jclass jcls, jint device_id)
  1007. {
  1008. #ifdef SDL_HAPTIC_ANDROID
  1009. Android_RemoveHaptic(device_id);
  1010. #endif
  1011. }
  1012. // Called from surfaceCreated()
  1013. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceCreated)(JNIEnv *env, jclass jcls)
  1014. {
  1015. SDL_LockMutex(Android_ActivityMutex);
  1016. if (Android_Window) {
  1017. SDL_WindowData *data = Android_Window->internal;
  1018. data->native_window = Android_JNI_GetNativeWindow();
  1019. SDL_SetPointerProperty(SDL_GetWindowProperties(Android_Window), SDL_PROP_WINDOW_ANDROID_WINDOW_POINTER, data->native_window);
  1020. if (data->native_window == NULL) {
  1021. SDL_SetError("Could not fetch native window from UI thread");
  1022. }
  1023. }
  1024. SDL_UnlockMutex(Android_ActivityMutex);
  1025. }
  1026. // Called from surfaceChanged()
  1027. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(JNIEnv *env, jclass jcls)
  1028. {
  1029. SDL_LockMutex(Android_ActivityMutex);
  1030. #ifdef SDL_VIDEO_OPENGL_EGL
  1031. if (Android_Window && (Android_Window->flags & SDL_WINDOW_OPENGL)) {
  1032. SDL_VideoDevice *_this = SDL_GetVideoDevice();
  1033. SDL_WindowData *data = Android_Window->internal;
  1034. // If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here
  1035. if (data->egl_surface == EGL_NO_SURFACE) {
  1036. data->egl_surface = SDL_EGL_CreateSurface(_this, Android_Window, (NativeWindowType)data->native_window);
  1037. SDL_SetPointerProperty(SDL_GetWindowProperties(Android_Window), SDL_PROP_WINDOW_ANDROID_SURFACE_POINTER, data->egl_surface);
  1038. }
  1039. // GL Context handling is done in the event loop because this function is run from the Java thread
  1040. }
  1041. #endif
  1042. SDL_UnlockMutex(Android_ActivityMutex);
  1043. }
  1044. // Called from surfaceDestroyed()
  1045. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(JNIEnv *env, jclass jcls)
  1046. {
  1047. int nb_attempt = 50;
  1048. retry:
  1049. SDL_LockMutex(Android_ActivityMutex);
  1050. if (Android_Window) {
  1051. SDL_WindowData *data = Android_Window->internal;
  1052. // Wait for Main thread being paused and context un-activated to release 'egl_surface'
  1053. if ((Android_Window->flags & SDL_WINDOW_OPENGL) && !data->backup_done) {
  1054. nb_attempt -= 1;
  1055. if (nb_attempt == 0) {
  1056. SDL_SetError("Try to release egl_surface with context probably still active");
  1057. } else {
  1058. SDL_UnlockMutex(Android_ActivityMutex);
  1059. SDL_Delay(10);
  1060. goto retry;
  1061. }
  1062. }
  1063. #ifdef SDL_VIDEO_OPENGL_EGL
  1064. if (data->egl_surface != EGL_NO_SURFACE) {
  1065. SDL_EGL_DestroySurface(SDL_GetVideoDevice(), data->egl_surface);
  1066. data->egl_surface = EGL_NO_SURFACE;
  1067. }
  1068. #endif
  1069. if (data->native_window) {
  1070. ANativeWindow_release(data->native_window);
  1071. data->native_window = NULL;
  1072. }
  1073. // GL Context handling is done in the event loop because this function is run from the Java thread
  1074. }
  1075. SDL_UnlockMutex(Android_ActivityMutex);
  1076. }
  1077. // Keydown
  1078. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
  1079. JNIEnv *env, jclass jcls,
  1080. jint keycode)
  1081. {
  1082. SDL_LockMutex(Android_ActivityMutex);
  1083. if (Android_Window) {
  1084. Android_OnKeyDown(keycode);
  1085. }
  1086. SDL_UnlockMutex(Android_ActivityMutex);
  1087. }
  1088. // Keyup
  1089. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
  1090. JNIEnv *env, jclass jcls,
  1091. jint keycode)
  1092. {
  1093. SDL_LockMutex(Android_ActivityMutex);
  1094. if (Android_Window) {
  1095. Android_OnKeyUp(keycode);
  1096. }
  1097. SDL_UnlockMutex(Android_ActivityMutex);
  1098. }
  1099. // Virtual keyboard return key might stop text input
  1100. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(onNativeSoftReturnKey)(
  1101. JNIEnv *env, jclass jcls)
  1102. {
  1103. if (SDL_GetHintBoolean(SDL_HINT_RETURN_KEY_HIDES_IME, false)) {
  1104. SDL_StopTextInput(Android_Window);
  1105. return JNI_TRUE;
  1106. }
  1107. return JNI_FALSE;
  1108. }
  1109. // Keyboard Focus Lost
  1110. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
  1111. JNIEnv *env, jclass jcls)
  1112. {
  1113. // Calling SDL_StopTextInput will take care of hiding the keyboard and cleaning up the DummyText widget
  1114. SDL_StopTextInput(Android_Window);
  1115. }
  1116. // Touch
  1117. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
  1118. JNIEnv *env, jclass jcls,
  1119. jint touch_device_id_in, jint pointer_finger_id_in,
  1120. jint action, jfloat x, jfloat y, jfloat p)
  1121. {
  1122. SDL_LockMutex(Android_ActivityMutex);
  1123. Android_OnTouch(Android_Window, touch_device_id_in, pointer_finger_id_in, action, x, y, p);
  1124. SDL_UnlockMutex(Android_ActivityMutex);
  1125. }
  1126. // Mouse
  1127. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
  1128. JNIEnv *env, jclass jcls,
  1129. jint button, jint action, jfloat x, jfloat y, jboolean relative)
  1130. {
  1131. SDL_LockMutex(Android_ActivityMutex);
  1132. Android_OnMouse(Android_Window, button, action, x, y, relative);
  1133. SDL_UnlockMutex(Android_ActivityMutex);
  1134. }
  1135. // Pen
  1136. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativePen)(
  1137. JNIEnv *env, jclass jcls,
  1138. jint pen_id_in, jint button, jint action, jfloat x, jfloat y, jfloat p)
  1139. {
  1140. SDL_LockMutex(Android_ActivityMutex);
  1141. Android_OnPen(Android_Window, pen_id_in, button, action, x, y, p);
  1142. SDL_UnlockMutex(Android_ActivityMutex);
  1143. }
  1144. // Accelerometer
  1145. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
  1146. JNIEnv *env, jclass jcls,
  1147. jfloat x, jfloat y, jfloat z)
  1148. {
  1149. fLastAccelerometer[0] = x;
  1150. fLastAccelerometer[1] = y;
  1151. fLastAccelerometer[2] = z;
  1152. bHasNewData = true;
  1153. }
  1154. // Clipboard
  1155. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeClipboardChanged)(
  1156. JNIEnv *env, jclass jcls)
  1157. {
  1158. // TODO: compute new mime types
  1159. SDL_SendClipboardUpdate(false, NULL, 0);
  1160. }
  1161. // Low memory
  1162. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
  1163. JNIEnv *env, jclass cls)
  1164. {
  1165. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_LOWMEMORY);
  1166. }
  1167. /* Locale
  1168. * requires android:configChanges="layoutDirection|locale" in AndroidManifest.xml */
  1169. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeLocaleChanged)(
  1170. JNIEnv *env, jclass cls)
  1171. {
  1172. SDL_SendAppEvent(SDL_EVENT_LOCALE_CHANGED);
  1173. }
  1174. // Dark mode
  1175. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDarkModeChanged)(
  1176. JNIEnv *env, jclass cls, jboolean enabled)
  1177. {
  1178. Android_SetDarkMode(enabled);
  1179. }
  1180. // Send Quit event to "SDLThread" thread
  1181. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSendQuit)(
  1182. JNIEnv *env, jclass cls)
  1183. {
  1184. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_DESTROY);
  1185. }
  1186. // Activity ends
  1187. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
  1188. JNIEnv *env, jclass cls)
  1189. {
  1190. const char *str;
  1191. if (Android_ActivityMutex) {
  1192. SDL_DestroyMutex(Android_ActivityMutex);
  1193. Android_ActivityMutex = NULL;
  1194. }
  1195. if (Android_LifecycleMutex) {
  1196. SDL_DestroyMutex(Android_LifecycleMutex);
  1197. Android_LifecycleMutex = NULL;
  1198. }
  1199. if (Android_LifecycleEventSem) {
  1200. SDL_DestroySemaphore(Android_LifecycleEventSem);
  1201. Android_LifecycleEventSem = NULL;
  1202. }
  1203. Android_NumLifecycleEvents = 0;
  1204. Internal_Android_Destroy_AssetManager();
  1205. str = SDL_GetError();
  1206. if (str && str[0]) {
  1207. __android_log_print(ANDROID_LOG_ERROR, "SDL", "SDLActivity thread ends (error=%s)", str);
  1208. } else {
  1209. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDLActivity thread ends");
  1210. }
  1211. }
  1212. // Pause
  1213. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
  1214. JNIEnv *env, jclass cls)
  1215. {
  1216. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativePause()");
  1217. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_PAUSE);
  1218. }
  1219. // Resume
  1220. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
  1221. JNIEnv *env, jclass cls)
  1222. {
  1223. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeResume()");
  1224. Android_SendLifecycleEvent(SDL_ANDROID_LIFECYCLE_RESUME);
  1225. }
  1226. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeFocusChanged)(
  1227. JNIEnv *env, jclass cls, jboolean hasFocus)
  1228. {
  1229. SDL_LockMutex(Android_ActivityMutex);
  1230. if (Android_Window) {
  1231. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeFocusChanged()");
  1232. SDL_SendWindowEvent(Android_Window, (hasFocus ? SDL_EVENT_WINDOW_FOCUS_GAINED : SDL_EVENT_WINDOW_FOCUS_LOST), 0, 0);
  1233. }
  1234. SDL_UnlockMutex(Android_ActivityMutex);
  1235. }
  1236. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
  1237. JNIEnv *env, jclass cls,
  1238. jstring text, jint newCursorPosition)
  1239. {
  1240. const char *utftext = (*env)->GetStringUTFChars(env, text, NULL);
  1241. SDL_SendKeyboardText(utftext);
  1242. (*env)->ReleaseStringUTFChars(env, text, utftext);
  1243. }
  1244. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeGenerateScancodeForUnichar)(
  1245. JNIEnv *env, jclass cls,
  1246. jchar chUnicode)
  1247. {
  1248. SDL_SendKeyboardUnicodeKey(0, chUnicode);
  1249. }
  1250. JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
  1251. JNIEnv *env, jclass cls,
  1252. jstring name)
  1253. {
  1254. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  1255. const char *hint = SDL_GetHint(utfname);
  1256. jstring result = (*env)->NewStringUTF(env, hint);
  1257. (*env)->ReleaseStringUTFChars(env, name, utfname);
  1258. return result;
  1259. }
  1260. JNIEXPORT jboolean JNICALL SDL_JAVA_INTERFACE(nativeGetHintBoolean)(
  1261. JNIEnv *env, jclass cls,
  1262. jstring name, jboolean default_value)
  1263. {
  1264. jboolean result;
  1265. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  1266. result = SDL_GetHintBoolean(utfname, default_value);
  1267. (*env)->ReleaseStringUTFChars(env, name, utfname);
  1268. return result;
  1269. }
  1270. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeSetenv)(
  1271. JNIEnv *env, jclass cls,
  1272. jstring name, jstring value)
  1273. {
  1274. const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
  1275. const char *utfvalue = (*env)->GetStringUTFChars(env, value, NULL);
  1276. // This is only called at startup, to initialize the environment
  1277. // Note that we call setenv() directly to avoid affecting SDL environments
  1278. setenv(utfname, utfvalue, 1); // This should NOT be SDL_setenv()
  1279. if (SDL_strcmp(utfname, SDL_HINT_ANDROID_ALLOW_RECREATE_ACTIVITY) == 0) {
  1280. // Special handling for this hint, which needs to persist outside the normal application flow
  1281. // Only set this the first time we run, in case it's been set by the application via SDL_SetHint()
  1282. if (!allow_recreate_activity_set) {
  1283. Android_SetAllowRecreateActivity(SDL_GetStringBoolean(utfvalue, false));
  1284. }
  1285. }
  1286. (*env)->ReleaseStringUTFChars(env, name, utfname);
  1287. (*env)->ReleaseStringUTFChars(env, value, utfvalue);
  1288. }
  1289. /*******************************************************************************
  1290. Functions called by SDL into Java
  1291. *******************************************************************************/
  1292. static SDL_AtomicInt s_active;
  1293. struct LocalReferenceHolder
  1294. {
  1295. JNIEnv *m_env;
  1296. const char *m_func;
  1297. };
  1298. static struct LocalReferenceHolder LocalReferenceHolder_Setup(const char *func)
  1299. {
  1300. struct LocalReferenceHolder refholder;
  1301. refholder.m_env = NULL;
  1302. refholder.m_func = func;
  1303. #ifdef DEBUG_JNI
  1304. SDL_Log("Entering function %s", func);
  1305. #endif
  1306. return refholder;
  1307. }
  1308. static bool LocalReferenceHolder_Init(struct LocalReferenceHolder *refholder, JNIEnv *env)
  1309. {
  1310. const int capacity = 16;
  1311. if ((*env)->PushLocalFrame(env, capacity) < 0) {
  1312. SDL_SetError("Failed to allocate enough JVM local references");
  1313. return false;
  1314. }
  1315. SDL_AtomicIncRef(&s_active);
  1316. refholder->m_env = env;
  1317. return true;
  1318. }
  1319. static void LocalReferenceHolder_Cleanup(struct LocalReferenceHolder *refholder)
  1320. {
  1321. #ifdef DEBUG_JNI
  1322. SDL_Log("Leaving function %s", refholder->m_func);
  1323. #endif
  1324. if (refholder->m_env) {
  1325. JNIEnv *env = refholder->m_env;
  1326. (*env)->PopLocalFrame(env, NULL);
  1327. SDL_AtomicDecRef(&s_active);
  1328. }
  1329. }
  1330. ANativeWindow *Android_JNI_GetNativeWindow(void)
  1331. {
  1332. ANativeWindow *anw = NULL;
  1333. jobject s;
  1334. JNIEnv *env = Android_JNI_GetEnv();
  1335. s = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetNativeSurface);
  1336. if (s) {
  1337. anw = ANativeWindow_fromSurface(env, s);
  1338. (*env)->DeleteLocalRef(env, s);
  1339. }
  1340. return anw;
  1341. }
  1342. void Android_JNI_SetActivityTitle(const char *title)
  1343. {
  1344. JNIEnv *env = Android_JNI_GetEnv();
  1345. jstring jtitle = (*env)->NewStringUTF(env, title);
  1346. (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetActivityTitle, jtitle);
  1347. (*env)->DeleteLocalRef(env, jtitle);
  1348. }
  1349. void Android_JNI_SetWindowStyle(bool fullscreen)
  1350. {
  1351. JNIEnv *env = Android_JNI_GetEnv();
  1352. (*env)->CallStaticVoidMethod(env, mActivityClass, midSetWindowStyle, fullscreen ? 1 : 0);
  1353. }
  1354. void Android_JNI_SetOrientation(int w, int h, int resizable, const char *hint)
  1355. {
  1356. JNIEnv *env = Android_JNI_GetEnv();
  1357. jstring jhint = (*env)->NewStringUTF(env, (hint ? hint : ""));
  1358. (*env)->CallStaticVoidMethod(env, mActivityClass, midSetOrientation, w, h, (resizable ? 1 : 0), jhint);
  1359. (*env)->DeleteLocalRef(env, jhint);
  1360. }
  1361. SDL_DisplayOrientation Android_JNI_GetDisplayNaturalOrientation(void)
  1362. {
  1363. return displayNaturalOrientation;
  1364. }
  1365. SDL_DisplayOrientation Android_JNI_GetDisplayCurrentOrientation(void)
  1366. {
  1367. return displayCurrentOrientation;
  1368. }
  1369. void Android_JNI_MinizeWindow(void)
  1370. {
  1371. JNIEnv *env = Android_JNI_GetEnv();
  1372. (*env)->CallStaticVoidMethod(env, mActivityClass, midMinimizeWindow);
  1373. }
  1374. bool Android_JNI_ShouldMinimizeOnFocusLoss(void)
  1375. {
  1376. JNIEnv *env = Android_JNI_GetEnv();
  1377. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midShouldMinimizeOnFocusLoss);
  1378. }
  1379. bool Android_JNI_GetAccelerometerValues(float values[3])
  1380. {
  1381. bool result = false;
  1382. if (bHasNewData) {
  1383. int i;
  1384. for (i = 0; i < 3; ++i) {
  1385. values[i] = fLastAccelerometer[i];
  1386. }
  1387. bHasNewData = false;
  1388. result = true;
  1389. }
  1390. return result;
  1391. }
  1392. /*
  1393. * Audio support
  1394. */
  1395. void Android_StartAudioHotplug(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording)
  1396. {
  1397. JNIEnv *env = Android_JNI_GetEnv();
  1398. // this will fire the callback for each existing device right away (which will eventually SDL_AddAudioDevice), and again later when things change.
  1399. (*env)->CallStaticVoidMethod(env, mAudioManagerClass, midRegisterAudioDeviceCallback);
  1400. *default_playback = *default_recording = NULL; // !!! FIXME: how do you decide the default device id?
  1401. }
  1402. void Android_StopAudioHotplug(void)
  1403. {
  1404. JNIEnv *env = Android_JNI_GetEnv();
  1405. (*env)->CallStaticVoidMethod(env, mAudioManagerClass, midUnregisterAudioDeviceCallback);
  1406. }
  1407. static void Android_JNI_AudioSetThreadPriority(int recording, int device_id)
  1408. {
  1409. JNIEnv *env = Android_JNI_GetEnv();
  1410. (*env)->CallStaticVoidMethod(env, mAudioManagerClass, midAudioSetThreadPriority, recording, device_id);
  1411. }
  1412. void Android_AudioThreadInit(SDL_AudioDevice *device)
  1413. {
  1414. Android_JNI_AudioSetThreadPriority((int) device->recording, (int)device->instance_id);
  1415. }
  1416. // Test for an exception and call SDL_SetError with its detail if one occurs
  1417. // If the parameter silent is truthy then SDL_SetError() will not be called.
  1418. static bool Android_JNI_ExceptionOccurred(bool silent)
  1419. {
  1420. JNIEnv *env = Android_JNI_GetEnv();
  1421. jthrowable exception;
  1422. // Detect mismatch LocalReferenceHolder_Init/Cleanup
  1423. SDL_assert(SDL_GetAtomicInt(&s_active) > 0);
  1424. exception = (*env)->ExceptionOccurred(env);
  1425. if (exception != NULL) {
  1426. jmethodID mid;
  1427. // Until this happens most JNI operations have undefined behaviour
  1428. (*env)->ExceptionClear(env);
  1429. if (!silent) {
  1430. jclass exceptionClass = (*env)->GetObjectClass(env, exception);
  1431. jclass classClass = (*env)->FindClass(env, "java/lang/Class");
  1432. jstring exceptionName;
  1433. const char *exceptionNameUTF8;
  1434. jstring exceptionMessage;
  1435. mid = (*env)->GetMethodID(env, classClass, "getName", "()Ljava/lang/String;");
  1436. exceptionName = (jstring)(*env)->CallObjectMethod(env, exceptionClass, mid);
  1437. exceptionNameUTF8 = (*env)->GetStringUTFChars(env, exceptionName, 0);
  1438. mid = (*env)->GetMethodID(env, exceptionClass, "getMessage", "()Ljava/lang/String;");
  1439. exceptionMessage = (jstring)(*env)->CallObjectMethod(env, exception, mid);
  1440. if (exceptionMessage != NULL) {
  1441. const char *exceptionMessageUTF8 = (*env)->GetStringUTFChars(env, exceptionMessage, 0);
  1442. SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
  1443. (*env)->ReleaseStringUTFChars(env, exceptionMessage, exceptionMessageUTF8);
  1444. } else {
  1445. SDL_SetError("%s", exceptionNameUTF8);
  1446. }
  1447. (*env)->ReleaseStringUTFChars(env, exceptionName, exceptionNameUTF8);
  1448. }
  1449. return true;
  1450. }
  1451. return false;
  1452. }
  1453. static void Internal_Android_Create_AssetManager(void)
  1454. {
  1455. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1456. JNIEnv *env = Android_JNI_GetEnv();
  1457. jmethodID mid;
  1458. jobject context;
  1459. jobject javaAssetManager;
  1460. if (!LocalReferenceHolder_Init(&refs, env)) {
  1461. LocalReferenceHolder_Cleanup(&refs);
  1462. return;
  1463. }
  1464. // context = SDLActivity.getContext();
  1465. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1466. // javaAssetManager = context.getAssets();
  1467. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  1468. "getAssets", "()Landroid/content/res/AssetManager;");
  1469. javaAssetManager = (*env)->CallObjectMethod(env, context, mid);
  1470. /**
  1471. * Given a Dalvik AssetManager object, obtain the corresponding native AAssetManager
  1472. * object. Note that the caller is responsible for obtaining and holding a VM reference
  1473. * to the jobject to prevent its being garbage collected while the native object is
  1474. * in use.
  1475. */
  1476. javaAssetManagerRef = (*env)->NewGlobalRef(env, javaAssetManager);
  1477. asset_manager = AAssetManager_fromJava(env, javaAssetManagerRef);
  1478. if (!asset_manager) {
  1479. (*env)->DeleteGlobalRef(env, javaAssetManagerRef);
  1480. Android_JNI_ExceptionOccurred(true);
  1481. }
  1482. LocalReferenceHolder_Cleanup(&refs);
  1483. }
  1484. static void Internal_Android_Destroy_AssetManager(void)
  1485. {
  1486. JNIEnv *env = Android_JNI_GetEnv();
  1487. if (asset_manager) {
  1488. (*env)->DeleteGlobalRef(env, javaAssetManagerRef);
  1489. asset_manager = NULL;
  1490. }
  1491. }
  1492. bool Android_JNI_FileOpen(void **puserdata, const char *fileName, const char *mode)
  1493. {
  1494. SDL_assert(puserdata != NULL);
  1495. AAsset *asset = NULL;
  1496. *puserdata = NULL;
  1497. if (!asset_manager) {
  1498. Internal_Android_Create_AssetManager();
  1499. }
  1500. if (!asset_manager) {
  1501. return SDL_SetError("Couldn't create asset manager");
  1502. }
  1503. asset = AAssetManager_open(asset_manager, fileName, AASSET_MODE_UNKNOWN);
  1504. if (!asset) {
  1505. return SDL_SetError("Couldn't open asset '%s'", fileName);
  1506. }
  1507. *puserdata = (void *)asset;
  1508. return true;
  1509. }
  1510. size_t Android_JNI_FileRead(void *userdata, void *buffer, size_t size, SDL_IOStatus *status)
  1511. {
  1512. const int bytes = AAsset_read((AAsset *)userdata, buffer, size);
  1513. if (bytes < 0) {
  1514. SDL_SetError("AAsset_read() failed");
  1515. return 0;
  1516. }
  1517. return (size_t)bytes;
  1518. }
  1519. size_t Android_JNI_FileWrite(void *userdata, const void *buffer, size_t size, SDL_IOStatus *status)
  1520. {
  1521. SDL_SetError("Cannot write to Android package filesystem");
  1522. return 0;
  1523. }
  1524. Sint64 Android_JNI_FileSize(void *userdata)
  1525. {
  1526. return (Sint64) AAsset_getLength64((AAsset *)userdata);
  1527. }
  1528. Sint64 Android_JNI_FileSeek(void *userdata, Sint64 offset, SDL_IOWhence whence)
  1529. {
  1530. return (Sint64) AAsset_seek64((AAsset *)userdata, offset, (int)whence);
  1531. }
  1532. bool Android_JNI_FileClose(void *userdata)
  1533. {
  1534. AAsset_close((AAsset *)userdata);
  1535. return true;
  1536. }
  1537. bool Android_JNI_SetClipboardText(const char *text)
  1538. {
  1539. JNIEnv *env = Android_JNI_GetEnv();
  1540. jstring string = (*env)->NewStringUTF(env, text);
  1541. (*env)->CallStaticVoidMethod(env, mActivityClass, midClipboardSetText, string);
  1542. (*env)->DeleteLocalRef(env, string);
  1543. return true;
  1544. }
  1545. char *Android_JNI_GetClipboardText(void)
  1546. {
  1547. JNIEnv *env = Android_JNI_GetEnv();
  1548. char *text = NULL;
  1549. jstring string;
  1550. string = (*env)->CallStaticObjectMethod(env, mActivityClass, midClipboardGetText);
  1551. if (string) {
  1552. const char *utf = (*env)->GetStringUTFChars(env, string, 0);
  1553. if (utf) {
  1554. text = SDL_strdup(utf);
  1555. (*env)->ReleaseStringUTFChars(env, string, utf);
  1556. }
  1557. (*env)->DeleteLocalRef(env, string);
  1558. }
  1559. return (!text) ? SDL_strdup("") : text;
  1560. }
  1561. bool Android_JNI_HasClipboardText(void)
  1562. {
  1563. JNIEnv *env = Android_JNI_GetEnv();
  1564. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midClipboardHasText);
  1565. }
  1566. /* returns 0 on success or -1 on error (others undefined then)
  1567. * returns truthy or falsy value in plugged, charged and battery
  1568. * returns the value in seconds and percent or -1 if not available
  1569. */
  1570. int Android_JNI_GetPowerInfo(int *plugged, int *charged, int *battery, int *seconds, int *percent)
  1571. {
  1572. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1573. JNIEnv *env = Android_JNI_GetEnv();
  1574. jmethodID mid;
  1575. jobject context;
  1576. jstring action;
  1577. jclass cls;
  1578. jobject filter;
  1579. jobject intent;
  1580. jstring iname;
  1581. jmethodID imid;
  1582. jstring bname;
  1583. jmethodID bmid;
  1584. if (!LocalReferenceHolder_Init(&refs, env)) {
  1585. LocalReferenceHolder_Cleanup(&refs);
  1586. return -1;
  1587. }
  1588. // context = SDLActivity.getContext();
  1589. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1590. action = (*env)->NewStringUTF(env, "android.intent.action.BATTERY_CHANGED");
  1591. cls = (*env)->FindClass(env, "android/content/IntentFilter");
  1592. mid = (*env)->GetMethodID(env, cls, "<init>", "(Ljava/lang/String;)V");
  1593. filter = (*env)->NewObject(env, cls, mid, action);
  1594. (*env)->DeleteLocalRef(env, action);
  1595. mid = (*env)->GetMethodID(env, mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
  1596. intent = (*env)->CallObjectMethod(env, context, mid, NULL, filter);
  1597. (*env)->DeleteLocalRef(env, filter);
  1598. cls = (*env)->GetObjectClass(env, intent);
  1599. imid = (*env)->GetMethodID(env, cls, "getIntExtra", "(Ljava/lang/String;I)I");
  1600. // Watch out for C89 scoping rules because of the macro
  1601. #define GET_INT_EXTRA(var, key) \
  1602. int var; \
  1603. iname = (*env)->NewStringUTF(env, key); \
  1604. (var) = (*env)->CallIntMethod(env, intent, imid, iname, -1); \
  1605. (*env)->DeleteLocalRef(env, iname);
  1606. bmid = (*env)->GetMethodID(env, cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
  1607. // Watch out for C89 scoping rules because of the macro
  1608. #define GET_BOOL_EXTRA(var, key) \
  1609. int var; \
  1610. bname = (*env)->NewStringUTF(env, key); \
  1611. (var) = (*env)->CallBooleanMethod(env, intent, bmid, bname, JNI_FALSE); \
  1612. (*env)->DeleteLocalRef(env, bname);
  1613. if (plugged) {
  1614. // Watch out for C89 scoping rules because of the macro
  1615. GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
  1616. if (plug == -1) {
  1617. LocalReferenceHolder_Cleanup(&refs);
  1618. return -1;
  1619. }
  1620. // 1 == BatteryManager.BATTERY_PLUGGED_AC
  1621. // 2 == BatteryManager.BATTERY_PLUGGED_USB
  1622. *plugged = (0 < plug) ? 1 : 0;
  1623. }
  1624. if (charged) {
  1625. // Watch out for C89 scoping rules because of the macro
  1626. GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
  1627. if (status == -1) {
  1628. LocalReferenceHolder_Cleanup(&refs);
  1629. return -1;
  1630. }
  1631. // 5 == BatteryManager.BATTERY_STATUS_FULL
  1632. *charged = (status == 5) ? 1 : 0;
  1633. }
  1634. if (battery) {
  1635. GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
  1636. *battery = present ? 1 : 0;
  1637. }
  1638. if (seconds) {
  1639. *seconds = -1; // not possible
  1640. }
  1641. if (percent) {
  1642. int level;
  1643. int scale;
  1644. // Watch out for C89 scoping rules because of the macro
  1645. {
  1646. GET_INT_EXTRA(level_temp, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
  1647. level = level_temp;
  1648. }
  1649. // Watch out for C89 scoping rules because of the macro
  1650. {
  1651. GET_INT_EXTRA(scale_temp, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
  1652. scale = scale_temp;
  1653. }
  1654. if ((level == -1) || (scale == -1)) {
  1655. LocalReferenceHolder_Cleanup(&refs);
  1656. return -1;
  1657. }
  1658. *percent = level * 100 / scale;
  1659. }
  1660. (*env)->DeleteLocalRef(env, intent);
  1661. LocalReferenceHolder_Cleanup(&refs);
  1662. return 0;
  1663. }
  1664. // Add all touch devices
  1665. void Android_JNI_InitTouch(void)
  1666. {
  1667. JNIEnv *env = Android_JNI_GetEnv();
  1668. (*env)->CallStaticVoidMethod(env, mActivityClass, midInitTouch);
  1669. }
  1670. void Android_JNI_PollInputDevices(void)
  1671. {
  1672. JNIEnv *env = Android_JNI_GetEnv();
  1673. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midPollInputDevices);
  1674. }
  1675. void Android_JNI_PollHapticDevices(void)
  1676. {
  1677. JNIEnv *env = Android_JNI_GetEnv();
  1678. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midPollHapticDevices);
  1679. }
  1680. void Android_JNI_HapticRun(int device_id, float intensity, int length)
  1681. {
  1682. JNIEnv *env = Android_JNI_GetEnv();
  1683. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticRun, device_id, intensity, length);
  1684. }
  1685. void Android_JNI_HapticRumble(int device_id, float low_frequency_intensity, float high_frequency_intensity, int length)
  1686. {
  1687. JNIEnv *env = Android_JNI_GetEnv();
  1688. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticRumble, device_id, low_frequency_intensity, high_frequency_intensity, length);
  1689. }
  1690. void Android_JNI_HapticStop(int device_id)
  1691. {
  1692. JNIEnv *env = Android_JNI_GetEnv();
  1693. (*env)->CallStaticVoidMethod(env, mControllerManagerClass, midHapticStop, device_id);
  1694. }
  1695. // See SDLActivity.java for constants.
  1696. #define COMMAND_SET_KEEP_SCREEN_ON 5
  1697. bool SDL_SendAndroidMessage(Uint32 command, int param)
  1698. {
  1699. if (command < 0x8000) {
  1700. return SDL_InvalidParamError("command");
  1701. }
  1702. return Android_JNI_SendMessage(command, param);
  1703. }
  1704. // sends message to be handled on the UI event dispatch thread
  1705. bool Android_JNI_SendMessage(int command, int param)
  1706. {
  1707. JNIEnv *env = Android_JNI_GetEnv();
  1708. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSendMessage, command, param);
  1709. }
  1710. bool Android_JNI_SuspendScreenSaver(bool suspend)
  1711. {
  1712. return Android_JNI_SendMessage(COMMAND_SET_KEEP_SCREEN_ON, (suspend == false) ? 0 : 1);
  1713. }
  1714. void Android_JNI_ShowScreenKeyboard(int input_type, SDL_Rect *inputRect)
  1715. {
  1716. JNIEnv *env = Android_JNI_GetEnv();
  1717. (*env)->CallStaticBooleanMethod(env, mActivityClass, midShowTextInput,
  1718. input_type,
  1719. inputRect->x,
  1720. inputRect->y,
  1721. inputRect->w,
  1722. inputRect->h);
  1723. }
  1724. void Android_JNI_HideScreenKeyboard(void)
  1725. {
  1726. // has to match Activity constant
  1727. const int COMMAND_TEXTEDIT_HIDE = 3;
  1728. Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
  1729. }
  1730. bool Android_JNI_IsScreenKeyboardShown(void)
  1731. {
  1732. JNIEnv *env = Android_JNI_GetEnv();
  1733. jboolean is_shown = 0;
  1734. is_shown = (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsScreenKeyboardShown);
  1735. return is_shown;
  1736. }
  1737. bool Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonID)
  1738. {
  1739. JNIEnv *env;
  1740. jclass clazz;
  1741. jmethodID mid;
  1742. jobject context;
  1743. jstring title;
  1744. jstring message;
  1745. jintArray button_flags;
  1746. jintArray button_ids;
  1747. jobjectArray button_texts;
  1748. jintArray colors;
  1749. jobject text;
  1750. jint temp;
  1751. int i;
  1752. env = Android_JNI_GetEnv();
  1753. // convert parameters
  1754. clazz = (*env)->FindClass(env, "java/lang/String");
  1755. title = (*env)->NewStringUTF(env, messageboxdata->title);
  1756. message = (*env)->NewStringUTF(env, messageboxdata->message);
  1757. button_flags = (*env)->NewIntArray(env, messageboxdata->numbuttons);
  1758. button_ids = (*env)->NewIntArray(env, messageboxdata->numbuttons);
  1759. button_texts = (*env)->NewObjectArray(env, messageboxdata->numbuttons,
  1760. clazz, NULL);
  1761. for (i = 0; i < messageboxdata->numbuttons; ++i) {
  1762. const SDL_MessageBoxButtonData *sdlButton;
  1763. if (messageboxdata->flags & SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT) {
  1764. sdlButton = &messageboxdata->buttons[messageboxdata->numbuttons - 1 - i];
  1765. } else {
  1766. sdlButton = &messageboxdata->buttons[i];
  1767. }
  1768. temp = sdlButton->flags;
  1769. (*env)->SetIntArrayRegion(env, button_flags, i, 1, &temp);
  1770. temp = sdlButton->buttonID;
  1771. (*env)->SetIntArrayRegion(env, button_ids, i, 1, &temp);
  1772. text = (*env)->NewStringUTF(env, sdlButton->text);
  1773. (*env)->SetObjectArrayElement(env, button_texts, i, text);
  1774. (*env)->DeleteLocalRef(env, text);
  1775. }
  1776. if (messageboxdata->colorScheme) {
  1777. colors = (*env)->NewIntArray(env, SDL_MESSAGEBOX_COLOR_COUNT);
  1778. for (i = 0; i < SDL_MESSAGEBOX_COLOR_COUNT; ++i) {
  1779. temp = (0xFFU << 24) |
  1780. (messageboxdata->colorScheme->colors[i].r << 16) |
  1781. (messageboxdata->colorScheme->colors[i].g << 8) |
  1782. (messageboxdata->colorScheme->colors[i].b << 0);
  1783. (*env)->SetIntArrayRegion(env, colors, i, 1, &temp);
  1784. }
  1785. } else {
  1786. colors = NULL;
  1787. }
  1788. (*env)->DeleteLocalRef(env, clazz);
  1789. // context = SDLActivity.getContext();
  1790. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1791. clazz = (*env)->GetObjectClass(env, context);
  1792. mid = (*env)->GetMethodID(env, clazz,
  1793. "messageboxShowMessageBox", "(ILjava/lang/String;Ljava/lang/String;[I[I[Ljava/lang/String;[I)I");
  1794. *buttonID = (*env)->CallIntMethod(env, context, mid,
  1795. messageboxdata->flags,
  1796. title,
  1797. message,
  1798. button_flags,
  1799. button_ids,
  1800. button_texts,
  1801. colors);
  1802. (*env)->DeleteLocalRef(env, context);
  1803. (*env)->DeleteLocalRef(env, clazz);
  1804. // delete parameters
  1805. (*env)->DeleteLocalRef(env, title);
  1806. (*env)->DeleteLocalRef(env, message);
  1807. (*env)->DeleteLocalRef(env, button_flags);
  1808. (*env)->DeleteLocalRef(env, button_ids);
  1809. (*env)->DeleteLocalRef(env, button_texts);
  1810. (*env)->DeleteLocalRef(env, colors);
  1811. return true;
  1812. }
  1813. /*
  1814. //////////////////////////////////////////////////////////////////////////////
  1815. //
  1816. // Functions exposed to SDL applications in SDL_system.h
  1817. //////////////////////////////////////////////////////////////////////////////
  1818. */
  1819. void *SDL_GetAndroidJNIEnv(void)
  1820. {
  1821. return Android_JNI_GetEnv();
  1822. }
  1823. void *SDL_GetAndroidActivity(void)
  1824. {
  1825. // See SDL_system.h for caveats on using this function.
  1826. JNIEnv *env = Android_JNI_GetEnv();
  1827. if (!env) {
  1828. return NULL;
  1829. }
  1830. // return SDLActivity.getContext();
  1831. return (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1832. }
  1833. int SDL_GetAndroidSDKVersion(void)
  1834. {
  1835. static int sdk_version;
  1836. if (!sdk_version) {
  1837. char sdk[PROP_VALUE_MAX] = { 0 };
  1838. if (__system_property_get("ro.build.version.sdk", sdk) != 0) {
  1839. sdk_version = SDL_atoi(sdk);
  1840. }
  1841. }
  1842. return sdk_version;
  1843. }
  1844. bool SDL_IsAndroidTablet(void)
  1845. {
  1846. JNIEnv *env = Android_JNI_GetEnv();
  1847. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsTablet);
  1848. }
  1849. bool SDL_IsAndroidTV(void)
  1850. {
  1851. JNIEnv *env = Android_JNI_GetEnv();
  1852. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsAndroidTV);
  1853. }
  1854. bool SDL_IsChromebook(void)
  1855. {
  1856. JNIEnv *env = Android_JNI_GetEnv();
  1857. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsChromebook);
  1858. }
  1859. bool SDL_IsDeXMode(void)
  1860. {
  1861. JNIEnv *env = Android_JNI_GetEnv();
  1862. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midIsDeXMode);
  1863. }
  1864. void SDL_SendAndroidBackButton(void)
  1865. {
  1866. JNIEnv *env = Android_JNI_GetEnv();
  1867. (*env)->CallStaticVoidMethod(env, mActivityClass, midManualBackButton);
  1868. }
  1869. const char *SDL_GetAndroidInternalStoragePath(void)
  1870. {
  1871. static char *s_AndroidInternalFilesPath = NULL;
  1872. if (!s_AndroidInternalFilesPath) {
  1873. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1874. jmethodID mid;
  1875. jobject context;
  1876. jobject fileObject;
  1877. jstring pathString;
  1878. const char *path;
  1879. JNIEnv *env = Android_JNI_GetEnv();
  1880. if (!LocalReferenceHolder_Init(&refs, env)) {
  1881. LocalReferenceHolder_Cleanup(&refs);
  1882. return NULL;
  1883. }
  1884. // context = SDLActivity.getContext();
  1885. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1886. if (!context) {
  1887. SDL_SetError("Couldn't get Android context!");
  1888. LocalReferenceHolder_Cleanup(&refs);
  1889. return NULL;
  1890. }
  1891. // fileObj = context.getFilesDir();
  1892. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  1893. "getFilesDir", "()Ljava/io/File;");
  1894. fileObject = (*env)->CallObjectMethod(env, context, mid);
  1895. if (!fileObject) {
  1896. SDL_SetError("Couldn't get internal directory");
  1897. LocalReferenceHolder_Cleanup(&refs);
  1898. return NULL;
  1899. }
  1900. // path = fileObject.getCanonicalPath();
  1901. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  1902. "getCanonicalPath", "()Ljava/lang/String;");
  1903. pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  1904. if (Android_JNI_ExceptionOccurred(false)) {
  1905. LocalReferenceHolder_Cleanup(&refs);
  1906. return NULL;
  1907. }
  1908. path = (*env)->GetStringUTFChars(env, pathString, NULL);
  1909. s_AndroidInternalFilesPath = SDL_strdup(path);
  1910. (*env)->ReleaseStringUTFChars(env, pathString, path);
  1911. LocalReferenceHolder_Cleanup(&refs);
  1912. }
  1913. return s_AndroidInternalFilesPath;
  1914. }
  1915. Uint32 SDL_GetAndroidExternalStorageState(void)
  1916. {
  1917. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1918. jmethodID mid;
  1919. jclass cls;
  1920. jstring stateString;
  1921. const char *state_string;
  1922. Uint32 stateFlags;
  1923. JNIEnv *env = Android_JNI_GetEnv();
  1924. if (!LocalReferenceHolder_Init(&refs, env)) {
  1925. LocalReferenceHolder_Cleanup(&refs);
  1926. return 0;
  1927. }
  1928. cls = (*env)->FindClass(env, "android/os/Environment");
  1929. mid = (*env)->GetStaticMethodID(env, cls,
  1930. "getExternalStorageState", "()Ljava/lang/String;");
  1931. stateString = (jstring)(*env)->CallStaticObjectMethod(env, cls, mid);
  1932. state_string = (*env)->GetStringUTFChars(env, stateString, NULL);
  1933. // Print an info message so people debugging know the storage state
  1934. __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state_string);
  1935. if (SDL_strcmp(state_string, "mounted") == 0) {
  1936. stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
  1937. SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
  1938. } else if (SDL_strcmp(state_string, "mounted_ro") == 0) {
  1939. stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
  1940. } else {
  1941. stateFlags = 0;
  1942. }
  1943. (*env)->ReleaseStringUTFChars(env, stateString, state_string);
  1944. LocalReferenceHolder_Cleanup(&refs);
  1945. return stateFlags;
  1946. }
  1947. const char *SDL_GetAndroidExternalStoragePath(void)
  1948. {
  1949. static char *s_AndroidExternalFilesPath = NULL;
  1950. if (!s_AndroidExternalFilesPath) {
  1951. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1952. jmethodID mid;
  1953. jobject context;
  1954. jobject fileObject;
  1955. jstring pathString;
  1956. const char *path;
  1957. JNIEnv *env = Android_JNI_GetEnv();
  1958. if (!LocalReferenceHolder_Init(&refs, env)) {
  1959. LocalReferenceHolder_Cleanup(&refs);
  1960. return NULL;
  1961. }
  1962. // context = SDLActivity.getContext();
  1963. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  1964. // fileObj = context.getExternalFilesDir();
  1965. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  1966. "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
  1967. fileObject = (*env)->CallObjectMethod(env, context, mid, NULL);
  1968. if (!fileObject) {
  1969. SDL_SetError("Couldn't get external directory");
  1970. LocalReferenceHolder_Cleanup(&refs);
  1971. return NULL;
  1972. }
  1973. // path = fileObject.getAbsolutePath();
  1974. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  1975. "getAbsolutePath", "()Ljava/lang/String;");
  1976. pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  1977. path = (*env)->GetStringUTFChars(env, pathString, NULL);
  1978. s_AndroidExternalFilesPath = SDL_strdup(path);
  1979. (*env)->ReleaseStringUTFChars(env, pathString, path);
  1980. LocalReferenceHolder_Cleanup(&refs);
  1981. }
  1982. return s_AndroidExternalFilesPath;
  1983. }
  1984. const char *SDL_GetAndroidCachePath(void)
  1985. {
  1986. // !!! FIXME: lots of duplication with SDL_GetAndroidExternalStoragePath and SDL_GetAndroidInternalStoragePath; consolidate these functions!
  1987. static char *s_AndroidCachePath = NULL;
  1988. if (!s_AndroidCachePath) {
  1989. struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1990. jmethodID mid;
  1991. jobject context;
  1992. jobject fileObject;
  1993. jstring pathString;
  1994. const char *path;
  1995. JNIEnv *env = Android_JNI_GetEnv();
  1996. if (!LocalReferenceHolder_Init(&refs, env)) {
  1997. LocalReferenceHolder_Cleanup(&refs);
  1998. return NULL;
  1999. }
  2000. // context = SDLActivity.getContext();
  2001. context = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetContext);
  2002. // fileObj = context.getExternalFilesDir();
  2003. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  2004. "getCacheDir", "()Ljava/io/File;");
  2005. fileObject = (*env)->CallObjectMethod(env, context, mid, NULL);
  2006. if (!fileObject) {
  2007. SDL_SetError("Couldn't get cache directory");
  2008. LocalReferenceHolder_Cleanup(&refs);
  2009. return NULL;
  2010. }
  2011. // path = fileObject.getAbsolutePath();
  2012. mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  2013. "getAbsolutePath", "()Ljava/lang/String;");
  2014. pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  2015. path = (*env)->GetStringUTFChars(env, pathString, NULL);
  2016. s_AndroidCachePath = SDL_strdup(path);
  2017. (*env)->ReleaseStringUTFChars(env, pathString, path);
  2018. LocalReferenceHolder_Cleanup(&refs);
  2019. }
  2020. return s_AndroidCachePath;
  2021. }
  2022. bool SDL_ShowAndroidToast(const char *message, int duration, int gravity, int xOffset, int yOffset)
  2023. {
  2024. return Android_JNI_ShowToast(message, duration, gravity, xOffset, yOffset);
  2025. }
  2026. void Android_JNI_GetManifestEnvironmentVariables(void)
  2027. {
  2028. if (!mActivityClass || !midGetManifestEnvironmentVariables) {
  2029. __android_log_print(ANDROID_LOG_WARN, "SDL", "Request to get environment variables before JNI is ready");
  2030. return;
  2031. }
  2032. if (!bHasEnvironmentVariables) {
  2033. JNIEnv *env = Android_JNI_GetEnv();
  2034. bool ret = (*env)->CallStaticBooleanMethod(env, mActivityClass, midGetManifestEnvironmentVariables);
  2035. if (ret) {
  2036. bHasEnvironmentVariables = true;
  2037. }
  2038. }
  2039. }
  2040. int Android_JNI_CreateCustomCursor(SDL_Surface *surface, int hot_x, int hot_y)
  2041. {
  2042. JNIEnv *env = Android_JNI_GetEnv();
  2043. int custom_cursor = 0;
  2044. jintArray pixels;
  2045. pixels = (*env)->NewIntArray(env, surface->w * surface->h);
  2046. if (pixels) {
  2047. (*env)->SetIntArrayRegion(env, pixels, 0, surface->w * surface->h, (int *)surface->pixels);
  2048. custom_cursor = (*env)->CallStaticIntMethod(env, mActivityClass, midCreateCustomCursor, pixels, surface->w, surface->h, hot_x, hot_y);
  2049. (*env)->DeleteLocalRef(env, pixels);
  2050. } else {
  2051. SDL_OutOfMemory();
  2052. }
  2053. return custom_cursor;
  2054. }
  2055. void Android_JNI_DestroyCustomCursor(int cursorID)
  2056. {
  2057. JNIEnv *env = Android_JNI_GetEnv();
  2058. (*env)->CallStaticVoidMethod(env, mActivityClass, midDestroyCustomCursor, cursorID);
  2059. }
  2060. bool Android_JNI_SetCustomCursor(int cursorID)
  2061. {
  2062. JNIEnv *env = Android_JNI_GetEnv();
  2063. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetCustomCursor, cursorID);
  2064. }
  2065. bool Android_JNI_SetSystemCursor(int cursorID)
  2066. {
  2067. JNIEnv *env = Android_JNI_GetEnv();
  2068. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetSystemCursor, cursorID);
  2069. }
  2070. bool Android_JNI_SupportsRelativeMouse(void)
  2071. {
  2072. JNIEnv *env = Android_JNI_GetEnv();
  2073. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSupportsRelativeMouse);
  2074. }
  2075. bool Android_JNI_SetRelativeMouseEnabled(bool enabled)
  2076. {
  2077. JNIEnv *env = Android_JNI_GetEnv();
  2078. return (*env)->CallStaticBooleanMethod(env, mActivityClass, midSetRelativeMouseEnabled, (enabled == 1));
  2079. }
  2080. typedef struct NativePermissionRequestInfo
  2081. {
  2082. int request_code;
  2083. char *permission;
  2084. SDL_RequestAndroidPermissionCallback callback;
  2085. void *userdata;
  2086. struct NativePermissionRequestInfo *next;
  2087. } NativePermissionRequestInfo;
  2088. static NativePermissionRequestInfo pending_permissions;
  2089. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePermissionResult)(
  2090. JNIEnv *env, jclass cls,
  2091. jint requestCode, jboolean result)
  2092. {
  2093. SDL_LockMutex(Android_ActivityMutex);
  2094. NativePermissionRequestInfo *prev = &pending_permissions;
  2095. for (NativePermissionRequestInfo *info = prev->next; info != NULL; info = info->next) {
  2096. if (info->request_code == (int) requestCode) {
  2097. prev->next = info->next;
  2098. SDL_UnlockMutex(Android_ActivityMutex);
  2099. info->callback(info->userdata, info->permission, result ? true : false);
  2100. SDL_free(info->permission);
  2101. SDL_free(info);
  2102. return;
  2103. }
  2104. prev = info;
  2105. }
  2106. SDL_UnlockMutex(Android_ActivityMutex);
  2107. }
  2108. bool SDL_RequestAndroidPermission(const char *permission, SDL_RequestAndroidPermissionCallback cb, void *userdata)
  2109. {
  2110. if (!permission) {
  2111. return SDL_InvalidParamError("permission");
  2112. } else if (!cb) {
  2113. return SDL_InvalidParamError("cb");
  2114. }
  2115. NativePermissionRequestInfo *info = (NativePermissionRequestInfo *) SDL_calloc(1, sizeof (NativePermissionRequestInfo));
  2116. if (!info) {
  2117. return false;
  2118. }
  2119. info->permission = SDL_strdup(permission);
  2120. if (!info->permission) {
  2121. SDL_free(info);
  2122. return false;
  2123. }
  2124. static SDL_AtomicInt next_request_code;
  2125. info->request_code = SDL_AddAtomicInt(&next_request_code, 1);
  2126. info->callback = cb;
  2127. info->userdata = userdata;
  2128. SDL_LockMutex(Android_ActivityMutex);
  2129. info->next = pending_permissions.next;
  2130. pending_permissions.next = info;
  2131. SDL_UnlockMutex(Android_ActivityMutex);
  2132. JNIEnv *env = Android_JNI_GetEnv();
  2133. jstring jpermission = (*env)->NewStringUTF(env, permission);
  2134. (*env)->CallStaticVoidMethod(env, mActivityClass, midRequestPermission, jpermission, info->request_code);
  2135. (*env)->DeleteLocalRef(env, jpermission);
  2136. return true;
  2137. }
  2138. // Show toast notification
  2139. bool Android_JNI_ShowToast(const char *message, int duration, int gravity, int xOffset, int yOffset)
  2140. {
  2141. bool result;
  2142. JNIEnv *env = Android_JNI_GetEnv();
  2143. jstring jmessage = (*env)->NewStringUTF(env, message);
  2144. result = (*env)->CallStaticBooleanMethod(env, mActivityClass, midShowToast, jmessage, duration, gravity, xOffset, yOffset);
  2145. (*env)->DeleteLocalRef(env, jmessage);
  2146. return result;
  2147. }
  2148. bool Android_JNI_GetLocale(char *buf, size_t buflen)
  2149. {
  2150. bool result = false;
  2151. if (buf && buflen > 0) {
  2152. *buf = '\0';
  2153. JNIEnv *env = Android_JNI_GetEnv();
  2154. jstring string = (jstring)(*env)->CallStaticObjectMethod(env, mActivityClass, midGetPreferredLocales);
  2155. if (string) {
  2156. const char *utf8string = (*env)->GetStringUTFChars(env, string, NULL);
  2157. if (utf8string) {
  2158. result = true;
  2159. SDL_strlcpy(buf, utf8string, buflen);
  2160. (*env)->ReleaseStringUTFChars(env, string, utf8string);
  2161. }
  2162. (*env)->DeleteLocalRef(env, string);
  2163. }
  2164. }
  2165. return result;
  2166. }
  2167. bool Android_JNI_OpenURL(const char *url)
  2168. {
  2169. bool result;
  2170. JNIEnv *env = Android_JNI_GetEnv();
  2171. jstring jurl = (*env)->NewStringUTF(env, url);
  2172. result = (*env)->CallStaticBooleanMethod(env, mActivityClass, midOpenURL, jurl);
  2173. (*env)->DeleteLocalRef(env, jurl);
  2174. return result;
  2175. }
  2176. int Android_JNI_OpenFileDescriptor(const char *uri, const char *mode)
  2177. {
  2178. // Get fopen-style modes
  2179. int moderead = 0, modewrite = 0, modeappend = 0, modeupdate = 0;
  2180. for (const char *cmode = mode; *cmode; cmode++) {
  2181. switch (*cmode) {
  2182. case 'a':
  2183. modeappend = 1;
  2184. break;
  2185. case 'r':
  2186. moderead = 1;
  2187. break;
  2188. case 'w':
  2189. modewrite = 1;
  2190. break;
  2191. case '+':
  2192. modeupdate = 1;
  2193. break;
  2194. default:
  2195. break;
  2196. }
  2197. }
  2198. // Translate fopen-style modes to ContentResolver modes.
  2199. // Android only allows "r", "w", "wt", "wa", "rw" or "rwt".
  2200. const char *contentResolverMode = "r";
  2201. if (moderead) {
  2202. if (modewrite) {
  2203. contentResolverMode = "rwt";
  2204. } else {
  2205. contentResolverMode = modeupdate ? "rw" : "r";
  2206. }
  2207. } else if (modewrite) {
  2208. contentResolverMode = modeupdate ? "rwt" : "wt";
  2209. } else if (modeappend) {
  2210. contentResolverMode = modeupdate ? "rw" : "wa";
  2211. }
  2212. JNIEnv *env = Android_JNI_GetEnv();
  2213. jstring jstringUri = (*env)->NewStringUTF(env, uri);
  2214. jstring jstringMode = (*env)->NewStringUTF(env, contentResolverMode);
  2215. jint fd = (*env)->CallStaticIntMethod(env, mActivityClass, midOpenFileDescriptor, jstringUri, jstringMode);
  2216. (*env)->DeleteLocalRef(env, jstringUri);
  2217. (*env)->DeleteLocalRef(env, jstringMode);
  2218. if (fd == -1) {
  2219. SDL_SetError("Unspecified error in JNI");
  2220. }
  2221. return fd;
  2222. }
  2223. static struct AndroidFileDialog
  2224. {
  2225. int request_code;
  2226. SDL_DialogFileCallback callback;
  2227. void *userdata;
  2228. } mAndroidFileDialogData;
  2229. JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeFileDialog)(
  2230. JNIEnv *env, jclass jcls,
  2231. jint requestCode, jobjectArray fileList, jint filter)
  2232. {
  2233. if (mAndroidFileDialogData.callback != NULL && mAndroidFileDialogData.request_code == requestCode) {
  2234. if (fileList == NULL) {
  2235. SDL_SetError("Unspecified error in JNI");
  2236. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, NULL, -1);
  2237. mAndroidFileDialogData.callback = NULL;
  2238. return;
  2239. }
  2240. // Convert fileList to string
  2241. size_t count = (*env)->GetArrayLength(env, fileList);
  2242. char **charFileList = SDL_calloc(count + 1, sizeof(char*));
  2243. if (charFileList == NULL) {
  2244. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, NULL, -1);
  2245. mAndroidFileDialogData.callback = NULL;
  2246. return;
  2247. }
  2248. // Convert to UTF-8
  2249. // TODO: Fix modified UTF-8 to classic UTF-8
  2250. for (int i = 0; i < count; i++) {
  2251. jstring string = (*env)->GetObjectArrayElement(env, fileList, i);
  2252. if (!string) {
  2253. continue;
  2254. }
  2255. const char *utf8string = (*env)->GetStringUTFChars(env, string, NULL);
  2256. if (!utf8string) {
  2257. (*env)->DeleteLocalRef(env, string);
  2258. continue;
  2259. }
  2260. char *newFile = SDL_strdup(utf8string);
  2261. if (!newFile) {
  2262. (*env)->ReleaseStringUTFChars(env, string, utf8string);
  2263. (*env)->DeleteLocalRef(env, string);
  2264. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, NULL, -1);
  2265. mAndroidFileDialogData.callback = NULL;
  2266. // Cleanup memory
  2267. for (int j = 0; j < i; j++) {
  2268. SDL_free(charFileList[j]);
  2269. }
  2270. SDL_free(charFileList);
  2271. return;
  2272. }
  2273. charFileList[i] = newFile;
  2274. (*env)->ReleaseStringUTFChars(env, string, utf8string);
  2275. (*env)->DeleteLocalRef(env, string);
  2276. }
  2277. // Call user-provided callback
  2278. SDL_ClearError();
  2279. mAndroidFileDialogData.callback(mAndroidFileDialogData.userdata, (const char *const *) charFileList, filter);
  2280. mAndroidFileDialogData.callback = NULL;
  2281. // Cleanup memory
  2282. for (int i = 0; i < count; i++) {
  2283. SDL_free(charFileList[i]);
  2284. }
  2285. SDL_free(charFileList);
  2286. }
  2287. }
  2288. bool Android_JNI_OpenFileDialog(
  2289. SDL_DialogFileCallback callback, void* userdata,
  2290. const SDL_DialogFileFilter *filters, int nfilters, bool forwrite,
  2291. bool multiple)
  2292. {
  2293. if (mAndroidFileDialogData.callback != NULL) {
  2294. SDL_SetError("Only one file dialog can be run at a time.");
  2295. return false;
  2296. }
  2297. if (forwrite) {
  2298. multiple = false;
  2299. }
  2300. JNIEnv *env = Android_JNI_GetEnv();
  2301. // Setup filters
  2302. jobjectArray filtersArray = NULL;
  2303. if (filters) {
  2304. jclass stringClass = (*env)->FindClass(env, "java/lang/String");
  2305. filtersArray = (*env)->NewObjectArray(env, nfilters, stringClass, NULL);
  2306. // Convert to string
  2307. for (int i = 0; i < nfilters; i++) {
  2308. jstring str = (*env)->NewStringUTF(env, filters[i].pattern);
  2309. (*env)->SetObjectArrayElement(env, filtersArray, i, str);
  2310. (*env)->DeleteLocalRef(env, str);
  2311. }
  2312. }
  2313. // Setup data
  2314. static SDL_AtomicInt next_request_code;
  2315. mAndroidFileDialogData.request_code = SDL_AddAtomicInt(&next_request_code, 1);
  2316. mAndroidFileDialogData.userdata = userdata;
  2317. mAndroidFileDialogData.callback = callback;
  2318. // Invoke JNI
  2319. jboolean success = (*env)->CallStaticBooleanMethod(env, mActivityClass,
  2320. midShowFileDialog, filtersArray, (jboolean) multiple, (jboolean) forwrite, mAndroidFileDialogData.request_code);
  2321. (*env)->DeleteLocalRef(env, filtersArray);
  2322. if (!success) {
  2323. mAndroidFileDialogData.callback = NULL;
  2324. SDL_AddAtomicInt(&next_request_code, -1);
  2325. SDL_SetError("Unspecified error in JNI");
  2326. return false;
  2327. }
  2328. return true;
  2329. }
  2330. #endif // SDL_PLATFORM_ANDROID