src/core/android/SDL_android.cpp
author Sam Lantinga <slouken@libsdl.org>
Mon, 31 Dec 2012 14:57:36 -0800
changeset 6792 a15821a3471f
parent 6654 2ecfb25be1e2
child 6802 8a6b8ce97656
permissions -rw-r--r--
Fixed bug 1616 - SDL does not use values set with SDL_GL_SetAttribute on Android

Philipp Wiesemann 2012-10-06 07:19:57 PDT

SDL does not use values set with SDL_GL_SetAttribute on Android.

I attached a patch which adds this functionality and makes it possible to set
(for example) depth buffer size or anti-aliasing in the actual application
instead of modifying the Java source (which seems currently the only way).
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, 
slouken@4998
   123
                                "audioInit", "(IZZI)Ljava/lang/Object;");
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
icculus@5996
   436
    audioBuffer = env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
slouken@4995
   437
slouken@4996
   438
    if (audioBuffer == NULL) {
slouken@4996
   439
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!");
slouken@4996
   440
        return 0;
slouken@4996
   441
    }
icculus@5996
   442
    audioBuffer = env->NewGlobalRef(audioBuffer);
slouken@4995
   443
slouken@4996
   444
    jboolean isCopy = JNI_FALSE;
slouken@4996
   445
    if (audioBuffer16Bit) {
icculus@5996
   446
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   447
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   448
    } else {
icculus@5996
   449
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   450
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   451
    }
slouken@4996
   452
    if (audioBufferStereo) {
slouken@4996
   453
        audioBufferFrames /= 2;
slouken@4996
   454
    }
icculus@5996
   455
 
slouken@4996
   456
    return audioBufferFrames;
slouken@4995
   457
}
slouken@4995
   458
slouken@4996
   459
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   460
{
slouken@4996
   461
    return audioBufferPinned;
slouken@4995
   462
}
slouken@4995
   463
slouken@4996
   464
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   465
{
gabomdq@6354
   466
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   467
slouken@4996
   468
    if (audioBuffer16Bit) {
slouken@4996
   469
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   470
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   471
    } else {
slouken@4996
   472
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   473
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   474
    }
slouken@4995
   475
slouken@4996
   476
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   477
}
slouken@4995
   478
slouken@4995
   479
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   480
{
icculus@5996
   481
    int status;
gabomdq@6354
   482
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   483
icculus@5996
   484
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   485
slouken@4997
   486
    if (audioBuffer) {
icculus@5996
   487
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   488
        audioBuffer = NULL;
slouken@4997
   489
        audioBufferPinned = NULL;
slouken@4997
   490
    }
slouken@4964
   491
}
slouken@4981
   492
tim@5650
   493
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   494
static bool Android_JNI_ExceptionOccurred()
tim@5650
   495
{
slouken@6284
   496
    SDL_assert(LocalReferenceHolder::IsActive());
gabomdq@6354
   497
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   498
tim@5650
   499
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   500
    if (exception != NULL) {
tim@5650
   501
        jmethodID mid;
tim@5650
   502
tim@5650
   503
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   504
        mEnv->ExceptionClear();
tim@5650
   505
tim@5650
   506
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   507
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   508
tim@5650
   509
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   510
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   511
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   512
tim@5650
   513
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   514
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   515
tim@5650
   516
        if (exceptionMessage != NULL) {
tim@5650
   517
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   518
                    exceptionMessage, 0);
tim@5650
   519
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   520
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   521
        } else {
tim@5650
   522
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   523
        }
tim@5650
   524
tim@5650
   525
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   526
tim@5650
   527
        return true;
tim@5650
   528
    }
tim@5650
   529
tim@5650
   530
    return false;
tim@5650
   531
}
tim@5650
   532
icculus@5582
   533
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   534
{
slouken@6650
   535
    LocalReferenceHolder refs(__FUNCTION__);
tim@5650
   536
    int result = 0;
tim@5650
   537
tim@5650
   538
    jmethodID mid;
tim@5650
   539
    jobject context;
tim@5650
   540
    jobject assetManager;
tim@5650
   541
    jobject inputStream;
tim@5650
   542
    jclass channels;
tim@5650
   543
    jobject readableByteChannel;
tim@5650
   544
    jstring fileNameJString;
tim@5650
   545
gabomdq@6354
   546
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   547
    if (!refs.init(mEnv)) {
tim@5650
   548
        goto failure;
tim@5650
   549
    }
tim@5650
   550
gabomdq@6308
   551
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
icculus@5582
   552
icculus@5582
   553
    // context = SDLActivity.getContext();
tim@5650
   554
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   555
            "getContext","()Landroid/content/Context;");
