src/core/android/SDL_android.cpp
author Gabriel Jacobo <gabomdq@gmail.com>
Mon, 14 Jan 2013 20:20:33 -0300
changeset 6816 b3d3ef1e15b5
parent 6806 9e57ff36fd7a
child 6828 ac7f004fb63c
permissions -rw-r--r--
Fixes bug 1696, thanks Paul Geerts!
Also adds a bit of information about asset loading on Android.
slouken@4964
     1
/*
slouken@5535
     2
  Simple DirectMedia Layer
slouken@6138
     3
  Copyright (C) 1997-2012 Sam Lantinga <slouken@libsdl.org>
slouken@4964
     4
slouken@5535
     5
  This software is provided 'as-is', without any express or implied
slouken@5535
     6
  warranty.  In no event will the authors be held liable for any damages
slouken@5535
     7
  arising from the use of this software.
slouken@4964
     8
slouken@5535
     9
  Permission is granted to anyone to use this software for any purpose,
slouken@5535
    10
  including commercial applications, and to alter it and redistribute it
slouken@5535
    11
  freely, subject to the following restrictions:
slouken@4964
    12
slouken@5535
    13
  1. The origin of this software must not be misrepresented; you must not
slouken@5535
    14
     claim that you wrote the original software. If you use this software
slouken@5535
    15
     in a product, an acknowledgment in the product documentation would be
slouken@5535
    16
     appreciated but is not required.
slouken@5535
    17
  2. Altered source versions must be plainly marked as such, and must not be
slouken@5535
    18
     misrepresented as being the original software.
slouken@5535
    19
  3. This notice may not be removed or altered from any source distribution.
slouken@4964
    20
*/
slouken@4964
    21
#include "SDL_config.h"
slouken@5222
    22
#include "SDL_stdinc.h"
slouken@6284
    23
#include "SDL_assert.h"
slouken@6650
    24
#include "SDL_log.h"
slouken@4964
    25
slouken@6044
    26
#ifdef __ANDROID__
slouken@6044
    27
slouken@6630
    28
#include "SDL_system.h"
slouken@4989
    29
#include "SDL_android.h"
slouken@6792
    30
#include <EGL/egl.h>
slouken@4989
    31
slouken@4980
    32
extern "C" {
slouken@5092
    33
#include "../../events/SDL_events_c.h"
slouken@5092
    34
#include "../../video/android/SDL_androidkeyboard.h"
slouken@5092
    35
#include "../../video/android/SDL_androidtouch.h"
slouken@5092
    36
#include "../../video/android/SDL_androidvideo.h"
slouken@4995
    37
icculus@5996
    38
#include <android/log.h>
gabomdq@6354
    39
#include <pthread.h>
gabomdq@6806
    40
#include <sys/types.h>
gabomdq@6806
    41
#include <unistd.h>
icculus@5996
    42
#define LOG_TAG "SDL_android"
icculus@5996
    43
//#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
icculus@5996
    44
//#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
icculus@5996
    45
#define LOGI(...) do {} while (false)
icculus@5996
    46
#define LOGE(...) do {} while (false)
icculus@5996
    47
slouken@6650
    48
/* Uncomment this to log messages entering and exiting methods in this file */
slouken@6650
    49
//#define DEBUG_JNI
icculus@5996
    50
slouken@6191
    51
/* Implemented in audio/android/SDL_androidaudio.c */
slouken@4995
    52
extern void Android_RunAudioThread();
slouken@4995
    53
} // C
slouken@4980
    54
slouken@4964
    55
/*******************************************************************************
slouken@4964
    56
 This file links the Java side of Android with libsdl
slouken@4964
    57
*******************************************************************************/
slouken@4964
    58
#include <jni.h>
slouken@4964
    59
#include <android/log.h>
slouken@4964
    60
slouken@4964
    61
slouken@4964
    62
/*******************************************************************************
slouken@4964
    63
                               Globals
slouken@4964
    64
*******************************************************************************/
gabomdq@6354
    65
static pthread_key_t mThreadKey;
icculus@5996
    66
static JavaVM* mJavaVM;
slouken@4964
    67
slouken@4995
    68
// Main activity
slouken@4998
    69
static jclass mActivityClass;
slouken@4964
    70
slouken@4995
    71
// method signatures
slouken@4995
    72
static jmethodID midCreateGLContext;
slouken@4995
    73
static jmethodID midFlipBuffers;
slouken@4995
    74
static jmethodID midAudioInit;
slouken@4995
    75
static jmethodID midAudioWriteShortBuffer;
slouken@4995
    76
static jmethodID midAudioWriteByteBuffer;
slouken@4996
    77
static jmethodID midAudioQuit;
slouken@4964
    78
slouken@4995
    79
// Accelerometer data storage
slouken@5000
    80
static float fLastAccelerometer[3];
slouken@6212
    81
static bool bHasNewData;
slouken@4964
    82
slouken@4964
    83
/*******************************************************************************
slouken@4964
    84
                 Functions called by JNI
slouken@4964
    85
*******************************************************************************/
slouken@4964
    86
slouken@4964
    87
// Library init
slouken@4964
    88
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
slouken@4964
    89
{
icculus@5996
    90
    JNIEnv *env;
icculus@5996
    91
    mJavaVM = vm;
icculus@5996
    92
    LOGI("JNI_OnLoad called");
icculus@5996
    93
    if (mJavaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
icculus@5996
    94
        LOGE("Failed to get the environment using GetEnv()");
icculus@5996
    95
        return -1;
icculus@5996
    96
    }
gabomdq@6354
    97
    /*
gabomdq@6354
    98
     * Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
gabomdq@6354
    99
     * Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
gabomdq@6354
   100
     */
gabomdq@6354
   101
    if (pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed)) {
gabomdq@6354
   102
        __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing pthread key");
gabomdq@6354
   103
    }
gabomdq@6354
   104
    else {
gabomdq@6354
   105
        Android_JNI_SetupThread();
gabomdq@6354
   106
    }
icculus@5996
   107
slouken@4964
   108
    return JNI_VERSION_1_4;
slouken@4964
   109
}
slouken@4964
   110
slouken@4964
   111
// Called before SDL_main() to initialize JNI bindings
gabomdq@6354
   112
extern "C" void SDL_Android_Init(JNIEnv* mEnv, jclass cls)
slouken@4964
   113
{
slouken@4964
   114
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
slouken@4964
   115
gabomdq@6354
   116
    Android_JNI_SetupThread();
gabomdq@6354
   117
gabomdq@6354
   118
    mActivityClass = (jclass)mEnv->NewGlobalRef(cls);
slouken@4998
   119
slouken@4998
   120
    midCreateGLContext = mEnv->GetStaticMethodID(mActivityClass,
slouken@6792
   121
                                "createGLContext","(II[I)Z");
slouken@4998
   122
    midFlipBuffers = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   123
                                "flipBuffers","()V");
slouken@4998
   124
    midAudioInit = mEnv->GetStaticMethodID(mActivityClass, 
gabomdq@6802
   125
                                "audioInit", "(IZZI)V");
slouken@4998
   126
    midAudioWriteShortBuffer = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   127
                                "audioWriteShortBuffer", "([S)V");
slouken@4998
   128
    midAudioWriteByteBuffer = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   129
                                "audioWriteByteBuffer", "([B)V");
