src/core/android/SDL_android.cpp
author Gabriel Jacobo <gabomdq@gmail.com>
Wed, 20 Jun 2012 11:25:40 -0300
changeset 6335 fbb84f5b985f
parent 6330 0fa55ca2efdd
child 6354 17840f487124
permissions -rwxr-xr-x
Fixes #1519, adds initialization to Android RWops internal variables.
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) {
gabomdq@6330
   179
        /* Signal the pause semaphore so the event loop knows to pause and (optionally) block itself */
gabomdq@6330
   180
        if (!SDL_SemValue(Android_PauseSem)) SDL_SemPost(Android_PauseSem);
slouken@6186
   181
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
slouken@6191
   182
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
slouken@6186
   183
    }
slouken@6186
   184
}
slouken@6186
   185
slouken@6186
   186
// Resume
slouken@6186
   187
extern "C" void Java_org_libsdl_app_SDLActivity_nativeResume(
slouken@6186
   188
                                    JNIEnv* env, jclass cls)
slouken@6186
   189
{
slouken@6186
   190
    if (Android_Window) {
gabomdq@6330
   191
        /* Signal the resume semaphore so the event loop knows to resume and restore the GL Context
gabomdq@6330
   192
         * We can't restore the GL Context here because it needs to be done on the SDL main thread
gabomdq@6330
   193
         * and this function will be called from the Java thread instead.
gabomdq@6330
   194
         */
gabomdq@6330
   195
        if (!SDL_SemValue(Android_ResumeSem)) SDL_SemPost(Android_ResumeSem);
slouken@6186
   196
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
slouken@6191
   197
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0);
slouken@6186
   198
    }
slouken@6186
   199
}
slouken@6186
   200
slouken@4995
   201
extern "C" void Java_org_libsdl_app_SDLActivity_nativeRunAudioThread(
slouken@4998
   202
                                    JNIEnv* env, jclass cls)
slouken@4995
   203
{
slouken@4998
   204
    /* This is the audio thread, with a different environment */
slouken@4998
   205
    mAudioEnv = env;
slouken@4998
   206
slouken@4996
   207
    Android_RunAudioThread();
slouken@4995
   208
}
slouken@4964
   209
slouken@4964
   210
slouken@4964
   211
/*******************************************************************************
slouken@4964
   212
             Functions called by SDL into Java
slouken@4964
   213
*******************************************************************************/
slouken@6284
   214
slouken@6284
   215
class LocalReferenceHolder
slouken@6284
   216
{
slouken@6284
   217
private:
slouken@6284
   218
    static int s_active;
slouken@6284
   219
slouken@6284
   220
public:
slouken@6284
   221
    static bool IsActive() {
slouken@6284
   222
        return s_active > 0;
slouken@6284
   223
    }
slouken@6284
   224
slouken@6284
   225
public:
slouken@6284
   226
    LocalReferenceHolder() : m_env(NULL) { }
slouken@6284
   227
    ~LocalReferenceHolder() {
slouken@6284
   228
        if (m_env) {
slouken@6284
   229
            m_env->PopLocalFrame(NULL);
slouken@6284
   230
            --s_active;
slouken@6284
   231
        }
slouken@6284
   232
    }
slouken@6284
   233
slouken@6284
   234
    bool init(JNIEnv *env, jint capacity = 16) {
slouken@6284
   235
        if (env->PushLocalFrame(capacity) < 0) {
slouken@6284
   236
            SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   237
            return false;
slouken@6284
   238
        }
slouken@6284
   239
        ++s_active;
slouken@6284
   240
        m_env = env;
slouken@6284
   241
        return true;
slouken@6284
   242
    }
slouken@6284
   243
slouken@6284
   244
protected:
slouken@6284
   245
    JNIEnv *m_env;
slouken@6284
   246
};
slouken@6284
   247
int LocalReferenceHolder::s_active;
slouken@6284
   248
slouken@5222
   249
extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion)
slouken@4964
   250
{
slouken@5222
   251
    if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) {
slouken@5222
   252
        return SDL_TRUE;
slouken@5222
   253
    } else {
slouken@5222
   254
        return SDL_FALSE;
slouken@5222
   255
    }
slouken@4964
   256
}
slouken@4964
   257
slouken@4989
   258
extern "C" void Android_JNI_SwapWindow()
slouken@4964
   259
{
slouken@4998
   260
    mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); 
