src/core/android/SDL_android.cpp
author Gabriel Jacobo <gabomdq@gmail.com>
Tue, 08 Jan 2013 09:30:53 -0300
changeset 6806 9e57ff36fd7a
parent 6802 8a6b8ce97656
child 6816 b3d3ef1e15b5
permissions -rw-r--r--
Android: Access APK files using AssetFileDescriptor
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@6806
   616
    if (false) {
gabomdq@6806
   617
fallback:
gabomdq@6806
   618
        __android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file");
gabomdq@6806
   619
        /* Try the old method using InputStream */
gabomdq@6806
   620
        ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   621
gabomdq@6806
   622
        // inputStream = assetManager.open(<filename>);
gabomdq@6806
   623
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
gabomdq@6806
   624
                "open", "(Ljava/lang/String;I)Ljava/io/InputStream;");
gabomdq@6806
   625
        inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString, 1 /*ACCESS_RANDOM*/);
gabomdq@6806
   626
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   627
            goto failure;
gabomdq@6806
   628
        }
gabomdq@6806
   629
gabomdq@6806
   630
        ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
gabomdq@6806
   631
gabomdq@6806
   632
        // Despite all the visible documentation on [Asset]InputStream claiming
gabomdq@6806
   633
        // that the .available() method is not guaranteed to return the entire file
gabomdq@6806
   634
        // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
gabomdq@6806
   635
        // android/apis/content/ReadAsset.java imply that Android's
gabomdq@6806
   636
        // AssetInputStream.available() /will/ always return the total file size
gabomdq@6806
   637
gabomdq@6806
   638
        // size = inputStream.available();
gabomdq@6806
   639
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   640
                "available", "()I");
gabomdq@6806
   641
        ctx->hidden.androidio.size = (long)mEnv->CallIntMethod(inputStream, mid);
gabomdq@6806
   642
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   643
            goto failure;
gabomdq@6806
   644
        }
gabomdq@6806
   645
gabomdq@6806
   646
        // readableByteChannel = Channels.newChannel(inputStream);
gabomdq@6806
   647
        channels = mEnv->FindClass("java/nio/channels/Channels");
gabomdq@6806
   648
        mid = mEnv->GetStaticMethodID(channels,
gabomdq@6806
   649
                "newChannel",
gabomdq@6806
   650
                "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
gabomdq@6806
   651
        readableByteChannel = mEnv->CallStaticObjectMethod(
gabomdq@6806
   652
                channels, mid, inputStream);
gabomdq@6806
   653
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   654
            goto failure;
gabomdq@6806
   655
        }
gabomdq@6806
   656
gabomdq@6806
   657
        ctx->hidden.androidio.readableByteChannelRef =
gabomdq@6806
   658
            mEnv->NewGlobalRef(readableByteChannel);
gabomdq@6806
   659
gabomdq@6806
   660
        // Store .read id for reading purposes
gabomdq@6806
   661
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
gabomdq@6806
   662
                "read", "(Ljava/nio/ByteBuffer;)I");
gabomdq@6806
   663
        ctx->hidden.androidio.readMethod = mid;
gabomdq@6806
   664
    }
icculus@5582
   665
tim@5650
   666
    if (false) {
tim@5650
   667
failure:
tim@5650
   668
        result = -1;
tim@5650
   669
tim@5650
   670
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   671
tim@5650
   672
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   673
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   674
        }
gabomdq@6308
   675
gabomdq@6308
   676
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   677
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   678
        }
gabomdq@6308
   679
gabomdq@6806
   680
        if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) {
gabomdq@6806
   681
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   682
        }
gabomdq@6806
   683
tim@5650
   684
    }
tim@5650
   685
tim@5650
   686
    return result;
icculus@5582
   687
}
icculus@5582
   688
icculus@5582
   689
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   690
        const char* fileName, const char*)
icculus@5582
   691
{
slouken@6650
   692
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6354
   693
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   694
slouken@6284
   695
    if (!refs.init(mEnv)) {
slouken@6284
   696
        return -1;
slouken@6284
   697
    }
slouken@6284
   698
icculus@5582
   699
    if (!ctx) {
icculus@5582
   700
        return -1;
icculus@5582
   701
    }
icculus@5582
   702
icculus@5582
   703
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   704
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   705
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   706
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   707
    ctx->hidden.androidio.readMethod = NULL;
gabomdq@6806
   708
    ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   709
icculus@5582
   710
    return Android_JNI_FileOpen(ctx);
icculus@5582
   711
}
icculus@5582
   712
