src/core/android/SDL_android.cpp
author Gabriel Jacobo <gabomdq@gmail.com>
Tue, 12 Feb 2013 13:59:04 -0300
changeset 6864 97187387ad79
parent 6828 ac7f004fb63c
child 6885 700f1b25f77f
permissions -rw-r--r--
Bug 1703 - SDL calls a wrong JNI function on Android by Philipp Wiesemann
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
slouken@4996
   433
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   434
    audioBuffer16Bit = is16Bit;
slouken@4996
   435
    audioBufferStereo = channelCount > 1;
slouken@4964
   436
gabomdq@6864
   437
    env->CallStaticVoidMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
gabomdq@6802
   438
gabomdq@6802
   439
    /* Allocating the audio buffer from the Java side and passing it as the return value for audioInit no longer works on
gabomdq@6802
   440
     * Android >= 4.2 due to a "stale global reference" error. So now we allocate this buffer directly from this side. */
gabomdq@6802
   441
    
gabomdq@6802
   442
    if (is16Bit) {
gabomdq@6802
   443
        jshortArray audioBufferLocal = env->NewShortArray(desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   444
        if (audioBufferLocal) {
gabomdq@6802
   445
            audioBuffer = env->NewGlobalRef(audioBufferLocal);
gabomdq@6802
   446
            env->DeleteLocalRef(audioBufferLocal);
gabomdq@6802
   447
        }
gabomdq@6802
   448
    }
gabomdq@6802
   449
    else {
gabomdq@6802
   450
        jbyteArray audioBufferLocal = env->NewByteArray(desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   451
        if (audioBufferLocal) {
gabomdq@6802
   452
            audioBuffer = env->NewGlobalRef(audioBufferLocal);
gabomdq@6802
   453
            env->DeleteLocalRef(audioBufferLocal);
gabomdq@6802
   454
        }
gabomdq@6802
   455
    }
slouken@4995
   456
slouken@4996
   457
    if (audioBuffer == NULL) {
gabomdq@6802
   458
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer!");
slouken@4996
   459
        return 0;
slouken@4996
   460
    }
slouken@4995
   461
slouken@4996
   462
    jboolean isCopy = JNI_FALSE;
slouken@4996
   463
    if (audioBuffer16Bit) {
icculus@5996
   464
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   465
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   466
    } else {
icculus@5996
   467
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   468
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   469
    }
slouken@4996
   470
    if (audioBufferStereo) {
slouken@4996
   471
        audioBufferFrames /= 2;
slouken@4996
   472
    }
gabomdq@6864
   473
slouken@4996
   474
    return audioBufferFrames;
slouken@4995
   475
}
slouken@4995
   476
slouken@4996
   477
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   478
{
slouken@4996
   479
    return audioBufferPinned;
slouken@4995
   480
}
slouken@4995
   481
slouken@4996
   482
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   483
{
gabomdq@6354
   484
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   485
slouken@4996
   486
    if (audioBuffer16Bit) {
slouken@4996
   487
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   488
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   489
    } else {
slouken@4996
   490
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   491
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   492
    }
slouken@4995
   493
slouken@4996
   494
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   495
}
slouken@4995
   496
slouken@4995
   497
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   498
{
icculus@5996
   499
    int status;
gabomdq@6354
   500
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   501
icculus@5996
   502
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   503
slouken@4997
   504
    if (audioBuffer) {
icculus@5996
   505
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   506
        audioBuffer = NULL;
slouken@4997
   507
        audioBufferPinned = NULL;
slouken@4997
   508
    }
slouken@4964
   509
}
slouken@4981
   510
tim@5650
   511
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   512
static bool Android_JNI_ExceptionOccurred()
tim@5650
   513
{
slouken@6284
   514
    SDL_assert(LocalReferenceHolder::IsActive());
gabomdq@6354
   515
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   516
tim@5650
   517
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   518
    if (exception != NULL) {
tim@5650
   519
        jmethodID mid;
tim@5650
   520
tim@5650
   521
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   522
        mEnv->ExceptionClear();
tim@5650
   523
tim@5650
   524
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   525
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   526
tim@5650
   527
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   528
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   529
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   530
tim@5650
   531
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   532
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   533
tim@5650
   534
        if (exceptionMessage != NULL) {
tim@5650
   535
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   536
                    exceptionMessage, 0);
tim@5650
   537
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   538
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   539
        } else {
tim@5650
   540
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   541
        }
tim@5650
   542
tim@5650
   543
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   544
tim@5650
   545
        return true;
tim@5650
   546
    }
tim@5650
   547
tim@5650
   548
    return false;
tim@5650
   549
}
tim@5650
   550