tim@5650
   556
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
icculus@5582
   557
icculus@5582
   558
    // assetManager = context.getAssets();
icculus@5582
   559
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   560
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   561
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   562
icculus@5582
   563
    // inputStream = assetManager.open(<filename>);
icculus@5582
   564
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
icculus@5582
   565
            "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
tim@5650
   566
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   567
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   568
        goto failure;
icculus@5582
   569
    }
icculus@5582
   570
tim@5650
   571
    ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
tim@5650
   572
icculus@5582
   573
    // Despite all the visible documentation on [Asset]InputStream claiming
icculus@5582
   574
    // that the .available() method is not guaranteed to return the entire file
icculus@5582
   575
    // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
icculus@5582
   576
    // android/apis/content/ReadAsset.java imply that Android's
icculus@5582
   577
    // AssetInputStream.available() /will/ always return the total file size
icculus@5582
   578
icculus@5582
   579
    // size = inputStream.available();
icculus@5582
   580
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   581
            "available", "()I");
icculus@5582
   582
    ctx->hidden.androidio.size = mEnv->CallIntMethod(inputStream, mid);
tim@5650
   583
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   584
        goto failure;
icculus@5582
   585
    }
icculus@5582
   586
icculus@5582
   587
    // readableByteChannel = Channels.newChannel(inputStream);
tim@5650
   588
    channels = mEnv->FindClass("java/nio/channels/Channels");
icculus@5582
   589
    mid = mEnv->GetStaticMethodID(channels,
icculus@5582
   590
            "newChannel",
icculus@5582
   591
            "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
tim@5650
   592
    readableByteChannel = mEnv->CallStaticObjectMethod(
icculus@5582
   593
            channels, mid, inputStream);
tim@5650
   594
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   595
        goto failure;
icculus@5582
   596
    }
icculus@5582
   597
tim@5650
   598
    ctx->hidden.androidio.readableByteChannelRef =
tim@5650
   599
        mEnv->NewGlobalRef(readableByteChannel);
tim@5650
   600
icculus@5582
   601
    // Store .read id for reading purposes
icculus@5582
   602
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
icculus@5582
   603
            "read", "(Ljava/nio/ByteBuffer;)I");
icculus@5582
   604
    ctx->hidden.androidio.readMethod = mid;
icculus@5582
   605
icculus@5582
   606
    ctx->hidden.androidio.position = 0;
icculus@5582
   607
tim@5650
   608
    if (false) {
tim@5650
   609
failure:
tim@5650
   610
        result = -1;
tim@5650
   611
tim@5650
   612
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   613
tim@5650
   614
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   615
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   616
        }
gabomdq@6308
   617
gabomdq@6308
   618
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   619
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   620
        }
gabomdq@6308
   621
tim@5650
   622
    }
tim@5650
   623
tim@5650
   624
    return result;
icculus@5582
   625
}
icculus@5582
   626
icculus@5582
   627
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   628
        const char* fileName, const char*)
icculus@5582
   629
{
slouken@6650
   630
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6354
   631
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   632
slouken@6284
   633
    if (!refs.init(mEnv)) {
slouken@6284
   634
        return -1;
slouken@6284
   635
    }
slouken@6284
   636
icculus@5582
   637
    if (!ctx) {
icculus@5582
   638
        return -1;
icculus@5582
   639
    }
icculus@5582
   640
icculus@5582
   641
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   642
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   643
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   644
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   645
    ctx->hidden.androidio.readMethod = NULL;
icculus@5582
   646
icculus@5582
   647
    return Android_JNI_FileOpen(ctx);
icculus@5582
   648
}
icculus@5582
   649
icculus@5582
   650
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   651
        size_t size, size_t maxnum)
