src/core/android/SDL_android.cpp
author Ryan C. Gordon <icculus@icculus.org>
Sat, 15 Oct 2011 23:50:06 -0700
changeset 5996 102a9ec1ea13
parent 5994 153d15ab3032
child 6044 35448a5ea044
permissions -rw-r--r--
Don't use a global JNIEnv across threads; it's not thread safe.

Obtain the correct environment in a thread-safe way when appropriate instead.

Fixes Bugzilla #1312.

Thanks to Bill Chenbin for the patch!
slouken@4964
     1
/*
slouken@5535
     2
  Simple DirectMedia Layer
slouken@5535
     3
  Copyright (C) 1997-2011 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@4964
    23
slouken@4989
    24
#include "SDL_android.h"
slouken@4989
    25
slouken@4980
    26
extern "C" {
slouken@5092
    27
#include "../../events/SDL_events_c.h"
slouken@5092
    28
#include "../../video/android/SDL_androidkeyboard.h"
slouken@5092
    29
#include "../../video/android/SDL_androidtouch.h"
slouken@5092
    30
#include "../../video/android/SDL_androidvideo.h"
slouken@4995
    31
icculus@5996
    32
#include <android/log.h>
icculus@5996
    33
#define LOG_TAG "SDL_android"
icculus@5996
    34
//#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
icculus@5996
    35
//#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
icculus@5996
    36
#define LOGI(...) do {} while (false)
icculus@5996
    37
#define LOGE(...) do {} while (false)
icculus@5996
    38
icculus@5996
    39
slouken@4995
    40
/* Impelemented in audio/android/SDL_androidaudio.c */
slouken@4995
    41
extern void Android_RunAudioThread();
slouken@4995
    42
} // C
slouken@4980
    43
slouken@4964
    44
/*******************************************************************************
slouken@4964
    45
 This file links the Java side of Android with libsdl
slouken@4964
    46
*******************************************************************************/
slouken@4964
    47
#include <jni.h>
slouken@4964
    48
#include <android/log.h>
slouken@4964
    49
slouken@4964
    50
slouken@4964
    51
/*******************************************************************************
slouken@4964
    52
                               Globals
slouken@4964
    53
*******************************************************************************/
slouken@4995
    54
static JNIEnv* mEnv = NULL;
slouken@4995
    55
static JNIEnv* mAudioEnv = NULL;
icculus@5996
    56
static JavaVM* mJavaVM;
slouken@4964
    57
slouken@4995
    58
// Main activity
slouken@4998
    59
static jclass mActivityClass;
slouken@4964
    60
slouken@4995
    61
// method signatures
slouken@4995
    62
static jmethodID midCreateGLContext;
slouken@4995
    63
static jmethodID midFlipBuffers;
slouken@4995
    64
static jmethodID midAudioInit;
slouken@4995
    65
static jmethodID midAudioWriteShortBuffer;
slouken@4995
    66
static jmethodID midAudioWriteByteBuffer;
slouken@4996
    67
static jmethodID midAudioQuit;
slouken@4964
    68
slouken@4995
    69
// Accelerometer data storage
slouken@5000
    70
static float fLastAccelerometer[3];
slouken@4964
    71
slouken@4964
    72
slouken@4964
    73
/*******************************************************************************
slouken@4964
    74
                 Functions called by JNI
slouken@4964
    75
*******************************************************************************/
slouken@4964
    76
slouken@4964
    77
// Library init
slouken@4964
    78
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
slouken@4964
    79
{
icculus@5996
    80
    JNIEnv *env;
icculus@5996
    81
    mJavaVM = vm;
icculus@5996
    82
    LOGI("JNI_OnLoad called");
icculus@5996
    83
    if (mJavaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
icculus@5996
    84
        LOGE("Failed to get the environment using GetEnv()");
icculus@5996
    85
        return -1;
icculus@5996
    86
    }
icculus@5996
    87
slouken@4964
    88
    return JNI_VERSION_1_4;
slouken@4964
    89
}
slouken@4964
    90
slouken@4964
    91
// Called before SDL_main() to initialize JNI bindings
slouken@4998
    92
extern "C" void SDL_Android_Init(JNIEnv* env, jclass cls)
slouken@4964
    93
{
slouken@4964
    94
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
slouken@4964
    95
slouken@4998
    96
    mEnv = env;
slouken@4998
    97
    mActivityClass = cls;
slouken@4998
    98
slouken@4998
    99
    midCreateGLContext = mEnv->GetStaticMethodID(mActivityClass,
slouken@5222
   100
                                "createGLContext","(II)Z");
slouken@4998
   101
    midFlipBuffers = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   102
                                "flipBuffers","()V");
