src/core/android/SDL_android.c
author Philipp Wiesemann <philipp.wiesemann@arcor.de>
Sun, 04 Aug 2013 23:38:25 +0200
changeset 7575 930f21eaacd7
parent 7569 9fd3f4b23223
child 7612 627d571587d3
permissions -rw-r--r--
Added missing function prototype and changed its signature.
Signature was changed to prevent a header for SDL_GLContext.
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
philipp@7575
   367
SDL_bool Android_JNI_DeleteContext(void)
gabomdq@7567
   368
{
philipp@7575
   369
    /* There's only one context, so no parameter for now */
gabomdq@7567
   370
    JNIEnv *env = Android_JNI_GetEnv();
philipp@7568
   371
    (*env)->CallStaticVoidMethod(env, mActivityClass, midDeleteGLContext);
philipp@7569
   372
    return SDL_TRUE;
gabomdq@7567
   373
}
gabomdq@7567
   374
ewing@7501
   375
void Android_JNI_SwapWindow()
slouken@4964
   376
{
gabomdq@6354
   377
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   378
    (*mEnv)->CallStaticVoidMethod(mEnv, mActivityClass, midFlipBuffers);
slouken@4998
   379
}
slouken@4998
   380
ewing@7501
   381
void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   382
{
slouken@4998
   383
    jmethodID mid;
gabomdq@6354
   384
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   385
    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,"setActivityTitle","(Ljava/lang/String;)Z");
slouken@4998
   386
    if (mid) {
ewing@7501
   387
        jstring jtitle = (jstring)((*mEnv)->NewStringUTF(mEnv, title));
ewing@7501
   388
        (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, mid, jtitle);
ewing@7501
   389
        (*mEnv)->DeleteLocalRef(mEnv, jtitle);
slouken@4998
   390
    }
slouken@4964
   391
}
slouken@4964
   392
ewing@7501
   393
SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   394
{
slouken@5000
   395
    int i;
slouken@6212
   396
    SDL_bool retval = SDL_FALSE;
slouken@6212
   397
slouken@6212
   398
    if (bHasNewData) {
slouken@6212
   399
        for (i = 0; i < 3; ++i) {
slouken@6212
   400
            values[i] = fLastAccelerometer[i];
slouken@6212
   401
        }
slouken@6212
   402
        bHasNewData = false;
slouken@6212
   403
        retval = SDL_TRUE;
slouken@5000
   404
    }
slouken@6212
   405
slouken@6212
   406
    return retval;
slouken@5000
   407
}
slouken@5000
   408
gabomdq@6354
   409
static void Android_JNI_ThreadDestroyed(void* value) {
gabomdq@6354
   410
    /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
gabomdq@6354
   411
    JNIEnv *env = (JNIEnv*) value;
gabomdq@6354
   412
    if (env != NULL) {
ewing@7501
   413
        (*mJavaVM)->DetachCurrentThread(mJavaVM);
gabomdq@6354
   414
        pthread_setspecific(mThreadKey, NULL);
gabomdq@6354
   415
    }
gabomdq@6354
   416
}
gabomdq@6354
   417
gabomdq@6354
   418
JNIEnv* Android_JNI_GetEnv(void) {
gabomdq@6354
   419
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   420
     * All threads are Linux threads, scheduled by the kernel.
gabomdq@6354
   421
     * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
gabomdq@6354
   422
     * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
gabomdq@6354
   423
     * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
gabomdq@6354
   424
     * and cannot make JNI calls.
gabomdq@6354
   425
     * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
gabomdq@6354
   426
     * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
gabomdq@6354
   427
     * is a no-op.
gabomdq@6354
   428
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   429
     */
gabomdq@6354
   430
gabomdq@6354
   431
    JNIEnv *env;
ewing@7501
   432
    int status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
gabomdq@6354
   433
    if(status < 0) {
gabomdq@6354
   434
        LOGE("failed to attach current thread");
gabomdq@6354
   435
        return 0;
gabomdq@6354
   436
    }
gabomdq@6354
   437
gabomdq@6354
   438
    return env;
gabomdq@6354
   439
}
gabomdq@6354
   440
gabomdq@6354
   441
int Android_JNI_SetupThread(void) {
gabomdq@6354
   442
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   443
     * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
gabomdq@6354
   444
     * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
gabomdq@6354
   445
     * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
gabomdq@6354
   446
     * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
gabomdq@6354
   447
     * Note: The destructor is not called unless the stored value is != NULL
gabomdq@6354
   448
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   449
     *       (except for some lost CPU cycles)
gabomdq@6354
   450
     */
gabomdq@6354
   451
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   452
    pthread_setspecific(mThreadKey, (void*) env);
gabomdq@6354
   453
    return 1;
gabomdq@6354
   454
}
gabomdq@6354
   455
slouken@4995
   456
//
slouken@4995
   457
// Audio support
slouken@4995
   458
//
slouken@4996
   459
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   460
static jboolean audioBufferStereo = JNI_FALSE;
slouken@4996
   461
static jobject audioBuffer = NULL;
slouken@4996
   462
static void* audioBufferPinned = NULL;
slouken@4995
   463
ewing@7501
   464
