SDL_android.c 97 KB

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