slouken@4998
   103
    midAudioInit = mEnv->GetStaticMethodID(mActivityClass, 
slouken@4998
   104
                                "audioInit", "(IZZI)Ljava/lang/Object;");
slouken@4998
   105
    midAudioWriteShortBuffer = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   106
                                "audioWriteShortBuffer", "([S)V");
slouken@4998
   107
    midAudioWriteByteBuffer = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   108
                                "audioWriteByteBuffer", "([B)V");
slouken@4998
   109
    midAudioQuit = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   110
                                "audioQuit", "()V");
slouken@4964
   111
slouken@4995
   112
    if(!midCreateGLContext || !midFlipBuffers || !midAudioInit ||
slouken@4996
   113
       !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) {
slouken@4996
   114
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
slouken@4964
   115
    }
icculus@5996
   116
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
slouken@4964
   117
}
slouken@4964
   118
slouken@4995
   119
// Resize
slouken@4995
   120
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeResize(
slouken@4998
   121
                                    JNIEnv* env, jclass jcls,
slouken@4995
   122
                                    jint width, jint height, jint format)
slouken@4995
   123
{
slouken@4995
   124
    Android_SetScreenResolution(width, height, format);
slouken@4995
   125
}
slouken@4995
   126
slouken@4964
   127
// Keydown
slouken@4995
   128
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyDown(
slouken@4998
   129
                                    JNIEnv* env, jclass jcls, jint keycode)
slouken@4964
   130
{
slouken@4980
   131
    Android_OnKeyDown(keycode);
slouken@4964
   132
}
slouken@4964
   133
slouken@4964
   134
// Keyup
slouken@4995
   135
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyUp(
slouken@4998
   136
                                    JNIEnv* env, jclass jcls, jint keycode)
slouken@4964
   137
{
slouken@4980
   138
    Android_OnKeyUp(keycode);
slouken@4964
   139
}
slouken@4964
   140
slouken@4964
   141
// Touch
slouken@4995
   142
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeTouch(
slouken@4998
   143
                                    JNIEnv* env, jclass jcls,
icculus@5982
   144
                                    jint touch_device_id_in, jint pointer_finger_id_in,
slouken@4995
   145
                                    jint action, jfloat x, jfloat y, jfloat p)
slouken@4964
   146
{
icculus@5982
   147
    Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p);
slouken@4964
   148
}
slouken@4964
   149
slouken@4995
   150
// Accelerometer
slouken@4964
   151
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeAccel(
slouken@4998
   152
                                    JNIEnv* env, jclass jcls,
slouken@4995
   153
                                    jfloat x, jfloat y, jfloat z)
slouken@4964
   154
{
slouken@4964
   155
    fLastAccelerometer[0] = x;
slouken@4964
   156
    fLastAccelerometer[1] = y;
slouken@4964
   157
    fLastAccelerometer[2] = z;   
slouken@4964
   158
}
slouken@4964
   159
slouken@4995
   160
// Quit
slouken@4995
   161
extern "C" void Java_org_libsdl_app_SDLActivity_nativeQuit(
slouken@4998
   162
                                    JNIEnv* env, jclass cls)
slouken@4995
   163
{    
slouken@4995
   164
    // Inject a SDL_QUIT event
slouken@4995
   165
    SDL_SendQuit();
slouken@4995
   166
}
slouken@4995
   167
slouken@4995
   168
extern "C" void Java_org_libsdl_app_SDLActivity_nativeRunAudioThread(
slouken@4998
   169
                                    JNIEnv* env, jclass cls)
slouken@4995
   170
{
slouken@4998
   171
    /* This is the audio thread, with a different environment */
slouken@4998
   172
    mAudioEnv = env;
slouken@4998
   173
slouken@4996
   174
    Android_RunAudioThread();
slouken@4995
   175
}
slouken@4964
   176
slouken@4964
   177
slouken@4964
   178
/*******************************************************************************
slouken@4964
   179
             Functions called by SDL into Java
slouken@4964
   180
*******************************************************************************/
slouken@5222
   181
extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion)
slouken@4964
   182
{
slouken@5222
   183
    if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) {
slouken@5222
   184
        return SDL_TRUE;
slouken@5222
   185
    } else {
slouken@5222
   186
        return SDL_FALSE;
slouken@5222
   187
    }