slouken@4998
   130
    midAudioQuit = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   131
                                "audioQuit", "()V");
slouken@4964
   132
slouken@6212
   133
    bHasNewData = false;
slouken@6212
   134
slouken@4995
   135
    if(!midCreateGLContext || !midFlipBuffers || !midAudioInit ||
slouken@4996
   136
       !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) {
slouken@4996
   137
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
slouken@4964
   138
    }
icculus@5996
   139
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
slouken@4964
   140
}
slouken@4964
   141
slouken@4995
   142
// Resize
slouken@4995
   143
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeResize(
slouken@4998
   144
                                    JNIEnv* env, jclass jcls,
slouken@4995
   145
                                    jint width, jint height, jint format)
slouken@4995
   146
{
slouken@4995
   147
    Android_SetScreenResolution(width, height, format);
slouken@4995
   148
}
slouken@4995
   149
slouken@4964
   150
// Keydown
slouken@4995
   151
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyDown(
slouken@4998
   152
                                    JNIEnv* env, jclass jcls, jint keycode)
slouken@4964
   153
{
slouken@4980
   154
    Android_OnKeyDown(keycode);
slouken@4964
   155
}
slouken@4964
   156
slouken@4964
   157
// Keyup
slouken@4995
   158
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyUp(
slouken@4998
   159
                                    JNIEnv* env, jclass jcls, jint keycode)
slouken@4964
   160
{
slouken@4980
   161
    Android_OnKeyUp(keycode);
slouken@4964
   162
}
slouken@4964
   163
slouken@4964
   164
// Touch
slouken@4995
   165
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeTouch(
slouken@4998
   166
                                    JNIEnv* env, jclass jcls,
icculus@5982
   167
                                    jint touch_device_id_in, jint pointer_finger_id_in,
slouken@4995
   168
                                    jint action, jfloat x, jfloat y, jfloat p)
slouken@4964
   169
{
icculus@5982
   170
    Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p);
slouken@4964
   171
}
slouken@4964
   172
slouken@4995
   173
// Accelerometer
slouken@4964
   174
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeAccel(
slouken@4998
   175
                                    JNIEnv* env, jclass jcls,
slouken@4995
   176
                                    jfloat x, jfloat y, jfloat z)
slouken@4964
   177
{
slouken@4964
   178
    fLastAccelerometer[0] = x;
slouken@4964
   179
    fLastAccelerometer[1] = y;
slouken@6212
   180
    fLastAccelerometer[2] = z;
slouken@6212
   181
    bHasNewData = true;
slouken@4964
   182
}
slouken@4964
   183
slouken@4995
   184
// Quit
slouken@4995
   185
extern "C" void Java_org_libsdl_app_SDLActivity_nativeQuit(
slouken@4998
   186
                                    JNIEnv* env, jclass cls)
slouken@4995
   187
{    
slouken@4995
   188
    // Inject a SDL_QUIT event
slouken@4995
   189
    SDL_SendQuit();
slouken@4995
   190
}
slouken@4995
   191
slouken@6186
   192
// Pause
slouken@6186
   193
extern "C" void Java_org_libsdl_app_SDLActivity_nativePause(
slouken@6186
   194
                                    JNIEnv* env, jclass cls)
slouken@6186
   195
{
slouken@6186
   196
    if (Android_Window) {
gabomdq@6330
   197
        /* Signal the pause semaphore so the event loop knows to pause and (optionally) block itself */
gabomdq@6330
   198
        if (!SDL_SemValue(Android_PauseSem)) SDL_SemPost(Android_PauseSem);
slouken@6186
   199
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
slouken@6191
   200
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
slouken@6186
   201
    }
slouken@6186
   202
}
slouken@6186
   203
slouken@6186
   204
// Resume
slouken@6186
   205
extern "C" void Java_org_libsdl_app_SDLActivity_nativeResume(
slouken@6186
   206
                                    JNIEnv* env, jclass cls)
slouken@6186
   207
{
slouken@6186
   208
    if (Android_Window) {
gabomdq@6330
   209
        /* Signal the resume semaphore so the event loop knows to resume and restore the GL Context
gabomdq@6330
   210
         * We can't restore the GL Context here because it needs to be done on the SDL main thread
gabomdq@6330
   211
         * and this function will be called from the Java thread instead.
gabomdq@6330
   212
         */
gabomdq@6330
   213
        if (!SDL_SemValue(Android_ResumeSem)) SDL_SemPost(Android_ResumeSem);
slouken@6186
   214
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
slouken@6191
   215
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0);
slouken@6186
   216
    }
slouken@6186
   217
}
slouken@6186
   218
slouken@4995
   219
extern "C" void Java_org_libsdl_app_SDLActivity_nativeRunAudioThread(
slouken@4998
   220
                                    JNIEnv* env, jclass cls)
slouken@4995
   221
{
slouken@4998
   222
    /* This is the audio thread, with a different environment */
gabomdq@6354
   223
    Android_JNI_SetupThread();
slouken@4998
   224
slouken@4996
   225
    Android_RunAudioThread();
slouken@4995
   226
}
slouken@4964
   227
slouken@6555
   228
extern "C" void Java_org_libsdl_app_SDLInputConnection_nativeCommitText(
slouken@6555
   229
                                    JNIEnv* env, jclass cls,
slouken@6555
   230
                                    jstring text, jint newCursorPosition)
slouken@6555
   231
{
slouken@6555
   232
    const char *utftext = env->GetStringUTFChars(text, NULL);
slouken@6555
   233
slouken@6555
   234
    SDL_SendKeyboardText(utftext);
slouken@6555
   235
slouken@6555
   236
    env->ReleaseStringUTFChars(text, utftext);
slouken@6555
   237
}
slouken@6555
   238
slouken@6555
   239
extern "C" void Java_org_libsdl_app_SDLInputConnection_nativeSetComposingText(
slouken@6555
   240
                                    JNIEnv* env, jclass cls,
slouken@6555
   241
                                    jstring text, jint newCursorPosition)
slouken@6555
   242
{
slouken@6555
   243
    const char *utftext = env->GetStringUTFChars(text, NULL);
slouken@6555
   244
slouken@6555
   245
    SDL_SendEditingText(utftext, 0, 0);
slouken@6555
   246
slouken@6555
   247
    env->ReleaseStringUTFChars(text, utftext);
slouken@6555
   248
}
slouken@6555
   249
slouken@6555
   250
slouken@6555
   251
slouken@4964
   252
/*******************************************************************************
slouken@4964
   253
             Functions called by SDL into Java
slouken@4964
   254
*******************************************************************************/
slouken@6284
   255
slouken@6284
   256