slouken@4998
   261
}
slouken@4998
   262
slouken@4998
   263
extern "C" void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   264
{
slouken@4998
   265
    jmethodID mid;
slouken@4998
   266
slouken@4998
   267
    mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V");
slouken@4998
   268
    if (mid) {
gabomdq@6307
   269
        jstring jtitle = reinterpret_cast<jstring>(mEnv->NewStringUTF(title));
gabomdq@6307
   270
        mEnv->CallStaticVoidMethod(mActivityClass, mid, jtitle);
gabomdq@6307
   271
        mEnv->DeleteLocalRef(jtitle);
slouken@4998
   272
    }
slouken@4964
   273
}
slouken@4964
   274
slouken@6212
   275
extern "C" SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   276
{
slouken@5000
   277
    int i;
slouken@6212
   278
    SDL_bool retval = SDL_FALSE;
slouken@6212
   279
slouken@6212
   280
    if (bHasNewData) {
slouken@6212
   281
        for (i = 0; i < 3; ++i) {
slouken@6212
   282
            values[i] = fLastAccelerometer[i];
slouken@6212
   283
        }
slouken@6212
   284
        bHasNewData = false;
slouken@6212
   285
        retval = SDL_TRUE;
slouken@5000
   286
    }
slouken@6212
   287
slouken@6212
   288
    return retval;
slouken@5000
   289
}
slouken@5000
   290
slouken@4995
   291
//
slouken@4995
   292
// Audio support
slouken@4995
   293
//
slouken@4996
   294
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   295
static jboolean audioBufferStereo = JNI_FALSE;
slouken@4996
   296
static jobject audioBuffer = NULL;
slouken@4996
   297
static void* audioBufferPinned = NULL;
slouken@4995
   298
slouken@4995
   299
extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   300
{
slouken@4996
   301
    int audioBufferFrames;
slouken@4964
   302
icculus@5996
   303
    int status;
icculus@5996
   304
    JNIEnv *env;
icculus@5996
   305
    static bool isAttached = false;    
icculus@5996
   306
    status = mJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4);
icculus@5996
   307
    if(status < 0) {
icculus@5996
   308
        LOGE("callback_handler: failed to get JNI environment, assuming native thread");
icculus@5996
   309
        status = mJavaVM->AttachCurrentThread(&env, NULL);
icculus@5996
   310
        if(status < 0) {
icculus@5996
   311
            LOGE("callback_handler: failed to attach current thread");
icculus@5996
   312
            return 0;
icculus@5996
   313
        }
icculus@5996
   314
        isAttached = true;
icculus@5996
   315
    }
icculus@5996
   316
icculus@5996
   317
    
slouken@4996
   318
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   319
    audioBuffer16Bit = is16Bit;
slouken@4996
   320
    audioBufferStereo = channelCount > 1;
slouken@4964
   321
icculus@5996
   322
    audioBuffer = env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
slouken@4995
   323
slouken@4996
   324
    if (audioBuffer == NULL) {
slouken@4996
   325
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!");
slouken@4996
   326
        return 0;
slouken@4996
   327
    }
icculus@5996
   328
    audioBuffer = env->NewGlobalRef(audioBuffer);
slouken@4995
   329
slouken@4996
   330
    jboolean isCopy = JNI_FALSE;
slouken@4996
   331
    if (audioBuffer16Bit) {
icculus@5996
   332
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   333
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   334
    } else {
icculus@5996
   335
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   336
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   337
    }
slouken@4996
   338
    if (audioBufferStereo) {
slouken@4996
   339
        audioBufferFrames /= 2;
slouken@4996
   340
    }
icculus@5996
   341
 
icculus@5996
   342
    if (isAttached) {
icculus@5996
   343
        mJavaVM->DetachCurrentThread();
icculus@5996
   344
    }
slouken@4996
   345
slouken@4996
   346
    return audioBufferFrames;
slouken@4995
   347
}
slouken@4995
   348
slouken@4996
   349
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   350
{
slouken@4996
   351
    return audioBufferPinned;
slouken@4995
   352
}
slouken@4995
   353
slouken@4996
   354
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   355
{
slouken@4996
   356
    if (audioBuffer16Bit) {
slouken@4996
   357
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   358
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   359
    } else {
slouken@4996
   360
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   361
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   362
    }
slouken@4995
   363
slouken@4996
   364
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   365
}
slouken@4995
   366