slouken@4964
   188
}
slouken@4964
   189
slouken@4989
   190
extern "C" void Android_JNI_SwapWindow()
slouken@4964
   191
{
slouken@4998
   192
    mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); 
slouken@4998
   193
}
slouken@4998
   194
slouken@4998
   195
extern "C" void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   196
{
slouken@4998
   197
    jmethodID mid;
slouken@4998
   198
slouken@4998
   199
    mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V");
slouken@4998
   200
    if (mid) {
slouken@4998
   201
        mEnv->CallStaticVoidMethod(mActivityClass, mid, mEnv->NewStringUTF(title));
slouken@4998
   202
    }
slouken@4964
   203
}
slouken@4964
   204
slouken@5000
   205
extern "C" void Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   206
{
slouken@5000
   207
    int i;
slouken@5000
   208
    for (i = 0; i < 3; ++i) {
slouken@5000
   209
        values[i] = fLastAccelerometer[i];
slouken@5000
   210
    }
slouken@5000
   211
}
slouken@5000
   212
slouken@4995
   213
//
slouken@4995
   214
// Audio support
slouken@4995
   215
//
slouken@4996
   216
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   217
static jboolean audioBufferStereo = JNI_FALSE;
slouken@4996
   218
static jobject audioBuffer = NULL;
slouken@4996
   219
static void* audioBufferPinned = NULL;
slouken@4995
   220
slouken@4995
   221
extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   222
{
slouken@4996
   223
    int audioBufferFrames;
slouken@4964
   224
icculus@5996
   225
    int status;
icculus@5996
   226
    JNIEnv *env;
icculus@5996
   227
    static bool isAttached = false;    
icculus@5996
   228
    status = mJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4);
icculus@5996
   229
    if(status < 0) {
icculus@5996
   230
        LOGE("callback_handler: failed to get JNI environment, assuming native thread");
icculus@5996
   231
        status = mJavaVM->AttachCurrentThread(&env, NULL);
icculus@5996
   232
        if(status < 0) {
icculus@5996
   233
            LOGE("callback_handler: failed to attach current thread");
icculus@5996
   234
            return 0;
icculus@5996
   235
        }
icculus@5996
   236
        isAttached = true;
icculus@5996
   237
    }
icculus@5996
   238
icculus@5996
   239
    
slouken@4996
   240
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   241
    audioBuffer16Bit = is16Bit;
slouken@4996
   242
    audioBufferStereo = channelCount > 1;
slouken@4964
   243
icculus@5996
   244
    audioBuffer = env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
slouken@4995
   245
slouken@4996
   246
    if (audioBuffer == NULL) {
slouken@4996
   247
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!");
slouken@4996
   248
        return 0;
slouken@4996
   249
    }
icculus@5996
   250
    audioBuffer = env->NewGlobalRef(audioBuffer);
slouken@4995
   251
slouken@4996
   252
    jboolean isCopy = JNI_FALSE;
slouken@4996
   253
    if (audioBuffer16Bit) {
icculus@5996
   254
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   255
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   256
    } else {
icculus@5996
   257
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   258
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   259
    }
slouken@4996
   260
    if (audioBufferStereo) {
slouken@4996
   261
        audioBufferFrames /= 2;
slouken@4996
   262
    }
icculus@5996
   263
 
icculus@5996
   264
    if (isAttached) {
icculus@5996
   265
        mJavaVM->DetachCurrentThread();
icculus@5996
   266
    }
slouken@4996
   267
slouken@4996
   268
    return audioBufferFrames;
slouken@4995
   269
}
slouken@4995
   270
slouken@4996
   271
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   272
{
slouken@4996
   273
    return audioBufferPinned;
slouken@4995
   274
}
slouken@4995
   275
slouken@4996
   276
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   277
{
slouken@4996
   278
    if (audioBuffer16Bit) {
slouken@4996
   279
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   280
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   281
    } else {
slouken@4996
   282
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   283
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   284
    }
slouken@4995
   285
slouken@4996
   286
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   287
}
slouken@4995
   288
slouken@4995
   289
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   290
{
icculus@5996
   291
    int status;
icculus@5996
   292
    JNIEnv *env;
icculus@5996
   293
    static bool isAttached = false;    
icculus@5996
   294
    status = mJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4);