class LocalReferenceHolder
slouken@6284
   257
{
slouken@6284
   258
private:
slouken@6284
   259
    static int s_active;
slouken@6284
   260
slouken@6284
   261
public:
slouken@6284
   262
    static bool IsActive() {
slouken@6284
   263
        return s_active > 0;
slouken@6284
   264
    }
slouken@6284
   265
slouken@6284
   266
public:
slouken@6650
   267
    LocalReferenceHolder(const char *func) : m_env(NULL), m_func(func) {
slouken@6650
   268
#ifdef DEBUG_JNI
slouken@6650
   269
        SDL_Log("Entering function %s", m_func);
slouken@6650
   270
#endif
slouken@6650
   271
    }
slouken@6284
   272
    ~LocalReferenceHolder() {
slouken@6650
   273
#ifdef DEBUG_JNI
slouken@6650
   274
        SDL_Log("Leaving function %s", m_func);
slouken@6650
   275
#endif
slouken@6284
   276
        if (m_env) {
slouken@6284
   277
            m_env->PopLocalFrame(NULL);
slouken@6284
   278
            --s_active;
slouken@6284
   279
        }
slouken@6284
   280
    }
slouken@6284
   281
slouken@6284
   282
    bool init(JNIEnv *env, jint capacity = 16) {
slouken@6284
   283
        if (env->PushLocalFrame(capacity) < 0) {
slouken@6284
   284
            SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   285
            return false;
slouken@6284
   286
        }
slouken@6284
   287
        ++s_active;
slouken@6284
   288
        m_env = env;
slouken@6284
   289
        return true;
slouken@6284
   290
    }
slouken@6284
   291
slouken@6284
   292
protected:
slouken@6284
   293
    JNIEnv *m_env;
slouken@6650
   294
    const char *m_func;
slouken@6284
   295
};
slouken@6284
   296
int LocalReferenceHolder::s_active;
slouken@6284
   297
slouken@6792
   298
extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion,
slouken@6792
   299
                                int red, int green, int blue, int alpha,
slouken@6792
   300
                                int buffer, int depth, int stencil,
slouken@6792
   301
                                int buffers, int samples)
slouken@4964
   302
{
slouken@6792
   303
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6792
   304
slouken@6792
   305
    jint attribs[] = {
slouken@6792
   306
        EGL_RED_SIZE, red,
slouken@6792
   307
        EGL_GREEN_SIZE, green,
slouken@6792
   308
        EGL_BLUE_SIZE, blue,
slouken@6792
   309
        EGL_ALPHA_SIZE, alpha,
slouken@6792
   310
        EGL_BUFFER_SIZE, buffer,
slouken@6792
   311
        EGL_DEPTH_SIZE, depth,
slouken@6792
   312
        EGL_STENCIL_SIZE, stencil,
slouken@6792
   313
        EGL_SAMPLE_BUFFERS, buffers,
slouken@6792
   314
        EGL_SAMPLES, samples,
slouken@6792
   315
        EGL_RENDERABLE_TYPE, (majorVersion == 1 ? EGL_OPENGL_ES_BIT : EGL_OPENGL_ES2_BIT),
slouken@6792
   316
        EGL_NONE
slouken@6792
   317
    };
slouken@6792
   318
    int len = SDL_arraysize(attribs);
slouken@6792
   319
slouken@6792
   320
    jintArray array;
slouken@6792
   321
slouken@6792
   322
    array = env->NewIntArray(len);
slouken@6792
   323
    env->SetIntArrayRegion(array, 0, len, attribs);
slouken@6792
   324
slouken@6792
   325
    jboolean success = env->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion, array);
slouken@6792
   326
slouken@6792
   327
    env->DeleteLocalRef(array);
slouken@6792
   328
slouken@6792
   329
    return success ? SDL_TRUE : SDL_FALSE;
slouken@4964
   330
}
slouken@4964
   331
slouken@4989
   332
extern "C" void Android_JNI_SwapWindow()
slouken@4964
   333
{
gabomdq@6354
   334
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@4998
   335
    mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); 
slouken@4998
   336
}
slouken@4998
   337
slouken@4998
   338
extern "C" void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   339
{
slouken@4998
   340
    jmethodID mid;
gabomdq@6354
   341
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@4998
   342
    mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V");
slouken@4998
   343
    if (mid) {
gabomdq@6307
   344
        jstring jtitle = reinterpret_cast<jstring>(mEnv->NewStringUTF(title));
gabomdq@6307
   345
        mEnv->CallStaticVoidMethod(mActivityClass, mid, jtitle);
gabomdq@6307
   346
        mEnv->DeleteLocalRef(jtitle);
slouken@4998
   347
    }
slouken@4964
   348
}
slouken@4964
   349
slouken@6212
   350
extern "C" SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   351
{
slouken@5000
   352
    int i;
slouken@6212
   353
    SDL_bool retval = SDL_FALSE;
slouken@6212
   354
slouken@6212
   355
    if (bHasNewData) {
slouken@6212
   356
        for (i = 0; i < 3; ++i) {
slouken@6212
   357
            values[i] = fLastAccelerometer[i];
slouken@6212
   358
        }
slouken@6212
   359
        bHasNewData = false;
slouken@6212
   360
        retval = SDL_TRUE;
slouken@5000
   361
    }
slouken@6212
   362
slouken@6212
   363
    return retval;
slouken@5000
   364
}
slouken@5000
   365
gabomdq@6354
   366
static void Android_JNI_ThreadDestroyed(void* value) {
gabomdq@6354
   367
    /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
gabomdq@6354
   368
    JNIEnv *env = (JNIEnv*) value;
gabomdq@6354
   369
    if (env != NULL) {
gabomdq@6354
   370
        mJavaVM->DetachCurrentThread();
gabomdq@6354
   371
        pthread_setspecific(mThreadKey, NULL);
gabomdq@6354
   372
    }
gabomdq@6354
   373
}
gabomdq@6354
   374
gabomdq@6354
   375
JNIEnv* Android_JNI_GetEnv(void) {
gabomdq@6354
   376
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   377
     * All threads are Linux threads, scheduled by the kernel.
gabomdq@6354
   378
     * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
gabomdq@6354
   379
     * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
gabomdq@6354
   380
     * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
gabomdq@6354
   381
     * and cannot make JNI calls.
gabomdq@6354
   382
     * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
gabomdq@6354
   383
     * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
gabomdq@6354
   384
     * is a no-op.
gabomdq@6354
   385
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   386
     */
gabomdq@6354
   387
gabomdq@6354
   388
    JNIEnv *env;
gabomdq@6354
   389
    int status = mJavaVM->AttachCurrentThread(&env, NULL);
gabomdq@6354
   390
    if(status < 0) {
gabomdq@6354
   391
        LOGE("failed to attach current thread");
gabomdq@6354
   392
        return 0;
gabomdq@6354
   393
    }
gabomdq@6354
   394
gabomdq@6354
   395
    return env;
gabomdq@6354
   396
}
gabomdq@6354
   397
gabomdq@6354
   398
int Android_JNI_SetupThread(void) {
gabomdq@6354
   399
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   400
     * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
gabomdq@6354
   401
     * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
gabomdq@6354
   402
     * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
gabomdq@6354
   403
     * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
gabomdq@6354
   404
     * Note: The destructor is not called unless the stored value is != NULL
gabomdq@6354
   405
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   406
     *       (except for some lost CPU cycles)
gabomdq@6354
   407
     */
gabomdq@6354
   408
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   409
    pthread_setspecific(mThreadKey, (void*) env);
gabomdq@6354
   410
    return 1;
gabomdq@6354
   411
}
gabomdq@6354
   412
slouken@4995
   413
//
slouken@4995
   414
// Audio support
slouken@4995
   415
//
slouken@4996
   416
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   417
static jboolean audioBufferStereo = JNI_FALSE;
slouken@4996
   418
static jobject audioBuffer = NULL;
slouken@4996
   419
static void* audioBufferPinned = NULL;
slouken@4995
   420
slouken@4995
   421
extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   422
{
slouken@4996
   423
    int audioBufferFrames;
slouken@4964
   424
icculus@5996
   425
    int status;
gabomdq@6354
   426
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   427
gabomdq@6354
   428
    if (!env) {
gabomdq@6354
   429
        LOGE("callback_handler: failed to attach current thread");
icculus@5996
   430
    }
gabomdq@6354
   431
    Android_JNI_SetupThread();
icculus@5996
   432
icculus@5996
   433
    
slouken@4996
   434
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   435
    audioBuffer16Bit = is16Bit;
slouken@4996
   436
    audioBufferStereo = channelCount > 1;
slouken@4964
   437
gabomdq@6802
   438
    env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
gabomdq@6802
   439
gabomdq@6802
   440
    /* Allocating the audio buffer from the Java side and passing it as the return value for audioInit no longer works on
gabomdq@6802
   441
     * Android >= 4.2 due to a "stale global reference" error. So now we allocate this buffer directly from this side. */
gabomdq@6802
   442
    
gabomdq@6802
   443
    if (is16Bit) {
gabomdq@6802
   444
        jshortArray audioBufferLocal = env->NewShortArray(desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   445
        if (audioBufferLocal) {
gabomdq@6802
   446
            audioBuffer = env->NewGlobalRef(audioBufferLocal);
gabomdq@6802
   447
            env->DeleteLocalRef(audioBufferLocal);
gabomdq@6802
   448
        }
gabomdq@6802
   449
    }
gabomdq@6802
   450
    else {
gabomdq@6802
   451
        jbyteArray audioBufferLocal = env->NewByteArray(desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   452
        if (audioBufferLocal) {
gabomdq@6802
   453
            audioBuffer = env->NewGlobalRef(audioBufferLocal);
gabomdq@6802
   454
            env->DeleteLocalRef(audioBufferLocal);
gabomdq@6802
   455
        }
gabomdq@6802
   456
    }
slouken@4995
   457
slouken@4996
   458
    if (audioBuffer == NULL) {
gabomdq@6802
   459
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer!");
slouken@4996
   460
        return 0;
slouken@4996
   461
    }
slouken@4995
   462
slouken@4996
   463
    jboolean isCopy = JNI_FALSE;
slouken@4996
   464
    if (audioBuffer16Bit) {
icculus@5996
   465
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   466
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   467
    } else {
icculus@5996
   468
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   469
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   470
    }
slouken@4996
   471
    if (audioBufferStereo) {
slouken@4996
   472
        audioBufferFrames /= 2;
slouken@4996
   473
    }
icculus@5996
   474
 
slouken@4996
   475
    return audioBufferFrames;
slouken@4995
   476
}
slouken@4995
   477
slouken@4996
   478
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   479
{
slouken@4996
   480
    return audioBufferPinned;
slouken@4995
   481
}
slouken@4995
   482
slouken@4996
   483
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   484
{
gabomdq@6354
   485
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   486
slouken@4996
   487
    if (audioBuffer16Bit) {
slouken@4996
   488
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   489
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   490
    } else {
slouken@4996
   491
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   492
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   493
    }
slouken@4995
   494
slouken@4996
   495
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   496
}
slouken@4995
   497
slouken@4995
   498
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   499
{
icculus@5996
   500
    int status;
gabomdq@6354
   501
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   502
icculus@5996
   503
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   504
slouken@4997
   505
    if (audioBuffer) {
icculus@5996
   506
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   507
        audioBuffer = NULL;
slouken@4997
   508
        audioBufferPinned = NULL;
slouken@4997
   509
    }
slouken@4964
   510
}
slouken@4981
   511
tim@5650
   512
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   513
static bool Android_JNI_ExceptionOccurred()
tim@5650
   514
{
slouken@6284
   515
    SDL_assert(LocalReferenceHolder::IsActive());
gabomdq@6354
   516
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   517
tim@5650
   518
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   519
    if (exception != NULL) {
tim@5650
   520
        jmethodID mid;
tim@5650
   521
tim@5650
   522
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   523
        mEnv->ExceptionClear();
tim@5650
   524
tim@5650
   525
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   526
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   527
tim@5650
   528
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   529
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   530
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   531
tim@5650
   532
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   533
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   534
tim@5650
   535
        if (exceptionMessage != NULL) {
tim@5650
   536
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   537
                    exceptionMessage, 0);
tim@5650
   538
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   539
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   540
        } else {
tim@5650
   541
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   542
        }
tim@5650
   543
tim@5650
   544
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   545
tim@5650
   546
        return true;
tim@5650
   547
    }
tim@5650
   548
tim@5650
   549
    return false;
tim@5650
   550
}
tim@5650
   551
icculus@5582
   552
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   553
{
slouken@6650
   554
    LocalReferenceHolder refs(__FUNCTION__);
tim@5650
   555
    int result = 0;
tim@5650
   556
tim@5650
   557
    jmethodID mid;
tim@5650
   558
    jobject context;
tim@5650
   559
    jobject assetManager;
tim@5650
   560
    jobject inputStream;
tim@5650
   561
    jclass channels;
tim@5650
   562
    jobject readableByteChannel;
tim@5650
   563
    jstring fileNameJString;
gabomdq@6806
   564
    jobject fd;
gabomdq@6806
   565
    jclass fdCls;
gabomdq@6806
   566
    jfieldID descriptor;
tim@5650
   567
gabomdq@6354
   568
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   569
    if (!refs.init(mEnv)) {
tim@5650
   570
        goto failure;
tim@5650
   571
    }
tim@5650
   572
gabomdq@6308
   573
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
gabomdq@6806
   574
    ctx->hidden.androidio.position = 0;
icculus@5582
   575
icculus@5582
   576
    // context = SDLActivity.getContext();
tim@5650
   577
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   578
            "getContext","()Landroid/content/Context;");
tim@5650
   579
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
gabomdq@6806
   580
    
icculus@5582
   581
icculus@5582
   582
    // assetManager = context.getAssets();
icculus@5582
   583
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   584
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   585
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   586
gabomdq@6806
   587
    /* First let's try opening the file to obtain an AssetFileDescriptor.
gabomdq@6806
   588
    * This method reads the files directly from the APKs using standard *nix calls
gabomdq@6806
   589
    */
gabomdq@6806
   590
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager), "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;");
tim@5650
   591
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   592
    if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   593
        goto fallback;
icculus@5582
   594
    }
icculus@5582
   595
gabomdq@6806
   596
    ctx->hidden.androidio.assetFileDescriptorRef = mEnv->NewGlobalRef(inputStream);
gabomdq@6806
   597
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getStartOffset", "()J");
gabomdq@6806
   598
    ctx->hidden.androidio.offset = mEnv->CallLongMethod(inputStream, mid);
tim@5650
   599
    if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   600
        goto fallback;
icculus@5582
   601
    }
icculus@5582
   602
gabomdq@6806
   603
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getDeclaredLength", "()J");
gabomdq@6806
   604
    ctx->hidden.androidio.size = mEnv->CallLongMethod(inputStream, mid);
gabomdq@6806
   605
    
tim@5650
   606
    if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   607
        goto fallback;
icculus@5582
   608
    }
icculus@5582
   609
gabomdq@6806
   610
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getFileDescriptor", "()Ljava/io/FileDescriptor;");
gabomdq@6806
   611
    fd = mEnv->CallObjectMethod(inputStream, mid);