icculus@5582
   713
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   714
        size_t size, size_t maxnum)
icculus@5582
   715
{
slouken@6650
   716
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   717
gabomdq@6806
   718
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   719
        size_t bytesMax = size * maxnum;
gabomdq@6806
   720
        if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && ctx->hidden.androidio.position + bytesMax > ctx->hidden.androidio.size) {
gabomdq@6806
   721
            bytesMax = ctx->hidden.androidio.size - ctx->hidden.androidio.position;
gabomdq@6806
   722
        }
gabomdq@6806
   723
        size_t result = read(ctx->hidden.androidio.fd, buffer, bytesMax );
gabomdq@6806
   724
        if (result > 0) {
gabomdq@6806
   725
            ctx->hidden.androidio.position += result;
gabomdq@6806
   726
            return result / size;
gabomdq@6806
   727
        }
gabomdq@6806
   728
        return 0;
gabomdq@6806
   729
    } else {
gabomdq@6806
   730
        jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6806
   731
        jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
gabomdq@6806
   732
        int bytesRead = 0;
gabomdq@6377
   733
gabomdq@6806
   734
        /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6806
   735
        if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
slouken@6284
   736
gabomdq@6806
   737
        JNIEnv *mEnv = Android_JNI_GetEnv();
gabomdq@6806
   738
        if (!refs.init(mEnv)) {
gabomdq@6806
   739
            return -1;
icculus@5582
   740
        }
icculus@5582
   741
gabomdq@6806
   742
        jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
gabomdq@6806
   743
        jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
gabomdq@6806
   744
        jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
gabomdq@6806
   745
gabomdq@6806
   746
        while (bytesRemaining > 0) {
gabomdq@6806
   747
            // result = readableByteChannel.read(...);
gabomdq@6806
   748
            int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
gabomdq@6806
   749
gabomdq@6806
   750
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   751
                return 0;
gabomdq@6806
   752
            }
gabomdq@6806
   753
gabomdq@6806
   754
            if (result < 0) {
gabomdq@6806
   755
                break;
gabomdq@6806
   756
            }
gabomdq@6806
   757
gabomdq@6806
   758
            bytesRemaining -= result;
gabomdq@6806
   759
            bytesRead += result;
gabomdq@6806
   760
            ctx->hidden.androidio.position += result;
icculus@5582
   761
        }
gabomdq@6806
   762
        return bytesRead / size;
gabomdq@6806
   763
    }    
icculus@5582
   764
}
icculus@5582
   765
icculus@5582
   766
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   767
        size_t size, size_t num)
icculus@5582
   768
{
icculus@5582
   769
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   770
    return 0;
icculus@5582
   771
}
icculus@5582
   772
icculus@5582
   773
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   774
{
slouken@6650
   775
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   776
    int result = 0;
gabomdq@6354
   777
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   778
slouken@6284
   779
    if (!refs.init(mEnv)) {
slouken@6284
   780
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   781
        return -1;
slouken@6284
   782
    }
slouken@6284
   783
icculus@5582
   784
    if (ctx) {
icculus@5582
   785
        if (release) {
icculus@5582
   786
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   787
        }
icculus@5582
   788
gabomdq@6806
   789
        if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   790
            jobject inputStream = (jobject)ctx->hidden.androidio.assetFileDescriptorRef;
gabomdq@6806
   791
            jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   792
                    "close", "()V");
gabomdq@6806
   793
            mEnv->CallVoidMethod(inputStream, mid);
gabomdq@6806
   794
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   795
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   796
                result = -1;
gabomdq@6806
   797
            }
gabomdq@6806
   798
        }
gabomdq@6806
   799
        else {
gabomdq@6806
   800
            jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   801
gabomdq@6806
   802
            // inputStream.close();
gabomdq@6806
   803
            jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   804
                    "close", "()V");