icculus@5996
   295
    if(status < 0) {
icculus@5996
   296
        LOGE("callback_handler: failed to get JNI environment, assuming native thread");
icculus@5996
   297
        status = mJavaVM->AttachCurrentThread(&env, NULL);
icculus@5996
   298
        if(status < 0) {
icculus@5996
   299
            LOGE("callback_handler: failed to attach current thread");
icculus@5996
   300
            return;
icculus@5996
   301
        }
icculus@5996
   302
        isAttached = true;
icculus@5996
   303
    }
icculus@5996
   304
icculus@5996
   305
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   306
slouken@4997
   307
    if (audioBuffer) {
icculus@5996
   308
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   309
        audioBuffer = NULL;
slouken@4997
   310
        audioBufferPinned = NULL;
slouken@4997
   311
    }
icculus@5996
   312
icculus@5996
   313
    if (isAttached) {
icculus@5996
   314
        mJavaVM->DetachCurrentThread();
icculus@5996
   315
    }
slouken@4964
   316
}
slouken@4981
   317
tim@5650
   318
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   319
static bool Android_JNI_ExceptionOccurred()
tim@5650
   320
{
tim@5650
   321
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   322
    if (exception != NULL) {
tim@5650
   323
        jmethodID mid;
tim@5650
   324
tim@5650
   325
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   326
        mEnv->ExceptionClear();
tim@5650
   327
tim@5650
   328
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   329
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   330
tim@5650
   331
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   332
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   333
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   334
tim@5650
   335
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   336
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   337
tim@5650
   338
        if (exceptionMessage != NULL) {
tim@5650
   339
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   340
                    exceptionMessage, 0);
tim@5650
   341
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   342
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   343
            mEnv->DeleteLocalRef(exceptionMessage);
tim@5650
   344
        } else {
tim@5650
   345
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   346
        }
tim@5650
   347
tim@5650
   348
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   349
        mEnv->DeleteLocalRef(exceptionName);
tim@5650
   350
        mEnv->DeleteLocalRef(classClass);
tim@5650
   351
        mEnv->DeleteLocalRef(exceptionClass);
tim@5650
   352
        mEnv->DeleteLocalRef(exception);
tim@5650
   353
tim@5650
   354
        return true;
tim@5650
   355
    }
tim@5650
   356
tim@5650
   357
    return false;
tim@5650
   358
}
tim@5650
   359
icculus@5582
   360
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   361
{
tim@5650
   362
    int result = 0;
tim@5650
   363
tim@5650
   364
    jmethodID mid;
tim@5650
   365
    jobject context;
tim@5650
   366
    jobject assetManager;
tim@5650
   367
    jobject inputStream;
tim@5650
   368
    jclass channels;
tim@5650
   369
    jobject readableByteChannel;
tim@5650
   370
    jstring fileNameJString;
tim@5650
   371
tim@5650
   372
    bool allocatedLocalFrame = false;
tim@5650
   373
tim@5650
   374
    if (mEnv->PushLocalFrame(16) < 0) {
tim@5650
   375
        SDL_SetError("Failed to allocate enough JVM local references");
tim@5650
   376
        goto failure;
tim@5650
   377
    } else {
tim@5650
   378
        allocatedLocalFrame = true;
tim@5650
   379
    }
tim@5650
   380
tim@5650
   381
    fileNameJString = (jstring)ctx->hidden.androidio.fileName;
icculus@5582
   382
icculus@5582
   383
    // context = SDLActivity.getContext();
tim@5650
   384
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   385
            "getContext","()Landroid/content/Context;");
tim@5650
   386
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
icculus@5582
   387
icculus@5582
   388
    // assetManager = context.getAssets();
icculus@5582
   389
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   390
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   391
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   392
icculus@5582
   393
    // inputStream = assetManager.open(<filename>);
icculus@5582
   394
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
icculus@5582
   395
            "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
tim@5650
   396
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   397
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   398
        goto failure;
icculus@5582
   399
    }
icculus@5582
   400
tim@5650
   401
    ctx->hidden.androidio.inputStream = inputStream;
tim@5650
   402
    ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
tim@5650
   403
icculus@5582
   404
    // Despite all the visible documentation on [Asset]InputStream claiming
icculus@5582
   405
    // that the .available() method is not guaranteed to return the entire file
icculus@5582
   406
    // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
icculus@5582
   407
    // android/apis/content/ReadAsset.java imply that Android's
