src/core/android/SDL_android.cpp
author Ryan C. Gordon <icculus@icculus.org>
Sun, 31 Mar 2013 12:48:50 -0400
changeset 7037 3fedf1f25b94
parent 7018 9cef1005df5f
child 7039 f69b305b053d
permissions -rw-r--r--
Make SDL_SetError and friends unconditionally return -1.

This lets us change things like this...

if (Failed) {
SDL_SetError("We failed");
return -1;
}

...into this...

if (Failed) {
return SDL_SetError("We failed");
}


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