slouken@4995
   367
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   368
{
icculus@5996
   369
    int status;
icculus@5996
   370
    JNIEnv *env;
icculus@5996
   371
    static bool isAttached = false;    
icculus@5996
   372
    status = mJavaVM->GetEnv((void **) &env, JNI_VERSION_1_4);
icculus@5996
   373
    if(status < 0) {
icculus@5996
   374
        LOGE("callback_handler: failed to get JNI environment, assuming native thread");
icculus@5996
   375
        status = mJavaVM->AttachCurrentThread(&env, NULL);
icculus@5996
   376
        if(status < 0) {
icculus@5996
   377
            LOGE("callback_handler: failed to attach current thread");
icculus@5996
   378
            return;
icculus@5996
   379
        }
icculus@5996
   380
        isAttached = true;
icculus@5996
   381
    }
icculus@5996
   382
icculus@5996
   383
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   384
slouken@4997
   385
    if (audioBuffer) {
icculus@5996
   386
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   387
        audioBuffer = NULL;
slouken@4997
   388
        audioBufferPinned = NULL;
slouken@4997
   389
    }
icculus@5996
   390
icculus@5996
   391
    if (isAttached) {
icculus@5996
   392
        mJavaVM->DetachCurrentThread();
icculus@5996
   393
    }
slouken@4964
   394
}
slouken@4981
   395
tim@5650
   396
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   397
static bool Android_JNI_ExceptionOccurred()
tim@5650
   398
{
slouken@6284
   399
    SDL_assert(LocalReferenceHolder::IsActive());
slouken@6284
   400
tim@5650
   401
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   402
    if (exception != NULL) {
tim@5650
   403
        jmethodID mid;
tim@5650
   404
tim@5650
   405
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   406
        mEnv->ExceptionClear();
tim@5650
   407
tim@5650
   408
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   409
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   410
tim@5650
   411
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   412
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   413
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   414
tim@5650
   415
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   416
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   417
tim@5650
   418
        if (exceptionMessage != NULL) {
tim@5650
   419
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   420
                    exceptionMessage, 0);
tim@5650
   421
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   422
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   423
        } else {
tim@5650
   424
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   425
        }
tim@5650
   426
tim@5650
   427
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   428
tim@5650
   429
        return true;
tim@5650
   430
    }
tim@5650
   431
tim@5650
   432
    return false;
tim@5650
   433
}
tim@5650
   434
icculus@5582
   435
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   436
{
slouken@6284
   437
    LocalReferenceHolder refs;
tim@5650
   438
    int result = 0;
tim@5650
   439
tim@5650
   440
    jmethodID mid;
tim@5650
   441
    jobject context;
tim@5650
   442
    jobject assetManager;
tim@5650
   443
    jobject inputStream;
tim@5650
   444
    jclass channels;
tim@5650
   445
    jobject readableByteChannel;
tim@5650
   446
    jstring fileNameJString;
tim@5650
   447
slouken@6284
   448
    if (!refs.init(mEnv)) {
tim@5650
   449
        goto failure;
tim@5650
   450
    }
tim@5650
   451
gabomdq@6308
   452
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
icculus@5582
   453
icculus@5582
   454
    // context = SDLActivity.getContext();
tim@5650
   455
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   456
            "getContext","()Landroid/content/Context;");
tim@5650
   457
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
icculus@5582
   458
icculus@5582
   459
    // assetManager = context.getAssets();
icculus@5582
   460
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   461
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   462
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   463
icculus@5582
   464
    // inputStream = assetManager.open(<filename>);
icculus@5582
   465
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
icculus@5582
   466
            "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
tim@5650
   467
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   468
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   469
        goto failure;
icculus@5582
   470
    }
icculus@5582
   471
tim@5650
   472
    ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
tim@5650
   473
icculus@5582
   474
    // Despite all the visible documentation on [Asset]InputStream claiming
icculus@5582
   475
    // that the .available() method is not guaranteed to return the entire file
icculus@5582
   476
    // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
icculus@5582
   477
    // android/apis/content/ReadAsset.java imply that Android's
icculus@5582
   478
    // AssetInputStream.available() /will/ always return the total file size
icculus@5582
   479
icculus@5582
   480
    // size = inputStream.available();
icculus@5582
   481
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   482
            "available", "()I");