icculus@5582
   408
    // AssetInputStream.available() /will/ always return the total file size
icculus@5582
   409
icculus@5582
   410
    // size = inputStream.available();
icculus@5582
   411
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   412
            "available", "()I");
icculus@5582
   413
    ctx->hidden.androidio.size = mEnv->CallIntMethod(inputStream, mid);
tim@5650
   414
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   415
        goto failure;
icculus@5582
   416
    }
icculus@5582
   417
icculus@5582
   418
    // readableByteChannel = Channels.newChannel(inputStream);
tim@5650
   419
    channels = mEnv->FindClass("java/nio/channels/Channels");
icculus@5582
   420
    mid = mEnv->GetStaticMethodID(channels,
icculus@5582
   421
            "newChannel",
icculus@5582
   422
            "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
tim@5650
   423
    readableByteChannel = mEnv->CallStaticObjectMethod(
icculus@5582
   424
            channels, mid, inputStream);
tim@5650
   425
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   426
        goto failure;
icculus@5582
   427
    }
icculus@5582
   428
tim@5650
   429
    ctx->hidden.androidio.readableByteChannel = readableByteChannel;
tim@5650
   430
    ctx->hidden.androidio.readableByteChannelRef =
tim@5650
   431
        mEnv->NewGlobalRef(readableByteChannel);
tim@5650
   432
icculus@5582
   433
    // Store .read id for reading purposes
icculus@5582
   434
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
icculus@5582
   435
            "read", "(Ljava/nio/ByteBuffer;)I");
icculus@5582
   436
    ctx->hidden.androidio.readMethod = mid;
icculus@5582
   437
icculus@5582
   438
    ctx->hidden.androidio.position = 0;
icculus@5582
   439
tim@5650
   440
    if (false) {
tim@5650
   441
failure:
tim@5650
   442
        result = -1;
tim@5650
   443
tim@5650
   444
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   445
tim@5650
   446
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   447
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   448
        }
tim@5650
   449
    }
tim@5650
   450
tim@5650
   451
    if (allocatedLocalFrame) {
tim@5650
   452
        mEnv->PopLocalFrame(NULL);
tim@5650
   453
    }
tim@5650
   454
tim@5650
   455
    return result;
icculus@5582
   456
}
icculus@5582
   457
icculus@5582
   458
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   459
        const char* fileName, const char*)
icculus@5582
   460
{
icculus@5582
   461
    if (!ctx) {
icculus@5582
   462
        return -1;
icculus@5582
   463
    }
icculus@5582
   464
icculus@5582
   465
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   466
    ctx->hidden.androidio.fileName = fileNameJString;
icculus@5582
   467
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   468
    ctx->hidden.androidio.inputStreamRef = NULL;
tim@5650
   469
    mEnv->DeleteLocalRef(fileNameJString);
icculus@5582
   470
icculus@5582
   471
    return Android_JNI_FileOpen(ctx);
icculus@5582
   472
}
icculus@5582
   473
icculus@5582
   474
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   475
        size_t size, size_t maxnum)
icculus@5582
   476
{
icculus@5582
   477
    int bytesRemaining = size * maxnum;
icculus@5582
   478
    int bytesRead = 0;
icculus@5582
   479
icculus@5582
   480
    jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannel;
icculus@5582
   481
    jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
icculus@5582
   482
    jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
icculus@5582
   483
icculus@5582
   484
    while (bytesRemaining > 0) {
icculus@5582
   485
        // result = readableByteChannel.read(...);
icculus@5582
   486
        int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
icculus@5582
   487
tim@5650
   488
        if (Android_JNI_ExceptionOccurred()) {
tim@5650
   489
            mEnv->DeleteLocalRef(byteBuffer);
icculus@5582
   490
            return 0;
icculus@5582
   491
        }
icculus@5582
   492
icculus@5582
   493
        if (result < 0) {
icculus@5582
   494
            break;
icculus@5582
   495
        }
icculus@5582
   496
icculus@5582
   497
        bytesRemaining -= result;
icculus@5582
   498
        bytesRead += result;
icculus@5582
   499
        ctx->hidden.androidio.position += result;
icculus@5582
   500
    }
icculus@5582
   501
tim@5650
   502
    mEnv->DeleteLocalRef(byteBuffer);
tim@5650
   503
icculus@5582
   504
    return bytesRead / size;
icculus@5582
   505
}
icculus@5582
   506
icculus@5582
   507
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   508
        size_t size, size_t num)
