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