icculus@5582
   652
{
slouken@6650
   653
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6377
   654
    jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6377
   655
    jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
icculus@5582
   656
    int bytesRead = 0;
icculus@5582
   657
gabomdq@6377
   658
    /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6377
   659
    if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
gabomdq@6377
   660
gabomdq@6354
   661
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   662
    if (!refs.init(mEnv)) {
slouken@6284
   663
        return -1;
slouken@6284
   664
    }
slouken@6284
   665
gabomdq@6308
   666
    jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
icculus@5582
   667
    jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
icculus@5582
   668
    jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
icculus@5582
   669
icculus@5582
   670
    while (bytesRemaining > 0) {
icculus@5582
   671
        // result = readableByteChannel.read(...);
icculus@5582
   672
        int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
icculus@5582
   673
tim@5650
   674
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   675
            return 0;
icculus@5582
   676
        }
icculus@5582
   677
icculus@5582
   678
        if (result < 0) {
icculus@5582
   679
            break;
icculus@5582
   680
        }
icculus@5582
   681
icculus@5582
   682
        bytesRemaining -= result;
icculus@5582
   683
        bytesRead += result;
icculus@5582
   684
        ctx->hidden.androidio.position += result;
icculus@5582
   685
    }
icculus@5582
   686
icculus@5582
   687
    return bytesRead / size;
icculus@5582
   688
}
icculus@5582
   689
icculus@5582
   690
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   691
        size_t size, size_t num)
icculus@5582
   692
{
icculus@5582
   693
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   694
    return 0;
icculus@5582
   695
}
icculus@5582
   696
icculus@5582
   697
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   698
{
slouken@6650
   699
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   700
    int result = 0;
gabomdq@6354
   701
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   702
slouken@6284
   703
    if (!refs.init(mEnv)) {
slouken@6284
   704
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   705
        return -1;
slouken@6284
   706
    }
slouken@6284
   707
icculus@5582
   708
    if (ctx) {
icculus@5582
   709
        if (release) {
icculus@5582
   710
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   711
        }
icculus@5582
   712
gabomdq@6308
   713
        jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   714
icculus@5582
   715
        // inputStream.close();
icculus@5582
   716
        jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   717
                "close", "()V");
icculus@5582
   718
        mEnv->CallVoidMethod(inputStream, mid);
icculus@5582
   719
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
icculus@5582
   720
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
tim@5650
   721
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   722
            result = -1;
icculus@5582
   723
        }
icculus@5582
   724
icculus@5582
   725
        if (release) {
icculus@5582
   726
            SDL_FreeRW(ctx);
icculus@5582
   727
        }
icculus@5582
   728
    }
icculus@5582
   729
icculus@5582
   730
    return result;
icculus@5582
   731
}
icculus@5582
   732
icculus@5582
   733
slouken@6642
   734
extern "C" Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   735
{
slouken@6642
   736
    return ctx->hidden.androidio.size;
slouken@6642
   737
}
slouken@6642
   738
slouken@6642
   739
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   740
{
slouken@6642
   741
    Sint64 newPosition;
icculus@5582
   742
icculus@5582
   743
    switch (whence) {
icculus@5582
   744
        case RW_SEEK_SET:
icculus@5582
   745
            newPosition = offset;
icculus@5582
   746
            break;
icculus@5582
   747
        case RW_SEEK_CUR:
icculus@5582
   748
            newPosition = ctx->hidden.androidio.position + offset;
icculus@5582
   749
            break;
icculus@5582
   750
        case RW_SEEK_END:
icculus@5582
   751
            newPosition = ctx->hidden.androidio.size + offset;
icculus@5582
   752
            break;
icculus@5582
   753
        default:
icculus@5582
   754
            SDL_SetError("Unknown value for 'whence'");
icculus@5582
   755
            return -1;
icculus@5582
   756
    }
slouken@6642
   757
slouken@6642
   758
    /* Validate the new position */
icculus@5582
   759
    if (newPosition < 0) {
slouken@6642
   760
        SDL_Error(SDL_EFSEEK);
slouken@6642
   761
        return -1;
icculus@5582
   762
    }
icculus@5582
   763
    if (newPosition > ctx->hidden.androidio.size) {
icculus@5582
   764
        newPosition = ctx->hidden.androidio.size;
icculus@5582
   765
    }
icculus@5582
   766
slouken@6642
   767
    Sint64 movement = newPosition - ctx->hidden.androidio.position;
icculus@5582
   768
    if (movement > 0) {
slouken@6650
   769
        unsigned char buffer[4096];
tim@5993
   770
icculus@5582
   771
        // The easy case where we're seeking forwards
icculus@5582
   772
        while (movement > 0) {
slouken@6642
   773
            Sint64 amount = sizeof (buffer);
icculus@5994
   774
            if (amount > movement) {
icculus@5994
   775
                amount = movement;
icculus@5994
   776
            }
icculus@5994
   777
            size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
tim@5993
   778
            if (result <= 0) {
tim@5993
   779
                // Failed to read/skip the required amount, so fail
icculus@5582
   780
                return -1;
icculus@5582
   781
            }
tim@5993
   782
tim@5993
   783
            movement -= result;
icculus@5582
   784
        }
slouken@6642
   785
icculus@5582
   786
    } else if (movement < 0) {
icculus@5582
   787
        // We can't seek backwards so we have to reopen the file and seek
icculus@5582
   788
        // forwards which obviously isn't very efficient
icculus@5582
   789
        Android_JNI_FileClose(ctx, false);
icculus@5582
   790
        Android_JNI_FileOpen(ctx);
icculus@5582
   791
        Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   792
    }
icculus@5582
   793
icculus@5582
   794
    return ctx->hidden.androidio.position;
icculus@5582
   795
}
icculus@5582
   796