gabomdq@6806
   612
    fdCls = mEnv->GetObjectClass(fd);
gabomdq@6806
   613
    descriptor = mEnv->GetFieldID(fdCls, "descriptor", "I");
gabomdq@6806
   614
    ctx->hidden.androidio.fd = mEnv->GetIntField(fd, descriptor);
tim@5650
   615
gabomdq@6816
   616
    // Seek to the correct offset in the file.
gabomdq@6816
   617
    lseek(ctx->hidden.androidio.fd, (off_t)ctx->hidden.androidio.offset, SEEK_SET);
gabomdq@6816
   618
gabomdq@6806
   619
    if (false) {
gabomdq@6806
   620
fallback:
gabomdq@6806
   621
        __android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file");
gabomdq@6806
   622
        /* Try the old method using InputStream */
gabomdq@6806
   623
        ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   624
gabomdq@6806
   625
        // inputStream = assetManager.open(<filename>);
gabomdq@6806
   626
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
gabomdq@6806
   627
                "open", "(Ljava/lang/String;I)Ljava/io/InputStream;");
gabomdq@6806
   628
        inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString, 1 /*ACCESS_RANDOM*/);
gabomdq@6806
   629
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   630
            goto failure;
gabomdq@6806
   631
        }
gabomdq@6806
   632
gabomdq@6806
   633
        ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
gabomdq@6806
   634
gabomdq@6806
   635
        // Despite all the visible documentation on [Asset]InputStream claiming
gabomdq@6806
   636
        // that the .available() method is not guaranteed to return the entire file
gabomdq@6806
   637
        // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
gabomdq@6806
   638
        // android/apis/content/ReadAsset.java imply that Android's
gabomdq@6806
   639
        // AssetInputStream.available() /will/ always return the total file size
gabomdq@6806
   640
gabomdq@6806
   641
        // size = inputStream.available();
gabomdq@6806
   642
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   643
                "available", "()I");
gabomdq@6806
   644
        ctx->hidden.androidio.size = (long)mEnv->CallIntMethod(inputStream, mid);
gabomdq@6806
   645
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   646
            goto failure;
gabomdq@6806
   647
        }
gabomdq@6806
   648
gabomdq@6806
   649
        // readableByteChannel = Channels.newChannel(inputStream);
gabomdq@6806
   650
        channels = mEnv->FindClass("java/nio/channels/Channels");
gabomdq@6806
   651
        mid = mEnv->GetStaticMethodID(channels,
gabomdq@6806
   652
                "newChannel",
gabomdq@6806
   653
                "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
gabomdq@6806
   654
        readableByteChannel = mEnv->CallStaticObjectMethod(
gabomdq@6806
   655
                channels, mid, inputStream);
gabomdq@6806
   656
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   657
            goto failure;
gabomdq@6806
   658
        }
gabomdq@6806
   659
gabomdq@6806
   660
        ctx->hidden.androidio.readableByteChannelRef =
gabomdq@6806
   661
            mEnv->NewGlobalRef(readableByteChannel);
gabomdq@6806
   662
gabomdq@6806
   663
        // Store .read id for reading purposes
gabomdq@6806
   664
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
gabomdq@6806
   665
                "read", "(Ljava/nio/ByteBuffer;)I");
gabomdq@6806
   666
        ctx->hidden.androidio.readMethod = mid;
gabomdq@6806
   667
    }
icculus@5582
   668
tim@5650
   669
    if (false) {
tim@5650
   670
failure:
tim@5650
   671
        result = -1;
tim@5650
   672
tim@5650
   673
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   674
tim@5650
   675
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   676
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   677
        }
gabomdq@6308
   678
gabomdq@6308
   679
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   680
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   681
        }
gabomdq@6308
   682
gabomdq@6806
   683
        if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) {
gabomdq@6806
   684
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   685
        }
gabomdq@6806
   686
tim@5650
   687
    }
tim@5650
   688
tim@5650
   689
    return result;
icculus@5582
   690
}
icculus@5582
   691
icculus@5582
   692
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   693
        const char* fileName, const char*)
icculus@5582
   694
{
slouken@6650
   695
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6354
   696
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   697
slouken@6284
   698
    if (!refs.init(mEnv)) {
slouken@6284
   699
        return -1;
slouken@6284
   700
    }
slouken@6284
   701
icculus@5582
   702
    if (!ctx) {
icculus@5582
   703
        return -1;
icculus@5582
   704
    }
icculus@5582
   705
icculus@5582
   706
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   707
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   708
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   709
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   710
    ctx->hidden.androidio.readMethod = NULL;
gabomdq@6806
   711
    ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   712
icculus@5582
   713
    return Android_JNI_FileOpen(ctx);
icculus@5582
   714
}
icculus@5582
   715
icculus@5582
   716
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   717
        size_t size, size_t maxnum)
icculus@5582
   718
{
slouken@6650
   719
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   720
gabomdq@6806
   721
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   722
        size_t bytesMax = size * maxnum;
gabomdq@6806
   723
        if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && ctx->hidden.androidio.position + bytesMax > ctx->hidden.androidio.size) {
gabomdq@6806
   724
            bytesMax = ctx->hidden.androidio.size - ctx->hidden.androidio.position;
gabomdq@6806
   725
        }
gabomdq@6806
   726
        size_t result = read(ctx->hidden.androidio.fd, buffer, bytesMax );
gabomdq@6806
   727
        if (result > 0) {
gabomdq@6806
   728
            ctx->hidden.androidio.position += result;
gabomdq@6806
   729
            return result / size;
gabomdq@6806
   730
        }
gabomdq@6806
   731
        return 0;
gabomdq@6806
   732
    } else {
gabomdq@6806
   733
        jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6806
   734
        jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
gabomdq@6806
   735
        int bytesRead = 0;
gabomdq@6377
   736
gabomdq@6806
   737
        /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6806
   738
        if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
slouken@6284
   739
gabomdq@6806
   740
        JNIEnv *mEnv = Android_JNI_GetEnv();
gabomdq@6806
   741
        if (!refs.init(mEnv)) {
gabomdq@6806
   742
            return -1;
icculus@5582
   743
        }
icculus@5582
   744
gabomdq@6806
   745
        jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
gabomdq@6806
   746
        jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
gabomdq@6806
   747
        jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
gabomdq@6806
   748
gabomdq@6806
   749
        while (bytesRemaining > 0) {
gabomdq@6806
   750
            // result = readableByteChannel.read(...);
gabomdq@6806
   751
            int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
gabomdq@6806
   752
gabomdq@6806
   753
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   754
                return 0;
gabomdq@6806
   755
            }
gabomdq@6806
   756
gabomdq@6806
   757
            if (result < 0) {
gabomdq@6806
   758
                break;
gabomdq@6806
   759
            }
gabomdq@6806
   760
gabomdq@6806
   761
            bytesRemaining -= result;
gabomdq@6806
   762
            bytesRead += result;
gabomdq@6806
   763
            ctx->hidden.androidio.position += result;
icculus@5582
   764
        }
gabomdq@6806
   765
        return bytesRead / size;
gabomdq@6806
   766
    }    
icculus@5582
   767
}
icculus@5582
   768
icculus@5582
   769
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   770
        size_t size, size_t num)