int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   465
{
slouken@4996
   466
    int audioBufferFrames;
slouken@4964
   467
gabomdq@6354
   468
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   469
gabomdq@6354
   470
    if (!env) {
gabomdq@6354
   471
        LOGE("callback_handler: failed to attach current thread");
icculus@5996
   472
    }
gabomdq@6354
   473
    Android_JNI_SetupThread();
icculus@5996
   474
slouken@4996
   475
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   476
    audioBuffer16Bit = is16Bit;
slouken@4996
   477
    audioBufferStereo = channelCount > 1;
slouken@4964
   478
gabomdq@7552
   479
    if ((*env)->CallStaticIntMethod(env, mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames) != 0) {
gabomdq@7552
   480
        /* Error during audio initialization */
gabomdq@7552
   481
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: error on AudioTrack initialization!");
gabomdq@7552
   482
        return 0;
gabomdq@7552
   483
    }
gabomdq@6802
   484
gabomdq@6802
   485
    /* Allocating the audio buffer from the Java side and passing it as the return value for audioInit no longer works on
gabomdq@6802
   486
     * Android >= 4.2 due to a "stale global reference" error. So now we allocate this buffer directly from this side. */
slouken@7191
   487
gabomdq@6802
   488
    if (is16Bit) {
ewing@7501
   489
        jshortArray audioBufferLocal = (*env)->NewShortArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   490
        if (audioBufferLocal) {
ewing@7501
   491
            audioBuffer = (*env)->NewGlobalRef(env, audioBufferLocal);
ewing@7501
   492
            (*env)->DeleteLocalRef(env, audioBufferLocal);
gabomdq@6802
   493
        }
gabomdq@6802
   494
    }
gabomdq@6802
   495
    else {
ewing@7501
   496
        jbyteArray audioBufferLocal = (*env)->NewByteArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   497
        if (audioBufferLocal) {
ewing@7501
   498
            audioBuffer = (*env)->NewGlobalRef(env, audioBufferLocal);
ewing@7501
   499
            (*env)->DeleteLocalRef(env, audioBufferLocal);
gabomdq@6802
   500
        }
gabomdq@6802
   501
    }
slouken@4995
   502
slouken@4996
   503
    if (audioBuffer == NULL) {
gabomdq@6802
   504
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer!");
slouken@4996
   505
        return 0;
slouken@4996
   506
    }
slouken@4995
   507
slouken@4996
   508
    jboolean isCopy = JNI_FALSE;
slouken@4996
   509
    if (audioBuffer16Bit) {
ewing@7501
   510
        audioBufferPinned = (*env)->GetShortArrayElements(env, (jshortArray)audioBuffer, &isCopy);
ewing@7501
   511
        audioBufferFrames = (*env)->GetArrayLength(env, (jshortArray)audioBuffer);
slouken@4996
   512
    } else {
ewing@7501
   513
        audioBufferPinned = (*env)->GetByteArrayElements(env, (jbyteArray)audioBuffer, &isCopy);
ewing@7501
   514
        audioBufferFrames = (*env)->GetArrayLength(env, (jbyteArray)audioBuffer);
slouken@4996
   515
    }
slouken@4996
   516
    if (audioBufferStereo) {
slouken@4996
   517
        audioBufferFrames /= 2;
slouken@4996
   518
    }
gabomdq@6864
   519
slouken@4996
   520
    return audioBufferFrames;
slouken@4995
   521
}
slouken@4995
   522
ewing@7501
   523
void * Android_JNI_GetAudioBuffer()
slouken@4995
   524
{
slouken@4996
   525
    return audioBufferPinned;
slouken@4995
   526
}
slouken@4995
   527
ewing@7501
   528