gabomdq@6806
   805
            mEnv->CallVoidMethod(inputStream, mid);
gabomdq@6806
   806
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
gabomdq@6806
   807
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6806
   808
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   809
                result = -1;
gabomdq@6806
   810
            }
icculus@5582
   811
        }
icculus@5582
   812
icculus@5582
   813
        if (release) {
icculus@5582
   814
            SDL_FreeRW(ctx);
icculus@5582
   815
        }
icculus@5582
   816
    }
icculus@5582
   817
icculus@5582
   818
    return result;
icculus@5582
   819
}
icculus@5582
   820
icculus@5582
   821
slouken@6642
   822
extern "C" Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   823
{
slouken@6642
   824
    return ctx->hidden.androidio.size;
slouken@6642
   825
}
slouken@6642
   826
slouken@6642
   827
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   828
{
gabomdq@6806
   829
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   830
        switch (whence) {
gabomdq@6806
   831
            case RW_SEEK_SET:
gabomdq@6806
   832
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   833
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   834
                break;
gabomdq@6806
   835
            case RW_SEEK_CUR:
gabomdq@6806
   836
                offset += ctx->hidden.androidio.position;
gabomdq@6806
   837
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   838
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   839
                break;
gabomdq@6806
   840
            case RW_SEEK_END:
gabomdq@6806
   841
                offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset;
gabomdq@6806
   842
                break;
gabomdq@6806
   843
            default:
gabomdq@6806
   844
                SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   845
                return -1;
gabomdq@6806
   846
        }
gabomdq@6806
   847
        whence = SEEK_SET;
icculus@5582
   848
gabomdq@6806
   849
        off_t ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET);
gabomdq@6806
   850
        if (ret == -1) return -1;
gabomdq@6806
   851
        ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset;
gabomdq@6806
   852
    } else {
gabomdq@6806
   853
        Sint64 newPosition;
gabomdq@6806
   854
gabomdq@6806
   855
        switch (whence) {
gabomdq@6806
   856
            case RW_SEEK_SET:
gabomdq@6806
   857
                newPosition = offset;
gabomdq@6806
   858
                break;
gabomdq@6806
   859
            case RW_SEEK_CUR:
gabomdq@6806
   860
                newPosition = ctx->hidden.androidio.position + offset;
gabomdq@6806
   861
                break;
gabomdq@6806
   862
            case RW_SEEK_END:
gabomdq@6806
   863
                newPosition = ctx->hidden.androidio.size + offset;
gabomdq@6806
   864
                break;
gabomdq@6806
   865
            default:
gabomdq@6806
   866
                SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   867
                return -1;
gabomdq@6806
   868
        }
gabomdq@6806
   869
gabomdq@6806
   870
        /* Validate the new position */
gabomdq@6806
   871
        if (newPosition < 0) {
gabomdq@6806
   872
            SDL_Error(SDL_EFSEEK);
icculus@5582
   873
            return -1;
gabomdq@6806
   874
        }
gabomdq@6806
   875
        if (newPosition > ctx->hidden.androidio.size) {
gabomdq@6806
   876
            newPosition = ctx->hidden.androidio.size;
gabomdq@6806
   877
        }
slouken@6642
   878
gabomdq@6806
   879
        Sint64 movement = newPosition - ctx->hidden.androidio.position;
gabomdq@6806
   880
        if (movement > 0) {
gabomdq@6806
   881
            unsigned char buffer[4096];
icculus@5582
   882
gabomdq@6806
   883
            // The easy case where we're seeking forwards
gabomdq@6806
   884
            while (movement > 0) {
gabomdq@6806
   885
                Sint64 amount = sizeof (buffer);
gabomdq@6806
   886
                if (amount > movement) {
gabomdq@6806
   887
                    amount = movement;
gabomdq@6806
   888
                }
gabomdq@6806
   889
                size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
gabomdq@6806
   890
                if (result <= 0) {
gabomdq@6806
   891
                    // Failed to read/skip the required amount, so fail
gabomdq@6806
   892
                    return -1;
gabomdq@6806
   893
                }
tim@5993
   894
gabomdq@6806
   895
                movement -= result;
icculus@5582
   896
            }
tim@5993
   897
gabomdq@6806
   898
        } else if (movement < 0) {
gabomdq@6806
   899
            // We can't seek backwards so we have to reopen the file and seek
gabomdq@6806
   900
            // forwards which obviously isn't very efficient
gabomdq@6806
   901
            Android_JNI_FileClose(ctx, false);
gabomdq@6806
   902
            Android_JNI_FileOpen(ctx);
gabomdq@6806
   903
            Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   904
        }
icculus@5582
   905
    }
