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