void Android_JNI_WriteAudioBuffer()
slouken@4995
   529
{
gabomdq@6354
   530
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   531
slouken@4996
   532
    if (audioBuffer16Bit) {
ewing@7501
   533
        (*mAudioEnv)->ReleaseShortArrayElements(mAudioEnv, (jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
ewing@7501
   534
        (*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   535
    } else {
ewing@7501
   536
        (*mAudioEnv)->ReleaseByteArrayElements(mAudioEnv, (jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
ewing@7501
   537
        (*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   538
    }
slouken@4995
   539
slouken@4996
   540
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   541
}
slouken@4995
   542
ewing@7501
   543
void Android_JNI_CloseAudioDevice()
slouken@4995
   544
{
gabomdq@6354
   545
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   546
ewing@7501
   547
    (*env)->CallStaticVoidMethod(env, mActivityClass, midAudioQuit);
slouken@4964
   548
slouken@4997
   549
    if (audioBuffer) {
ewing@7501
   550
        (*env)->DeleteGlobalRef(env, audioBuffer);
slouken@4997
   551
        audioBuffer = NULL;
slouken@4997
   552
        audioBufferPinned = NULL;
slouken@4997
   553
    }
slouken@4964
   554
}
slouken@4981
   555
tim@5650
   556
// Test for an exception and call SDL_SetError with its detail if one occurs
philipp@7515
   557
// If the parameter silent is truthy then SDL_SetError() will not be called.
ewing@7501
   558
static bool Android_JNI_ExceptionOccurred(bool silent)
tim@5650
   559
{
ewing@7501
   560
    SDL_assert(LocalReferenceHolder_IsActive());
gabomdq@6354
   561
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   562
ewing@7501
   563
    jthrowable exception = (*mEnv)->ExceptionOccurred(mEnv);
tim@5650
   564
    if (exception != NULL) {
tim@5650
   565
        jmethodID mid;
tim@5650
   566
tim@5650
   567
        // Until this happens most JNI operations have undefined behaviour
ewing@7501
   568
        (*mEnv)->ExceptionClear(mEnv);
tim@5650
   569
slouken@7045
   570
        if (!silent) {
ewing@7501
   571
            jclass exceptionClass = (*mEnv)->GetObjectClass(mEnv, exception);
ewing@7501
   572
            jclass classClass = (*mEnv)->FindClass(mEnv, "java/lang/Class");
tim@5650
   573
ewing@7501
   574
            mid = (*mEnv)->GetMethodID(mEnv, classClass, "getName", "()Ljava/lang/String;");
ewing@7501
   575
            jstring exceptionName = (jstring)(*mEnv)->CallObjectMethod(mEnv, exceptionClass, mid);
ewing@7501
   576
            const char* exceptionNameUTF8 = (*mEnv)->GetStringUTFChars(mEnv, exceptionName, 0);
tim@5650
   577
ewing@7501
   578
            mid = (*mEnv)->GetMethodID(mEnv, exceptionClass, "getMessage", "()Ljava/lang/String;");
ewing@7501
   579
            jstring exceptionMessage = (jstring)(*mEnv)->CallObjectMethod(mEnv, exception, mid);
tim@5650
   580
slouken@7045
   581
            if (exceptionMessage != NULL) {
ewing@7501
   582
                const char* exceptionMessageUTF8 = (*mEnv)->GetStringUTFChars(mEnv, exceptionMessage, 0);
slouken@7045
   583
                SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
ewing@7501
   584
                (*mEnv)->ReleaseStringUTFChars(mEnv, exceptionMessage, exceptionMessageUTF8);
slouken@7045
   585
            } else {
slouken@7045
   586
                SDL_SetError("%s", exceptionNameUTF8);
slouken@7045
   587
            }
slouken@7045
   588
ewing@7501
   589
            (*mEnv)->ReleaseStringUTFChars(mEnv, exceptionName, exceptionNameUTF8);
tim@5650
   590
        }
tim@5650
   591
tim@5650
   592
        return true;
tim@5650
   593
    }
tim@5650
   594
tim@5650
   595
    return false;
tim@5650
   596
}
tim@5650
   597
ewing@7501
   598
static int Internal_Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   599
{
ewing@7501
   600
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
ewing@7501
   601
tim@5650
   602
    int result = 0;
tim@5650
   603
tim@5650
   604
    jmethodID mid;
tim@5650
   605
    jobject context;
tim@5650
   606
    jobject assetManager;
tim@5650
   607
    jobject inputStream;
tim@5650
   608
    jclass channels;
tim@5650
   609
    jobject readableByteChannel;
tim@5650
   610
    jstring fileNameJString;
gabomdq@6806
   611
    jobject fd;
gabomdq@6806
   612
    jclass fdCls;
gabomdq@6806
   613
    jfieldID descriptor;
tim@5650
   614
gabomdq@6354
   615
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   616
    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
tim@5650
   617
        goto failure;
tim@5650
   618
    }
tim@5650
   619
gabomdq@6308
   620
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
gabomdq@6806
   621
    ctx->hidden.androidio.position = 0;
icculus@5582
   622
icculus@5582
   623
    // context = SDLActivity.getContext();
ewing@7501
   624
    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@5582
   625
            "getContext","()Landroid/content/Context;");
ewing@7501
   626
    context = (*mEnv)->CallStaticObjectMethod(mEnv, mActivityClass, mid);
slouken@7191
   627
icculus@5582
   628
icculus@5582
   629
    // assetManager = context.getAssets();
ewing@7501
   630
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, context),
tim@5650
   631
            "getAssets", "()Landroid/content/res/AssetManager;");
ewing@7501
   632
    assetManager = (*mEnv)->CallObjectMethod(mEnv, context, mid);
icculus@5582
   633
gabomdq@6806
   634
    /* First let's try opening the file to obtain an AssetFileDescriptor.
gabomdq@6806
   635
    * This method reads the files directly from the APKs using standard *nix calls
gabomdq@6806
   636
    */
ewing@7501
   637
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, assetManager), "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;");
ewing@7501
   638
    inputStream = (*mEnv)->CallObjectMethod(mEnv, assetManager, mid, fileNameJString);
slouken@7045
   639
    if (Android_JNI_ExceptionOccurred(true)) {
gabomdq@6806
   640
        goto fallback;
icculus@5582
   641
    }
icculus@5582
   642
ewing@7501
   643
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getStartOffset", "()J");
ewing@7501
   644
    ctx->hidden.androidio.offset = (*mEnv)->CallLongMethod(mEnv, inputStream, mid);
slouken@7045
   645
    if (Android_JNI_ExceptionOccurred(true)) {
gabomdq@6806
   646
        goto fallback;
icculus@5582
   647
    }
icculus@5582
   648
ewing@7501
   649
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getDeclaredLength", "()J");
ewing@7501
   650
    ctx->hidden.androidio.size = (*mEnv)->CallLongMethod(mEnv, inputStream, mid);
slouken@7045
   651
    if (Android_JNI_ExceptionOccurred(true)) {
gabomdq@6806
   652
        goto fallback;
icculus@5582
   653
    }
icculus@5582
   654
ewing@7501
   655
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getFileDescriptor", "()Ljava/io/FileDescriptor;");
ewing@7501
   656
    fd = (*mEnv)->CallObjectMethod(mEnv, inputStream, mid);
ewing@7501
   657
    fdCls = (*mEnv)->GetObjectClass(mEnv, fd);
ewing@7501
   658
    descriptor = (*mEnv)->GetFieldID(mEnv, fdCls, "descriptor", "I");
ewing@7501
   659
    ctx->hidden.androidio.fd = (*mEnv)->GetIntField(mEnv, fd, descriptor);
ewing@7501
   660
    ctx->hidden.androidio.assetFileDescriptorRef = (*mEnv)->NewGlobalRef(mEnv, inputStream);
tim@5650
   661
gabomdq@6816
   662
    // Seek to the correct offset in the file.
gabomdq@6816
   663
    lseek(ctx->hidden.androidio.fd, (off_t)ctx->hidden.androidio.offset, SEEK_SET);
gabomdq@6816
   664
gabomdq@6806
   665
    if (false) {
gabomdq@6806
   666
fallback:
slouken@7190
   667
        // Disabled log message because of spam on the Nexus 7
slouken@7190
   668
        //__android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file");
slouken@7190
   669
gabomdq@6806
   670
        /* Try the old method using InputStream */
gabomdq@6806
   671
        ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   672
gabomdq@6806
   673
        // inputStream = assetManager.open(<filename>);
ewing@7501
   674
        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, assetManager),
gabomdq@6806
   675
                "open", "(Ljava/lang/String;I)Ljava/io/InputStream;");
ewing@7501
   676
        inputStream = (*mEnv)->CallObjectMethod(mEnv, assetManager, mid, fileNameJString, 1 /*ACCESS_RANDOM*/);
ewing@7501
   677
        if (Android_JNI_ExceptionOccurred(false)) {
gabomdq@6806
   678
            goto failure;
gabomdq@6806
   679
        }
gabomdq@6806
   680
ewing@7501
   681
        ctx->hidden.androidio.inputStreamRef = (*mEnv)->NewGlobalRef(mEnv, inputStream);
gabomdq@6806
   682
gabomdq@6806
   683
        // Despite all the visible documentation on [Asset]InputStream claiming
gabomdq@6806
   684
        // that the .available() method is not guaranteed to return the entire file
gabomdq@6806
   685
        // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
gabomdq@6806
   686
        // android/apis/content/ReadAsset.java imply that Android's
gabomdq@6806
   687
        // AssetInputStream.available() /will/ always return the total file size
gabomdq@6806
   688
gabomdq@6806
   689
        // size = inputStream.available();
ewing@7501
   690
        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
gabomdq@6806
   691
                "available", "()I");
ewing@7501
   692
        ctx->hidden.androidio.size = (long)(*mEnv)->CallIntMethod(mEnv, inputStream, mid);
ewing@7501
   693
        if (Android_JNI_ExceptionOccurred(false)) {
gabomdq@6806
   694
            goto failure;
gabomdq@6806
   695
        }
gabomdq@6806
   696
gabomdq@6806
   697
        // readableByteChannel = Channels.newChannel(inputStream);
ewing@7501
   698
        channels = (*mEnv)->FindClass(mEnv, "java/nio/channels/Channels");