icculus@5582
   771
{
icculus@5582
   772
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   773
    return 0;
icculus@5582
   774
}
icculus@5582
   775
icculus@5582
   776
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   777
{
slouken@6650
   778
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   779
    int result = 0;
gabomdq@6354
   780
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   781
slouken@6284
   782
    if (!refs.init(mEnv)) {
slouken@6284
   783
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   784
        return -1;
slouken@6284
   785
    }
slouken@6284
   786
icculus@5582
   787
    if (ctx) {
icculus@5582
   788
        if (release) {
icculus@5582
   789
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   790
        }
icculus@5582
   791
gabomdq@6806
   792
        if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   793
            jobject inputStream = (jobject)ctx->hidden.androidio.assetFileDescriptorRef;
gabomdq@6806
   794
            jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   795
                    "close", "()V");
gabomdq@6806
   796
            mEnv->CallVoidMethod(inputStream, mid);
gabomdq@6806
   797
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   798
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   799
                result = -1;
gabomdq@6806
   800
            }
gabomdq@6806
   801
        }
gabomdq@6806
   802
        else {
gabomdq@6806
   803
            jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   804
gabomdq@6806
   805
            // inputStream.close();
gabomdq@6806
   806
            jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   807
                    "close", "()V");
gabomdq@6806
   808
            mEnv->CallVoidMethod(inputStream, mid);
gabomdq@6806
   809
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
gabomdq@6806
   810
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6806
   811
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   812
                result = -1;
gabomdq@6806
   813
            }
icculus@5582
   814
        }
icculus@5582
   815
icculus@5582
   816
        if (release) {
icculus@5582
   817
            SDL_FreeRW(ctx);
icculus@5582
   818
        }
icculus@5582
   819
    }
icculus@5582
   820
icculus@5582
   821
    return result;
icculus@5582
   822
}
icculus@5582
   823
icculus@5582
   824
slouken@6642
   825
extern "C" Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   826
{
slouken@6642
   827
    return ctx->hidden.androidio.size;
slouken@6642
   828
}
slouken@6642
   829
slouken@6642
   830
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   831
{
gabomdq@6806
   832
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   833
        switch (whence) {
gabomdq@6806
   834
            case RW_SEEK_SET:
gabomdq@6806
   835
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   836
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   837
                break;
gabomdq@6806
   838
            case RW_SEEK_CUR:
gabomdq@6806
   839
                offset += ctx->hidden.androidio.position;
gabomdq@6806
   840
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   841
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   842
                break;
gabomdq@6806
   843
            case RW_SEEK_END:
gabomdq@6806
   844
                offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset;
gabomdq@6806
   845
                break;
gabomdq@6806
   846
            default:
gabomdq@6806
   847
                SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   848
                return -1;
gabomdq@6806
   849
        }
gabomdq@6806
   850
        whence = SEEK_SET;
icculus@5582
   851
gabomdq@6806
   852
        off_t ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET);
gabomdq@6806
   853
        if (ret == -1) return -1;
gabomdq@6806
   854
        ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset;
gabomdq@6806
   855
    } else {
gabomdq@6806
   856
        Sint64 newPosition;
gabomdq@6806
   857
gabomdq@6806
   858
        switch (whence) {
gabomdq@6806
   859
            case RW_SEEK_SET:
gabomdq@6806
   860
                newPosition = offset;
gabomdq@6806
   861
                break;
gabomdq@6806
   862
            case RW_SEEK_CUR:
gabomdq@6806
   863
                newPosition = ctx->hidden.androidio.position + offset;
gabomdq@6806
   864
                break;
gabomdq@6806
   865
            case RW_SEEK_END:
gabomdq@6806
   866
                newPosition = ctx->hidden.androidio.size + offset;
gabomdq@6806
   867
                break;
gabomdq@6806
   868
            default:
gabomdq@6806
   869
                SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   870
                return -1;
gabomdq@6806
   871
        }
gabomdq@6806
   872
gabomdq@6806
   873
        /* Validate the new position */
gabomdq@6806
   874
        if (newPosition < 0) {
gabomdq@6806
   875
            SDL_Error(SDL_EFSEEK);
icculus@5582
   876
            return -1;
gabomdq@6806
   877
        }
gabomdq@6806
   878
        if (newPosition > ctx->hidden.androidio.size) {
gabomdq@6806
   879
            newPosition = ctx->hidden.androidio.size;
gabomdq@6806
   880
        }
slouken@6642
   881
gabomdq@6806
   882
        Sint64 movement = newPosition - ctx->hidden.androidio.position;
gabomdq@6806
   883
        if (movement > 0) {
gabomdq@6806
   884
            unsigned char buffer[4096];
icculus@5582
   885
gabomdq@6806
   886
            // The easy case where we're seeking forwards
gabomdq@6806
   887
            while (movement > 0) {
gabomdq@6806
   888
                Sint64 amount = sizeof (buffer);
gabomdq@6806
   889
                if (amount > movement) {
gabomdq@6806
   890
                    amount = movement;
gabomdq@6806
   891
                }
gabomdq@6806
   892
                size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
gabomdq@6806
   893
                if (result <= 0) {
gabomdq@6806
   894
                    // Failed to read/skip the required amount, so fail
gabomdq@6806
   895
                    return -1;
gabomdq@6806
   896
                }
tim@5993
   897
gabomdq@6806
   898
                movement -= result;
icculus@5582
   899
            }
tim@5993
   900
gabomdq@6806
   901
        } else if (movement < 0) {
gabomdq@6806
   902
            // We can't seek backwards so we have to reopen the file and seek
gabomdq@6806
   903
            // forwards which obviously isn't very efficient
gabomdq@6806
   904
            Android_JNI_FileClose(ctx, false);
gabomdq@6806
   905
            Android_JNI_FileOpen(ctx);
gabomdq@6806
   906
            Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   907
        }
icculus@5582
   908
    }
icculus@5582
   909
icculus@5582
   910
    return ctx->hidden.androidio.position;
gabomdq@6806
   911
    
icculus@5582
   912
}
icculus@5582
   913
icculus@5582
   914
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   915
{
icculus@5582
   916
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   917
}
icculus@5582
   918
slouken@6464
   919
// returns a new global reference which needs to be released later
slouken@6464
   920
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   921
{
slouken@6650
   922
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6464
   923
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6464
   924
    if (!refs.init(env)) {
slouken@6464
   925
        return NULL;
slouken@6464
   926
    }
slouken@6464
   927
slouken@6464
   928
    jstring service = env->NewStringUTF(name);
slouken@6464
   929
slouken@6464
   930
    jmethodID mid;
slouken@6464
   931
slouken@6464
   932
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6464
   933
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6464
   934
slouken@6464
   935
    mid = env->GetMethodID(mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
slouken@6464
   936
    jobject manager = env->CallObjectMethod(context, mid, service);
slouken@6464
   937
slouken@6464
   938
    env->DeleteLocalRef(service);
slouken@6464
   939
slouken@6464
   940
    return manager ? env->NewGlobalRef(manager) : NULL;
slouken@6464
   941
}
slouken@6464
   942
slouken@6464
   943
#define SETUP_CLIPBOARD(error) \
slouken@6650
   944
    LocalReferenceHolder refs(__FUNCTION__); \
slouken@6464
   945
    JNIEnv* env = Android_JNI_GetEnv(); \
slouken@6464
   946
    if (!refs.init(env)) { \
slouken@6464
   947
        return error; \
slouken@6464
   948
    } \
slouken@6464
   949
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
   950
    if (!clipboard) { \
slouken@6464
   951
        return error; \
slouken@6464
   952
    }
slouken@6464
   953
slouken@6464
   954
extern "C" int Android_JNI_SetClipboardText(const char* text)
slouken@6464
   955
{
slouken@6464
   956
    SETUP_CLIPBOARD(-1)
slouken@6464
   957
slouken@6464
   958
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "setText", "(Ljava/lang/CharSequence;)V");
slouken@6464
   959
    jstring string = env->NewStringUTF(text);
slouken@6464
   960
    env->CallVoidMethod(clipboard, mid, string);
slouken@6464
   961
    env->DeleteGlobalRef(clipboard);
slouken@6464
   962
    env->DeleteLocalRef(string);
slouken@6464
   963
    return 0;
slouken@6464
   964
}
slouken@6464
   965
