src/core/android/SDL_android.cpp
author Sam Lantinga <slouken@libsdl.org>
Fri, 13 Jan 2012 20:57:35 -0500
changeset 6212 78d854de3a66
parent 6191 2c0d35b1af4e
child 6284 1893d507ba42
permissions -rwxr-xr-x
Fixed bug 1368 - Enabling joystick subsystem cause an infinite loop

morgan.devel@gmail.com 2012-01-13 00:32:23 PST

The android version of SDL_SYS_JoystickUpdate doesn't check if there is
actually new data and always generate the SDL_JOYAXISMOTION event.
Consequently, doing a while(SDL_PollEvent()) will result in an endless loop.

The attached patch fix this issue.

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