src/core/android/SDL_android.c
author Gabriel Jacobo <gabomdq@gmail.com>
Wed, 31 Jul 2013 10:04:59 -0300
changeset 7552 463f78515a07
parent 7516 4a98853e8e4c
child 7564 d2bc997ef5d6
permissions -rw-r--r--
Fix for bug 2001, verify that the AudioTrack is properly initialized

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