icculus@5582
   797
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   798
{
icculus@5582
   799
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   800
}
icculus@5582
   801
slouken@6464
   802
// returns a new global reference which needs to be released later
slouken@6464
   803
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   804
{
slouken@6650
   805
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6464
   806
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6464
   807
    if (!refs.init(env)) {
slouken@6464
   808
        return NULL;
slouken@6464
   809
    }
slouken@6464
   810
slouken@6464
   811
    jstring service = env->NewStringUTF(name);
slouken@6464
   812
slouken@6464
   813
    jmethodID mid;
slouken@6464
   814
slouken@6464
   815
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6464
   816
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6464
   817
slouken@6464
   818
    mid = env->GetMethodID(mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
slouken@6464
   819
    jobject manager = env->CallObjectMethod(context, mid, service);
slouken@6464
   820
slouken@6464
   821
    env->DeleteLocalRef(service);
slouken@6464
   822
slouken@6464
   823
    return manager ? env->NewGlobalRef(manager) : NULL;
slouken@6464
   824
}
slouken@6464
   825
slouken@6464
   826
#define SETUP_CLIPBOARD(error) \
slouken@6650
   827
    LocalReferenceHolder refs(__FUNCTION__); \
slouken@6464
   828
    JNIEnv* env = Android_JNI_GetEnv(); \
slouken@6464
   829
    if (!refs.init(env)) { \
slouken@6464
   830
        return error; \
slouken@6464
   831
    } \
slouken@6464
   832
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
   833
    if (!clipboard) { \
slouken@6464
   834
        return error; \
slouken@6464
   835
    }
slouken@6464
   836
slouken@6464
   837
extern "C" int Android_JNI_SetClipboardText(const char* text)
slouken@6464
   838
{
slouken@6464
   839
    SETUP_CLIPBOARD(-1)
slouken@6464
   840
slouken@6464
   841
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "setText", "(Ljava/lang/CharSequence;)V");
slouken@6464
   842
    jstring string = env->NewStringUTF(text);
slouken@6464
   843
    env->CallVoidMethod(clipboard, mid, string);
slouken@6464
   844
    env->DeleteGlobalRef(clipboard);
slouken@6464
   845
    env->DeleteLocalRef(string);
slouken@6464
   846
    return 0;
slouken@6464
   847
}
slouken@6464
   848
slouken@6464
   849
extern "C" char* Android_JNI_GetClipboardText()
slouken@6464
   850
{
slouken@6464
   851
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
   852
slouken@6464
   853
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "getText", "()Ljava/lang/CharSequence;");
slouken@6464
   854
    jobject sequence = env->CallObjectMethod(clipboard, mid);
slouken@6464
   855
    env->DeleteGlobalRef(clipboard);