icculus@5582
   551
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   552
{
slouken@6650
   553
    LocalReferenceHolder refs(__FUNCTION__);
tim@5650
   554
    int result = 0;
tim@5650
   555
tim@5650
   556
    jmethodID mid;
tim@5650
   557
    jobject context;
tim@5650
   558
    jobject assetManager;
tim@5650
   559
    jobject inputStream;
tim@5650
   560
    jclass channels;
tim@5650
   561
    jobject readableByteChannel;
tim@5650
   562
    jstring fileNameJString;
gabomdq@6806
   563
    jobject fd;
gabomdq@6806
   564
    jclass fdCls;
gabomdq@6806
   565
    jfieldID descriptor;
tim@5650
   566
gabomdq@6354
   567
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   568
    if (!refs.init(mEnv)) {
tim@5650
   569
        goto failure;
tim@5650
   570
    }
tim@5650
   571
gabomdq@6308
   572
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
gabomdq@6806
   573
    ctx->hidden.androidio.position = 0;
icculus@5582
   574
icculus@5582
   575
    // context = SDLActivity.getContext();
tim@5650
   576
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   577
            "getContext","()Landroid/content/Context;");
tim@5650
   578
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
gabomdq@6806
   579
    
icculus@5582
   580
icculus@5582
   581
    // assetManager = context.getAssets();
icculus@5582
   582
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   583
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   584
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   585
gabomdq@6806
   586
    /* First let's try opening the file to obtain an AssetFileDescriptor.
gabomdq@6806
   587
    * This method reads the files directly from the APKs using standard *nix calls
gabomdq@6806
   588
    */
gabomdq@6806
   589
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager), "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;");
tim@5650
   590
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   591
    if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   592
        goto fallback;
icculus@5582
   593
    }
icculus@5582
   594
gabomdq@6806
   595
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getStartOffset", "()J");
gabomdq@6806
   596
    ctx->hidden.androidio.offset = mEnv->CallLongMethod(inputStream, mid);
tim@5650
   597
    if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   598
        goto fallback;
icculus@5582
   599
    }
icculus@5582
   600
gabomdq@6806
   601
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getDeclaredLength", "()J");
gabomdq@6806
   602
    ctx->hidden.androidio.size = mEnv->CallLongMethod(inputStream, mid);
tim@5650
   603
    if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   604
        goto fallback;
icculus@5582
   605
    }
icculus@5582
   606
gabomdq@6806
   607
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream), "getFileDescriptor", "()Ljava/io/FileDescriptor;");
gabomdq@6806
   608
    fd = mEnv->CallObjectMethod(inputStream, mid);
gabomdq@6806
   609
    fdCls = mEnv->GetObjectClass(fd);
gabomdq@6806
   610
    descriptor = mEnv->GetFieldID(fdCls, "descriptor", "I");
gabomdq@6806
   611
    ctx->hidden.androidio.fd = mEnv->GetIntField(fd, descriptor);
gabomdq@6828
   612
    ctx->hidden.androidio.assetFileDescriptorRef = mEnv->NewGlobalRef(inputStream);
tim@5650
   613
gabomdq@6816
   614
    // Seek to the correct offset in the file.
gabomdq@6816
   615
    lseek(ctx->hidden.androidio.fd, (off_t)ctx->hidden.androidio.offset, SEEK_SET);
gabomdq@6816
   616
gabomdq@6806
   617
    if (false) {
gabomdq@6806
   618
fallback:
gabomdq@6806
   619
        __android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file");
gabomdq@6806
   620
        /* Try the old method using InputStream */
gabomdq@6806
   621
        ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   622
gabomdq@6806
   623
        // inputStream = assetManager.open(<filename>);
gabomdq@6806
   624
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
gabomdq@6806
   625
                "open", "(Ljava/lang/String;I)Ljava/io/InputStream;");
gabomdq@6806
   626
        inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString, 1 /*ACCESS_RANDOM*/);
gabomdq@6806
   627
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   628
            goto failure;
gabomdq@6806
   629
        }
gabomdq@6806
   630
gabomdq@6806
   631
        ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
gabomdq@6806
   632
gabomdq@6806
   633
        // Despite all the visible documentation on [Asset]InputStream claiming
gabomdq@6806
   634
        // that the .available() method is not guaranteed to return the entire file
gabomdq@6806
   635
        // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
gabomdq@6806
   636
        // android/apis/content/ReadAsset.java imply that Android's
gabomdq@6806
   637
        // AssetInputStream.available() /will/ always return the total file size
gabomdq@6806
   638
gabomdq@6806
   639
        // size = inputStream.available();