ewing@7501
   699
        mid = (*mEnv)->GetStaticMethodID(mEnv, channels,
gabomdq@6806
   700
                "newChannel",
gabomdq@6806
   701
                "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
ewing@7501
   702
        readableByteChannel = (*mEnv)->CallStaticObjectMethod(
ewing@7501
   703
                mEnv, channels, mid, inputStream);
ewing@7501
   704
        if (Android_JNI_ExceptionOccurred(false)) {
gabomdq@6806
   705
            goto failure;
gabomdq@6806
   706
        }
gabomdq@6806
   707
gabomdq@6806
   708
        ctx->hidden.androidio.readableByteChannelRef =
ewing@7501
   709
            (*mEnv)->NewGlobalRef(mEnv, readableByteChannel);
gabomdq@6806
   710
gabomdq@6806
   711
        // Store .read id for reading purposes
ewing@7501
   712
        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, readableByteChannel),
gabomdq@6806
   713
                "read", "(Ljava/nio/ByteBuffer;)I");
gabomdq@6806
   714
        ctx->hidden.androidio.readMethod = mid;
gabomdq@6806
   715
    }
icculus@5582
   716
tim@5650
   717
    if (false) {
tim@5650
   718
failure:
tim@5650
   719
        result = -1;
tim@5650
   720
ewing@7501
   721
        (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   722
tim@5650
   723
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
ewing@7501
   724
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   725
        }
gabomdq@6308
   726
gabomdq@6308
   727
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
ewing@7501
   728
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   729
        }
gabomdq@6308
   730
gabomdq@6806
   731
        if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) {
ewing@7501
   732
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
   733
        }
gabomdq@6806
   734
tim@5650
   735
    }
ewing@7501
   736
    
ewing@7501
   737
    LocalReferenceHolder_Cleanup(&refs);
tim@5650
   738
    return result;
icculus@5582
   739
}
icculus@5582
   740
ewing@7501
   741
int Android_JNI_FileOpen(SDL_RWops* ctx,
ewing@7501
   742
        const char* fileName, const char* mode)
icculus@5582
   743
{
ewing@7501
   744
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
gabomdq@6354
   745
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   746
    int retval;
slouken@6284
   747
ewing@7501
   748
    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
ewing@7501
   749
        LocalReferenceHolder_Cleanup(&refs);        
slouken@6284
   750
        return -1;
slouken@6284
   751
    }
slouken@6284
   752
icculus@5582
   753
    if (!ctx) {
ewing@7501
   754
        LocalReferenceHolder_Cleanup(&refs);
icculus@5582
   755
        return -1;
icculus@5582
   756
    }
icculus@5582
   757
ewing@7501
   758
    jstring fileNameJString = (*mEnv)->NewStringUTF(mEnv, fileName);
ewing@7501
   759
    ctx->hidden.androidio.fileNameRef = (*mEnv)->NewGlobalRef(mEnv, fileNameJString);
tim@5650
   760
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   761
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   762
    ctx->hidden.androidio.readMethod = NULL;
gabomdq@6806
   763
    ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
   764
ewing@7501
   765
    retval = Internal_Android_JNI_FileOpen(ctx);
ewing@7501
   766
    LocalReferenceHolder_Cleanup(&refs);
ewing@7501
   767
    return retval;
icculus@5582
   768
}
icculus@5582
   769
ewing@7501
   770
size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   771
        size_t size, size_t maxnum)
icculus@5582
   772
{
ewing@7501
   773
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
icculus@5582
   774
gabomdq@6806
   775
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   776
        size_t bytesMax = size * maxnum;
gabomdq@6806
   777
        if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && ctx->hidden.androidio.position + bytesMax > ctx->hidden.androidio.size) {
gabomdq@6806
   778
            bytesMax = ctx->hidden.androidio.size - ctx->hidden.androidio.position;
gabomdq@6806
   779
        }
gabomdq@6806
   780
        size_t result = read(ctx->hidden.androidio.fd, buffer, bytesMax );
gabomdq@6806
   781
        if (result > 0) {
gabomdq@6806
   782
            ctx->hidden.androidio.position += result;
ewing@7501
   783
            LocalReferenceHolder_Cleanup(&refs);
gabomdq@6806
   784
            return result / size;
gabomdq@6806
   785
        }
ewing@7501
   786
        LocalReferenceHolder_Cleanup(&refs);
gabomdq@6806
   787
        return 0;
gabomdq@6806
   788
    } else {
gabomdq@6806
   789
        jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6806
   790
        jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
gabomdq@6806
   791
        int bytesRead = 0;
gabomdq@6377
   792
gabomdq@6806
   793
        /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6806
   794
        if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
slouken@6284
   795
gabomdq@6806
   796
        JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   797
        if (!LocalReferenceHolder_Init(&refs, mEnv)) {
ewing@7501
   798
            LocalReferenceHolder_Cleanup(&refs);            
philipp@7368
   799
            return 0;
icculus@5582
   800
        }
icculus@5582
   801
gabomdq@6806
   802
        jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
gabomdq@6806
   803
        jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
ewing@7501
   804
        jobject byteBuffer = (*mEnv)->NewDirectByteBuffer(mEnv, buffer, bytesRemaining);
gabomdq@6806
   805
gabomdq@6806
   806
        while (bytesRemaining > 0) {
gabomdq@6806
   807
            // result = readableByteChannel.read(...);
ewing@7501
   808
            int result = (*mEnv)->CallIntMethod(mEnv, readableByteChannel, readMethod, byteBuffer);
gabomdq@6806
   809
ewing@7501
   810
            if (Android_JNI_ExceptionOccurred(false)) {
ewing@7501
   811
                LocalReferenceHolder_Cleanup(&refs);            
gabomdq@6806
   812
                return 0;
gabomdq@6806
   813
            }
gabomdq@6806
   814
gabomdq@6806
   815
            if (result < 0) {
gabomdq@6806
   816
                break;
gabomdq@6806
   817
            }
gabomdq@6806
   818
gabomdq@6806
   819
            bytesRemaining -= result;
gabomdq@6806
   820
            bytesRead += result;
gabomdq@6806
   821
            ctx->hidden.androidio.position += result;
icculus@5582
   822
        }
ewing@7501
   823
        LocalReferenceHolder_Cleanup(&refs);                    
gabomdq@6806
   824
        return bytesRead / size;
slouken@7191
   825
    }
icculus@5582
   826
}
icculus@5582
   827
ewing@7501
   828
size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   829
        size_t size, size_t num)
icculus@5582
   830
{
icculus@5582
   831
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   832
    return 0;
icculus@5582
   833
}
icculus@5582
   834
