src/core/android/SDL_android.c
changeset 7501 b27825bb5879
parent 7368 0e12e09df086
child 7514 a9008fa2548a
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/core/android/SDL_android.c	Mon Jul 22 02:51:45 2013 -0700
     1.3 @@ -0,0 +1,1353 @@
     1.4 +/*
     1.5 +  Simple DirectMedia Layer
     1.6 +  Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
     1.7 +
     1.8 +  This software is provided 'as-is', without any express or implied
     1.9 +  warranty.  In no event will the authors be held liable for any damages
    1.10 +  arising from the use of this software.
    1.11 +
    1.12 +  Permission is granted to anyone to use this software for any purpose,
    1.13 +  including commercial applications, and to alter it and redistribute it
    1.14 +  freely, subject to the following restrictions:
    1.15 +
    1.16 +  1. The origin of this software must not be misrepresented; you must not
    1.17 +     claim that you wrote the original software. If you use this software
    1.18 +     in a product, an acknowledgment in the product documentation would be
    1.19 +     appreciated but is not required.
    1.20 +  2. Altered source versions must be plainly marked as such, and must not be
    1.21 +     misrepresented as being the original software.
    1.22 +  3. This notice may not be removed or altered from any source distribution.
    1.23 +*/
    1.24 +#include "SDL_config.h"
    1.25 +#include "SDL_stdinc.h"
    1.26 +#include "SDL_assert.h"
    1.27 +#include "SDL_log.h"
    1.28 +
    1.29 +#ifdef __ANDROID__
    1.30 +
    1.31 +#include "SDL_system.h"
    1.32 +#include "SDL_android.h"
    1.33 +#include <EGL/egl.h>
    1.34 +
    1.35 +#include "../../events/SDL_events_c.h"
    1.36 +#include "../../video/android/SDL_androidkeyboard.h"
    1.37 +#include "../../video/android/SDL_androidtouch.h"
    1.38 +#include "../../video/android/SDL_androidvideo.h"
    1.39 +
    1.40 +#include <android/log.h>
    1.41 +#include <pthread.h>
    1.42 +#include <sys/types.h>
    1.43 +#include <unistd.h>
    1.44 +#define LOG_TAG "SDL_android"
    1.45 +//#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
    1.46 +//#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
    1.47 +#define LOGI(...) do {} while (false)
    1.48 +#define LOGE(...) do {} while (false)
    1.49 +
    1.50 +/* Uncomment this to log messages entering and exiting methods in this file */
    1.51 +//#define DEBUG_JNI
    1.52 +
    1.53 +/* Implemented in audio/android/SDL_androidaudio.c */
    1.54 +extern void Android_RunAudioThread();
    1.55 +
    1.56 +static void Android_JNI_ThreadDestroyed(void*);
    1.57 +
    1.58 +/*******************************************************************************
    1.59 + This file links the Java side of Android with libsdl
    1.60 +*******************************************************************************/
    1.61 +#include <jni.h>
    1.62 +#include <android/log.h>
    1.63 +#include <stdbool.h>
    1.64 +
    1.65 +
    1.66 +/*******************************************************************************
    1.67 +                               Globals
    1.68 +*******************************************************************************/
    1.69 +static pthread_key_t mThreadKey;
    1.70 +static JavaVM* mJavaVM;
    1.71 +
    1.72 +// Main activity
    1.73 +static jclass mActivityClass;
    1.74 +
    1.75 +// method signatures
    1.76 +static jmethodID midCreateGLContext;
    1.77 +static jmethodID midFlipBuffers;
    1.78 +static jmethodID midAudioInit;
    1.79 +static jmethodID midAudioWriteShortBuffer;
    1.80 +static jmethodID midAudioWriteByteBuffer;
    1.81 +static jmethodID midAudioQuit;
    1.82 +
    1.83 +// Accelerometer data storage
    1.84 +static float fLastAccelerometer[3];
    1.85 +static bool bHasNewData;
    1.86 +
    1.87 +/*******************************************************************************
    1.88 +                 Functions called by JNI
    1.89 +*******************************************************************************/
    1.90 +
    1.91 +// Library init
    1.92 +jint JNI_OnLoad(JavaVM* vm, void* reserved)
    1.93 +{
    1.94 +    JNIEnv *env;
    1.95 +    mJavaVM = vm;
    1.96 +    LOGI("JNI_OnLoad called");
    1.97 +    if ((*mJavaVM)->GetEnv(mJavaVM, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
    1.98 +        LOGE("Failed to get the environment using GetEnv()");
    1.99 +        return -1;
   1.100 +    }
   1.101 +    /*
   1.102 +     * Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
   1.103 +     * Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
   1.104 +     */
   1.105 +    if (pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed)) {
   1.106 +        __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing pthread key");
   1.107 +    }
   1.108 +    else {
   1.109 +        Android_JNI_SetupThread();
   1.110 +    }
   1.111 +
   1.112 +    return JNI_VERSION_1_4;
   1.113 +}
   1.114 +
   1.115 +// Called before SDL_main() to initialize JNI bindings
   1.116 +void SDL_Android_Init(JNIEnv* mEnv, jclass cls)
   1.117 +{
   1.118 +    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
   1.119 +
   1.120 +    Android_JNI_SetupThread();
   1.121 +
   1.122 +    mActivityClass = (jclass)((*mEnv)->NewGlobalRef(mEnv, cls));
   1.123 +
   1.124 +    midCreateGLContext = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.125 +                                "createGLContext","(II[I)Z");
   1.126 +    midFlipBuffers = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.127 +                                "flipBuffers","()V");
   1.128 +    midAudioInit = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.129 +                                "audioInit", "(IZZI)V");
   1.130 +    midAudioWriteShortBuffer = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.131 +                                "audioWriteShortBuffer", "([S)V");
   1.132 +    midAudioWriteByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.133 +                                "audioWriteByteBuffer", "([B)V");
   1.134 +    midAudioQuit = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.135 +                                "audioQuit", "()V");
   1.136 +
   1.137 +    bHasNewData = false;
   1.138 +
   1.139 +    if(!midCreateGLContext || !midFlipBuffers || !midAudioInit ||
   1.140 +       !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) {
   1.141 +        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
   1.142 +    }
   1.143 +    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
   1.144 +}
   1.145 +
   1.146 +// Resize
   1.147 +void Java_org_libsdl_app_SDLActivity_onNativeResize(
   1.148 +                                    JNIEnv* env, jclass jcls,
   1.149 +                                    jint width, jint height, jint format)
   1.150 +{
   1.151 +    Android_SetScreenResolution(width, height, format);
   1.152 +}
   1.153 +
   1.154 +// Keydown
   1.155 +void Java_org_libsdl_app_SDLActivity_onNativeKeyDown(
   1.156 +                                    JNIEnv* env, jclass jcls, jint keycode)
   1.157 +{
   1.158 +    Android_OnKeyDown(keycode);
   1.159 +}
   1.160 +
   1.161 +// Keyup
   1.162 +void Java_org_libsdl_app_SDLActivity_onNativeKeyUp(
   1.163 +                                    JNIEnv* env, jclass jcls, jint keycode)
   1.164 +{
   1.165 +    Android_OnKeyUp(keycode);
   1.166 +}
   1.167 +
   1.168 +// Touch
   1.169 +void Java_org_libsdl_app_SDLActivity_onNativeTouch(
   1.170 +                                    JNIEnv* env, jclass jcls,
   1.171 +                                    jint touch_device_id_in, jint pointer_finger_id_in,
   1.172 +                                    jint action, jfloat x, jfloat y, jfloat p)
   1.173 +{
   1.174 +    Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p);
   1.175 +}
   1.176 +
   1.177 +// Accelerometer
   1.178 +void Java_org_libsdl_app_SDLActivity_onNativeAccel(
   1.179 +                                    JNIEnv* env, jclass jcls,
   1.180 +                                    jfloat x, jfloat y, jfloat z)
   1.181 +{
   1.182 +    fLastAccelerometer[0] = x;
   1.183 +    fLastAccelerometer[1] = y;
   1.184 +    fLastAccelerometer[2] = z;
   1.185 +    bHasNewData = true;
   1.186 +}
   1.187 +
   1.188 +// Low memory
   1.189 +void Java_org_libsdl_app_SDLActivity_nativeLowMemory(
   1.190 +                                    JNIEnv* env, jclass cls)
   1.191 +{
   1.192 +    SDL_SendAppEvent(SDL_APP_LOWMEMORY);
   1.193 +}
   1.194 +
   1.195 +// Quit
   1.196 +void Java_org_libsdl_app_SDLActivity_nativeQuit(
   1.197 +                                    JNIEnv* env, jclass cls)
   1.198 +{
   1.199 +    // Inject a SDL_QUIT event
   1.200 +    SDL_SendQuit();
   1.201 +    SDL_SendAppEvent(SDL_APP_TERMINATING);
   1.202 +}
   1.203 +
   1.204 +// Pause
   1.205 +void Java_org_libsdl_app_SDLActivity_nativePause(
   1.206 +                                    JNIEnv* env, jclass cls)
   1.207 +{
   1.208 +    if (Android_Window) {
   1.209 +        /* Signal the pause semaphore so the event loop knows to pause and (optionally) block itself */
   1.210 +        if (!SDL_SemValue(Android_PauseSem)) SDL_SemPost(Android_PauseSem);
   1.211 +        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
   1.212 +        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
   1.213 +    }
   1.214 +
   1.215 +    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativePause()");
   1.216 +    SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
   1.217 +    SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
   1.218 +}
   1.219 +
   1.220 +// Resume
   1.221 +void Java_org_libsdl_app_SDLActivity_nativeResume(
   1.222 +                                    JNIEnv* env, jclass cls)
   1.223 +{
   1.224 +    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeResume()");
   1.225 +    SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
   1.226 +    SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
   1.227 +
   1.228 +    if (Android_Window) {
   1.229 +        /* Signal the resume semaphore so the event loop knows to resume and restore the GL Context
   1.230 +         * We can't restore the GL Context here because it needs to be done on the SDL main thread
   1.231 +         * and this function will be called from the Java thread instead.
   1.232 +         */
   1.233 +        if (!SDL_SemValue(Android_ResumeSem)) SDL_SemPost(Android_ResumeSem);
   1.234 +        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
   1.235 +        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0);
   1.236 +    }
   1.237 +}
   1.238 +
   1.239 +void Java_org_libsdl_app_SDLActivity_nativeRunAudioThread(
   1.240 +                                    JNIEnv* env, jclass cls)
   1.241 +{
   1.242 +    /* This is the audio thread, with a different environment */
   1.243 +    Android_JNI_SetupThread();
   1.244 +
   1.245 +    Android_RunAudioThread();
   1.246 +}
   1.247 +
   1.248 +void Java_org_libsdl_app_SDLInputConnection_nativeCommitText(
   1.249 +                                    JNIEnv* env, jclass cls,
   1.250 +                                    jstring text, jint newCursorPosition)
   1.251 +{
   1.252 +    const char *utftext = (*env)->GetStringUTFChars(env, text, NULL);
   1.253 +
   1.254 +    SDL_SendKeyboardText(utftext);
   1.255 +
   1.256 +    (*env)->ReleaseStringUTFChars(env, text, utftext);
   1.257 +}
   1.258 +
   1.259 +void Java_org_libsdl_app_SDLInputConnection_nativeSetComposingText(
   1.260 +                                    JNIEnv* env, jclass cls,
   1.261 +                                    jstring text, jint newCursorPosition)
   1.262 +{
   1.263 +    const char *utftext = (*env)->GetStringUTFChars(env, text, NULL);
   1.264 +
   1.265 +    SDL_SendEditingText(utftext, 0, 0);
   1.266 +
   1.267 +    (*env)->ReleaseStringUTFChars(env, text, utftext);
   1.268 +}
   1.269 +
   1.270 +
   1.271 +
   1.272 +/*******************************************************************************
   1.273 +             Functions called by SDL into Java
   1.274 +*******************************************************************************/
   1.275 +
   1.276 +static int s_active = 0;
   1.277 +struct LocalReferenceHolder
   1.278 +{
   1.279 +    JNIEnv *m_env;
   1.280 +    const char *m_func;
   1.281 +};
   1.282 +
   1.283 +static struct LocalReferenceHolder LocalReferenceHolder_Setup(const char *func)
   1.284 +{
   1.285 +    struct LocalReferenceHolder refholder;
   1.286 +    refholder.m_env = NULL;
   1.287 +    refholder.m_func = func;
   1.288 +#ifdef DEBUG_JNI
   1.289 +    SDL_Log("Entering function %s", func);
   1.290 +#endif
   1.291 +    return refholder;
   1.292 +}
   1.293 +
   1.294 +static SDL_bool LocalReferenceHolder_Init(struct LocalReferenceHolder *refholder, JNIEnv *env)
   1.295 +{
   1.296 +    const int capacity = 16;
   1.297 +    if ((*env)->PushLocalFrame(env, capacity) < 0) {
   1.298 +        SDL_SetError("Failed to allocate enough JVM local references");
   1.299 +        return false;
   1.300 +    }
   1.301 +    ++s_active;
   1.302 +    refholder->m_env = env;
   1.303 +    return SDL_TRUE;
   1.304 +}
   1.305 +
   1.306 +static void LocalReferenceHolder_Cleanup(struct LocalReferenceHolder *refholder)
   1.307 +{
   1.308 +#ifdef DEBUG_JNI
   1.309 +    SDL_Log("Leaving function %s", refholder->m_func);
   1.310 +#endif
   1.311 +    if (refholder->m_env) {
   1.312 +        JNIEnv* env = refholder->m_env;
   1.313 +        (*env)->PopLocalFrame(env, NULL);
   1.314 +        --s_active;
   1.315 +    }
   1.316 +}
   1.317 +
   1.318 +static SDL_bool LocalReferenceHolder_IsActive()
   1.319 +{
   1.320 +    return s_active > 0;    
   1.321 +}
   1.322 +
   1.323 +
   1.324 +SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion,
   1.325 +                                int red, int green, int blue, int alpha,
   1.326 +                                int buffer, int depth, int stencil,
   1.327 +                                int buffers, int samples)
   1.328 +{
   1.329 +    JNIEnv *env = Android_JNI_GetEnv();
   1.330 +
   1.331 +    jint attribs[] = {
   1.332 +        EGL_RED_SIZE, red,
   1.333 +        EGL_GREEN_SIZE, green,
   1.334 +        EGL_BLUE_SIZE, blue,
   1.335 +        EGL_ALPHA_SIZE, alpha,
   1.336 +        EGL_BUFFER_SIZE, buffer,
   1.337 +        EGL_DEPTH_SIZE, depth,
   1.338 +        EGL_STENCIL_SIZE, stencil,
   1.339 +        EGL_SAMPLE_BUFFERS, buffers,
   1.340 +        EGL_SAMPLES, samples,
   1.341 +        EGL_RENDERABLE_TYPE, (majorVersion == 1 ? EGL_OPENGL_ES_BIT : EGL_OPENGL_ES2_BIT),
   1.342 +        EGL_NONE
   1.343 +    };
   1.344 +    int len = SDL_arraysize(attribs);
   1.345 +
   1.346 +    jintArray array;
   1.347 +
   1.348 +    array = (*env)->NewIntArray(env, len);
   1.349 +    (*env)->SetIntArrayRegion(env, array, 0, len, attribs);
   1.350 +
   1.351 +    jboolean success = (*env)->CallStaticBooleanMethod(env, mActivityClass, midCreateGLContext, majorVersion, minorVersion, array);
   1.352 +
   1.353 +    (*env)->DeleteLocalRef(env, array);
   1.354 +
   1.355 +    return success ? SDL_TRUE : SDL_FALSE;
   1.356 +}
   1.357 +
   1.358 +void Android_JNI_SwapWindow()
   1.359 +{
   1.360 +    JNIEnv *mEnv = Android_JNI_GetEnv();
   1.361 +    (*mEnv)->CallStaticVoidMethod(mEnv, mActivityClass, midFlipBuffers);
   1.362 +}
   1.363 +
   1.364 +void Android_JNI_SetActivityTitle(const char *title)
   1.365 +{
   1.366 +    jmethodID mid;
   1.367 +    JNIEnv *mEnv = Android_JNI_GetEnv();
   1.368 +    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,"setActivityTitle","(Ljava/lang/String;)Z");
   1.369 +    if (mid) {
   1.370 +        jstring jtitle = (jstring)((*mEnv)->NewStringUTF(mEnv, title));
   1.371 +        (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, mid, jtitle);
   1.372 +        (*mEnv)->DeleteLocalRef(mEnv, jtitle);
   1.373 +    }
   1.374 +}
   1.375 +
   1.376 +SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
   1.377 +{
   1.378 +    int i;
   1.379 +    SDL_bool retval = SDL_FALSE;
   1.380 +
   1.381 +    if (bHasNewData) {
   1.382 +        for (i = 0; i < 3; ++i) {
   1.383 +            values[i] = fLastAccelerometer[i];
   1.384 +        }
   1.385 +        bHasNewData = false;
   1.386 +        retval = SDL_TRUE;
   1.387 +    }
   1.388 +
   1.389 +    return retval;
   1.390 +}
   1.391 +
   1.392 +static void Android_JNI_ThreadDestroyed(void* value) {
   1.393 +    /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
   1.394 +    JNIEnv *env = (JNIEnv*) value;
   1.395 +    if (env != NULL) {
   1.396 +        (*mJavaVM)->DetachCurrentThread(mJavaVM);
   1.397 +        pthread_setspecific(mThreadKey, NULL);
   1.398 +    }
   1.399 +}
   1.400 +
   1.401 +JNIEnv* Android_JNI_GetEnv(void) {
   1.402 +    /* From http://developer.android.com/guide/practices/jni.html
   1.403 +     * All threads are Linux threads, scheduled by the kernel.
   1.404 +     * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
   1.405 +     * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
   1.406 +     * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
   1.407 +     * and cannot make JNI calls.
   1.408 +     * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
   1.409 +     * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
   1.410 +     * is a no-op.
   1.411 +     * Note: You can call this function any number of times for the same thread, there's no harm in it
   1.412 +     */
   1.413 +
   1.414 +    JNIEnv *env;
   1.415 +    int status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
   1.416 +    if(status < 0) {
   1.417 +        LOGE("failed to attach current thread");
   1.418 +        return 0;
   1.419 +    }
   1.420 +
   1.421 +    return env;
   1.422 +}
   1.423 +
   1.424 +int Android_JNI_SetupThread(void) {
   1.425 +    /* From http://developer.android.com/guide/practices/jni.html
   1.426 +     * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
   1.427 +     * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
   1.428 +     * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
   1.429 +     * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
   1.430 +     * Note: The destructor is not called unless the stored value is != NULL
   1.431 +     * Note: You can call this function any number of times for the same thread, there's no harm in it
   1.432 +     *       (except for some lost CPU cycles)
   1.433 +     */
   1.434 +    JNIEnv *env = Android_JNI_GetEnv();
   1.435 +    pthread_setspecific(mThreadKey, (void*) env);
   1.436 +    return 1;
   1.437 +}
   1.438 +
   1.439 +//
   1.440 +// Audio support
   1.441 +//
   1.442 +static jboolean audioBuffer16Bit = JNI_FALSE;
   1.443 +static jboolean audioBufferStereo = JNI_FALSE;
   1.444 +static jobject audioBuffer = NULL;
   1.445 +static void* audioBufferPinned = NULL;
   1.446 +
   1.447 +int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
   1.448 +{
   1.449 +    int audioBufferFrames;
   1.450 +
   1.451 +    JNIEnv *env = Android_JNI_GetEnv();
   1.452 +
   1.453 +    if (!env) {
   1.454 +        LOGE("callback_handler: failed to attach current thread");
   1.455 +    }
   1.456 +    Android_JNI_SetupThread();
   1.457 +
   1.458 +    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
   1.459 +    audioBuffer16Bit = is16Bit;
   1.460 +    audioBufferStereo = channelCount > 1;
   1.461 +
   1.462 +    (*env)->CallStaticVoidMethod(env, mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
   1.463 +
   1.464 +    /* Allocating the audio buffer from the Java side and passing it as the return value for audioInit no longer works on
   1.465 +     * Android >= 4.2 due to a "stale global reference" error. So now we allocate this buffer directly from this side. */
   1.466 +
   1.467 +    if (is16Bit) {
   1.468 +        jshortArray audioBufferLocal = (*env)->NewShortArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
   1.469 +        if (audioBufferLocal) {
   1.470 +            audioBuffer = (*env)->NewGlobalRef(env, audioBufferLocal);
   1.471 +            (*env)->DeleteLocalRef(env, audioBufferLocal);
   1.472 +        }
   1.473 +    }
   1.474 +    else {
   1.475 +        jbyteArray audioBufferLocal = (*env)->NewByteArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
   1.476 +        if (audioBufferLocal) {
   1.477 +            audioBuffer = (*env)->NewGlobalRef(env, audioBufferLocal);
   1.478 +            (*env)->DeleteLocalRef(env, audioBufferLocal);
   1.479 +        }
   1.480 +    }
   1.481 +
   1.482 +    if (audioBuffer == NULL) {
   1.483 +        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer!");
   1.484 +        return 0;
   1.485 +    }
   1.486 +
   1.487 +    jboolean isCopy = JNI_FALSE;
   1.488 +    if (audioBuffer16Bit) {
   1.489 +        audioBufferPinned = (*env)->GetShortArrayElements(env, (jshortArray)audioBuffer, &isCopy);
   1.490 +        audioBufferFrames = (*env)->GetArrayLength(env, (jshortArray)audioBuffer);
   1.491 +    } else {
   1.492 +        audioBufferPinned = (*env)->GetByteArrayElements(env, (jbyteArray)audioBuffer, &isCopy);
   1.493 +        audioBufferFrames = (*env)->GetArrayLength(env, (jbyteArray)audioBuffer);
   1.494 +    }
   1.495 +    if (audioBufferStereo) {
   1.496 +        audioBufferFrames /= 2;
   1.497 +    }
   1.498 +
   1.499 +    return audioBufferFrames;
   1.500 +}
   1.501 +
   1.502 +void * Android_JNI_GetAudioBuffer()
   1.503 +{
   1.504 +    return audioBufferPinned;
   1.505 +}
   1.506 +
   1.507 +void Android_JNI_WriteAudioBuffer()
   1.508 +{
   1.509 +    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
   1.510 +
   1.511 +    if (audioBuffer16Bit) {
   1.512 +        (*mAudioEnv)->ReleaseShortArrayElements(mAudioEnv, (jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
   1.513 +        (*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
   1.514 +    } else {
   1.515 +        (*mAudioEnv)->ReleaseByteArrayElements(mAudioEnv, (jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
   1.516 +        (*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
   1.517 +    }
   1.518 +
   1.519 +    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
   1.520 +}
   1.521 +
   1.522 +void Android_JNI_CloseAudioDevice()
   1.523 +{
   1.524 +    JNIEnv *env = Android_JNI_GetEnv();
   1.525 +
   1.526 +    (*env)->CallStaticVoidMethod(env, mActivityClass, midAudioQuit);
   1.527 +
   1.528 +    if (audioBuffer) {
   1.529 +        (*env)->DeleteGlobalRef(env, audioBuffer);
   1.530 +        audioBuffer = NULL;
   1.531 +        audioBufferPinned = NULL;
   1.532 +    }
   1.533 +}
   1.534 +
   1.535 +// Test for an exception and call SDL_SetError with its detail if one occurs
   1.536 +// If optional parameter silent is truthy then SDL_SetError() is not called.
   1.537 +static bool Android_JNI_ExceptionOccurred(bool silent)
   1.538 +{
   1.539 +    SDL_assert(LocalReferenceHolder_IsActive());
   1.540 +    JNIEnv *mEnv = Android_JNI_GetEnv();
   1.541 +
   1.542 +    jthrowable exception = (*mEnv)->ExceptionOccurred(mEnv);
   1.543 +    if (exception != NULL) {
   1.544 +        jmethodID mid;
   1.545 +
   1.546 +        // Until this happens most JNI operations have undefined behaviour
   1.547 +        (*mEnv)->ExceptionClear(mEnv);
   1.548 +
   1.549 +        if (!silent) {
   1.550 +            jclass exceptionClass = (*mEnv)->GetObjectClass(mEnv, exception);
   1.551 +            jclass classClass = (*mEnv)->FindClass(mEnv, "java/lang/Class");
   1.552 +
   1.553 +            mid = (*mEnv)->GetMethodID(mEnv, classClass, "getName", "()Ljava/lang/String;");
   1.554 +            jstring exceptionName = (jstring)(*mEnv)->CallObjectMethod(mEnv, exceptionClass, mid);
   1.555 +            const char* exceptionNameUTF8 = (*mEnv)->GetStringUTFChars(mEnv, exceptionName, 0);
   1.556 +
   1.557 +            mid = (*mEnv)->GetMethodID(mEnv, exceptionClass, "getMessage", "()Ljava/lang/String;");
   1.558 +            jstring exceptionMessage = (jstring)(*mEnv)->CallObjectMethod(mEnv, exception, mid);
   1.559 +
   1.560 +            if (exceptionMessage != NULL) {
   1.561 +                const char* exceptionMessageUTF8 = (*mEnv)->GetStringUTFChars(mEnv, exceptionMessage, 0);
   1.562 +                SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
   1.563 +                (*mEnv)->ReleaseStringUTFChars(mEnv, exceptionMessage, exceptionMessageUTF8);
   1.564 +            } else {
   1.565 +                SDL_SetError("%s", exceptionNameUTF8);
   1.566 +            }
   1.567 +
   1.568 +            (*mEnv)->ReleaseStringUTFChars(mEnv, exceptionName, exceptionNameUTF8);
   1.569 +        }
   1.570 +
   1.571 +        return true;
   1.572 +    }
   1.573 +
   1.574 +    return false;
   1.575 +}
   1.576 +
   1.577 +static int Internal_Android_JNI_FileOpen(SDL_RWops* ctx)
   1.578 +{
   1.579 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
   1.580 +
   1.581 +    int result = 0;
   1.582 +
   1.583 +    jmethodID mid;
   1.584 +    jobject context;
   1.585 +    jobject assetManager;
   1.586 +    jobject inputStream;
   1.587 +    jclass channels;
   1.588 +    jobject readableByteChannel;
   1.589 +    jstring fileNameJString;
   1.590 +    jobject fd;
   1.591 +    jclass fdCls;
   1.592 +    jfieldID descriptor;
   1.593 +
   1.594 +    JNIEnv *mEnv = Android_JNI_GetEnv();
   1.595 +    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
   1.596 +        goto failure;
   1.597 +    }
   1.598 +
   1.599 +    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
   1.600 +    ctx->hidden.androidio.position = 0;
   1.601 +
   1.602 +    // context = SDLActivity.getContext();
   1.603 +    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
   1.604 +            "getContext","()Landroid/content/Context;");
   1.605 +    context = (*mEnv)->CallStaticObjectMethod(mEnv, mActivityClass, mid);
   1.606 +
   1.607 +
   1.608 +    // assetManager = context.getAssets();
   1.609 +    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, context),
   1.610 +            "getAssets", "()Landroid/content/res/AssetManager;");
   1.611 +    assetManager = (*mEnv)->CallObjectMethod(mEnv, context, mid);
   1.612 +
   1.613 +    /* First let's try opening the file to obtain an AssetFileDescriptor.
   1.614 +    * This method reads the files directly from the APKs using standard *nix calls
   1.615 +    */
   1.616 +    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, assetManager), "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;");
   1.617 +    inputStream = (*mEnv)->CallObjectMethod(mEnv, assetManager, mid, fileNameJString);
   1.618 +    if (Android_JNI_ExceptionOccurred(true)) {
   1.619 +        goto fallback;
   1.620 +    }
   1.621 +
   1.622 +    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getStartOffset", "()J");
   1.623 +    ctx->hidden.androidio.offset = (*mEnv)->CallLongMethod(mEnv, inputStream, mid);
   1.624 +    if (Android_JNI_ExceptionOccurred(true)) {
   1.625 +        goto fallback;
   1.626 +    }
   1.627 +
   1.628 +    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getDeclaredLength", "()J");
   1.629 +    ctx->hidden.androidio.size = (*mEnv)->CallLongMethod(mEnv, inputStream, mid);
   1.630 +    if (Android_JNI_ExceptionOccurred(true)) {
   1.631 +        goto fallback;
   1.632 +    }
   1.633 +
   1.634 +    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getFileDescriptor", "()Ljava/io/FileDescriptor;");
   1.635 +    fd = (*mEnv)->CallObjectMethod(mEnv, inputStream, mid);
   1.636 +    fdCls = (*mEnv)->GetObjectClass(mEnv, fd);
   1.637 +    descriptor = (*mEnv)->GetFieldID(mEnv, fdCls, "descriptor", "I");
   1.638 +    ctx->hidden.androidio.fd = (*mEnv)->GetIntField(mEnv, fd, descriptor);
   1.639 +    ctx->hidden.androidio.assetFileDescriptorRef = (*mEnv)->NewGlobalRef(mEnv, inputStream);
   1.640 +
   1.641 +    // Seek to the correct offset in the file.
   1.642 +    lseek(ctx->hidden.androidio.fd, (off_t)ctx->hidden.androidio.offset, SEEK_SET);
   1.643 +
   1.644 +    if (false) {
   1.645 +fallback:
   1.646 +        // Disabled log message because of spam on the Nexus 7
   1.647 +        //__android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file");
   1.648 +
   1.649 +        /* Try the old method using InputStream */
   1.650 +        ctx->hidden.androidio.assetFileDescriptorRef = NULL;
   1.651 +
   1.652 +        // inputStream = assetManager.open(<filename>);
   1.653 +        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, assetManager),
   1.654 +                "open", "(Ljava/lang/String;I)Ljava/io/InputStream;");
   1.655 +        inputStream = (*mEnv)->CallObjectMethod(mEnv, assetManager, mid, fileNameJString, 1 /*ACCESS_RANDOM*/);
   1.656 +        if (Android_JNI_ExceptionOccurred(false)) {
   1.657 +            goto failure;
   1.658 +        }
   1.659 +
   1.660 +        ctx->hidden.androidio.inputStreamRef = (*mEnv)->NewGlobalRef(mEnv, inputStream);
   1.661 +
   1.662 +        // Despite all the visible documentation on [Asset]InputStream claiming
   1.663 +        // that the .available() method is not guaranteed to return the entire file
   1.664 +        // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
   1.665 +        // android/apis/content/ReadAsset.java imply that Android's
   1.666 +        // AssetInputStream.available() /will/ always return the total file size
   1.667 +
   1.668 +        // size = inputStream.available();
   1.669 +        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
   1.670 +                "available", "()I");
   1.671 +        ctx->hidden.androidio.size = (long)(*mEnv)->CallIntMethod(mEnv, inputStream, mid);
   1.672 +        if (Android_JNI_ExceptionOccurred(false)) {
   1.673 +            goto failure;
   1.674 +        }
   1.675 +
   1.676 +        // readableByteChannel = Channels.newChannel(inputStream);
   1.677 +        channels = (*mEnv)->FindClass(mEnv, "java/nio/channels/Channels");
   1.678 +        mid = (*mEnv)->GetStaticMethodID(mEnv, channels,
   1.679 +                "newChannel",
   1.680 +                "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
   1.681 +        readableByteChannel = (*mEnv)->CallStaticObjectMethod(
   1.682 +                mEnv, channels, mid, inputStream);
   1.683 +        if (Android_JNI_ExceptionOccurred(false)) {
   1.684 +            goto failure;
   1.685 +        }
   1.686 +
   1.687 +        ctx->hidden.androidio.readableByteChannelRef =
   1.688 +            (*mEnv)->NewGlobalRef(mEnv, readableByteChannel);
   1.689 +
   1.690 +        // Store .read id for reading purposes
   1.691 +        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, readableByteChannel),
   1.692 +                "read", "(Ljava/nio/ByteBuffer;)I");
   1.693 +        ctx->hidden.androidio.readMethod = mid;
   1.694 +    }
   1.695 +
   1.696 +    if (false) {
   1.697 +failure:
   1.698 +        result = -1;
   1.699 +
   1.700 +        (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.fileNameRef);
   1.701 +
   1.702 +        if(ctx->hidden.androidio.inputStreamRef != NULL) {
   1.703 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.inputStreamRef);
   1.704 +        }
   1.705 +
   1.706 +        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
   1.707 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.readableByteChannelRef);
   1.708 +        }
   1.709 +
   1.710 +        if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) {
   1.711 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.assetFileDescriptorRef);
   1.712 +        }
   1.713 +
   1.714 +    }
   1.715 +    
   1.716 +    LocalReferenceHolder_Cleanup(&refs);
   1.717 +    return result;
   1.718 +}
   1.719 +
   1.720 +int Android_JNI_FileOpen(SDL_RWops* ctx,
   1.721 +        const char* fileName, const char* mode)
   1.722 +{
   1.723 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
   1.724 +    JNIEnv *mEnv = Android_JNI_GetEnv();
   1.725 +    int retval;
   1.726 +
   1.727 +    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
   1.728 +        LocalReferenceHolder_Cleanup(&refs);        
   1.729 +        return -1;
   1.730 +    }
   1.731 +
   1.732 +    if (!ctx) {
   1.733 +        LocalReferenceHolder_Cleanup(&refs);
   1.734 +        return -1;
   1.735 +    }
   1.736 +
   1.737 +    jstring fileNameJString = (*mEnv)->NewStringUTF(mEnv, fileName);
   1.738 +    ctx->hidden.androidio.fileNameRef = (*mEnv)->NewGlobalRef(mEnv, fileNameJString);
   1.739 +    ctx->hidden.androidio.inputStreamRef = NULL;
   1.740 +    ctx->hidden.androidio.readableByteChannelRef = NULL;
   1.741 +    ctx->hidden.androidio.readMethod = NULL;
   1.742 +    ctx->hidden.androidio.assetFileDescriptorRef = NULL;
   1.743 +
   1.744 +    retval = Internal_Android_JNI_FileOpen(ctx);
   1.745 +    LocalReferenceHolder_Cleanup(&refs);
   1.746 +    return retval;
   1.747 +}
   1.748 +
   1.749 +size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
   1.750 +        size_t size, size_t maxnum)
   1.751 +{
   1.752 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
   1.753 +
   1.754 +    if (ctx->hidden.androidio.assetFileDescriptorRef) {
   1.755 +        size_t bytesMax = size * maxnum;
   1.756 +        if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && ctx->hidden.androidio.position + bytesMax > ctx->hidden.androidio.size) {
   1.757 +            bytesMax = ctx->hidden.androidio.size - ctx->hidden.androidio.position;
   1.758 +        }
   1.759 +        size_t result = read(ctx->hidden.androidio.fd, buffer, bytesMax );
   1.760 +        if (result > 0) {
   1.761 +            ctx->hidden.androidio.position += result;
   1.762 +            LocalReferenceHolder_Cleanup(&refs);
   1.763 +            return result / size;
   1.764 +        }
   1.765 +        LocalReferenceHolder_Cleanup(&refs);
   1.766 +        return 0;
   1.767 +    } else {
   1.768 +        jlong bytesRemaining = (jlong) (size * maxnum);
   1.769 +        jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
   1.770 +        int bytesRead = 0;
   1.771 +
   1.772 +        /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
   1.773 +        if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
   1.774 +
   1.775 +        JNIEnv *mEnv = Android_JNI_GetEnv();
   1.776 +        if (!LocalReferenceHolder_Init(&refs, mEnv)) {
   1.777 +            LocalReferenceHolder_Cleanup(&refs);            
   1.778 +            return 0;
   1.779 +        }
   1.780 +
   1.781 +        jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
   1.782 +        jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
   1.783 +        jobject byteBuffer = (*mEnv)->NewDirectByteBuffer(mEnv, buffer, bytesRemaining);
   1.784 +
   1.785 +        while (bytesRemaining > 0) {
   1.786 +            // result = readableByteChannel.read(...);
   1.787 +            int result = (*mEnv)->CallIntMethod(mEnv, readableByteChannel, readMethod, byteBuffer);
   1.788 +
   1.789 +            if (Android_JNI_ExceptionOccurred(false)) {
   1.790 +                LocalReferenceHolder_Cleanup(&refs);            
   1.791 +                return 0;
   1.792 +            }
   1.793 +
   1.794 +            if (result < 0) {
   1.795 +                break;
   1.796 +            }
   1.797 +
   1.798 +            bytesRemaining -= result;
   1.799 +            bytesRead += result;
   1.800 +            ctx->hidden.androidio.position += result;
   1.801 +        }
   1.802 +        LocalReferenceHolder_Cleanup(&refs);                    
   1.803 +        return bytesRead / size;
   1.804 +    }
   1.805 +    LocalReferenceHolder_Cleanup(&refs);            
   1.806 +}
   1.807 +
   1.808 +size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
   1.809 +        size_t size, size_t num)
   1.810 +{
   1.811 +    SDL_SetError("Cannot write to Android package filesystem");
   1.812 +    return 0;
   1.813 +}
   1.814 +
   1.815 +static int Internal_Android_JNI_FileClose(SDL_RWops* ctx, bool release)
   1.816 +{
   1.817 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
   1.818 +
   1.819 +    int result = 0;
   1.820 +    JNIEnv *mEnv = Android_JNI_GetEnv();
   1.821 +
   1.822 +    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
   1.823 +        LocalReferenceHolder_Cleanup(&refs);
   1.824 +        return SDL_SetError("Failed to allocate enough JVM local references");
   1.825 +    }
   1.826 +
   1.827 +    if (ctx) {
   1.828 +        if (release) {
   1.829 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.fileNameRef);
   1.830 +        }
   1.831 +
   1.832 +        if (ctx->hidden.androidio.assetFileDescriptorRef) {
   1.833 +            jobject inputStream = (jobject)ctx->hidden.androidio.assetFileDescriptorRef;
   1.834 +            jmethodID mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
   1.835 +                    "close", "()V");
   1.836 +            (*mEnv)->CallVoidMethod(mEnv, inputStream, mid);
   1.837 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.assetFileDescriptorRef);
   1.838 +            if (Android_JNI_ExceptionOccurred(false)) {
   1.839 +                result = -1;
   1.840 +            }
   1.841 +        }
   1.842 +        else {
   1.843 +            jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
   1.844 +
   1.845 +            // inputStream.close();
   1.846 +            jmethodID mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
   1.847 +                    "close", "()V");
   1.848 +            (*mEnv)->CallVoidMethod(mEnv, inputStream, mid);
   1.849 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.inputStreamRef);
   1.850 +            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.readableByteChannelRef);
   1.851 +            if (Android_JNI_ExceptionOccurred(false)) {
   1.852 +                result = -1;
   1.853 +            }
   1.854 +        }
   1.855 +
   1.856 +        if (release) {
   1.857 +            SDL_FreeRW(ctx);
   1.858 +        }
   1.859 +    }
   1.860 +
   1.861 +    LocalReferenceHolder_Cleanup(&refs);
   1.862 +    return result;
   1.863 +}
   1.864 +
   1.865 +
   1.866 +Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
   1.867 +{
   1.868 +    return ctx->hidden.androidio.size;
   1.869 +}
   1.870 +
   1.871 +Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
   1.872 +{
   1.873 +    if (ctx->hidden.androidio.assetFileDescriptorRef) {
   1.874 +        switch (whence) {
   1.875 +            case RW_SEEK_SET:
   1.876 +                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
   1.877 +                offset += ctx->hidden.androidio.offset;
   1.878 +                break;
   1.879 +            case RW_SEEK_CUR:
   1.880 +                offset += ctx->hidden.androidio.position;
   1.881 +                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
   1.882 +                offset += ctx->hidden.androidio.offset;
   1.883 +                break;
   1.884 +            case RW_SEEK_END:
   1.885 +                offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset;
   1.886 +                break;
   1.887 +            default:
   1.888 +                return SDL_SetError("Unknown value for 'whence'");
   1.889 +        }
   1.890 +        whence = SEEK_SET;
   1.891 +
   1.892 +        off_t ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET);
   1.893 +        if (ret == -1) return -1;
   1.894 +        ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset;
   1.895 +    } else {
   1.896 +        Sint64 newPosition;
   1.897 +
   1.898 +        switch (whence) {
   1.899 +            case RW_SEEK_SET:
   1.900 +                newPosition = offset;
   1.901 +                break;
   1.902 +            case RW_SEEK_CUR:
   1.903 +                newPosition = ctx->hidden.androidio.position + offset;
   1.904 +                break;
   1.905 +            case RW_SEEK_END:
   1.906 +                newPosition = ctx->hidden.androidio.size + offset;
   1.907 +                break;
   1.908 +            default:
   1.909 +                return SDL_SetError("Unknown value for 'whence'");
   1.910 +        }
   1.911 +
   1.912 +        /* Validate the new position */
   1.913 +        if (newPosition < 0) {
   1.914 +            return SDL_Error(SDL_EFSEEK);
   1.915 +        }
   1.916 +        if (newPosition > ctx->hidden.androidio.size) {
   1.917 +            newPosition = ctx->hidden.androidio.size;
   1.918 +        }
   1.919 +
   1.920 +        Sint64 movement = newPosition - ctx->hidden.androidio.position;
   1.921 +        if (movement > 0) {
   1.922 +            unsigned char buffer[4096];
   1.923 +
   1.924 +            // The easy case where we're seeking forwards
   1.925 +            while (movement > 0) {
   1.926 +                Sint64 amount = sizeof (buffer);
   1.927 +                if (amount > movement) {
   1.928 +                    amount = movement;
   1.929 +                }
   1.930 +                size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
   1.931 +                if (result <= 0) {
   1.932 +                    // Failed to read/skip the required amount, so fail
   1.933 +                    return -1;
   1.934 +                }
   1.935 +
   1.936 +                movement -= result;
   1.937 +            }
   1.938 +
   1.939 +        } else if (movement < 0) {
   1.940 +            // We can't seek backwards so we have to reopen the file and seek
   1.941 +            // forwards which obviously isn't very efficient
   1.942 +            Internal_Android_JNI_FileClose(ctx, false);
   1.943 +            Internal_Android_JNI_FileOpen(ctx);
   1.944 +            Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
   1.945 +        }
   1.946 +    }
   1.947 +
   1.948 +    return ctx->hidden.androidio.position;
   1.949 +
   1.950 +}
   1.951 +
   1.952 +int Android_JNI_FileClose(SDL_RWops* ctx)
   1.953 +{
   1.954 +    return Internal_Android_JNI_FileClose(ctx, true);
   1.955 +}
   1.956 +
   1.957 +// returns a new global reference which needs to be released later
   1.958 +static jobject Android_JNI_GetSystemServiceObject(const char* name)
   1.959 +{
   1.960 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
   1.961 +    JNIEnv* env = Android_JNI_GetEnv();
   1.962 +    jobject retval = NULL;
   1.963 +
   1.964 +    if (!LocalReferenceHolder_Init(&refs, env)) {
   1.965 +        LocalReferenceHolder_Cleanup(&refs);
   1.966 +        return NULL;
   1.967 +    }
   1.968 +
   1.969 +    jstring service = (*env)->NewStringUTF(env, name);
   1.970 +
   1.971 +    jmethodID mid;
   1.972 +
   1.973 +    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
   1.974 +    jobject context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
   1.975 +
   1.976 +    mid = (*env)->GetMethodID(env, mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
   1.977 +    jobject manager = (*env)->CallObjectMethod(env, context, mid, service);
   1.978 +
   1.979 +    (*env)->DeleteLocalRef(env, service);
   1.980 +
   1.981 +    retval = manager ? (*env)->NewGlobalRef(env, manager) : NULL;
   1.982 +    LocalReferenceHolder_Cleanup(&refs);
   1.983 +    return retval;
   1.984 +}
   1.985 +
   1.986 +#define SETUP_CLIPBOARD(error) \
   1.987 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__); \
   1.988 +    JNIEnv* env = Android_JNI_GetEnv(); \
   1.989 +    if (!LocalReferenceHolder_Init(&refs, env)) { \
   1.990 +        LocalReferenceHolder_Cleanup(&refs); \
   1.991 +        return error; \
   1.992 +    } \
   1.993 +    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
   1.994 +    if (!clipboard) { \
   1.995 +        LocalReferenceHolder_Cleanup(&refs); \
   1.996 +        return error; \
   1.997 +    }
   1.998 +
   1.999 +#define CLEANUP_CLIPBOARD() \
  1.1000 +    LocalReferenceHolder_Cleanup(&refs);
  1.1001 +
  1.1002 +int Android_JNI_SetClipboardText(const char* text)
  1.1003 +{
  1.1004 +    SETUP_CLIPBOARD(-1)
  1.1005 +
  1.1006 +    jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "setText", "(Ljava/lang/CharSequence;)V");
  1.1007 +    jstring string = (*env)->NewStringUTF(env, text);
  1.1008 +    (*env)->CallVoidMethod(env, clipboard, mid, string);
  1.1009 +    (*env)->DeleteGlobalRef(env, clipboard);
  1.1010 +    (*env)->DeleteLocalRef(env, string);
  1.1011 +
  1.1012 +    CLEANUP_CLIPBOARD();
  1.1013 +
  1.1014 +    return 0;
  1.1015 +}
  1.1016 +
  1.1017 +char* Android_JNI_GetClipboardText()
  1.1018 +{
  1.1019 +    SETUP_CLIPBOARD(SDL_strdup(""))
  1.1020 +
  1.1021 +    jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "getText", "()Ljava/lang/CharSequence;");
  1.1022 +    jobject sequence = (*env)->CallObjectMethod(env, clipboard, mid);
  1.1023 +    (*env)->DeleteGlobalRef(env, clipboard);
  1.1024 +    if (sequence) {
  1.1025 +        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, sequence), "toString", "()Ljava/lang/String;");
  1.1026 +        jstring string = (jstring)((*env)->CallObjectMethod(env, sequence, mid));
  1.1027 +        const char* utf = (*env)->GetStringUTFChars(env, string, 0);
  1.1028 +        if (utf) {
  1.1029 +            char* text = SDL_strdup(utf);
  1.1030 +            (*env)->ReleaseStringUTFChars(env, string, utf);
  1.1031 +
  1.1032 +            CLEANUP_CLIPBOARD();
  1.1033 +
  1.1034 +            return text;
  1.1035 +        }
  1.1036 +    }
  1.1037 +
  1.1038 +    CLEANUP_CLIPBOARD();    
  1.1039 +
  1.1040 +    return SDL_strdup("");
  1.1041 +}
  1.1042 +
  1.1043 +SDL_bool Android_JNI_HasClipboardText()
  1.1044 +{
  1.1045 +    SETUP_CLIPBOARD(SDL_FALSE)
  1.1046 +
  1.1047 +    jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "hasText", "()Z");
  1.1048 +    jboolean has = (*env)->CallBooleanMethod(env, clipboard, mid);
  1.1049 +    (*env)->DeleteGlobalRef(env, clipboard);
  1.1050 +
  1.1051 +    CLEANUP_CLIPBOARD();
  1.1052 +    
  1.1053 +    return has ? SDL_TRUE : SDL_FALSE;
  1.1054 +}
  1.1055 +
  1.1056 +
  1.1057 +// returns 0 on success or -1 on error (others undefined then)
  1.1058 +// returns truthy or falsy value in plugged, charged and battery
  1.1059 +// returns the value in seconds and percent or -1 if not available
  1.1060 +int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
  1.1061 +{
  1.1062 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1.1063 +    JNIEnv* env = Android_JNI_GetEnv();
  1.1064 +    if (!LocalReferenceHolder_Init(&refs, env)) {
  1.1065 +        LocalReferenceHolder_Cleanup(&refs);
  1.1066 +        return -1;
  1.1067 +    }
  1.1068 +
  1.1069 +    jmethodID mid;
  1.1070 +
  1.1071 +    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
  1.1072 +    jobject context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
  1.1073 +
  1.1074 +    jstring action = (*env)->NewStringUTF(env, "android.intent.action.BATTERY_CHANGED");
  1.1075 +
  1.1076 +    jclass cls = (*env)->FindClass(env, "android/content/IntentFilter");
  1.1077 +
  1.1078 +    mid = (*env)->GetMethodID(env, cls, "<init>", "(Ljava/lang/String;)V");
  1.1079 +    jobject filter = (*env)->NewObject(env, cls, mid, action);
  1.1080 +
  1.1081 +    (*env)->DeleteLocalRef(env, action);
  1.1082 +
  1.1083 +    mid = (*env)->GetMethodID(env, mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
  1.1084 +    jobject intent = (*env)->CallObjectMethod(env, context, mid, NULL, filter);
  1.1085 +
  1.1086 +    (*env)->DeleteLocalRef(env, filter);
  1.1087 +
  1.1088 +    cls = (*env)->GetObjectClass(env, intent);
  1.1089 +
  1.1090 +    jstring iname;
  1.1091 +    jmethodID imid = (*env)->GetMethodID(env, cls, "getIntExtra", "(Ljava/lang/String;I)I");
  1.1092 +
  1.1093 +#define GET_INT_EXTRA(var, key) \
  1.1094 +    iname = (*env)->NewStringUTF(env, key); \
  1.1095 +    int var = (*env)->CallIntMethod(env, intent, imid, iname, -1); \
  1.1096 +    (*env)->DeleteLocalRef(env, iname);
  1.1097 +
  1.1098 +    jstring bname;
  1.1099 +    jmethodID bmid = (*env)->GetMethodID(env, cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
  1.1100 +
  1.1101 +#define GET_BOOL_EXTRA(var, key) \
  1.1102 +    bname = (*env)->NewStringUTF(env, key); \
  1.1103 +    int var = (*env)->CallBooleanMethod(env, intent, bmid, bname, JNI_FALSE); \
  1.1104 +    (*env)->DeleteLocalRef(env, bname);
  1.1105 +
  1.1106 +    if (plugged) {
  1.1107 +        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
  1.1108 +        if (plug == -1) {
  1.1109 +            LocalReferenceHolder_Cleanup(&refs);
  1.1110 +            return -1;
  1.1111 +        }
  1.1112 +        // 1 == BatteryManager.BATTERY_PLUGGED_AC
  1.1113 +        // 2 == BatteryManager.BATTERY_PLUGGED_USB
  1.1114 +        *plugged = (0 < plug) ? 1 : 0;
  1.1115 +    }
  1.1116 +
  1.1117 +    if (charged) {
  1.1118 +        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
  1.1119 +        if (status == -1) {
  1.1120 +            LocalReferenceHolder_Cleanup(&refs);
  1.1121 +            return -1;
  1.1122 +        }
  1.1123 +        // 5 == BatteryManager.BATTERY_STATUS_FULL
  1.1124 +        *charged = (status == 5) ? 1 : 0;
  1.1125 +    }
  1.1126 +
  1.1127 +    if (battery) {
  1.1128 +        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
  1.1129 +        *battery = present ? 1 : 0;
  1.1130 +    }
  1.1131 +
  1.1132 +    if (seconds) {
  1.1133 +        *seconds = -1; // not possible
  1.1134 +    }
  1.1135 +
  1.1136 +    if (percent) {
  1.1137 +        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
  1.1138 +        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
  1.1139 +        if ((level == -1) || (scale == -1)) {
  1.1140 +            LocalReferenceHolder_Cleanup(&refs);
  1.1141 +            return -1;
  1.1142 +        }
  1.1143 +        *percent = level * 100 / scale;
  1.1144 +    }
  1.1145 +
  1.1146 +    (*env)->DeleteLocalRef(env, intent);
  1.1147 +
  1.1148 +    LocalReferenceHolder_Cleanup(&refs);
  1.1149 +    return 0;
  1.1150 +}
  1.1151 +
  1.1152 +// sends message to be handled on the UI event dispatch thread
  1.1153 +int Android_JNI_SendMessage(int command, int param)
  1.1154 +{
  1.1155 +    JNIEnv *env = Android_JNI_GetEnv();
  1.1156 +    if (!env) {
  1.1157 +        return -1;
  1.1158 +    }
  1.1159 +    jmethodID mid = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
  1.1160 +    if (!mid) {
  1.1161 +        return -1;
  1.1162 +    }
  1.1163 +    jboolean success = (*env)->CallStaticBooleanMethod(env, mActivityClass, mid, command, param);
  1.1164 +    return success ? 0 : -1;
  1.1165 +}
  1.1166 +
  1.1167 +void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
  1.1168 +{
  1.1169 +    JNIEnv *env = Android_JNI_GetEnv();
  1.1170 +    if (!env) {
  1.1171 +        return;
  1.1172 +    }
  1.1173 +
  1.1174 +    jmethodID mid = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIII)Z");
  1.1175 +    if (!mid) {
  1.1176 +        return;
  1.1177 +    }
  1.1178 +    (*env)->CallStaticBooleanMethod(env, mActivityClass, mid,
  1.1179 +                               inputRect->x,
  1.1180 +                               inputRect->y,
  1.1181 +                               inputRect->w,
  1.1182 +                               inputRect->h );
  1.1183 +}
  1.1184 +
  1.1185 +void Android_JNI_HideTextInput()
  1.1186 +{
  1.1187 +    // has to match Activity constant
  1.1188 +    const int COMMAND_TEXTEDIT_HIDE = 3;
  1.1189 +    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
  1.1190 +}
  1.1191 +
  1.1192 +//////////////////////////////////////////////////////////////////////////////
  1.1193 +//
  1.1194 +// Functions exposed to SDL applications in SDL_system.h
  1.1195 +//
  1.1196 +
  1.1197 +void *SDL_AndroidGetJNIEnv()
  1.1198 +{
  1.1199 +    return Android_JNI_GetEnv();
  1.1200 +}
  1.1201 +
  1.1202 +
  1.1203 +
  1.1204 +void *SDL_AndroidGetActivity()
  1.1205 +{
  1.1206 +    /* See SDL_system.h for caveats on using this function. */
  1.1207 +
  1.1208 +    jmethodID mid;
  1.1209 +
  1.1210 +    JNIEnv *env = Android_JNI_GetEnv();
  1.1211 +    if (!env) {
  1.1212 +        return NULL;
  1.1213 +    }
  1.1214 +
  1.1215 +    // return SDLActivity.getContext();
  1.1216 +    mid = (*env)->GetStaticMethodID(env, mActivityClass,
  1.1217 +            "getContext","()Landroid/content/Context;");
  1.1218 +    return (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
  1.1219 +}
  1.1220 +
  1.1221 +const char * SDL_AndroidGetInternalStoragePath()
  1.1222 +{
  1.1223 +    static char *s_AndroidInternalFilesPath = NULL;
  1.1224 +
  1.1225 +    if (!s_AndroidInternalFilesPath) {
  1.1226 +        struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1.1227 +        jmethodID mid;
  1.1228 +        jobject context;
  1.1229 +        jobject fileObject;
  1.1230 +        jstring pathString;
  1.1231 +        const char *path;
  1.1232 +
  1.1233 +        JNIEnv *env = Android_JNI_GetEnv();
  1.1234 +        if (!LocalReferenceHolder_Init(&refs, env)) {
  1.1235 +            LocalReferenceHolder_Cleanup(&refs);
  1.1236 +            return NULL;
  1.1237 +        }
  1.1238 +
  1.1239 +        // context = SDLActivity.getContext();
  1.1240 +        mid = (*env)->GetStaticMethodID(env, mActivityClass,
  1.1241 +                "getContext","()Landroid/content/Context;");
  1.1242 +        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
  1.1243 +
  1.1244 +        // fileObj = context.getFilesDir();
  1.1245 +        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  1.1246 +                "getFilesDir", "()Ljava/io/File;");
  1.1247 +        fileObject = (*env)->CallObjectMethod(env, context, mid);
  1.1248 +        if (!fileObject) {
  1.1249 +            SDL_SetError("Couldn't get internal directory");
  1.1250 +            LocalReferenceHolder_Cleanup(&refs);
  1.1251 +            return NULL;
  1.1252 +        }
  1.1253 +
  1.1254 +        // path = fileObject.getAbsolutePath();
  1.1255 +        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  1.1256 +                "getAbsolutePath", "()Ljava/lang/String;");
  1.1257 +        pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  1.1258 +
  1.1259 +        path = (*env)->GetStringUTFChars(env, pathString, NULL);
  1.1260 +        s_AndroidInternalFilesPath = SDL_strdup(path);
  1.1261 +        (*env)->ReleaseStringUTFChars(env, pathString, path);
  1.1262 +
  1.1263 +        LocalReferenceHolder_Cleanup(&refs);
  1.1264 +    }
  1.1265 +    return s_AndroidInternalFilesPath;
  1.1266 +}
  1.1267 +
  1.1268 +int SDL_AndroidGetExternalStorageState()
  1.1269 +{
  1.1270 +    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1.1271 +    jmethodID mid;
  1.1272 +    jclass cls;
  1.1273 +    jstring stateString;
  1.1274 +    const char *state;
  1.1275 +    int stateFlags;
  1.1276 +
  1.1277 +    JNIEnv *env = Android_JNI_GetEnv();
  1.1278 +    if (!LocalReferenceHolder_Init(&refs, env)) {
  1.1279 +        LocalReferenceHolder_Cleanup(&refs);
  1.1280 +        return 0;
  1.1281 +    }
  1.1282 +
  1.1283 +    cls = (*env)->FindClass(env, "android/os/Environment");
  1.1284 +    mid = (*env)->GetStaticMethodID(env, cls,
  1.1285 +            "getExternalStorageState", "()Ljava/lang/String;");
  1.1286 +    stateString = (jstring)(*env)->CallStaticObjectMethod(env, cls, mid);
  1.1287 +
  1.1288 +    state = (*env)->GetStringUTFChars(env, stateString, NULL);
  1.1289 +
  1.1290 +    // Print an info message so people debugging know the storage state
  1.1291 +    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
  1.1292 +
  1.1293 +    if (SDL_strcmp(state, "mounted") == 0) {
  1.1294 +        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
  1.1295 +                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
  1.1296 +    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
  1.1297 +        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
  1.1298 +    } else {
  1.1299 +        stateFlags = 0;
  1.1300 +    }
  1.1301 +    (*env)->ReleaseStringUTFChars(env, stateString, state);
  1.1302 +
  1.1303 +    LocalReferenceHolder_Cleanup(&refs);
  1.1304 +    return stateFlags;
  1.1305 +}
  1.1306 +
  1.1307 +const char * SDL_AndroidGetExternalStoragePath()
  1.1308 +{
  1.1309 +    static char *s_AndroidExternalFilesPath = NULL;
  1.1310 +
  1.1311 +    if (!s_AndroidExternalFilesPath) {
  1.1312 +        struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
  1.1313 +        jmethodID mid;
  1.1314 +        jobject context;
  1.1315 +        jobject fileObject;
  1.1316 +        jstring pathString;
  1.1317 +        const char *path;
  1.1318 +
  1.1319 +        JNIEnv *env = Android_JNI_GetEnv();
  1.1320 +        if (!LocalReferenceHolder_Init(&refs, env)) {
  1.1321 +            LocalReferenceHolder_Cleanup(&refs);
  1.1322 +            return NULL;
  1.1323 +        }
  1.1324 +
  1.1325 +        // context = SDLActivity.getContext();
  1.1326 +        mid = (*env)->GetStaticMethodID(env, mActivityClass,
  1.1327 +                "getContext","()Landroid/content/Context;");
  1.1328 +        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
  1.1329 +
  1.1330 +        // fileObj = context.getExternalFilesDir();
  1.1331 +        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
  1.1332 +                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
  1.1333 +        fileObject = (*env)->CallObjectMethod(env, context, mid, NULL);
  1.1334 +        if (!fileObject) {
  1.1335 +            SDL_SetError("Couldn't get external directory");
  1.1336 +            LocalReferenceHolder_Cleanup(&refs);
  1.1337 +            return NULL;
  1.1338 +        }
  1.1339 +
  1.1340 +        // path = fileObject.getAbsolutePath();
  1.1341 +        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
  1.1342 +                "getAbsolutePath", "()Ljava/lang/String;");
  1.1343 +        pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
  1.1344 +
  1.1345 +        path = (*env)->GetStringUTFChars(env, pathString, NULL);
  1.1346 +        s_AndroidExternalFilesPath = SDL_strdup(path);
  1.1347 +        (*env)->ReleaseStringUTFChars(env, pathString, path);
  1.1348 +
  1.1349 +        LocalReferenceHolder_Cleanup(&refs);
  1.1350 +    }
  1.1351 +    return s_AndroidExternalFilesPath;
  1.1352 +}
  1.1353 +
  1.1354 +#endif /* __ANDROID__ */
  1.1355 +
  1.1356 +/* vi: set ts=4 sw=4 expandtab: */