slouken@6464
   966
extern "C" char* Android_JNI_GetClipboardText()
slouken@6464
   967
{
slouken@6464
   968
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
   969
slouken@6464
   970
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "getText", "()Ljava/lang/CharSequence;");
slouken@6464
   971
    jobject sequence = env->CallObjectMethod(clipboard, mid);
slouken@6464
   972
    env->DeleteGlobalRef(clipboard);
slouken@6464
   973
    if (sequence) {
slouken@6464
   974
        mid = env->GetMethodID(env->GetObjectClass(sequence), "toString", "()Ljava/lang/String;");
slouken@6464
   975
        jstring string = reinterpret_cast<jstring>(env->CallObjectMethod(sequence, mid));
slouken@6464
   976
        const char* utf = env->GetStringUTFChars(string, 0);
slouken@6464
   977
        if (utf) {
slouken@6464
   978
            char* text = SDL_strdup(utf);
slouken@6464
   979
            env->ReleaseStringUTFChars(string, utf);
slouken@6464
   980
            return text;
slouken@6464
   981
        }
slouken@6464
   982
    }
slouken@6464
   983
    return SDL_strdup("");
slouken@6464
   984
}
slouken@6464
   985
slouken@6464
   986
extern "C" SDL_bool Android_JNI_HasClipboardText()
slouken@6464
   987
{
slouken@6464
   988
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
   989
slouken@6464
   990
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "hasText", "()Z");
slouken@6464
   991
    jboolean has = env->CallBooleanMethod(clipboard, mid);
slouken@6464
   992
    env->DeleteGlobalRef(clipboard);
slouken@6464
   993
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
   994
}
slouken@6464
   995
slouken@6464
   996
slouken@6448
   997
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
   998
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
   999
// returns the value in seconds and percent or -1 if not available
slouken@6448
  1000
extern "C" int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
  1001
{
slouken@6650
  1002
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6448
  1003
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6448
  1004
    if (!refs.init(env)) {
slouken@6448
  1005
        return -1;
slouken@6448
  1006
    }
slouken@6448
  1007
slouken@6448
  1008
    jmethodID mid;
slouken@6448
  1009
slouken@6448
  1010
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6448
  1011
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6448
  1012
slouken@6448
  1013
    jstring action = env->NewStringUTF("android.intent.action.BATTERY_CHANGED");
slouken@6448
  1014
slouken@6448
  1015
    jclass cls = env->FindClass("android/content/IntentFilter");
slouken@6448
  1016
slouken@6448
  1017
    mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
slouken@6448
  1018
    jobject filter = env->NewObject(cls, mid, action);
slouken@6448
  1019
slouken@6448
  1020
    env->DeleteLocalRef(action);
slouken@6448
  1021
slouken@6448
  1022
    mid = env->GetMethodID(mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
slouken@6448
  1023
    jobject intent = env->CallObjectMethod(context, mid, NULL, filter);
slouken@6448
  1024
slouken@6448
  1025
    env->DeleteLocalRef(filter);
slouken@6448
  1026
slouken@6448
  1027
    cls = env->GetObjectClass(intent);
slouken@6448
  1028
slouken@6448
  1029
    jstring iname;
slouken@6448
  1030
    jmethodID imid = env->GetMethodID(cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
  1031
slouken@6448
  1032
#define GET_INT_EXTRA(var, key) \
slouken@6448
  1033
    iname = env->NewStringUTF(key); \
slouken@6448
  1034
    int var = env->CallIntMethod(intent, imid, iname, -1); \
slouken@6448
  1035
    env->DeleteLocalRef(iname);
slouken@6448
  1036
slouken@6448
  1037
    jstring bname;
slouken@6448
  1038
    jmethodID bmid = env->GetMethodID(cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
  1039
slouken@6448
  1040
#define GET_BOOL_EXTRA(var, key) \
slouken@6448
  1041
    bname = env->NewStringUTF(key); \
slouken@6448
  1042
    int var = env->CallBooleanMethod(intent, bmid, bname, JNI_FALSE); \
slouken@6448
  1043
    env->DeleteLocalRef(bname);
slouken@6448
  1044
slouken@6448
  1045
    if (plugged) {
slouken@6448
  1046
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
  1047
        if (plug == -1) {
slouken@6448
  1048
            return -1;
slouken@6448
  1049
        }
slouken@6448
  1050
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
  1051
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
  1052
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
  1053
    }
slouken@6448
  1054
slouken@6448
  1055
    if (charged) {
slouken@6448
  1056
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
  1057
        if (status == -1) {
slouken@6448
  1058
            return -1;
slouken@6448
  1059
        }
slouken@6448
  1060
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
  1061
        *charged = (status == 5) ? 1 : 0;
slouken@6448
  1062
    }
slouken@6448
  1063
slouken@6448
  1064
    if (battery) {
slouken@6448
  1065
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
  1066
        *battery = present ? 1 : 0;
slouken@6448
  1067
    }
slouken@6448
  1068
slouken@6448
  1069
    if (seconds) {
slouken@6448
  1070
        *seconds = -1; // not possible
slouken@6448
  1071
    }
slouken@6448
  1072
slouken@6448
  1073
    if (percent) {
slouken@6448
  1074
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
  1075
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
  1076
        if ((level == -1) || (scale == -1)) {
slouken@6448
  1077
            return -1;
slouken@6448
  1078
        }
slouken@6448
  1079
        *percent = level * 100 / scale;
slouken@6448
  1080
    }
slouken@6448
  1081
slouken@6448
  1082
    env->DeleteLocalRef(intent);
slouken@6448
  1083
slouken@6448
  1084
    return 0;
slouken@6448
  1085
}
slouken@6448
  1086
slouken@6392
  1087
// sends message to be handled on the UI event dispatch thread
slouken@6392
  1088
extern "C" int Android_JNI_SendMessage(int command, int param)
slouken@6392
  1089
{
slouken@6392
  1090
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
  1091
    if (!env) {
slouken@6392
  1092
        return -1;
slouken@6392
  1093
    }
slouken@6392
  1094
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "sendMessage", "(II)V");
slouken@6392
  1095
    if (!mid) {
slouken@6392
  1096
        return -1;
slouken@6392
  1097
    }
slouken@6392
  1098
    env->CallStaticVoidMethod(mActivityClass, mid, command, param);
slouken@6392
  1099
    return 0;
slouken@6392
  1100
}
slouken@6392
  1101
slouken@6654
  1102
extern "C" void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
  1103
{
slouken@6555
  1104
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
  1105
    if (!env) {
slouken@6654
  1106
        return;
slouken@6555
  1107
    }
slouken@6555
  1108
slouken@6555
  1109
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "showTextInput", "(IIII)V");
slouken@6555
  1110
    if (!mid) {
slouken@6654
  1111
        return;
slouken@6555
  1112
    }
slouken@6555
  1113
    env->CallStaticVoidMethod( mActivityClass, mid,
slouken@6555
  1114
                               inputRect->x,
slouken@6555
  1115
                               inputRect->y,
slouken@6555
  1116
                               inputRect->w,
slouken@6555
  1117
                               inputRect->h );
slouken@6555
  1118
}
slouken@6555
  1119
slouken@6654
  1120
extern "C" void Android_JNI_HideTextInput()
slouken@6555
  1121
{
slouken@6654
  1122
    // has to match Activity constant
slouken@6654
  1123
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
  1124
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
  1125
}
slouken@6555
  1126
slouken@6630
  1127
//////////////////////////////////////////////////////////////////////////////
slouken@6630
  1128
//
slouken@6630
  1129
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
  1130
//
slouken@6630
  1131
slouken@6630
  1132
extern "C" void *SDL_AndroidGetJNIEnv()
slouken@6630
  1133
{
slouken@6630
  1134
    return Android_JNI_GetEnv();
slouken@6630
  1135
}
slouken@6630
  1136
slouken@6630
  1137
extern "C" void *SDL_AndroidGetActivity()
slouken@6630
  1138
{
slouken@6650
  1139
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1140
    jmethodID mid;
slouken@6630
  1141
slouken@6630
  1142
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1143
    if (!refs.init(env)) {
slouken@6630
  1144
        return NULL;
slouken@6630
  1145
    }
slouken@6630
  1146
slouken@6630
  1147
    // return SDLActivity.getContext();
slouken@6630
  1148
    mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1149
            "getContext","()Landroid/content/Context;");
slouken@6630
  1150
    return env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1151
}
slouken@6630
  1152