icculus@5582
   509
{
icculus@5582
   510
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   511
    return 0;
icculus@5582
   512
}
icculus@5582
   513
icculus@5582
   514
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   515
{
icculus@5582
   516
    int result = 0;
icculus@5582
   517
icculus@5582
   518
    if (ctx) {
icculus@5582
   519
        if (release) {
icculus@5582
   520
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   521
        }
icculus@5582
   522
icculus@5582
   523
        jobject inputStream = (jobject)ctx->hidden.androidio.inputStream;
icculus@5582
   524
icculus@5582
   525
        // inputStream.close();
icculus@5582
   526
        jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   527
                "close", "()V");
icculus@5582
   528
        mEnv->CallVoidMethod(inputStream, mid);
icculus@5582
   529
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
icculus@5582
   530
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
tim@5650
   531
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   532
            result = -1;
icculus@5582
   533
        }
icculus@5582
   534
icculus@5582
   535
        if (release) {
icculus@5582
   536
            SDL_FreeRW(ctx);
icculus@5582
   537
        }
icculus@5582
   538
    }
icculus@5582
   539
icculus@5582
   540
    return result;
icculus@5582
   541
}
icculus@5582
   542
icculus@5582
   543
icculus@5582
   544
extern "C" long Android_JNI_FileSeek(SDL_RWops* ctx, long offset, int whence)
icculus@5582
   545
{
icculus@5582
   546
    long newPosition;
icculus@5582
   547
icculus@5582
   548
    switch (whence) {
icculus@5582
   549
        case RW_SEEK_SET:
icculus@5582
   550
            newPosition = offset;
icculus@5582
   551
            break;
icculus@5582
   552
        case RW_SEEK_CUR:
icculus@5582
   553
            newPosition = ctx->hidden.androidio.position + offset;
icculus@5582
   554
            break;
icculus@5582
   555
        case RW_SEEK_END:
icculus@5582
   556
            newPosition = ctx->hidden.androidio.size + offset;
icculus@5582
   557
            break;
icculus@5582
   558
        default:
icculus@5582
   559
            SDL_SetError("Unknown value for 'whence'");
icculus@5582
   560
            return -1;
icculus@5582
   561
    }
icculus@5582
   562
    if (newPosition < 0) {
icculus@5582
   563
        newPosition = 0;
icculus@5582
   564
    }
icculus@5582
   565
    if (newPosition > ctx->hidden.androidio.size) {
icculus@5582
   566
        newPosition = ctx->hidden.androidio.size;
icculus@5582
   567
    }
icculus@5582
   568
icculus@5582
   569
    long movement = newPosition - ctx->hidden.androidio.position;
icculus@5582
   570
    jobject inputStream = (jobject)ctx->hidden.androidio.inputStream;
icculus@5582
   571
icculus@5582
   572
    if (movement > 0) {
tim@5993
   573
        unsigned char buffer[1024];
tim@5993
   574
icculus@5582
   575
        // The easy case where we're seeking forwards
icculus@5582
   576
        while (movement > 0) {
icculus@5994
   577
            long amount = (long) sizeof (buffer);
icculus@5994
   578
            if (amount > movement) {
icculus@5994
   579
                amount = movement;
icculus@5994
   580
            }
icculus@5994
   581
            size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
tim@5993
   582
tim@5993
   583
            if (result <= 0) {
tim@5993
   584
                // Failed to read/skip the required amount, so fail
icculus@5582
   585
                return -1;
icculus@5582
   586
            }
tim@5993
   587
tim@5993
   588
            movement -= result;
icculus@5582
   589
        }
icculus@5582
   590
    } else if (movement < 0) {
icculus@5582
   591
        // We can't seek backwards so we have to reopen the file and seek
icculus@5582
   592
        // forwards which obviously isn't very efficient
icculus@5582
   593
        Android_JNI_FileClose(ctx, false);
icculus@5582
   594
        Android_JNI_FileOpen(ctx);
icculus@5582
   595
        Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   596
    }
icculus@5582
   597
icculus@5582
   598
    ctx->hidden.androidio.position = newPosition;
icculus@5582
   599
icculus@5582
   600
    return ctx->hidden.androidio.position;
icculus@5582
   601
}
icculus@5582
   602
icculus@5582
   603
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   604
{
icculus@5582
   605
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   606
}
icculus@5582
   607
slouken@4981
   608
/* vi: set ts=4 sw=4 expandtab: */