icculus@5582
   483
    ctx->hidden.androidio.size = mEnv->CallIntMethod(inputStream, mid);
tim@5650
   484
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   485
        goto failure;
icculus@5582
   486
    }
icculus@5582
   487
icculus@5582
   488
    // readableByteChannel = Channels.newChannel(inputStream);
tim@5650
   489
    channels = mEnv->FindClass("java/nio/channels/Channels");
icculus@5582
   490
    mid = mEnv->GetStaticMethodID(channels,
icculus@5582
   491
            "newChannel",
icculus@5582
   492
            "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
tim@5650
   493
    readableByteChannel = mEnv->CallStaticObjectMethod(
icculus@5582
   494
            channels, mid, inputStream);
tim@5650
   495
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   496
        goto failure;
icculus@5582
   497
    }
icculus@5582
   498
tim@5650
   499
    ctx->hidden.androidio.readableByteChannelRef =
tim@5650
   500
        mEnv->NewGlobalRef(readableByteChannel);
tim@5650
   501
icculus@5582
   502
    // Store .read id for reading purposes
icculus@5582
   503
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
icculus@5582
   504
            "read", "(Ljava/nio/ByteBuffer;)I");
icculus@5582
   505
    ctx->hidden.androidio.readMethod = mid;
icculus@5582
   506
icculus@5582
   507
    ctx->hidden.androidio.position = 0;
icculus@5582
   508
tim@5650
   509
    if (false) {
tim@5650
   510
failure:
tim@5650
   511
        result = -1;
tim@5650
   512
tim@5650
   513
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   514
tim@5650
   515
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   516
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   517
        }
gabomdq@6308
   518
gabomdq@6308
   519
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   520
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   521
        }
gabomdq@6308
   522
tim@5650
   523
    }
tim@5650
   524
tim@5650
   525
    return result;
icculus@5582
   526
}
icculus@5582
   527
icculus@5582
   528
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   529
        const char* fileName, const char*)
icculus@5582
   530
{
slouken@6284
   531
    LocalReferenceHolder refs;
slouken@6284
   532
slouken@6284
   533
    if (!refs.init(mEnv)) {
slouken@6284
   534
        return -1;
slouken@6284
   535
    }
slouken@6284
   536
icculus@5582
   537
    if (!ctx) {
icculus@5582
   538
        return -1;
icculus@5582
   539
    }
icculus@5582
   540
icculus@5582
   541
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   542
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   543
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   544
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   545
    ctx->hidden.androidio.readMethod = NULL;
icculus@5582
   546
icculus@5582
   547
    return Android_JNI_FileOpen(ctx);
icculus@5582
   548
}
icculus@5582
   549
icculus@5582
   550
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   551
        size_t size, size_t maxnum)
icculus@5582
   552
{
slouken@6284
   553
    LocalReferenceHolder refs;
icculus@5582
   554
    int bytesRemaining = size * maxnum;
icculus@5582
   555
    int bytesRead = 0;
icculus@5582
   556
slouken@6284
   557
    if (!refs.init(mEnv)) {
slouken@6284
   558
        return -1;
slouken@6284
   559
    }
slouken@6284
   560
gabomdq@6308
   561
    jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
icculus@5582
   562
    jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
icculus@5582
   563
    jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
icculus@5582
   564
icculus@5582
   565
    while (bytesRemaining > 0) {
icculus@5582
   566
        // result = readableByteChannel.read(...);
icculus@5582
   567
        int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
icculus@5582
   568
tim@5650
   569
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   570
            return 0;
icculus@5582
   571
        }
icculus@5582
   572
icculus@5582
   573
        if (result < 0) {
icculus@5582
   574
            break;
icculus@5582
   575
        }
icculus@5582
   576
icculus@5582
   577
        bytesRemaining -= result;
icculus@5582
   578
        bytesRead += result;
icculus@5582
   579
        ctx->hidden.androidio.position += result;
icculus@5582
   580
    }
icculus@5582
   581
icculus@5582
   582
    return bytesRead / size;
icculus@5582
   583
}
icculus@5582
   584
icculus@5582
   585
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   586
        size_t size, size_t num)
icculus@5582
   587
{
icculus@5582
   588
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   589
    return 0;
icculus@5582
   590
}
icculus@5582
   591