icculus@5582
   906
icculus@5582
   907
    return ctx->hidden.androidio.position;
gabomdq@6806
   908
    
icculus@5582
   909
}
icculus@5582
   910
icculus@5582
   911
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   912
{
icculus@5582
   913
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   914
}
icculus@5582
   915
slouken@6464
   916
// returns a new global reference which needs to be released later
slouken@6464
   917
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   918
{
slouken@6650
   919
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6464
   920
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6464
   921
    if (!refs.init(env)) {
slouken@6464
   922
        return NULL;
slouken@6464
   923
    }
slouken@6464
   924
slouken@6464
   925
    jstring service = env->NewStringUTF(name);
slouken@6464
   926
slouken@6464
   927
    jmethodID mid;
slouken@6464
   928
slouken@6464
   929
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6464
   930
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6464
   931
slouken@6464
   932
    mid = env->GetMethodID(mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
slouken@6464
   933
    jobject manager = env->CallObjectMethod(context, mid, service);
slouken@6464
   934
slouken@6464
   935
    env->DeleteLocalRef(service);
slouken@6464
   936
slouken@6464
   937
    return manager ? env->NewGlobalRef(manager) : NULL;
slouken@6464
   938
}
slouken@6464
   939
slouken@6464
   940
#define SETUP_CLIPBOARD(error) \
slouken@6650
   941
    LocalReferenceHolder refs(__FUNCTION__); \
slouken@6464
   942
    JNIEnv* env = Android_JNI_GetEnv(); \
slouken@6464
   943
    if (!refs.init(env)) { \
slouken@6464
   944
        return error; \
slouken@6464
   945
    } \
slouken@6464
   946
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
   947
    if (!clipboard) { \
slouken@6464
   948
        return error; \
slouken@6464
   949
    }
slouken@6464
   950
slouken@6464
   951
extern "C" int Android_JNI_SetClipboardText(const char* text)
slouken@6464
   952
{
slouken@6464
   953
    SETUP_CLIPBOARD(-1)
slouken@6464
   954
slouken@6464
   955
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "setText", "(Ljava/lang/CharSequence;)V");
slouken@6464
   956
    jstring string = env->NewStringUTF(text);
slouken@6464
   957
    env->CallVoidMethod(clipboard, mid, string);
slouken@6464
   958
    env->DeleteGlobalRef(clipboard);
slouken@6464
   959
    env->DeleteLocalRef(string);
slouken@6464
   960
    return 0;
slouken@6464
   961
}
slouken@6464
   962
slouken@6464
   963
extern "C" char* Android_JNI_GetClipboardText()
slouken@6464
   964
{
slouken@6464
   965
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
   966
slouken@6464
   967
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "getText", "()Ljava/lang/CharSequence;");
slouken@6464
   968
    jobject sequence = env->CallObjectMethod(clipboard, mid);
slouken@6464
   969
    env->DeleteGlobalRef(clipboard);
slouken@6464
   970
    if (sequence) {
slouken@6464
   971
        mid = env->GetMethodID(env->GetObjectClass(sequence), "toString", "()Ljava/lang/String;");
slouken@6464
   972
        jstring string = reinterpret_cast<jstring>(env->CallObjectMethod(sequence, mid));
slouken@6464
   973
        const char* utf = env->GetStringUTFChars(string, 0);
slouken@6464
   974
        if (utf) {
slouken@6464
   975
            char* text = SDL_strdup(utf);
slouken@6464
   976
            env->ReleaseStringUTFChars(string, utf);
slouken@6464
   977
            return text;
slouken@6464
   978
        }
slouken@6464
   979
    }
slouken@6464
   980
    return SDL_strdup("");
slouken@6464
   981
}
slouken@6464
   982
slouken@6464
   983