ewing@7501
   835
static int Internal_Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   836
{
ewing@7501
   837
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
ewing@7501
   838
icculus@5582
   839
    int result = 0;
gabomdq@6354
   840
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   841
ewing@7501
   842
    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
ewing@7501
   843
        LocalReferenceHolder_Cleanup(&refs);
icculus@7037
   844
        return SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   845
    }
slouken@6284
   846
icculus@5582
   847
    if (ctx) {
icculus@5582
   848
        if (release) {
ewing@7501
   849
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   850
        }
icculus@5582
   851
gabomdq@6806
   852
        if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   853
            jobject inputStream = (jobject)ctx->hidden.androidio.assetFileDescriptorRef;
ewing@7501
   854
            jmethodID mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
gabomdq@6806
   855
                    "close", "()V");
ewing@7501
   856
            (*mEnv)->CallVoidMethod(mEnv, inputStream, mid);
ewing@7501
   857
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.assetFileDescriptorRef);
ewing@7501
   858
            if (Android_JNI_ExceptionOccurred(false)) {
gabomdq@6806
   859
                result = -1;
gabomdq@6806
   860
            }
gabomdq@6806
   861
        }
gabomdq@6806
   862
        else {
gabomdq@6806
   863
            jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   864
gabomdq@6806
   865
            // inputStream.close();
ewing@7501
   866
            jmethodID mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
gabomdq@6806
   867
                    "close", "()V");
ewing@7501
   868
            (*mEnv)->CallVoidMethod(mEnv, inputStream, mid);
ewing@7501
   869
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.inputStreamRef);
ewing@7501
   870
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.readableByteChannelRef);
ewing@7501
   871
            if (Android_JNI_ExceptionOccurred(false)) {
gabomdq@6806
   872
                result = -1;
gabomdq@6806
   873
            }
icculus@5582
   874
        }
icculus@5582
   875
icculus@5582
   876
        if (release) {
icculus@5582
   877
            SDL_FreeRW(ctx);
icculus@5582
   878
        }
icculus@5582
   879
    }
icculus@5582
   880
ewing@7501
   881
    LocalReferenceHolder_Cleanup(&refs);
icculus@5582
   882
    return result;
icculus@5582
   883
}
icculus@5582
   884
icculus@5582
   885
ewing@7501
   886
Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   887
{
slouken@6642
   888
    return ctx->hidden.androidio.size;
slouken@6642
   889
}
slouken@6642
   890
ewing@7501
   891
Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   892
{
gabomdq@6806
   893
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
   894
        switch (whence) {
gabomdq@6806
   895
            case RW_SEEK_SET:
gabomdq@6806
   896
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   897
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   898
                break;
gabomdq@6806
   899
            case RW_SEEK_CUR:
gabomdq@6806
   900
                offset += ctx->hidden.androidio.position;
gabomdq@6806
   901
                if (ctx->hidden.androidio.size != -1 /*UNKNOWN_LENGTH*/ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
   902
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
   903
                break;
gabomdq@6806
   904
            case RW_SEEK_END:
gabomdq@6806
   905
                offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset;
gabomdq@6806
   906
                break;
gabomdq@6806
   907
            default:
icculus@7037
   908
                return SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   909
        }
gabomdq@6806
   910
        whence = SEEK_SET;
icculus@5582
   911
gabomdq@6806
   912
        off_t ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET);
gabomdq@6806
   913
        if (ret == -1) return -1;
gabomdq@6806
   914
        ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset;
gabomdq@6806
   915
    } else {
gabomdq@6806
   916
        Sint64 newPosition;
gabomdq@6806
   917
gabomdq@6806
   918
        switch (whence) {
gabomdq@6806
   919
            case RW_SEEK_SET:
gabomdq@6806
   920
                newPosition = offset;
gabomdq@6806
   921
                break;
gabomdq@6806
   922
            case RW_SEEK_CUR:
gabomdq@6806
   923
                newPosition = ctx->hidden.androidio.position + offset;
gabomdq@6806
   924
                break;
gabomdq@6806
   925
            case RW_SEEK_END:
gabomdq@6806
   926
                newPosition = ctx->hidden.androidio.size + offset;
gabomdq@6806
   927
                break;
gabomdq@6806
   928
            default:
icculus@7037
   929
                return SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
   930
        }
gabomdq@6806
   931
gabomdq@6806
   932
        /* Validate the new position */
gabomdq@6806
   933
        if (newPosition < 0) {
icculus@7037
   934
            return SDL_Error(SDL_EFSEEK);
gabomdq@6806
   935
        }
gabomdq@6806
   936
        if (newPosition > ctx->hidden.androidio.size) {
gabomdq@6806
   937
            newPosition = ctx->hidden.androidio.size;
gabomdq@6806
   938
        }
slouken@6642
   939
gabomdq@6806
   940
        Sint64 movement = newPosition - ctx->hidden.androidio.position;
gabomdq@6806
   941
        if (movement > 0) {
gabomdq@6806
   942
            unsigned char buffer[4096];
icculus@5582
   943
gabomdq@6806
   944
            // The easy case where we're seeking forwards
gabomdq@6806
   945
            while (movement > 0) {
gabomdq@6806
   946
                Sint64 amount = sizeof (buffer);
gabomdq@6806
   947
                if (amount > movement) {
gabomdq@6806
   948
                    amount = movement;
gabomdq@6806
   949
                }
gabomdq@6806
   950
                size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
gabomdq@6806
   951
                if (result <= 0) {
gabomdq@6806
   952
                    // Failed to read/skip the required amount, so fail
gabomdq@6806
   953
                    return -1;
gabomdq@6806
   954
                }
tim@5993
   955
gabomdq@6806
   956
                movement -= result;
icculus@5582
   957
            }
tim@5993
   958
gabomdq@6806
   959
        } else if (movement < 0) {
gabomdq@6806
   960
            // We can't seek backwards so we have to reopen the file and seek
gabomdq@6806
   961
            // forwards which obviously isn't very efficient
ewing@7501
   962
            Internal_Android_JNI_FileClose(ctx, false);
ewing@7501
   963
            Internal_Android_JNI_FileOpen(ctx);
gabomdq@6806
   964
            Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   965
        }
icculus@5582
   966
    }
icculus@5582
   967
icculus@5582
   968
    return ctx->hidden.androidio.position;
slouken@7191
   969
icculus@5582
   970
}
icculus@5582
   971
ewing@7501
   972
