src/core/android/SDL_android.c
author Gabriel Jacobo <gabomdq@gmail.com>
Fri, 02 Aug 2013 12:38:39 -0300
changeset 7564 d2bc997ef5d6
parent 7552 463f78515a07
child 7567 52da75545aaa
permissions -rw-r--r--
Temporary fix for bug #1639 SDL does not message back closing of screen keyboard

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