extern "C" SDL_bool Android_JNI_HasClipboardText()
slouken@6464
   984
{
slouken@6464
   985
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
   986
slouken@6464
   987
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "hasText", "()Z");
slouken@6464
   988
    jboolean has = env->CallBooleanMethod(clipboard, mid);
slouken@6464
   989
    env->DeleteGlobalRef(clipboard);
slouken@6464
   990
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
   991
}
slouken@6464
   992
slouken@6464
   993
slouken@6448
   994
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
   995
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
   996
// returns the value in seconds and percent or -1 if not available
slouken@6448
   997
extern "C" int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
   998
{
slouken@6650
   999
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6448
  1000
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6448
  1001
    if (!refs.init(env)) {
slouken@6448
  1002
        return -1;
slouken@6448
  1003
    }
slouken@6448
  1004
slouken@6448
  1005
    jmethodID mid;
slouken@6448
  1006
slouken@6448
  1007
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6448
  1008
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6448
  1009
slouken@6448
  1010
    jstring action = env->NewStringUTF("android.intent.action.BATTERY_CHANGED");
slouken@6448
  1011
slouken@6448
  1012
    jclass cls = env->FindClass("android/content/IntentFilter");
slouken@6448
  1013
slouken@6448
  1014
    mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
slouken@6448
  1015
    jobject filter = env->NewObject(cls, mid, action);
slouken@6448
  1016
slouken@6448
  1017
    env->DeleteLocalRef(action);
slouken@6448
  1018
slouken@6448
  1019
    mid = env->GetMethodID(mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
slouken@6448
  1020
    jobject intent = env->CallObjectMethod(context, mid, NULL, filter);
slouken@6448
  1021
slouken@6448
  1022
    env->DeleteLocalRef(filter);
slouken@6448
  1023
slouken@6448
  1024
    cls = env->GetObjectClass(intent);
slouken@6448
  1025
slouken@6448
  1026
    jstring iname;
slouken@6448
  1027
    jmethodID imid = env->GetMethodID(cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
  1028
slouken@6448
  1029
#define GET_INT_EXTRA(var, key) \
slouken@6448
  1030
    iname = env->NewStringUTF(key); \
slouken@6448
  1031
    int var = env->CallIntMethod(intent, imid, iname, -1); \
slouken@6448
  1032
    env->DeleteLocalRef(iname);
slouken@6448
  1033
slouken@6448
  1034
    jstring bname;
slouken@6448
  1035
    jmethodID bmid = env->GetMethodID(cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
  1036
slouken@6448
  1037
#define GET_BOOL_EXTRA(var, key) \
slouken@6448
  1038
    bname = env->NewStringUTF(key); \
slouken@6448
  1039
    int var = env->CallBooleanMethod(intent, bmid, bname, JNI_FALSE); \
slouken@6448
  1040
    env->DeleteLocalRef(bname);
slouken@6448
  1041
slouken@6448
  1042
    if (plugged) {
slouken@6448
  1043
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
  1044
        if (plug == -1) {
slouken@6448
  1045
            return -1;
slouken@6448
  1046
        }
slouken@6448
  1047
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
  1048
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
  1049
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
  1050
    }
slouken@6448
  1051
slouken@6448
  1052
    if (charged) {
slouken@6448
  1053
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
  1054
        if (status == -1) {
slouken@6448
  1055
            return -1;
slouken@6448
  1056
        }
slouken@6448
  1057
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
  1058
        *charged = (status == 5) ? 1 : 0;
slouken@6448
  1059
    }
slouken@6448
  1060
slouken@6448
  1061
    if (battery) {
slouken@6448
  1062
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
  1063
        *battery = present ? 1 : 0;
slouken@6448
  1064
    }
slouken@6448
  1065
slouken@6448
  1066
    if (seconds) {
slouken@6448
  1067
        *seconds = -1; // not possible
slouken@6448
  1068
    }
slouken@6448
  1069
slouken@6448
  1070
    if (percent) {
slouken@6448
  1071
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
  1072
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
  1073
        if ((level == -1) || (scale == -1)) {
slouken@6448
  1074
            return -1;
slouken@6448
  1075
        }
slouken@6448
  1076
        *percent = level * 100 / scale;
slouken@6448
  1077
    }
slouken@6448
  1078
slouken@6448
  1079
    env->DeleteLocalRef(intent);
slouken@6448
  1080
slouken@6448
  1081
    return 0;
slouken@6448
  1082
}
slouken@6448
  1083
slouken@6392
  1084
// sends message to be handled on the UI event dispatch thread
slouken@6392
  1085
extern "C" int Android_JNI_SendMessage(int command, int param)
slouken@6392
  1086
{
slouken@6392
  1087
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
  1088
    if (!env) {
slouken@6392
  1089
        return -1;
slouken@6392
  1090
    }
slouken@6392
  1091
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "sendMessage", "(II)V");
slouken@6392
  1092
    if (!mid) {
slouken@6392
  1093
        return -1;
slouken@6392
  1094
    }
slouken@6392
  1095
    env->CallStaticVoidMethod(mActivityClass, mid, command, param);
slouken@6392
  1096
    return 0;
slouken@6392
  1097
}
slouken@6392
  1098
slouken@6654
  1099
extern "C" void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
  1100
{
slouken@6555
  1101
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
  1102
    if (!env) {
slouken@6654
  1103
        return;
slouken@6555
  1104
    }
slouken@6555
  1105
slouken@6555
  1106
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "showTextInput", "(IIII)V");
slouken@6555
  1107
    if (!mid) {
slouken@6654
  1108
        return;
slouken@6555
  1109
    }
slouken@6555
  1110
    env->CallStaticVoidMethod( mActivityClass, mid,
slouken@6555
  1111
                               inputRect->x,
slouken@6555
  1112
                               inputRect->y,
slouken@6555
  1113
                               inputRect->w,
slouken@6555
  1114
                               inputRect->h );
slouken@6555
  1115
}
slouken@6555
  1116
slouken@6654
  1117
extern "C" void Android_JNI_HideTextInput()
slouken@6555
  1118
{
slouken@6654
  1119
    // has to match Activity constant
slouken@6654
  1120
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
  1121
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
  1122
}
slouken@6555
  1123
slouken@6630
  1124
//////////////////////////////////////////////////////////////////////////////
slouken@6630
  1125
//
slouken@6630
  1126
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
  1127
//
slouken@6630
  1128
slouken@6630
  1129
extern "C" void *SDL_AndroidGetJNIEnv()
slouken@6630
  1130
{
slouken@6630
  1131
    return Android_JNI_GetEnv();
slouken@6630
  1132
}
slouken@6630
  1133
slouken@6630
  1134
extern "C" void *SDL_AndroidGetActivity()
slouken@6630
  1135
{
slouken@6650
  1136
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1137
    jmethodID mid;
slouken@6630
  1138
slouken@6630
  1139
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1140
    if (!refs.init(env)) {
slouken@6630
  1141
        return NULL;
slouken@6630
  1142
    }
slouken@6630
  1143
slouken@6630
  1144
    // return SDLActivity.getContext();
slouken@6630
  1145
    mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1146
            "getContext","()Landroid/content/Context;");
slouken@6630
  1147
    return env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1148
}
slouken@6630
  1149