int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   973
{
ewing@7501
   974
    return Internal_Android_JNI_FileClose(ctx, true);
icculus@5582
   975
}
icculus@5582
   976
slouken@6464
   977
// returns a new global reference which needs to be released later
slouken@6464
   978
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   979
{
ewing@7501
   980
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6464
   981
    JNIEnv* env = Android_JNI_GetEnv();
ewing@7501
   982
    jobject retval = NULL;
ewing@7501
   983
ewing@7501
   984
    if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
   985
        LocalReferenceHolder_Cleanup(&refs);
slouken@6464
   986
        return NULL;
slouken@6464
   987
    }
slouken@6464
   988
ewing@7501
   989
    jstring service = (*env)->NewStringUTF(env, name);
slouken@6464
   990
slouken@6464
   991
    jmethodID mid;
slouken@6464
   992
ewing@7501
   993
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
ewing@7501
   994
    jobject context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6464
   995
ewing@7501
   996
    mid = (*env)->GetMethodID(env, mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
ewing@7501
   997
    jobject manager = (*env)->CallObjectMethod(env, context, mid, service);
slouken@6464
   998
ewing@7501
   999
    (*env)->DeleteLocalRef(env, service);
slouken@6464
  1000
ewing@7501
  1001
    retval = manager ? (*env)->NewGlobalRef(env, manager) : NULL;
ewing@7501
  1002
    LocalReferenceHolder_Cleanup(&refs);
ewing@7501
  1003
    return retval;
slouken@6464
  1004
}
slouken@6464
  1005
slouken@6464
  1006
#define SETUP_CLIPBOARD(error) \
ewing@7501
  1007
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__); \
slouken@6464
  1008
    JNIEnv* env = Android_JNI_GetEnv(); \
ewing@7501
  1009
    if (!LocalReferenceHolder_Init(&refs, env)) { \
ewing@7501
  1010
        LocalReferenceHolder_Cleanup(&refs); \
slouken@6464
  1011
        return error; \
slouken@6464
  1012
    } \
slouken@6464
  1013
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
  1014
    if (!clipboard) { \
ewing@7501
  1015
        LocalReferenceHolder_Cleanup(&refs); \
slouken@6464
  1016
        return error; \
slouken@6464
  1017
    }
slouken@6464
  1018
ewing@7501
  1019
#define CLEANUP_CLIPBOARD() \
ewing@7501
  1020
    LocalReferenceHolder_Cleanup(&refs);
ewing@7501
  1021
ewing@7501
  1022
int Android_JNI_SetClipboardText(const char* text)
slouken@6464
  1023
{
slouken@6464
  1024
    SETUP_CLIPBOARD(-1)
slouken@6464
  1025
ewing@7501
  1026
    jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "setText", "(Ljava/lang/CharSequence;)V");
ewing@7501
  1027
    jstring string = (*env)->NewStringUTF(env, text);
ewing@7501
  1028
    (*env)->CallVoidMethod(env, clipboard, mid, string);
ewing@7501
  1029
    (*env)->DeleteGlobalRef(env, clipboard);
ewing@7501
  1030
    (*env)->DeleteLocalRef(env, string);
ewing@7501
  1031
ewing@7501
  1032
    CLEANUP_CLIPBOARD();
ewing@7501
  1033
slouken@6464
  1034
    return 0;
slouken@6464
  1035
}
slouken@6464
  1036
ewing@7501
  1037
char* Android_JNI_GetClipboardText()
slouken@6464
  1038
{
slouken@6464
  1039
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
  1040
ewing@7501
  1041
    jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "getText", "()Ljava/lang/CharSequence;");
ewing@7501
  1042
    jobject sequence = (*env)->CallObjectMethod(env, clipboard, mid);
ewing@7501
  1043
    (*env)->DeleteGlobalRef(env, clipboard);
slouken@6464
  1044
    if (sequence) {
ewing@7501
  1045
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, sequence), "toString", "()Ljava/lang/String;");
ewing@7501
  1046
        jstring string = (jstring)((*env)->CallObjectMethod(env, sequence, mid));
ewing@7501
  1047
        const char* utf = (*env)->GetStringUTFChars(env, string, 0);
slouken@6464
  1048
        if (utf) {
slouken@6464
  1049
            char* text = SDL_strdup(utf);
ewing@7501
  1050
            (*env)->ReleaseStringUTFChars(env, string, utf);
ewing@7501
  1051
ewing@7501
  1052
            CLEANUP_CLIPBOARD();
ewing@7501
  1053
slouken@6464
  1054
            return text;
slouken@6464
  1055
        }
slouken@6464
  1056
    }
ewing@7501
  1057
ewing@7501
  1058
    CLEANUP_CLIPBOARD();    
ewing@7501
  1059
slouken@6464
  1060
    return SDL_strdup("");
slouken@6464
  1061
}
slouken@6464
  1062
ewing@7501
  1063
SDL_bool Android_JNI_HasClipboardText()
slouken@6464
  1064
{
slouken@6464
  1065
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
  1066
ewing@7501
  1067
    jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "hasText", "()Z");
ewing@7501
  1068
    jboolean has = (*env)->CallBooleanMethod(env, clipboard, mid);
ewing@7501
  1069
    (*env)->DeleteGlobalRef(env, clipboard);
ewing@7501
  1070
ewing@7501
  1071
    CLEANUP_CLIPBOARD();
ewing@7501
  1072
    
slouken@6464
  1073
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
  1074
}
slouken@6464
  1075
slouken@6464
  1076
slouken@6448
  1077
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
  1078
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
  1079
// returns the value in seconds and percent or -1 if not available
ewing@7501
  1080
int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
  1081
{
ewing@7501
  1082
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6448
  1083
    JNIEnv* env = Android_JNI_GetEnv();
ewing@7501
  1084
    if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1085
        LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1086
        return -1;
slouken@6448
  1087
    }
slouken@6448
  1088
slouken@6448
  1089
    jmethodID mid;
slouken@6448
  1090
ewing@7501
  1091
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
ewing@7501
  1092
    jobject context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6448
  1093
ewing@7501
  1094
    jstring action = (*env)->NewStringUTF(env, "android.intent.action.BATTERY_CHANGED");
slouken@6448
  1095
ewing@7501
  1096
    jclass cls = (*env)->FindClass(env, "android/content/IntentFilter");
slouken@6448
  1097
ewing@7501
  1098
    mid = (*env)->GetMethodID(env, cls, "<init>", "(Ljava/lang/String;)V");