slouken@6464
   856
    if (sequence) {
slouken@6464
   857
        mid = env->GetMethodID(env->GetObjectClass(sequence), "toString", "()Ljava/lang/String;");
slouken@6464
   858
        jstring string = reinterpret_cast<jstring>(env->CallObjectMethod(sequence, mid));
slouken@6464
   859
        const char* utf = env->GetStringUTFChars(string, 0);
slouken@6464
   860
        if (utf) {
slouken@6464
   861
            char* text = SDL_strdup(utf);
slouken@6464
   862
            env->ReleaseStringUTFChars(string, utf);
slouken@6464
   863
            return text;
slouken@6464
   864
        }
slouken@6464
   865
    }
slouken@6464
   866
    return SDL_strdup("");
slouken@6464
   867
}
slouken@6464
   868
slouken@6464
   869
extern "C" SDL_bool Android_JNI_HasClipboardText()
slouken@6464
   870
{
slouken@6464
   871
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
   872
slouken@6464
   873
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "hasText", "()Z");
slouken@6464
   874
    jboolean has = env->CallBooleanMethod(clipboard, mid);
slouken@6464
   875
    env->DeleteGlobalRef(clipboard);
slouken@6464
   876
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
   877
}
slouken@6464
   878
slouken@6464
   879
slouken@6448
   880
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
   881
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
   882
// returns the value in seconds and percent or -1 if not available
slouken@6448
   883