icculus@5582
   592
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   593
{
slouken@6284
   594
    LocalReferenceHolder refs;
icculus@5582
   595
    int result = 0;
icculus@5582
   596
slouken@6284
   597
    if (!refs.init(mEnv)) {
slouken@6284
   598
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   599
        return -1;
slouken@6284
   600
    }
slouken@6284
   601
icculus@5582
   602
    if (ctx) {
icculus@5582
   603
        if (release) {
icculus@5582
   604
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   605
        }
icculus@5582
   606
gabomdq@6308
   607
        jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   608
icculus@5582
   609
        // inputStream.close();
icculus@5582
   610
        jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   611
                "close", "()V");
icculus@5582
   612
        mEnv->CallVoidMethod(inputStream, mid);
icculus@5582
   613
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
icculus@5582
   614
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
tim@5650
   615
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   616
            result = -1;
icculus@5582
   617
        }
icculus@5582
   618
icculus@5582
   619
        if (release) {
icculus@5582
   620
            SDL_FreeRW(ctx);
icculus@5582
   621
        }
icculus@5582
   622
    }
icculus@5582
   623
icculus@5582
   624
    return result;
icculus@5582
   625
}
icculus@5582
   626
icculus@5582
   627
icculus@5582
   628
extern "C" long Android_JNI_FileSeek(SDL_RWops* ctx, long offset, int whence)
icculus@5582
   629
{
icculus@5582
   630
    long newPosition;
icculus@5582
   631
icculus@5582
   632
    switch (whence) {
icculus@5582
   633
        case RW_SEEK_SET:
icculus@5582
   634
            newPosition = offset;
icculus@5582
   635
            break;
icculus@5582
   636
        case RW_SEEK_CUR:
icculus@5582
   637
            newPosition = ctx->hidden.androidio.position + offset;
icculus@5582
   638
            break;
icculus@5582
   639
        case RW_SEEK_END:
icculus@5582
   640
            newPosition = ctx->hidden.androidio.size + offset;
icculus@5582
   641
            break;
icculus@5582
   642
        default:
icculus@5582
   643
            SDL_SetError("Unknown value for 'whence'");
icculus@5582
   644
            return -1;
icculus@5582
   645
    }
icculus@5582
   646
    if (newPosition < 0) {
icculus@5582
   647
        newPosition = 0;
icculus@5582
   648
    }
icculus@5582
   649
    if (newPosition > ctx->hidden.androidio.size) {
icculus@5582
   650
        newPosition = ctx->hidden.androidio.size;
icculus@5582
   651
    }
icculus@5582
   652
icculus@5582
   653
    long movement = newPosition - ctx->hidden.androidio.position;
gabomdq@6308
   654
    jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   655
icculus@5582
   656
    if (movement > 0) {
tim@5993
   657
        unsigned char buffer[1024];
tim@5993
   658
icculus@5582
   659
        // The easy case where we're seeking forwards
icculus@5582
   660
        while (movement > 0) {
icculus@5994
   661
            long amount = (long) sizeof (buffer);
icculus@5994
   662
            if (amount > movement) {
icculus@5994
   663
                amount = movement;
icculus@5994
   664
            }
icculus@5994
   665
            size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
tim@5993
   666
tim@5993
   667
            if (result <= 0) {
tim@5993
   668
                // Failed to read/skip the required amount, so fail
icculus@5582
   669
                return -1;
icculus@5582
   670
            }
tim@5993
   671
tim@5993
   672
            movement -= result;
icculus@5582
   673
        }
icculus@5582
   674
    } else if (movement < 0) {
icculus@5582
   675
        // We can't seek backwards so we have to reopen the file and seek
icculus@5582
   676
        // forwards which obviously isn't very efficient
icculus@5582
   677
        Android_JNI_FileClose(ctx, false);
icculus@5582
   678
        Android_JNI_FileOpen(ctx);
icculus@5582
   679
        Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   680
    }
icculus@5582
   681
icculus@5582
   682
    ctx->hidden.androidio.position = newPosition;
icculus@5582
   683
icculus@5582
   684
    return ctx->hidden.androidio.position;
icculus@5582
   685
}
icculus@5582
   686
icculus@5582
   687
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   688
{
icculus@5582
   689
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   690
}
icculus@5582
   691
slouken@6044
   692
#endif /* __ANDROID__ */
slouken@6044
   693
slouken@4981
   694
/* vi: set ts=4 sw=4 expandtab: */