ewing@7501
  1099
    jobject filter = (*env)->NewObject(env, cls, mid, action);
slouken@6448
  1100
ewing@7501
  1101
    (*env)->DeleteLocalRef(env, action);
slouken@6448
  1102
ewing@7501
  1103
    mid = (*env)->GetMethodID(env, mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
ewing@7501
  1104
    jobject intent = (*env)->CallObjectMethod(env, context, mid, NULL, filter);
slouken@6448
  1105
ewing@7501
  1106
    (*env)->DeleteLocalRef(env, filter);
slouken@6448
  1107
ewing@7501
  1108
    cls = (*env)->GetObjectClass(env, intent);
slouken@6448
  1109
slouken@6448
  1110
    jstring iname;
ewing@7501
  1111
    jmethodID imid = (*env)->GetMethodID(env, cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
  1112
slouken@6448
  1113
#define GET_INT_EXTRA(var, key) \
ewing@7501
  1114
    iname = (*env)->NewStringUTF(env, key); \
ewing@7501
  1115
    int var = (*env)->CallIntMethod(env, intent, imid, iname, -1); \
ewing@7501
  1116
    (*env)->DeleteLocalRef(env, iname);
slouken@6448
  1117
slouken@6448
  1118
    jstring bname;
ewing@7501
  1119
    jmethodID bmid = (*env)->GetMethodID(env, cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
  1120
slouken@6448
  1121
#define GET_BOOL_EXTRA(var, key) \
ewing@7501
  1122
    bname = (*env)->NewStringUTF(env, key); \
ewing@7501
  1123
    int var = (*env)->CallBooleanMethod(env, intent, bmid, bname, JNI_FALSE); \
ewing@7501
  1124
    (*env)->DeleteLocalRef(env, bname);
slouken@6448
  1125
slouken@6448
  1126
    if (plugged) {
slouken@6448
  1127
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
  1128
        if (plug == -1) {
ewing@7501
  1129
            LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1130
            return -1;
slouken@6448
  1131
        }
slouken@6448
  1132
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
  1133
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
  1134
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
  1135
    }
slouken@6448
  1136
slouken@6448
  1137
    if (charged) {
slouken@6448
  1138
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
  1139
        if (status == -1) {
ewing@7501
  1140
            LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1141
            return -1;
slouken@6448
  1142
        }
slouken@6448
  1143
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
  1144
        *charged = (status == 5) ? 1 : 0;
slouken@6448
  1145
    }
slouken@6448
  1146
slouken@6448
  1147
    if (battery) {
slouken@6448
  1148
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
  1149
        *battery = present ? 1 : 0;
slouken@6448
  1150
    }
slouken@6448
  1151
slouken@6448
  1152
    if (seconds) {
slouken@6448
  1153
        *seconds = -1; // not possible
slouken@6448
  1154
    }
slouken@6448
  1155
slouken@6448
  1156
    if (percent) {
slouken@6448
  1157
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
  1158
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
  1159
        if ((level == -1) || (scale == -1)) {
ewing@7501
  1160
            LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1161
            return -1;
slouken@6448
  1162
        }
slouken@6448
  1163
        *percent = level * 100 / scale;
slouken@6448
  1164
    }
slouken@6448
  1165
ewing@7501
  1166
    (*env)->DeleteLocalRef(env, intent);
slouken@6448
  1167
ewing@7501
  1168
    LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1169
    return 0;
slouken@6448
  1170
}
slouken@6448
  1171
slouken@6392
  1172
// sends message to be handled on the UI event dispatch thread
ewing@7501
  1173
int Android_JNI_SendMessage(int command, int param)
slouken@6392
  1174
{
slouken@6392
  1175
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
  1176
    if (!env) {
slouken@6392
  1177
        return -1;
slouken@6392
  1178
    }
ewing@7501
  1179
    jmethodID mid = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
slouken@6392
  1180
    if (!mid) {
slouken@6392
  1181
        return -1;
slouken@6392
  1182
    }
ewing@7501
  1183
    jboolean success = (*env)->CallStaticBooleanMethod(env, mActivityClass, mid, command, param);
philipp@7149
  1184
    return success ? 0 : -1;
slouken@6392
  1185
}
slouken@6392
  1186
ewing@7501
  1187
void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
  1188
{
slouken@6555
  1189
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
  1190
    if (!env) {
slouken@6654
  1191
        return;
slouken@6555
  1192
    }
slouken@6555
  1193
ewing@7501
  1194
    jmethodID mid = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIII)Z");
slouken@6555
  1195
    if (!mid) {
slouken@6654
  1196
        return;
slouken@6555
  1197
    }
ewing@7501
  1198
    (*env)->CallStaticBooleanMethod(env, mActivityClass, mid,
slouken@6555
  1199
                               inputRect->x,
slouken@6555
  1200
                               inputRect->y,
slouken@6555
  1201
                               inputRect->w,
slouken@6555
  1202
                               inputRect->h );
slouken@6555
  1203
}
slouken@6555
  1204
ewing@7501
  1205
void Android_JNI_HideTextInput()
slouken@6555
  1206
{
slouken@6654
  1207
    // has to match Activity constant
slouken@6654
  1208
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
  1209
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
  1210
}
slouken@6555
  1211
slouken@6630
  1212
//////////////////////////////////////////////////////////////////////////////
slouken@6630
  1213
//
slouken@6630
  1214
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
  1215
//
slouken@6630
  1216
ewing@7501
  1217
void *SDL_AndroidGetJNIEnv()
slouken@6630
  1218
{
slouken@6630
  1219
    return Android_JNI_GetEnv();
slouken@6630
  1220
}
slouken@6630
  1221
gabomdq@7095
  1222
gabomdq@7083
  1223
ewing@7501
  1224
void *SDL_AndroidGetActivity()
slouken@6630
  1225
{
gabomdq@7095
  1226
    /* See SDL_system.h for caveats on using this function. */
slouken@7191
  1227
slouken@6630
  1228
    jmethodID mid;
slouken@6630
  1229
slouken@6630
  1230
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@7083
  1231
    if (!env) {
slouken@6630
  1232
        return NULL;
slouken@6630
  1233
    }
slouken@6630
  1234
slouken@6630
  1235
    // return SDLActivity.getContext();
ewing@7501
  1236
    mid = (*env)->GetStaticMethodID(env, mActivityClass,
slouken@6630
  1237
            "getContext","()Landroid/content/Context;");
ewing@7501
  1238
    return (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6630
  1239
}
slouken@6630
  1240
ewing@7501
  1241
const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1242
{
slouken@6630
  1243
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1244
slouken@6630
  1245
    if (!s_AndroidInternalFilesPath) {
ewing@7501
  1246
        struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6630
  1247
        jmethodID mid;
slouken@6630
  1248
        jobject context;
slouken@6630
  1249
        jobject fileObject;
slouken@6630
  1250
        jstring pathString;
slouken@6630
  1251
        const char *path;
slouken@6630
  1252
slouken@6630
  1253
        JNIEnv *env = Android_JNI_GetEnv();
ewing@7501
  1254
        if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1255
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1256
            return NULL;
slouken@6630
  1257
        }
slouken@6630
  1258
slouken@6630
  1259
        // context = SDLActivity.getContext();
ewing@7501
  1260
        mid = (*env)->GetStaticMethodID(env, mActivityClass,
slouken@6630
  1261
                "getContext","()Landroid/content/Context;");
ewing@7501
  1262
        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6630
  1263
slouken@6630
  1264
        // fileObj = context.getFilesDir();
ewing@7501
  1265
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
slouken@6630
  1266
                "getFilesDir", "()Ljava/io/File;");
ewing@7501
  1267
        fileObject = (*env)->CallObjectMethod(env, context, mid);
slouken@6630
  1268
        if (!fileObject) {
slouken@6630
  1269
            SDL_SetError("Couldn't get internal directory");
ewing@7501
  1270
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1271
            return NULL;
slouken@6630
  1272
        }
slouken@6630
  1273
slouken@6630
  1274
        // path = fileObject.getAbsolutePath();
ewing@7501
  1275
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
slouken@6630
  1276
                "getAbsolutePath", "()Ljava/lang/String;");
ewing@7501
  1277
        pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
slouken@6630
  1278
ewing@7501
  1279
        path = (*env)->GetStringUTFChars(env, pathString, NULL);
slouken@6630
  1280
        s_AndroidInternalFilesPath = SDL_strdup(path);
ewing@7501
  1281
        (*env)->ReleaseStringUTFChars(env, pathString, path);
ewing@7501
  1282
ewing@7501
  1283
        LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1284
    }