gabomdq@6806
   640
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   641
                "available", "()I");
gabomdq@6806
   642
        ctx->hidden.androidio.size = (long)mEnv->CallIntMethod(inputStream, mid);
gabomdq@6806
   643
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   644
            goto failure;
gabomdq@6806
   645
        }
gabomdq@6806
   646
gabomdq@6806
   647
        // readableByteChannel = Channels.newChannel(inputStream);
gabomdq@6806
   648
        channels = mEnv->FindClass("java/nio/channels/Channels");
gabomdq@6806
   649
        mid = mEnv->GetStaticMethodID(channels,
gabomdq@6806
   650
                "newChannel",
gabomdq@6806
   651
                "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
gabomdq@6806
   652
        readableByteChannel = mEnv->CallStaticObjectMethod(
gabomdq@6806
   653
                channels, mid, inputStream);
gabomdq@6806
   654
        if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   655
            goto failure;
gabomdq@6806
   656
        }
gabomdq@6806
   657
gabomdq@6806
   658
        ctx->hidden.androidio.readableByteChannelRef =
gabomdq@6806
   659
            mEnv->NewGlobalRef(readableByteChannel);
gabomdq@6806
   660
gabomdq@6806
   661
        // Store .read id for reading purposes
gabomdq@6806
   662
        mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
gabomdq@6806
   663
                "read", "(Ljava/nio/ByteBuffer;)I");
gabomdq@6806
   664
        ctx->hidden.androidio.readMethod = mid;
gabomdq@6806
   665
    }
icculus@5582
   666
tim@5650
   667
    if (false) {
tim@5650
   668
failure:
tim@5650
   669
        result = -1;
tim@5650
   670
tim@5650
   671
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   672
tim@5650
   673
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   674
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   675
        }
gabomdq@6308
   676
gabomdq@6308
   677
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   678
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   679
        }
gabomdq@6308
   680
gabomdq@6806
   681
        if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) {
gabomdq@6806
   682
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   683
        }
gabomdq@6806
   684
tim@5650
   685
    }
tim@5650
   686
tim@5650
   687
    return result;
icculus@5582
   688
}
icculus@5582
   689
icculus@5582
   690
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   691
        const char* fileName, const char*)
icculus@5582
   692
{
slouken@6650
   693
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6354
   694
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   695
slouken@6284
   696
    if (!refs.init(mEnv)) {
slouken@6284
   697
        return -1;
slouken@6284
   698
    }
slouken@6284
   699
icculus@5582
   700
    if (!ctx) {
icculus@5582
   701
        return -1;
icculus@5582
   702
    }
icculus@5582
   703
icculus@5582
   704
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   705
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   706
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   707
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   708
    ctx->hidden.androidio.readMethod = NULL;
gabomdq@6806
   709
    ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   710
icculus@5582
   711
    return Android_JNI_FileOpen(ctx);
icculus@5582
   712
}
icculus@5582
   713
icculus@5582
   714
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   715
        size_t size, size_t maxnum)
icculus@5582
   716
{
slouken@6650
   717
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   718
gabomdq@6806
   719
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   720
        size_t bytesMax = size * maxnum;
gabomdq@6806
   721
        if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && ctx->hidden.androidio.position + bytesMax > ctx->hidden.androidio.size) {
gabomdq@6806
   722
            bytesMax = ctx->hidden.androidio.size - ctx->hidden.androidio.position;
gabomdq@6806
   723
        }
gabomdq@6806
   724
        size_t result = read(ctx->hidden.androidio.fd, buffer, bytesMax );
gabomdq@6806
   725
        if (result > 0) {
gabomdq@6806
   726
            ctx->hidden.androidio.position += result;
gabomdq@6806
   727
            return result / size;
gabomdq@6806
   728
        }
gabomdq@6806
   729
        return 0;
gabomdq@6806
   730
    } else {
gabomdq@6806
   731
        jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6806
   732
        jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
gabomdq@6806
   733
        int bytesRead = 0;
gabomdq@6377
   734
gabomdq@6806
   735
        /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6806
   736
        if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
slouken@6284
   737
gabomdq@6806
   738
        JNIEnv *mEnv = Android_JNI_GetEnv();
gabomdq@6806
   739
        if (!refs.init(mEnv)) {
gabomdq@6806
   740
            return -1;
icculus@5582
   741
        }
icculus@5582
   742
gabomdq@6806
   743
        jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
gabomdq@6806
   744
        jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
gabomdq@6806
   745
        jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
gabomdq@6806
   746
gabomdq@6806
   747
        while (bytesRemaining > 0) {
gabomdq@6806
   748
            // result = readableByteChannel.read(...);
gabomdq@6806
   749
            int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
gabomdq@6806
   750
gabomdq@6806
   751
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   752
                return 0;
gabomdq@6806
   753
            }
gabomdq@6806
   754
gabomdq@6806
   755
            if (result < 0) {
gabomdq@6806
   756
                break;
gabomdq@6806
   757
            }
gabomdq@6806
   758
gabomdq@6806
   759
            bytesRemaining -= result;
gabomdq@6806
   760
            bytesRead += result;
gabomdq@6806
   761
            ctx->hidden.androidio.position += result;
icculus@5582
   762
        }
