SDL_android.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2012 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. // Modified by Lasse Öörni for Urho3D
  19. #include "SDL_config.h"
  20. #include "SDL_stdinc.h"
  21. #include "SDL_assert.h"
  22. #ifdef __ANDROID__
  23. #include "SDL_android.h"
  24. extern "C" {
  25. #include "../../events/SDL_events_c.h"
  26. #include "../../video/android/SDL_androidkeyboard.h"
  27. #include "../../video/android/SDL_androidtouch.h"
  28. #include "../../video/android/SDL_androidvideo.h"
  29. #include <android/log.h>
  30. #define LOG_TAG "SDL_android"
  31. //#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
  32. //#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
  33. #define LOGI(...) do {} while (false)
  34. #define LOGE(...) do {} while (false)
  35. /* Implemented in audio/android/SDL_androidaudio.c */
  36. extern void Android_RunAudioThread();
  37. } // C
  38. /*******************************************************************************
  39. This file links the Java side of Android with libsdl
  40. *******************************************************************************/
  41. #include <jni.h>
  42. #include <android/log.h>
  43. /*******************************************************************************
  44. Globals
  45. *******************************************************************************/
  46. static JNIEnv* mEnv = NULL;
  47. static JNIEnv* mAudioEnv = NULL;
  48. static JavaVM* mJavaVM;
  49. // Main activity
  50. static jclass mActivityClass;
  51. // method signatures
  52. static jmethodID midCreateGLContext;
  53. static jmethodID midFlipBuffers;
  54. static jmethodID midAudioInit;
  55. static jmethodID midAudioWriteShortBuffer;
  56. static jmethodID midAudioWriteByteBuffer;
  57. static jmethodID midAudioQuit;
  58. // Accelerometer data storage
  59. static float fLastAccelerometer[3];
  60. static bool bHasNewData;
  61. // Application files dir
  62. static char* mFilesDir = 0;
  63. /*******************************************************************************
  64. Functions called by JNI
  65. *******************************************************************************/
  66. // Library init
  67. extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
  68. {
  69. JNIEnv *env;
  70. mJavaVM = vm;
  71. LOGI("JNI_OnLoad called");
  72. if (mJavaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
  73. LOGE("Failed to get the environment using GetEnv()");
  74. return -1;
  75. }
  76. return JNI_VERSION_1_4;
  77. }
  78. extern "C" const char* SDL_Android_GetFilesDir()
  79. {
  80. return mFilesDir;
  81. }
  82. // Called before SDL_main() to initialize JNI bindings
  83. extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls, jstring filesDir)
  84. {
  85. __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
  86. // Copy the files dir
  87. const char *str;
  88. str = env->GetStringUTFChars(filesDir, 0);
  89. if (str)
  90. {
  91. if (mFilesDir)
  92. free(mFilesDir);
  93. size_t length = strlen(str) + 1;
  94. mFilesDir = (char*)malloc(length);
  95. memcpy(mFilesDir, str, length);
  96. env->ReleaseStringUTFChars(filesDir, str);
  97. }
  98. mEnv = env;
  99. mActivityClass = (jclass)env->NewGlobalRef(cls);
  100. midCreateGLContext = mEnv->GetStaticMethodID(mActivityClass,
  101. "createGLContext","(II)Z");
  102. midFlipBuffers = mEnv->GetStaticMethodID(mActivityClass,
  103. "flipBuffers","()V");
  104. midAudioInit = mEnv->GetStaticMethodID(mActivityClass,
  105. "audioInit", "(IZZI)Ljava/lang/Object;");
  106. midAudioWriteShortBuffer = mEnv->GetStaticMethodID(mActivityClass,
  107. "audioWriteShortBuffer", "([S)V");
  108. midAudioWriteByteBuffer = mEnv->GetStaticMethodID(mActivityClass,
  109. "audioWriteByteBuffer", "([B)V");
  110. midAudioQuit = mEnv->GetStaticMethodID(mActivityClass,
  111. "audioQuit", "()V");
  112. bHasNewData = false;
  113. if(!midCreateGLContext || !midFlipBuffers || !midAudioInit ||
  114. !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) {
  115. __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
  116. }
  117. __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
  118. }
  119. // Resize
  120. extern "C" void Java_org_libsdl_app_SDLActivity_onNativeResize(
  121. JNIEnv* env, jclass jcls,
  122. jint width, jint height, jint format)
  123. {
  124. Android_SetScreenResolution(width, height, format);
  125. }
  126. // Keydown
  127. extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyDown(
  128. JNIEnv* env, jclass jcls, jint keycode)
  129. {
  130. Android_OnKeyDown(keycode);
  131. }
  132. // Keyup
  133. extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyUp(
  134. JNIEnv* env, jclass jcls, jint keycode)
  135. {
  136. Android_OnKeyUp(keycode);
  137. }
  138. // Touch
  139. extern "C" void Java_org_libsdl_app_SDLActivity_onNativeTouch(
  140. JNIEnv* env, jclass jcls,
  141. jint touch_device_id_in, jint pointer_finger_id_in,
  142. jint action, jfloat x, jfloat y, jfloat p)
  143. {
  144. Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p);
  145. }
  146. // Accelerometer
  147. extern "C" void Java_org_libsdl_app_SDLActivity_onNativeAccel(
  148. JNIEnv* env, jclass jcls,
  149. jfloat x, jfloat y, jfloat z)
  150. {
  151. fLastAccelerometer[0] = x;
  152. fLastAccelerometer[1] = y;
  153. fLastAccelerometer[2] = z;
  154. bHasNewData = true;
  155. }
  156. // Quit
  157. extern "C" void Java_org_libsdl_app_SDLActivity_nativeQuit(
  158. JNIEnv* env, jclass cls)
  159. {
  160. // Inject a SDL_QUIT event
  161. SDL_Event event;
  162. event.type=SDL_SYSEVENT_TERMINATE;
  163. event.sysevent.data=NULL;
  164. if (SDL_SysEventHandler)
  165. SDL_SysEventHandler(&event);
  166. else SDL_SendQuit();
  167. }
  168. // Pause
  169. extern "C" void Java_org_libsdl_app_SDLActivity_nativePause(
  170. JNIEnv* env, jclass cls)
  171. {
  172. SDL_Event event;
  173. event.type=SDL_SYSEVENT_WILL_SUSPEND;
  174. event.sysevent.data=NULL;
  175. if (SDL_SysEventHandler)
  176. SDL_SysEventHandler(&event);
  177. event.type=SDL_SYSEVENT_SUSPEND;
  178. event.sysevent.data=NULL;
  179. if (SDL_SysEventHandler)
  180. SDL_SysEventHandler(&event);
  181. else if (Android_Window) {
  182. SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
  183. SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
  184. }
  185. }
  186. // Resume
  187. extern "C" void Java_org_libsdl_app_SDLActivity_nativeResume(
  188. JNIEnv* env, jclass cls)
  189. {
  190. SDL_Event event;
  191. event.type=SDL_SYSEVENT_WILL_RESUME;
  192. event.sysevent.data=NULL;
  193. if (SDL_SysEventHandler)
  194. SDL_SysEventHandler(&event);
  195. event.type=SDL_SYSEVENT_RESUME;
  196. event.sysevent.data=NULL;
  197. if (SDL_SysEventHandler)
  198. SDL_SysEventHandler(&event);
  199. else if (Android_Window) {
  200. SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
  201. SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0);
  202. }
  203. }
  204. extern "C" void Java_org_libsdl_app_SDLActivity_nativeRunAudioThread(
  205. JNIEnv* env, jclass cls)
  206. {
  207. /* This is the audio thread, with a different environment */
  208. mAudioEnv = env;
  209. Android_RunAudioThread();
  210. }
  211. /*******************************************************************************
  212. Functions called by SDL into Java
  213. *******************************************************************************/
  214. class LocalReferenceHolder
  215. {
  216. private:
  217. static int s_active;
  218. public:
  219. static bool IsActive() {
  220. return s_active > 0;
  221. }
  222. public:
  223. LocalReferenceHolder() : m_env(NULL) { }
  224. ~LocalReferenceHolder() {
  225. if (m_env) {
  226. m_env->PopLocalFrame(NULL);
  227. --s_active;
  228. }
  229. }
  230. bool init(JNIEnv *env, jint capacity = 16) {
  231. if (env->PushLocalFrame(capacity) < 0) {
  232. SDL_SetError("Failed to allocate enough JVM local references");
  233. return false;
  234. }
  235. ++s_active;
  236. m_env = env;
  237. return true;
  238. }
  239. protected:
  240. JNIEnv *m_env;
  241. };
  242. int LocalReferenceHolder::s_active;
  243. extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion)
  244. {
  245. if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) {
  246. return SDL_TRUE;
  247. } else {
  248. return SDL_FALSE;
  249. }
  250. }
  251. extern "C" void Android_JNI_SwapWindow()
  252. {
  253. mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers);
  254. }
  255. extern "C" void Android_JNI_SetActivityTitle(const char *title)
  256. {
  257. jmethodID mid;
  258. mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V");
  259. if (mid) {
  260. mEnv->CallStaticVoidMethod(mActivityClass, mid, mEnv->NewStringUTF(title));
  261. }
  262. }
  263. extern "C" SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
  264. {
  265. int i;
  266. SDL_bool retval = SDL_FALSE;
  267. if (bHasNewData) {
  268. for (i = 0; i < 3; ++i) {
  269. values[i] = fLastAccelerometer[i];
  270. }
  271. bHasNewData = false;
  272. retval = SDL_TRUE;
  273. }
  274. return retval;
  275. }
  276. //
  277. // Audio support
  278. //
  279. static jboolean audioBuffer16Bit = JNI_FALSE;
  280. static jboolean audioBufferStereo = JNI_FALSE;
  281. static jobject audioBuffer = NULL;
  282. static void* audioBufferPinned = NULL;
  283. extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
  284. {
  285. int audioBufferFrames;
  286. int status;
  287. JNIEnv *env;
  288. static bool isAttached = false;
  289. status = mJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4);
  290. if(status < 0) {
  291. LOGE("callback_handler: failed to get JNI environment, assuming native thread");
  292. status = mJavaVM->AttachCurrentThread(&env, NULL);
  293. if(status < 0) {
  294. LOGE("callback_handler: failed to attach current thread");
  295. return 0;
  296. }
  297. isAttached = true;
  298. }
  299. __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
  300. audioBuffer16Bit = is16Bit;
  301. audioBufferStereo = channelCount > 1;
  302. audioBuffer = env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
  303. if (audioBuffer == NULL) {
  304. __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!");
  305. return 0;
  306. }
  307. audioBuffer = env->NewGlobalRef(audioBuffer);
  308. jboolean isCopy = JNI_FALSE;
  309. if (audioBuffer16Bit) {
  310. audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
  311. audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
  312. } else {
  313. audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
  314. audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
  315. }
  316. if (audioBufferStereo) {
  317. audioBufferFrames /= 2;
  318. }
  319. if (isAttached) {
  320. mJavaVM->DetachCurrentThread();
  321. }
  322. return audioBufferFrames;
  323. }
  324. extern "C" void * Android_JNI_GetAudioBuffer()
  325. {
  326. return audioBufferPinned;
  327. }
  328. extern "C" void Android_JNI_WriteAudioBuffer()
  329. {
  330. if (audioBuffer16Bit) {
  331. mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
  332. mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
  333. } else {
  334. mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
  335. mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
  336. }
  337. /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
  338. }
  339. extern "C" void Android_JNI_CloseAudioDevice()
  340. {
  341. int status;
  342. JNIEnv *env;
  343. static bool isAttached = false;
  344. status = mJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4);
  345. if(status < 0) {
  346. LOGE("callback_handler: failed to get JNI environment, assuming native thread");
  347. status = mJavaVM->AttachCurrentThread(&env, NULL);
  348. if(status < 0) {
  349. LOGE("callback_handler: failed to attach current thread");
  350. return;
  351. }
  352. isAttached = true;
  353. }
  354. env->CallStaticVoidMethod(mActivityClass, midAudioQuit);
  355. if (audioBuffer) {
  356. env->DeleteGlobalRef(audioBuffer);
  357. audioBuffer = NULL;
  358. audioBufferPinned = NULL;
  359. }
  360. if (isAttached) {
  361. mJavaVM->DetachCurrentThread();
  362. }
  363. }
  364. // Test for an exception and call SDL_SetError with its detail if one occurs
  365. static bool Android_JNI_ExceptionOccurred()
  366. {
  367. SDL_assert(LocalReferenceHolder::IsActive());
  368. jthrowable exception = mEnv->ExceptionOccurred();
  369. if (exception != NULL) {
  370. jmethodID mid;
  371. // Until this happens most JNI operations have undefined behaviour
  372. mEnv->ExceptionClear();
  373. jclass exceptionClass = mEnv->GetObjectClass(exception);
  374. jclass classClass = mEnv->FindClass("java/lang/Class");
  375. mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
  376. jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
  377. const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
  378. mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
  379. jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
  380. if (exceptionMessage != NULL) {
  381. const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
  382. exceptionMessage, 0);
  383. SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
  384. mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
  385. } else {
  386. SDL_SetError("%s", exceptionNameUTF8);
  387. }
  388. mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
  389. return true;
  390. }
  391. return false;
  392. }
  393. static int Android_JNI_FileOpen(SDL_RWops* ctx)
  394. {
  395. LocalReferenceHolder refs;
  396. int result = 0;
  397. jmethodID mid;
  398. jobject context;
  399. jobject assetManager;
  400. jobject inputStream;
  401. jclass channels;
  402. jobject readableByteChannel;
  403. jstring fileNameJString;
  404. if (!refs.init(mEnv)) {
  405. goto failure;
  406. }
  407. fileNameJString = (jstring)ctx->hidden.androidio.fileName;
  408. // context = SDLActivity.getContext();
  409. mid = mEnv->GetStaticMethodID(mActivityClass,
  410. "getContext","()Landroid/content/Context;");
  411. context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
  412. // assetManager = context.getAssets();
  413. mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
  414. "getAssets", "()Landroid/content/res/AssetManager;");
  415. assetManager = mEnv->CallObjectMethod(context, mid);
  416. // inputStream = assetManager.open(<filename>);
  417. mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
  418. "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
  419. inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
  420. if (Android_JNI_ExceptionOccurred()) {
  421. goto failure;
  422. }
  423. ctx->hidden.androidio.inputStream = inputStream;
  424. ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
  425. // Despite all the visible documentation on [Asset]InputStream claiming
  426. // that the .available() method is not guaranteed to return the entire file
  427. // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
  428. // android/apis/content/ReadAsset.java imply that Android's
  429. // AssetInputStream.available() /will/ always return the total file size
  430. // size = inputStream.available();
  431. mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
  432. "available", "()I");
  433. ctx->hidden.androidio.size = mEnv->CallIntMethod(inputStream, mid);
  434. if (Android_JNI_ExceptionOccurred()) {
  435. goto failure;
  436. }
  437. // readableByteChannel = Channels.newChannel(inputStream);
  438. channels = mEnv->FindClass("java/nio/channels/Channels");
  439. mid = mEnv->GetStaticMethodID(channels,
  440. "newChannel",
  441. "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
  442. readableByteChannel = mEnv->CallStaticObjectMethod(
  443. channels, mid, inputStream);
  444. if (Android_JNI_ExceptionOccurred()) {
  445. goto failure;
  446. }
  447. ctx->hidden.androidio.readableByteChannel = readableByteChannel;
  448. ctx->hidden.androidio.readableByteChannelRef =
  449. mEnv->NewGlobalRef(readableByteChannel);
  450. // Store .read id for reading purposes
  451. mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
  452. "read", "(Ljava/nio/ByteBuffer;)I");
  453. ctx->hidden.androidio.readMethod = mid;
  454. ctx->hidden.androidio.position = 0;
  455. if (false) {
  456. failure:
  457. result = -1;
  458. mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
  459. if(ctx->hidden.androidio.inputStreamRef != NULL) {
  460. mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
  461. }
  462. }
  463. return result;
  464. }
  465. extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
  466. const char* fileName, const char*)
  467. {
  468. LocalReferenceHolder refs;
  469. if (!refs.init(mEnv)) {
  470. return -1;
  471. }
  472. if (!ctx) {
  473. return -1;
  474. }
  475. jstring fileNameJString = mEnv->NewStringUTF(fileName);
  476. ctx->hidden.androidio.fileName = fileNameJString;
  477. ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
  478. ctx->hidden.androidio.inputStreamRef = NULL;
  479. return Android_JNI_FileOpen(ctx);
  480. }
  481. extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
  482. size_t size, size_t maxnum)
  483. {
  484. LocalReferenceHolder refs;
  485. int bytesRemaining = size * maxnum;
  486. int bytesRead = 0;
  487. if (!refs.init(mEnv)) {
  488. return -1;
  489. }
  490. jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannel;
  491. jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
  492. jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
  493. while (bytesRemaining > 0) {
  494. // result = readableByteChannel.read(...);
  495. int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
  496. if (Android_JNI_ExceptionOccurred()) {
  497. return 0;
  498. }
  499. if (result < 0) {
  500. break;
  501. }
  502. bytesRemaining -= result;
  503. bytesRead += result;
  504. ctx->hidden.androidio.position += result;
  505. }
  506. return bytesRead / size;
  507. }
  508. extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
  509. size_t size, size_t num)
  510. {
  511. SDL_SetError("Cannot write to Android package filesystem");
  512. return 0;
  513. }
  514. static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
  515. {
  516. LocalReferenceHolder refs;
  517. int result = 0;
  518. if (!refs.init(mEnv)) {
  519. SDL_SetError("Failed to allocate enough JVM local references");
  520. return -1;
  521. }
  522. if (ctx) {
  523. if (release) {
  524. mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
  525. }
  526. jobject inputStream = (jobject)ctx->hidden.androidio.inputStream;
  527. // inputStream.close();
  528. jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
  529. "close", "()V");
  530. mEnv->CallVoidMethod(inputStream, mid);
  531. mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
  532. mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
  533. if (Android_JNI_ExceptionOccurred()) {
  534. result = -1;
  535. }
  536. if (release) {
  537. SDL_FreeRW(ctx);
  538. }
  539. }
  540. return result;
  541. }
  542. extern "C" long Android_JNI_FileSeek(SDL_RWops* ctx, long offset, int whence)
  543. {
  544. long newPosition;
  545. switch (whence) {
  546. case RW_SEEK_SET:
  547. newPosition = offset;
  548. break;
  549. case RW_SEEK_CUR:
  550. newPosition = ctx->hidden.androidio.position + offset;
  551. break;
  552. case RW_SEEK_END:
  553. newPosition = ctx->hidden.androidio.size + offset;
  554. break;
  555. default:
  556. SDL_SetError("Unknown value for 'whence'");
  557. return -1;
  558. }
  559. if (newPosition < 0) {
  560. newPosition = 0;
  561. }
  562. if (newPosition > ctx->hidden.androidio.size) {
  563. newPosition = ctx->hidden.androidio.size;
  564. }
  565. long movement = newPosition - ctx->hidden.androidio.position;
  566. jobject inputStream = (jobject)ctx->hidden.androidio.inputStream;
  567. if (movement > 0) {
  568. unsigned char buffer[1024];
  569. // The easy case where we're seeking forwards
  570. while (movement > 0) {
  571. long amount = (long) sizeof (buffer);
  572. if (amount > movement) {
  573. amount = movement;
  574. }
  575. size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
  576. if (result <= 0) {
  577. // Failed to read/skip the required amount, so fail
  578. return -1;
  579. }
  580. movement -= result;
  581. }
  582. } else if (movement < 0) {
  583. // We can't seek backwards so we have to reopen the file and seek
  584. // forwards which obviously isn't very efficient
  585. Android_JNI_FileClose(ctx, false);
  586. Android_JNI_FileOpen(ctx);
  587. Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
  588. }
  589. ctx->hidden.androidio.position = newPosition;
  590. return ctx->hidden.androidio.position;
  591. }
  592. extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
  593. {
  594. return Android_JNI_FileClose(ctx, true);
  595. }
  596. #endif /* __ANDROID__ */
  597. /* vi: set ts=4 sw=4 expandtab: */