slouken@6630
  1153
extern "C" const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1154
{
slouken@6630
  1155
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1156
slouken@6630
  1157
    if (!s_AndroidInternalFilesPath) {
slouken@6650
  1158
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1159
        jmethodID mid;
slouken@6630
  1160
        jobject context;
slouken@6630
  1161
        jobject fileObject;
slouken@6630
  1162
        jstring pathString;
slouken@6630
  1163
        const char *path;
slouken@6630
  1164
slouken@6630
  1165
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1166
        if (!refs.init(env)) {
slouken@6630
  1167
            return NULL;
slouken@6630
  1168
        }
slouken@6630
  1169
slouken@6630
  1170
        // context = SDLActivity.getContext();
slouken@6630
  1171
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1172
                "getContext","()Landroid/content/Context;");
slouken@6630
  1173
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1174
slouken@6630
  1175
        // fileObj = context.getFilesDir();
slouken@6630
  1176
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1177
                "getFilesDir", "()Ljava/io/File;");
slouken@6630
  1178
        fileObject = env->CallObjectMethod(context, mid);
slouken@6630
  1179
        if (!fileObject) {
slouken@6630
  1180
            SDL_SetError("Couldn't get internal directory");
slouken@6630
  1181
            return NULL;
slouken@6630
  1182
        }
slouken@6630
  1183
slouken@6630
  1184
        // path = fileObject.getAbsolutePath();
slouken@6630
  1185
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1186
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1187
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1188
slouken@6630
  1189
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1190
        s_AndroidInternalFilesPath = SDL_strdup(path);
slouken@6630
  1191
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1192
    }
slouken@6630
  1193
    return s_AndroidInternalFilesPath;
slouken@6630
  1194
}
slouken@6630
  1195
slouken@6630
  1196
extern "C" int SDL_AndroidGetExternalStorageState()
slouken@6630
  1197
{
slouken@6650
  1198
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1199
    jmethodID mid;
slouken@6630
  1200
    jclass cls;
slouken@6630
  1201
    jstring stateString;
slouken@6630
  1202
    const char *state;
slouken@6630
  1203
    int stateFlags;
slouken@6630
  1204
slouken@6630
  1205
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1206
    if (!refs.init(env)) {
slouken@6630
  1207
        return 0;
slouken@6630
  1208
    }
slouken@6630
  1209
slouken@6630
  1210
    cls = env->FindClass("android/os/Environment");
slouken@6630
  1211
    mid = env->GetStaticMethodID(cls,
slouken@6630
  1212
            "getExternalStorageState", "()Ljava/lang/String;");
slouken@6630
  1213
    stateString = (jstring)env->CallStaticObjectMethod(cls, mid);
slouken@6630
  1214
slouken@6630
  1215
    state = env->GetStringUTFChars(stateString, NULL);
slouken@6630
  1216
slouken@6630
  1217
    // Print an info message so people debugging know the storage state
slouken@6630
  1218
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1219
slouken@6630
  1220
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1221
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1222
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1223
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1224
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1225
    } else {
slouken@6630
  1226
        stateFlags = 0;
slouken@6630
  1227
    }
slouken@6630
  1228
    env->ReleaseStringUTFChars(stateString, state);
slouken@6630
  1229
slouken@6630
  1230
    return stateFlags;
slouken@6630
  1231
}
slouken@6630
  1232
slouken@6630
  1233
extern "C" const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1234
{
slouken@6630
  1235
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1236
slouken@6630
  1237
    if (!s_AndroidExternalFilesPath) {
slouken@6650
  1238
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1239
        jmethodID mid;
slouken@6630
  1240
        jobject context;
slouken@6630
  1241
        jobject fileObject;
slouken@6630
  1242
        jstring pathString;
slouken@6630
  1243
        const char *path;
slouken@6630
  1244
slouken@6630
  1245
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1246
        if (!refs.init(env)) {
slouken@6630
  1247
            return NULL;
slouken@6630
  1248
        }
slouken@6630
  1249
slouken@6630
  1250
        // context = SDLActivity.getContext();
slouken@6630
  1251
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1252
                "getContext","()Landroid/content/Context;");
slouken@6630
  1253
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1254
slouken@6630
  1255
        // fileObj = context.getExternalFilesDir();
slouken@6630
  1256
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1257
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
slouken@6630
  1258
        fileObject = env->CallObjectMethod(context, mid, NULL);
slouken@6630
  1259
        if (!fileObject) {
slouken@6630
  1260
            SDL_SetError("Couldn't get external directory");
slouken@6630
  1261
            return NULL;
slouken@6630
  1262
        }
slouken@6630
  1263
slouken@6630
  1264
        // path = fileObject.getAbsolutePath();
slouken@6630
  1265
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1266
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1267
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1268
slouken@6630
  1269
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1270
        s_AndroidExternalFilesPath = SDL_strdup(path);
slouken@6630
  1271
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1272
    }
slouken@6630
  1273
    return s_AndroidExternalFilesPath;
slouken@6630
  1274
}
slouken@6630
  1275
slouken@6044
  1276
#endif /* __ANDROID__ */
slouken@6044
  1277
slouken@4981
  1278
/* vi: set ts=4 sw=4 expandtab: */