gabomdq@6806
   763
        return bytesRead / size;
gabomdq@6806
   764
    }    
icculus@5582
   765
}
icculus@5582
   766
icculus@5582
   767
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   768
        size_t size, size_t num)
icculus@5582
   769
{
icculus@5582
   770
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   771
    return 0;
icculus@5582
   772
}
icculus@5582
   773
icculus@5582
   774
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   775
{
slouken@6650
   776
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   777
    int result = 0;
gabomdq@6354
   778
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   779
slouken@6284
   780
    if (!refs.init(mEnv)) {
slouken@6284
   781
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   782
        return -1;
slouken@6284
   783
    }
slouken@6284
   784
icculus@5582
   785
    if (ctx) {
icculus@5582
   786
        if (release) {
icculus@5582
   787
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   788
        }
icculus@5582
   789
gabomdq@6806
   790
        if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   791
            jobject inputStream = (jobject)ctx->hidden.androidio.assetFileDescriptorRef;
gabomdq@6806
   792
            jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   793
                    "close", "()V");
gabomdq@6806
   794
            mEnv->CallVoidMethod(inputStream, mid);
gabomdq@6806
   795
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   796
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   797
                result = -1;
gabomdq@6806
   798
            }
gabomdq@6806
   799
        }
gabomdq@6806
   800
        else {
gabomdq@6806
   801
            jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   802
gabomdq@6806
   803
            // inputStream.close();
gabomdq@6806
   804
            jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
gabomdq@6806
   805
                    "close", "()V");
gabomdq@6806
   806
            mEnv->CallVoidMethod(inputStream, mid);
gabomdq@6806
   807
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
gabomdq@6806
   808
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6806
   809
            if (Android_JNI_ExceptionOccurred()) {
gabomdq@6806
   810
                result = -1;
gabomdq@6806
   811
            }
icculus@5582
   812
        }
icculus@5582
   813
icculus@5582
   814
        if (release) {
icculus@5582
   815
            SDL_FreeRW(ctx);
icculus@5582
   816
        }
icculus@5582
   817
    }
icculus@5582
   818
icculus@5582
   819
    return result;
icculus@5582
   820
}
icculus@5582
   821
icculus@5582
   822
slouken@6642
   823
extern "C" Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   824
{
slouken@6642
   825
    return ctx->hidden.androidio.size;
slouken@6642
   826
}
slouken@6642
   827
slouken@6642
   828
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   829
{
gabomdq@6806
   830
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   831
        switch (whence) {
gabomdq@6806
   832
            case RW_SEEK_SET:
gabomdq@6806
   833
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   834
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   835
                break;
gabomdq@6806
   836
            case RW_SEEK_CUR:
gabomdq@6806
   837
                offset += ctx->hidden.androidio.position;
gabomdq@6806
   838
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   839
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   840
                break;
gabomdq@6806
   841
            case RW_SEEK_END:
gabomdq@6806
   842
                offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset;
gabomdq@6806
   843
                break;
gabomdq@6806
   844
            default:
gabomdq@6806
   845
                SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   846
                return -1;
gabomdq@6806
   847
        }
gabomdq@6806
   848
        whence = SEEK_SET;
icculus@5582
   849
gabomdq@6806
   850
        off_t ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET);
gabomdq@6806
   851
        if (ret == -1) return -1;
gabomdq@6806
   852
        ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset;
