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