slouken@6630
  1285
    return s_AndroidInternalFilesPath;
slouken@6630
  1286
}
slouken@6630
  1287
ewing@7501
  1288
int SDL_AndroidGetExternalStorageState()
slouken@6630
  1289
{
ewing@7501
  1290
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6630
  1291
    jmethodID mid;
slouken@6630
  1292
    jclass cls;
slouken@6630
  1293
    jstring stateString;
slouken@6630
  1294
    const char *state;
slouken@6630
  1295
    int stateFlags;
slouken@6630
  1296
slouken@6630
  1297
    JNIEnv *env = Android_JNI_GetEnv();
ewing@7501
  1298
    if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1299
        LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1300
        return 0;
slouken@6630
  1301
    }
slouken@6630
  1302
ewing@7501
  1303
    cls = (*env)->FindClass(env, "android/os/Environment");
ewing@7501
  1304
    mid = (*env)->GetStaticMethodID(env, cls,
slouken@6630
  1305
            "getExternalStorageState", "()Ljava/lang/String;");
ewing@7501
  1306
    stateString = (jstring)(*env)->CallStaticObjectMethod(env, cls, mid);
slouken@6630
  1307
ewing@7501
  1308
    state = (*env)->GetStringUTFChars(env, stateString, NULL);
slouken@6630
  1309
slouken@6630
  1310
    // Print an info message so people debugging know the storage state
slouken@6630
  1311
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1312
slouken@6630
  1313
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1314
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1315
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1316
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1317
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1318
    } else {
slouken@6630
  1319
        stateFlags = 0;
slouken@6630
  1320
    }
ewing@7501
  1321
    (*env)->ReleaseStringUTFChars(env, stateString, state);
slouken@6630
  1322
ewing@7501
  1323
    LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1324
    return stateFlags;
slouken@6630
  1325
}
slouken@6630
  1326
ewing@7501
  1327
const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1328
{
slouken@6630
  1329
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1330
slouken@6630
  1331
    if (!s_AndroidExternalFilesPath) {
ewing@7501
  1332
        struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6630
  1333
        jmethodID mid;
slouken@6630
  1334
        jobject context;
slouken@6630
  1335
        jobject fileObject;
slouken@6630
  1336
        jstring pathString;
slouken@6630
  1337
        const char *path;
slouken@6630
  1338
slouken@6630
  1339
        JNIEnv *env = Android_JNI_GetEnv();
ewing@7501
  1340
        if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1341
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1342
            return NULL;
slouken@6630
  1343
        }
slouken@6630
  1344
slouken@6630
  1345
        // context = SDLActivity.getContext();
ewing@7501
  1346
        mid = (*env)->GetStaticMethodID(env, mActivityClass,
slouken@6630
  1347
                "getContext","()Landroid/content/Context;");
ewing@7501
  1348
        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6630
  1349
slouken@6630
  1350
        // fileObj = context.getExternalFilesDir();
ewing@7501
  1351
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
slouken@6630
  1352
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
ewing@7501
  1353
        fileObject = (*env)->CallObjectMethod(env, context, mid, NULL);
slouken@6630
  1354
        if (!fileObject) {
slouken@6630
  1355
            SDL_SetError("Couldn't get external directory");
ewing@7501
  1356
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1357
            return NULL;
slouken@6630
  1358
        }
slouken@6630
  1359
slouken@6630
  1360
        // path = fileObject.getAbsolutePath();
ewing@7501
  1361
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
slouken@6630
  1362
                "getAbsolutePath", "()Ljava/lang/String;");
ewing@7501
  1363
        pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
slouken@6630
  1364
ewing@7501
  1365
        path = (*env)->GetStringUTFChars(env, pathString, NULL);
slouken@6630
  1366
        s_AndroidExternalFilesPath = SDL_strdup(path);
ewing@7501
  1367
        (*env)->ReleaseStringUTFChars(env, pathString, path);
ewing@7501
  1368
ewing@7501
  1369
        LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1370
    }
slouken@6630
  1371
    return s_AndroidExternalFilesPath;
slouken@6630
  1372
}
slouken@6630
  1373
slouken@6044
  1374
#endif /* __ANDROID__ */
slouken@6044
  1375
slouken@4981
  1376
/* vi: set ts=4 sw=4 expandtab: */