gabomdq@6806
   853
    } else {
gabomdq@6806
   854
        Sint64 newPosition;
gabomdq@6806
   855
gabomdq@6806
   856
        switch (whence) {
gabomdq@6806
   857
            case RW_SEEK_SET:
gabomdq@6806
   858
                newPosition = offset;
gabomdq@6806
   859
                break;
gabomdq@6806
   860
            case RW_SEEK_CUR:
gabomdq@6806
   861
                newPosition = ctx->hidden.androidio.position + offset;
gabomdq@6806
   862
                break;
gabomdq@6806
   863
            case RW_SEEK_END:
gabomdq@6806
   864
                newPosition = ctx->hidden.androidio.size + offset;
gabomdq@6806
   865
                break;
gabomdq@6806
   866
            default:
gabomdq@6806
   867
                SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   868
                return -1;
gabomdq@6806
   869
        }
gabomdq@6806
   870
gabomdq@6806
   871
        /* Validate the new position */
gabomdq@6806
   872
        if (newPosition < 0) {
gabomdq@6806
   873
            SDL_Error(SDL_EFSEEK);
icculus@5582
   874
            return -1;
gabomdq@6806
   875
        }
gabomdq@6806
   876
        if (newPosition > ctx->hidden.androidio.size) {
gabomdq@6806
   877
            newPosition = ctx->hidden.androidio.size;
gabomdq@6806
   878
        }
slouken@6642
   879
gabomdq@6806
   880
        Sint64 movement = newPosition - ctx->hidden.androidio.position;
gabomdq@6806
   881
        if (movement > 0) {
gabomdq@6806
   882
            unsigned char buffer[4096];
icculus@5582
   883
gabomdq@6806
   884
            // The easy case where we're seeking forwards
gabomdq@6806
   885
            while (movement > 0) {
gabomdq@6806
   886
                Sint64 amount = sizeof (buffer);
gabomdq@6806
   887
                if (amount > movement) {
gabomdq@6806
   888
                    amount = movement;
gabomdq@6806
   889
                }
gabomdq@6806
   890
                size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
gabomdq@6806
   891
                if (result <= 0) {
gabomdq@6806
   892
                    // Failed to read/skip the required amount, so fail
gabomdq@6806
   893
                    return -1;
gabomdq@6806
   894
                }
tim@5993
   895
gabomdq@6806
   896
                movement -= result;
icculus@5582
   897
            }
tim@5993
   898
gabomdq@6806
   899
        } else if (movement < 0) {
gabomdq@6806
   900
            // We can't seek backwards so we have to reopen the file and seek
gabomdq@6806
   901
            // forwards which obviously isn't very efficient
gabomdq@6806
   902
            Android_JNI_FileClose(ctx, false);
gabomdq@6806
   903
            Android_JNI_FileOpen(ctx);
gabomdq@6806
   904
            Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   905
        }
icculus@5582
   906
    }
icculus@5582
   907
icculus@5582
   908
    return ctx->hidden.androidio.position;
gabomdq@6806
   909
    
icculus@5582
   910
}
icculus@5582
   911
icculus@5582
   912
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   913
{
icculus@5582
   914
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   915
}
icculus@5582
   916
slouken@6464
   917
// returns a new global reference which needs to be released later
slouken@6464
   918
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   919
{
slouken@6650
   920
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6464
   921
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6464
   922
    if (!refs.init(env)) {
slouken@6464
   923
        return NULL;
slouken@6464
   924
    }
slouken@6464
   925
slouken@6464
   926
    jstring service = env->NewStringUTF(name);
slouken@6464
   927
slouken@6464
   928
    jmethodID mid;
slouken@6464
   929
slouken@6464
   930
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6464
   931
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6464
   932
slouken@6464
   933
    mid = env->GetMethodID(mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
slouken@6464
   934
    jobject manager = env->CallObjectMethod(context, mid, service);
slouken@6464
   935
slouken@6464
   936
    env->DeleteLocalRef(service);
slouken@6464
   937
slouken@6464
   938
    return manager ? env->NewGlobalRef(manager) : NULL;
slouken@6464
   939
}
slouken@6464
   940
slouken@6464
   941
#define SETUP_CLIPBOARD(error) \
slouken@6650
   942
    LocalReferenceHolder refs(__FUNCTION__); \
slouken@6464
   943
    JNIEnv* env = Android_JNI_GetEnv(); \
slouken@6464
   944
    if (!refs.init(env)) { \
slouken@6464
   945
        return error; \
slouken@6464
   946
    } \
slouken@6464
   947
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
   948
    if (!clipboard) { \
slouken@6464
   949
        return error; \
slouken@6464
   950
    }
slouken@6464
   951
slouken@6464
   952
extern "C" int Android_JNI_SetClipboardText(const char* text)
slouken@6464
   953
{
slouken@6464
   954
    SETUP_CLIPBOARD(-1)
slouken@6464
   955
slouken@6464
   956
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "setText", "(Ljava/lang/CharSequence;)V");
slouken@6464
   957
    jstring string = env->NewStringUTF(text);
slouken@6464
   958
    env->CallVoidMethod(clipboard, mid, string);
slouken@6464
   959
    env->DeleteGlobalRef(clipboard);
slouken@6464
   960
    env->DeleteLocalRef(string);
slouken@6464
   961
    return 0;
slouken@6464
   962
}
slouken@6464
   963