slouken@6630
  1150
extern "C" const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1151
{
slouken@6630
  1152
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1153
slouken@6630
  1154
    if (!s_AndroidInternalFilesPath) {
slouken@6650
  1155
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1156
        jmethodID mid;
slouken@6630
  1157
        jobject context;
slouken@6630
  1158
        jobject fileObject;
slouken@6630
  1159
        jstring pathString;
slouken@6630
  1160
        const char *path;
slouken@6630
  1161
slouken@6630
  1162
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1163
        if (!refs.init(env)) {
slouken@6630
  1164
            return NULL;
slouken@6630
  1165
        }
slouken@6630
  1166
slouken@6630
  1167
        // context = SDLActivity.getContext();
slouken@6630
  1168
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1169
                "getContext","()Landroid/content/Context;");
slouken@6630
  1170
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1171
slouken@6630
  1172
        // fileObj = context.getFilesDir();
slouken@6630
  1173
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1174
                "getFilesDir", "()Ljava/io/File;");
slouken@6630
  1175
        fileObject = env->CallObjectMethod(context, mid);
slouken@6630
  1176
        if (!fileObject) {
slouken@6630
  1177
            SDL_SetError("Couldn't get internal directory");
slouken@6630
  1178
            return NULL;
slouken@6630
  1179
        }