extern "C" int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
   884
{
slouken@6650
   885
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6448
   886
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6448
   887
    if (!refs.init(env)) {
slouken@6448
   888
        return -1;
slouken@6448
   889
    }
slouken@6448
   890
slouken@6448
   891
    jmethodID mid;
slouken@6448
   892
slouken@6448
   893
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6448
   894
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6448
   895
slouken@6448
   896
    jstring action = env->NewStringUTF("android.intent.action.BATTERY_CHANGED");
slouken@6448
   897
slouken@6448
   898
    jclass cls = env->FindClass("android/content/IntentFilter");
slouken@6448
   899
slouken@6448
   900
    mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
slouken@6448
   901
    jobject filter = env->NewObject(cls, mid, action);
slouken@6448
   902
slouken@6448
   903
    env->DeleteLocalRef(action);
slouken@6448
   904
slouken@6448
   905
    mid = env->GetMethodID(mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
slouken@6448
   906
    jobject intent = env->CallObjectMethod(context, mid, NULL, filter);
slouken@6448
   907
slouken@6448
   908
    env->DeleteLocalRef(filter);
slouken@6448
   909
slouken@6448
   910
    cls = env->GetObjectClass(intent);
slouken@6448
   911
slouken@6448
   912
    jstring iname;
slouken@6448
   913
    jmethodID imid = env->GetMethodID(cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
   914
slouken@6448
   915
#define GET_INT_EXTRA(var, key) \
slouken@6448
   916
    iname = env->NewStringUTF(key); \
slouken@6448
   917
    int var = env->CallIntMethod(intent, imid, iname, -1); \
slouken@6448
   918
    env->DeleteLocalRef(iname);
slouken@6448
   919
slouken@6448
   920
    jstring bname;
slouken@6448
   921
    jmethodID bmid = env->GetMethodID(cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
   922
slouken@6448
   923
#define GET_BOOL_EXTRA(var, key) \
slouken@6448
   924
    bname = env->NewStringUTF(key); \
slouken@6448
   925
    int var = env->CallBooleanMethod(intent, bmid, bname, JNI_FALSE); \
slouken@6448
   926
    env->DeleteLocalRef(bname);
slouken@6448
   927
slouken@6448
   928
    if (plugged) {
slouken@6448
   929
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
   930
        if (plug == -1) {
slouken@6448
   931
            return -1;
slouken@6448
   932
        }
slouken@6448
   933
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
   934
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
   935
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
   936
    }
slouken@6448
   937
slouken@6448
   938
    if (charged) {
slouken@6448
   939
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
   940
        if (status == -1) {
slouken@6448
   941
            return -1;
slouken@6448
   942
        }
slouken@6448
   943
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
   944
        *charged = (status == 5) ? 1 : 0;
slouken@6448
   945
    }
slouken@6448
   946
slouken@6448
   947
    if (battery) {
slouken@6448
   948
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
   949
        *battery = present ? 1 : 0;
slouken@6448
   950
    }
slouken@6448
   951
slouken@6448
   952
    if (seconds) {
slouken@6448
   953
        *seconds = -1; // not possible
slouken@6448
   954
    }
slouken@6448
   955
slouken@6448
   956
    if (percent) {
slouken@6448
   957
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
   958
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
   959
        if ((level == -1) || (scale == -1)) {
slouken@6448
   960
            return -1;
slouken@6448
   961
        }
slouken@6448
   962
        *percent = level * 100 / scale;
slouken@6448
   963
    }
slouken@6448
   964
slouken@6448
   965
    env->DeleteLocalRef(intent);
slouken@6448
   966
slouken@6448
   967
    return 0;
slouken@6448
   968
}
slouken@6448
   969
slouken@6392
   970
// sends message to be handled on the UI event dispatch thread
slouken@6392
   971
extern "C" int Android_JNI_SendMessage(int command, int param)
slouken@6392
   972
{
slouken@6392
   973
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
   974
    if (!env) {
slouken@6392
   975
        return -1;
slouken@6392
   976
    }
slouken@6392
   977
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "sendMessage", "(II)V");
slouken@6392
   978
    if (!mid) {
slouken@6392
   979
        return -1;
slouken@6392
   980
    }
slouken@6392
   981
    env->CallStaticVoidMethod(mActivityClass, mid, command, param);
slouken@6392
   982
    return 0;
slouken@6392
   983
}
slouken@6392
   984
slouken@6654
   985
extern "C" void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
   986
{
slouken@6555
   987
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
   988
    if (!env) {
slouken@6654
   989
        return;
slouken@6555
   990
    }
slouken@6555
   991
slouken@6555
   992
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "showTextInput", "(IIII)V");
slouken@6555
   993
    if (!mid) {
slouken@6654
   994
        return;
slouken@6555
   995
    }
slouken@6555
   996
    env->CallStaticVoidMethod( mActivityClass, mid,
slouken@6555
   997
                               inputRect->x,
slouken@6555
   998
                               inputRect->y,
slouken@6555
   999
                               inputRect->w,
slouken@6555
  1000
                               inputRect->h );
slouken@6555
  1001
}
slouken@6555
  1002
slouken@6654
  1003
extern "C" void Android_JNI_HideTextInput()
slouken@6555
  1004
{
slouken@6654
  1005
    // has to match Activity constant
slouken@6654
  1006
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
  1007
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
  1008
}
slouken@6555
  1009
slouken@6630
  1010
//////////////////////////////////////////////////////////////////////////////
slouken@6630
  1011
//
slouken@6630
  1012
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
  1013
//
slouken@6630
  1014
slouken@6630
  1015
extern "C" void *SDL_AndroidGetJNIEnv()
slouken@6630
  1016
{
slouken@6630
  1017
    return Android_JNI_GetEnv();
slouken@6630
  1018
}
slouken@6630
  1019
slouken@6630
  1020
extern "C" void *SDL_AndroidGetActivity()
slouken@6630
  1021
{
slouken@6650
  1022
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1023
    jmethodID mid;
slouken@6630
  1024
slouken@6630
  1025
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1026
    if (!refs.init(env)) {
slouken@6630
  1027
        return NULL;
slouken@6630
  1028
    }
slouken@6630
  1029
slouken@6630
  1030
    // return SDLActivity.getContext();
slouken@6630
  1031
    mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1032
            "getContext","()Landroid/content/Context;");
slouken@6630
  1033
    return env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1034
}
slouken@6630
  1035
slouken@6630
  1036
extern "C" const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1037
{
slouken@6630
  1038
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1039
slouken@6630
  1040
    if (!s_AndroidInternalFilesPath) {
slouken@6650
  1041
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1042
        jmethodID mid;
slouken@6630
  1043
        jobject context;
slouken@6630
  1044
        jobject fileObject;
slouken@6630
  1045
        jstring pathString;
slouken@6630
  1046
        const char *path;
slouken@6630
  1047
slouken@6630
  1048
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1049
        if (!refs.init(env)) {
slouken@6630
  1050
            return NULL;
slouken@6630
  1051
        }
slouken@6630
  1052
slouken@6630
  1053
        // context = SDLActivity.getContext();
slouken@6630
  1054
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1055
                "getContext","()Landroid/content/Context;");
slouken@6630
  1056
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1057
slouken@6630
  1058
        // fileObj = context.getFilesDir();
slouken@6630
  1059
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1060
                "getFilesDir", "()Ljava/io/File;");
