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