slouken@6464
   964
extern "C" char* Android_JNI_GetClipboardText()
slouken@6464
   965
{
slouken@6464
   966
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
   967
slouken@6464
   968
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "getText", "()Ljava/lang/CharSequence;");
slouken@6464
   969
    jobject sequence = env->CallObjectMethod(clipboard, mid);
slouken@6464
   970
    env->DeleteGlobalRef(clipboard);
slouken@6464
   971
    if (sequence) {
slouken@6464
   972
        mid = env->GetMethodID(env->GetObjectClass(sequence), "toString", "()Ljava/lang/String;");
slouken@6464
   973
        jstring string = reinterpret_cast<jstring>(env->CallObjectMethod(sequence, mid));
slouken@6464
   974
        const char* utf = env->GetStringUTFChars(string, 0);
slouken@6464
   975
        if (utf) {
slouken@6464
   976
            char* text = SDL_strdup(utf);
slouken@6464
   977
            env->ReleaseStringUTFChars(string, utf);
slouken@6464
   978
            return text;
slouken@6464
   979
        }
slouken@6464
   980
    }
slouken@6464
   981
    return SDL_strdup("");
slouken@6464
   982
}
slouken@6464
   983
slouken@6464
   984
extern "C" SDL_bool Android_JNI_HasClipboardText()
slouken@6464
   985
{
slouken@6464
   986
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
   987
slouken@6464
   988
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "hasText", "()Z");
slouken@6464
   989
    jboolean has = env->CallBooleanMethod(clipboard, mid);
slouken@6464
   990
    env->DeleteGlobalRef(clipboard);
slouken@6464
   991
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
   992
}
slouken@6464
   993
slouken@6464
   994
slouken@6448
   995
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
   996
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
   997
// returns the value in seconds and percent or -1 if not available
slouken@6448
   998