slouken@6630
  1061
        fileObject = env->CallObjectMethod(context, mid);
slouken@6630
  1062
        if (!fileObject) {
slouken@6630
  1063
            SDL_SetError("Couldn't get internal directory");
slouken@6630
  1064
            return NULL;
slouken@6630
  1065
        }
slouken@6630
  1066
slouken@6630
  1067
        // path = fileObject.getAbsolutePath();
slouken@6630
  1068
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1069
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1070
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1071
slouken@6630
  1072
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1073
        s_AndroidInternalFilesPath = SDL_strdup(path);
slouken@6630
  1074
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1075
    }
slouken@6630
  1076
    return s_AndroidInternalFilesPath;
slouken@6630
  1077
}
slouken@6630
  1078
slouken@6630
  1079
extern "C" int SDL_AndroidGetExternalStorageState()
slouken@6630
  1080
{
slouken@6650
  1081
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1082
    jmethodID mid;
slouken@6630
  1083
    jclass cls;
slouken@6630
  1084
    jstring stateString;
slouken@6630
  1085
    const char *state;
slouken@6630
  1086
    int stateFlags;
slouken@6630
  1087
slouken@6630
  1088
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1089
    if (!refs.init(env)) {
slouken@6630
  1090
        return 0;
slouken@6630
  1091
    }
slouken@6630
  1092
slouken@6630
  1093
    cls = env->FindClass("android/os/Environment");
slouken@6630
  1094
    mid = env->GetStaticMethodID(cls,
slouken@6630
  1095
            "getExternalStorageState", "()Ljava/lang/String;");
slouken@6630
  1096
    stateString = (jstring)env->CallStaticObjectMethod(cls, mid);
slouken@6630
  1097
slouken@6630
  1098
    state = env->GetStringUTFChars(stateString, NULL);
slouken@6630
  1099
slouken@6630
  1100
    // Print an info message so people debugging know the storage state
slouken@6630
  1101
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1102
slouken@6630
  1103
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1104
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1105
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1106
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1107
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1108
    } else {
slouken@6630
  1109
        stateFlags = 0;
slouken@6630
  1110
    }
slouken@6630
  1111
    env->ReleaseStringUTFChars(stateString, state);
slouken@6630
  1112
slouken@6630
  1113
    return stateFlags;
slouken@6630
  1114
}
slouken@6630
  1115
slouken@6630
  1116
extern "C" const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1117
{
slouken@6630
  1118
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1119
slouken@6630
  1120
    if (!s_AndroidExternalFilesPath) {
slouken@6650
  1121
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1122
        jmethodID mid;
slouken@6630
  1123
        jobject context;
slouken@6630
  1124
        jobject fileObject;
slouken@6630
  1125
        jstring pathString;
slouken@6630
  1126
        const char *path;
slouken@6630
  1127
slouken@6630
  1128
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1129
        if (!refs.init(env)) {
slouken@6630
  1130
            return NULL;
slouken@6630
  1131
        }
slouken@6630
  1132
slouken@6630
  1133
        // context = SDLActivity.getContext();
slouken@6630
  1134
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1135
                "getContext","()Landroid/content/Context;");
slouken@6630
  1136
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1137
slouken@6630
  1138
        // fileObj = context.getExternalFilesDir();
slouken@6630
  1139
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1140
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
slouken@6630
  1141
        fileObject = env->CallObjectMethod(context, mid, NULL);
slouken@6630
  1142
        if (!fileObject) {
slouken@6630
  1143
            SDL_SetError("Couldn't get external directory");
slouken@6630
  1144
            return NULL;
slouken@6630
  1145
        }
slouken@6630
  1146
slouken@6630
  1147
        // path = fileObject.getAbsolutePath();
slouken@6630
  1148
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1149
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1150
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1151
slouken@6630
  1152
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1153
        s_AndroidExternalFilesPath = SDL_strdup(path);
slouken@6630
  1154
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1155
    }
slouken@6630
  1156
    return s_AndroidExternalFilesPath;
slouken@6630
  1157
}
slouken@6630
  1158
slouken@6044
  1159
#endif /* __ANDROID__ */
slouken@6044
  1160
slouken@4981
  1161
/* vi: set ts=4 sw=4 expandtab: */