src/core/android/SDL_android.cpp
author Sam Lantinga <slouken@libsdl.org>
Sun, 12 Feb 2012 20:57:32 -0500
changeset 6284 1893d507ba42
parent 6212 78d854de3a66
child 6307 6048116f40b1
permissions -rwxr-xr-x
Fixed bug 1417 - Android_JNI_FileClose local reference bug

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