extern "C" int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
   999
{
slouken@6650
  1000
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6448
  1001
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6448
  1002
    if (!refs.init(env)) {
slouken@6448
  1003
        return -1;
slouken@6448
  1004
    }
slouken@6448
  1005
slouken@6448
  1006
    jmethodID mid;
slouken@6448
  1007
slouken@6448
  1008
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6448
  1009
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6448
  1010
slouken@6448
  1011
    jstring action = env->NewStringUTF("android.intent.action.BATTERY_CHANGED");
slouken@6448
  1012
slouken@6448
  1013
    jclass cls = env->FindClass("android/content/IntentFilter");
slouken@6448
  1014
slouken@6448
  1015
    mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
slouken@6448
  1016
    jobject filter = env->NewObject(cls, mid, action);
slouken@6448
  1017
slouken@6448
  1018
    env->DeleteLocalRef(action);
slouken@6448
  1019
slouken@6448
  1020
    mid = env->GetMethodID(mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
slouken@6448
  1021
    jobject intent = env->CallObjectMethod(context, mid, NULL, filter);
slouken@6448
  1022
slouken@6448
  1023
    env->DeleteLocalRef(filter);
slouken@6448
  1024
slouken@6448
  1025
    cls = env->GetObjectClass(intent);
slouken@6448
  1026
slouken@6448
  1027
    jstring iname;
slouken@6448
  1028
    jmethodID imid = env->GetMethodID(cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
  1029
slouken@6448
  1030
#define GET_INT_EXTRA(var, key) \
slouken@6448
  1031
    iname = env->NewStringUTF(key); \
slouken@6448
  1032
    int var = env->CallIntMethod(intent, imid, iname, -1); \
slouken@6448
  1033
    env->DeleteLocalRef(iname);
slouken@6448
  1034
slouken@6448
  1035
    jstring bname;
slouken@6448
  1036
    jmethodID bmid = env->GetMethodID(cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
  1037
slouken@6448
  1038
#define GET_BOOL_EXTRA(var, key) \
slouken@6448
  1039
    bname = env->NewStringUTF(key); \
slouken@6448
  1040
    int var = env->CallBooleanMethod(intent, bmid, bname, JNI_FALSE); \
slouken@6448
  1041
    env->DeleteLocalRef(bname);
slouken@6448
  1042
slouken@6448
  1043
    if (plugged) {
slouken@6448
  1044
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
  1045
        if (plug == -1) {
slouken@6448
  1046
            return -1;
slouken@6448
  1047
        }
slouken@6448
  1048
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
  1049
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
  1050
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
  1051
    }
slouken@6448
  1052
slouken@6448
  1053
    if (charged) {
slouken@6448
  1054
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
  1055
        if (status == -1) {
slouken@6448
  1056
            return -1;
slouken@6448
  1057
        }
slouken@6448
  1058
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
  1059
        *charged = (status == 5) ? 1 : 0;
slouken@6448
  1060
    }
slouken@6448
  1061
slouken@6448
  1062
    if (battery) {
slouken@6448
  1063
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
  1064
        *battery = present ? 1 : 0;
slouken@6448
  1065
    }
slouken@6448
  1066
slouken@6448
  1067
    if (seconds) {
slouken@6448
  1068
        *seconds = -1; // not possible
slouken@6448
  1069
    }
slouken@6448
  1070
slouken@6448
  1071
    if (percent) {
slouken@6448
  1072
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
  1073
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
  1074
        if ((level == -1) || (scale == -1)) {
slouken@6448
  1075
            return -1;
slouken@6448
  1076
        }
slouken@6448
  1077
        *percent = level * 100 / scale;
slouken@6448
  1078
    }
slouken@6448
  1079
slouken@6448
  1080
    env->DeleteLocalRef(intent);
slouken@6448
  1081
slouken@6448
  1082
    return 0;
slouken@6448
  1083
}
slouken@6448
  1084
slouken@6392
  1085
// sends message to be handled on the UI event dispatch thread
slouken@6392
  1086
extern "C" int Android_JNI_SendMessage(int command, int param)
slouken@6392
  1087
{
slouken@6392
  1088
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
  1089
    if (!env) {
slouken@6392
  1090
        return -1;
slouken@6392
  1091
    }
slouken@6392
  1092
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "sendMessage", "(II)V");
slouken@6392
  1093
    if (!mid) {
slouken@6392
  1094
        return -1;
slouken@6392
  1095
    }
slouken@6392
  1096
    env->CallStaticVoidMethod(mActivityClass, mid, command, param);
slouken@6392
  1097
    return 0;
slouken@6392
  1098
}
slouken@6392
  1099
slouken@6654
  1100
extern "C" void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
  1101
{
slouken@6555
  1102
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
  1103
    if (!env) {
slouken@6654
  1104
        return;
slouken@6555
  1105
    }
slouken@6555
  1106
slouken@6555
  1107
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "showTextInput", "(IIII)V");
slouken@6555
  1108
    if (!mid) {
slouken@6654
  1109
        return;
slouken@6555
  1110
    }
slouken@6555
  1111
    env->CallStaticVoidMethod( mActivityClass, mid,
slouken@6555
  1112
                               inputRect->x,
slouken@6555
  1113
                               inputRect->y,
slouken@6555
  1114
                               inputRect->w,
slouken@6555
  1115
                               inputRect->h );
slouken@6555
  1116
}
slouken@6555
  1117
slouken@6654
  1118
extern "C" void Android_JNI_HideTextInput()
slouken@6555
  1119
{
slouken@6654
  1120
    // has to match Activity constant
slouken@6654
  1121
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
  1122
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
  1123
}
slouken@6555
  1124
slouken@6630
  1125
//////////////////////////////////////////////////////////////////////////////
slouken@6630
  1126
//
slouken@6630
  1127
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
  1128
//
slouken@6630
  1129
slouken@6630
  1130
extern "C" void *SDL_AndroidGetJNIEnv()
slouken@6630
  1131
{
slouken@6630
  1132
    return Android_JNI_GetEnv();
slouken@6630
  1133
}
slouken@6630
  1134
slouken@6630
  1135
extern "C" void *SDL_AndroidGetActivity()
slouken@6630
  1136
{
slouken@6650
  1137
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1138
    jmethodID mid;
slouken@6630
  1139
slouken@6630
  1140
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1141
    if (!refs.init(env)) {
slouken@6630
  1142
        return NULL;
slouken@6630
  1143
    }
slouken@6630
  1144
slouken@6630
  1145
    // return SDLActivity.getContext();
slouken@6630
  1146
    mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1147
            "getContext","()Landroid/content/Context;");
slouken@6630
  1148
    return env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1149
}
slouken@6630
  1150
slouken@6630
  1151
extern "C" const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1152
{
slouken@6630
  1153
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1154
slouken@6630
  1155
    if (!s_AndroidInternalFilesPath) {
slouken@6650
  1156
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1157
        jmethodID mid;
slouken@6630
  1158
        jobject context;
slouken@6630
  1159
        jobject fileObject;
slouken@6630
  1160
        jstring pathString;
slouken@6630
  1161
        const char *path;
slouken@6630
  1162
slouken@6630
  1163
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1164
        if (!refs.init(env)) {
slouken@6630
  1165
            return NULL;
slouken@6630
  1166
        }
slouken@6630
  1167
slouken@6630
  1168
        // context = SDLActivity.getContext();
slouken@6630
  1169
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1170
                "getContext","()Landroid/content/Context;");
slouken@6630
  1171
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1172
slouken@6630
  1173
        // fileObj = context.getFilesDir();
slouken@6630
  1174
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1175
                "getFilesDir", "()Ljava/io/File;");