slouken@6630
  1180
slouken@6630
  1181
        // path = fileObject.getAbsolutePath();
slouken@6630
  1182
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1183
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1184
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1185
slouken@6630
  1186
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1187
        s_AndroidInternalFilesPath = SDL_strdup(path);
slouken@6630
  1188
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1189
    }
slouken@6630
  1190
    return s_AndroidInternalFilesPath;
slouken@6630
  1191
}
slouken@6630
  1192
slouken@6630
  1193
extern "C" int SDL_AndroidGetExternalStorageState()
slouken@6630
  1194
{
slouken@6650
  1195
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1196
    jmethodID mid;
slouken@6630
  1197
    jclass cls;
slouken@6630
  1198
    jstring stateString;
slouken@6630
  1199
    const char *state;
slouken@6630
  1200
    int stateFlags;
slouken@6630
  1201
slouken@6630
  1202
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1203
    if (!refs.init(env)) {
slouken@6630
  1204
        return 0;
slouken@6630
  1205
    }
slouken@6630
  1206
slouken@6630
  1207
    cls = env->FindClass("android/os/Environment");
slouken@6630
  1208
    mid = env->GetStaticMethodID(cls,
slouken@6630
  1209
            "getExternalStorageState", "()Ljava/lang/String;");
slouken@6630
  1210
    stateString = (jstring)env->CallStaticObjectMethod(cls, mid);
slouken@6630
  1211
slouken@6630
  1212
    state = env->GetStringUTFChars(stateString, NULL);
slouken@6630
  1213
slouken@6630
  1214
    // Print an info message so people debugging know the storage state
slouken@6630
  1215
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1216
slouken@6630
  1217
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1218
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1219
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1220
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1221
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1222
    } else {
slouken@6630
  1223
        stateFlags = 0;
slouken@6630
  1224
    }
slouken@6630
  1225
    env->ReleaseStringUTFChars(stateString, state);
slouken@6630
  1226
slouken@6630
  1227
    return stateFlags;
slouken@6630
  1228
}
slouken@6630
  1229
slouken@6630
  1230
extern "C" const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1231
{
slouken@6630
  1232
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1233
slouken@6630
  1234
    if (!s_AndroidExternalFilesPath) {
slouken@6650
  1235
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1236
        jmethodID mid;
slouken@6630
  1237
        jobject context;
slouken@6630
  1238
        jobject fileObject;
slouken@6630
  1239
        jstring pathString;
slouken@6630
  1240
        const char *path;
slouken@6630
  1241
slouken@6630
  1242
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1243
        if (!refs.init(env)) {
slouken@6630
  1244
            return NULL;
slouken@6630
  1245
        }
slouken@6630
  1246
slouken@6630
  1247
        // context = SDLActivity.getContext();
slouken@6630
  1248
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1249
                "getContext","()Landroid/content/Context;");
slouken@6630
  1250
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1251
slouken@6630
  1252
        // fileObj = context.getExternalFilesDir();
slouken@6630
  1253
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1254
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
slouken@6630
  1255
        fileObject = env->CallObjectMethod(context, mid, NULL);
slouken@6630
  1256
        if (!fileObject) {
slouken@6630
  1257
            SDL_SetError("Couldn't get external directory");
slouken@6630
  1258
            return NULL;
slouken@6630
  1259
        }
slouken@6630
  1260
slouken@6630
  1261
        // path = fileObject.getAbsolutePath();
slouken@6630
  1262
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1263
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1264
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1265
slouken@6630
  1266
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1267
        s_AndroidExternalFilesPath = SDL_strdup(path);
slouken@6630
  1268
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1269
    }
slouken@6630
  1270
    return s_AndroidExternalFilesPath;
slouken@6630
  1271
}
slouken@6630
  1272
slouken@6044
  1273
#endif /* __ANDROID__ */
slouken@6044
  1274
slouken@4981
  1275
/* vi: set ts=4 sw=4 expandtab: */