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