slouken@6630
  1176
        fileObject = env->CallObjectMethod(context, mid);
slouken@6630
  1177
        if (!fileObject) {
slouken@6630
  1178
            SDL_SetError("Couldn't get internal directory");
slouken@6630
  1179
            return NULL;
slouken@6630
  1180
        }
slouken@6630
  1181
slouken@6630
  1182
        // path = fileObject.getAbsolutePath();
slouken@6630
  1183
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1184
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1185
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1186
slouken@6630
  1187
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1188
        s_AndroidInternalFilesPath = SDL_strdup(path);
slouken@6630
  1189
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1190
    }
slouken@6630
  1191
    return s_AndroidInternalFilesPath;
slouken@6630
  1192
}
slouken@6630
  1193
slouken@6630
  1194
extern "C" int SDL_AndroidGetExternalStorageState()
slouken@6630
  1195
{
slouken@6650
  1196
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1197
    jmethodID mid;
slouken@6630
  1198
    jclass cls;
slouken@6630
  1199
    jstring stateString;
slouken@6630
  1200
    const char *state;
slouken@6630
  1201
    int stateFlags;
slouken@6630
  1202
slouken@6630
  1203
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1204
    if (!refs.init(env)) {
slouken@6630
  1205
        return 0;
slouken@6630
  1206
    }
slouken@6630
  1207
slouken@6630
  1208
    cls = env->FindClass("android/os/Environment");
slouken@6630
  1209
    mid = env->GetStaticMethodID(cls,
slouken@6630
  1210
            "getExternalStorageState", "()Ljava/lang/String;");
slouken@6630
  1211
    stateString = (jstring)env->CallStaticObjectMethod(cls, mid);
slouken@6630
  1212
slouken@6630
  1213
    state = env->GetStringUTFChars(stateString, NULL);
slouken@6630
  1214
slouken@6630
  1215
    // Print an info message so people debugging know the storage state
slouken@6630
  1216
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1217
slouken@6630
  1218
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1219
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1220
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1221
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1222
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1223
    } else {
slouken@6630
  1224
        stateFlags = 0;
slouken@6630
  1225
    }
slouken@6630
  1226
    env->ReleaseStringUTFChars(stateString, state);
slouken@6630
  1227
slouken@6630
  1228
    return stateFlags;
slouken@6630
  1229
}
slouken@6630
  1230
slouken@6630
  1231
extern "C" const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1232
{
slouken@6630
  1233
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1234
slouken@6630
  1235
    if (!s_AndroidExternalFilesPath) {
slouken@6650
  1236
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1237
        jmethodID mid;
slouken@6630
  1238
        jobject context;
slouken@6630
  1239
        jobject fileObject;
slouken@6630
  1240
        jstring pathString;
slouken@6630
  1241
        const char *path;
slouken@6630
  1242
slouken@6630
  1243
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1244
        if (!refs.init(env)) {
slouken@6630
  1245
            return NULL;
slouken@6630
  1246
        }
slouken@6630
  1247
slouken@6630
  1248
        // context = SDLActivity.getContext();
slouken@6630
  1249
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1250
                "getContext","()Landroid/content/Context;");
slouken@6630
  1251
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1252
slouken@6630
  1253
        // fileObj = context.getExternalFilesDir();
slouken@6630
  1254
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1255
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
slouken@6630
  1256
        fileObject = env->CallObjectMethod(context, mid, NULL);
slouken@6630
  1257
        if (!fileObject) {
slouken@6630
  1258
            SDL_SetError("Couldn't get external directory");
slouken@6630
  1259
            return NULL;
slouken@6630
  1260
        }
slouken@6630
  1261
slouken@6630
  1262
        // path = fileObject.getAbsolutePath();
slouken@6630
  1263
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1264
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1265
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1266
slouken@6630
  1267
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1268
        s_AndroidExternalFilesPath = SDL_strdup(path);
slouken@6630
  1269
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1270
    }
slouken@6630
  1271
    return s_AndroidExternalFilesPath;
slouken@6630
  1272
}
slouken@6630
  1273
slouken@6044
  1274
#endif /* __ANDROID__ */
slouken@6044
  1275
slouken@4981
  1276
/* vi: set ts=4 sw=4 expandtab: */