src/core/android/SDL_android.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 12 Aug 2017 08:15:09 -0700
changeset 11238 c728c661cec7
parent 11066 f39b145db3eb
child 11239 856e5e3c1e86
permissions -rw-r--r--
Fixed bug 3191 - haptic system on android?

Patch provided by jintiao and Milan Nikolic, thanks!
slouken@4964
     1
/*
slouken@5535
     2
  Simple DirectMedia Layer
slouken@10737
     3
  Copyright (C) 1997-2017 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
*/
icculus@8093
    21
#include "../../SDL_internal.h"
slouken@5222
    22
#include "SDL_stdinc.h"
slouken@6284
    23
#include "SDL_assert.h"
slouken@8961
    24
#include "SDL_hints.h"
slouken@6650
    25
#include "SDL_log.h"
slouken@4964
    26
slouken@6044
    27
#ifdef __ANDROID__
slouken@6044
    28
slouken@6630
    29
#include "SDL_system.h"
slouken@4989
    30
#include "SDL_android.h"
slouken@6792
    31
#include <EGL/egl.h>
slouken@4989
    32
slouken@5092
    33
#include "../../events/SDL_events_c.h"
slouken@5092
    34
#include "../../video/android/SDL_androidkeyboard.h"
joseba@9438
    35
#include "../../video/android/SDL_androidmouse.h"
slouken@5092
    36
#include "../../video/android/SDL_androidtouch.h"
slouken@5092
    37
#include "../../video/android/SDL_androidvideo.h"
gabomdq@7659
    38
#include "../../video/android/SDL_androidwindow.h"
gabomdq@8057
    39
#include "../../joystick/android/SDL_sysjoystick_c.h"
slouken@11238
    40
#include "../../haptic/android/SDL_syshaptic_c.h"
slouken@4995
    41
icculus@5996
    42
#include <android/log.h>
gabomdq@6354
    43
#include <pthread.h>
gabomdq@6806
    44
#include <sys/types.h>
gabomdq@6806
    45
#include <unistd.h>
slouken@10672
    46
/* #define LOG_TAG "SDL_android" */
gabomdq@7678
    47
/* #define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__) */
gabomdq@7678
    48
/* #define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__) */
philipp@9271
    49
#define LOGI(...) do {} while (0)
philipp@9271
    50
#define LOGE(...) do {} while (0)
icculus@5996
    51
slouken@10672
    52
slouken@10672
    53
#define SDL_JAVA_PREFIX                                 org_libsdl_app
slouken@10672
    54
#define CONCAT1(prefix, class, function)                CONCAT2(prefix, class, function)
slouken@10672
    55
#define CONCAT2(prefix, class, function)                Java_ ## prefix ## _ ## class ## _ ## function
slouken@10672
    56
#define SDL_JAVA_INTERFACE(function)                    CONCAT1(SDL_JAVA_PREFIX, SDLActivity, function)
slouken@10672
    57
#define SDL_JAVA_INTERFACE_INPUT_CONNECTION(function)   CONCAT1(SDL_JAVA_PREFIX, SDLInputConnection, function)
slouken@10672
    58
slouken@10672
    59
slouken@10672
    60
/* Java class SDLActivity */
slouken@10672
    61
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
slouken@10672
    62
        JNIEnv* env, jclass jcls,
slouken@10672
    63
        jstring filename);
slouken@10672
    64
slouken@10672
    65
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
slouken@10672
    66
        JNIEnv* env, jclass jcls,
slouken@10672
    67
        jint width, jint height, jint format, jfloat rate);
slouken@10672
    68
slouken@10672
    69
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadDown)(
slouken@10672
    70
        JNIEnv* env, jclass jcls,
slouken@10672
    71
        jint device_id, jint keycode);
slouken@10672
    72
slouken@10672
    73
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadUp)(
slouken@10672
    74
        JNIEnv* env, jclass jcls,
slouken@10672
    75
        jint device_id, jint keycode);
slouken@10672
    76
slouken@10672
    77
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeJoy)(
slouken@10672
    78
        JNIEnv* env, jclass jcls,
slouken@10672
    79
        jint device_id, jint axis, jfloat value);
slouken@10672
    80
slouken@10672
    81
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeHat)(
slouken@10672
    82
        JNIEnv* env, jclass jcls,
slouken@10672
    83
        jint device_id, jint hat_id, jint x, jint y);
slouken@10672
    84
slouken@10672
    85
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeAddJoystick)(
slouken@10672
    86
        JNIEnv* env, jclass jcls,
slouken@10672
    87
        jint device_id, jstring device_name, jint is_accelerometer, 
slouken@10672
    88
        jint nbuttons, jint naxes, jint nhats, jint nballs);
slouken@10672
    89
slouken@10672
    90
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeRemoveJoystick)(
slouken@10672
    91
        JNIEnv* env, jclass jcls,
slouken@10672
    92
        jint device_id);
slouken@10672
    93
slouken@10672
    94
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(
slouken@10672
    95
        JNIEnv* env, jclass jcls);
slouken@10672
    96
slouken@10672
    97
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(
slouken@10672
    98
        JNIEnv* env, jclass jcls);
slouken@10672
    99
slouken@10672
   100
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
slouken@10672
   101
        JNIEnv* env, jclass jcls,
slouken@10672
   102
        jint keycode);
slouken@10672
   103
slouken@10672
   104
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
slouken@10672
   105
        JNIEnv* env, jclass jcls,
slouken@10672
   106
        jint keycode);
slouken@10672
   107
slouken@10672
   108
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
slouken@10672
   109
        JNIEnv* env, jclass jcls);
slouken@10672
   110
slouken@10672
   111
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
slouken@10672
   112
        JNIEnv* env, jclass jcls,
slouken@10672
   113
        jint touch_device_id_in, jint pointer_finger_id_in,
slouken@10672
   114
        jint action, jfloat x, jfloat y, jfloat p);
slouken@10672
   115
slouken@10672
   116
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
slouken@10672
   117
        JNIEnv* env, jclass jcls,
slouken@10672
   118
        jint button, jint action, jfloat x, jfloat y);
slouken@10672
   119
slouken@10672
   120
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
slouken@10672
   121
        JNIEnv* env, jclass jcls,
slouken@10672
   122
        jfloat x, jfloat y, jfloat z);
slouken@10672
   123
slouken@10672
   124
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
slouken@10672
   125
        JNIEnv* env, jclass cls);
slouken@10672
   126
slouken@10672
   127
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
slouken@10672
   128
        JNIEnv* env, jclass cls);
slouken@10672
   129
slouken@10672
   130
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
slouken@10672
   131
        JNIEnv* env, jclass cls);
slouken@10672
   132
slouken@10672
   133
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
slouken@10672
   134
        JNIEnv* env, jclass cls);
slouken@10672
   135
slouken@10672
   136
JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
slouken@10672
   137
        JNIEnv* env, jclass cls,
slouken@10672
   138
        jstring name);
slouken@10672
   139
slouken@10672
   140
/* Java class SDLInputConnection */
slouken@10672
   141
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
slouken@10672
   142
        JNIEnv* env, jclass cls,
slouken@10672
   143
        jstring text, jint newCursorPosition);
slouken@10672
   144
slouken@10672
   145
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeSetComposingText)(
slouken@10672
   146
        JNIEnv* env, jclass cls,
slouken@10672
   147
        jstring text, jint newCursorPosition);
slouken@10672
   148
slouken@10672
   149
slouken@6650
   150
/* Uncomment this to log messages entering and exiting methods in this file */
gabomdq@7678
   151
/* #define DEBUG_JNI */
icculus@5996
   152
philipp@7246
   153
static void Android_JNI_ThreadDestroyed(void*);
slouken@4980
   154
slouken@4964
   155
/*******************************************************************************
slouken@4964
   156
 This file links the Java side of Android with libsdl
slouken@4964
   157
*******************************************************************************/
slouken@4964
   158
#include <jni.h>
slouken@4964
   159
slouken@4964
   160
slouken@4964
   161
/*******************************************************************************
slouken@4964
   162
                               Globals
slouken@4964
   163
*******************************************************************************/
gabomdq@6354
   164
static pthread_key_t mThreadKey;
icculus@5996
   165
static JavaVM* mJavaVM;
slouken@4964
   166
gabomdq@7663
   167
/* Main activity */
slouken@4998
   168
static jclass mActivityClass;
slouken@4964
   169
gabomdq@7663
   170
/* method signatures */
gabomdq@7659
   171
static jmethodID midGetNativeSurface;
icculus@10280
   172
static jmethodID midAudioOpen;
slouken@4995
   173
static jmethodID midAudioWriteShortBuffer;
slouken@4995
   174
static jmethodID midAudioWriteByteBuffer;
icculus@10280
   175
static jmethodID midAudioClose;
icculus@10280
   176
static jmethodID midCaptureOpen;
icculus@10280
   177
static jmethodID midCaptureReadShortBuffer;
icculus@10280
   178
static jmethodID midCaptureReadByteBuffer;
icculus@10280
   179
static jmethodID midCaptureClose;
gabomdq@8057
   180
static jmethodID midPollInputDevices;
slouken@11238
   181
static jmethodID midPollHapticDevices;
slouken@11238
   182
static jmethodID midHapticRun;
slouken@4964
   183
gabomdq@7663
   184
/* Accelerometer data storage */
slouken@5000
   185
static float fLastAccelerometer[3];
philipp@9271
   186
static SDL_bool bHasNewData;
slouken@4964
   187
slouken@4964
   188
/*******************************************************************************
slouken@4964
   189
                 Functions called by JNI
slouken@4964
   190
*******************************************************************************/
slouken@4964
   191
gabomdq@7663
   192
/* Library init */
dimitris@8760
   193
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
slouken@4964
   194
{
icculus@5996
   195
    JNIEnv *env;
icculus@5996
   196
    mJavaVM = vm;
icculus@5996
   197
    LOGI("JNI_OnLoad called");
ewing@7501
   198
    if ((*mJavaVM)->GetEnv(mJavaVM, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
icculus@5996
   199
        LOGE("Failed to get the environment using GetEnv()");
icculus@5996
   200
        return -1;
icculus@5996
   201
    }
gabomdq@6354
   202
    /*
gabomdq@6354
   203
     * Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
gabomdq@6354
   204
     * Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
gabomdq@6354
   205
     */
slouken@8055
   206
    if (pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed) != 0) {
gabomdq@6354
   207
        __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing pthread key");
gabomdq@6354
   208
    }
slouken@8055
   209
    Android_JNI_SetupThread();
icculus@5996
   210
slouken@4964
   211
    return JNI_VERSION_1_4;
slouken@4964
   212
}
slouken@4964
   213
gabomdq@7663
   214
/* Called before SDL_main() to initialize JNI bindings */
dimitris@8760
   215
JNIEXPORT void JNICALL SDL_Android_Init(JNIEnv* mEnv, jclass cls)
slouken@4964
   216
{
slouken@4964
   217
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
slouken@4964
   218
gabomdq@6354
   219
    Android_JNI_SetupThread();
gabomdq@6354
   220
ewing@7501
   221
    mActivityClass = (jclass)((*mEnv)->NewGlobalRef(mEnv, cls));
slouken@4998
   222
gabomdq@7659
   223
    midGetNativeSurface = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
gabomdq@7659
   224
                                "getNativeSurface","()Landroid/view/Surface;");
icculus@10280
   225
    midAudioOpen = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@10280
   226
                                "audioOpen", "(IZZI)I");
ewing@7501
   227
    midAudioWriteShortBuffer = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
slouken@4998
   228
                                "audioWriteShortBuffer", "([S)V");
ewing@7501
   229
    midAudioWriteByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
slouken@4998
   230
                                "audioWriteByteBuffer", "([B)V");
icculus@10280
   231
    midAudioClose = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@10280
   232
                                "audioClose", "()V");
icculus@10280
   233
    midCaptureOpen = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@10280
   234
                                "captureOpen", "(IZZI)I");
icculus@10280
   235
    midCaptureReadShortBuffer = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@10280
   236
                                "captureReadShortBuffer", "([SZ)I");
icculus@10280
   237
    midCaptureReadByteBuffer = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@10280
   238
                                "captureReadByteBuffer", "([BZ)I");
icculus@10280
   239
    midCaptureClose = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@10280
   240
                                "captureClose", "()V");
gabomdq@8057
   241
    midPollInputDevices = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
gabomdq@8057
   242
                                "pollInputDevices", "()V");
slouken@11238
   243
    midPollHapticDevices = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
slouken@11238
   244
                                "pollHapticDevices", "()V");
slouken@11238
   245
    midHapticRun = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
slouken@11238
   246
                                "hapticRun", "(II)V");
slouken@4964
   247
philipp@9271
   248
    bHasNewData = SDL_FALSE;
slouken@6212
   249
icculus@10280
   250
    if (!midGetNativeSurface ||
philipp@10296
   251
       !midAudioOpen || !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioClose ||
icculus@10280
   252
       !midCaptureOpen || !midCaptureReadShortBuffer || !midCaptureReadByteBuffer || !midCaptureClose ||
slouken@11238
   253
       !midPollInputDevices || !midPollHapticDevices || !midHapticRun) {
slouken@4996
   254
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
slouken@4964
   255
    }
icculus@5996
   256
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
slouken@4964
   257
}
slouken@4964
   258
icculus@9640
   259
/* Drop file */
slouken@10672
   260
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeDropFile)(
icculus@9640
   261
                                    JNIEnv* env, jclass jcls,
icculus@9640
   262
                                    jstring filename)
icculus@9640
   263
{
icculus@9640
   264
    const char *path = (*env)->GetStringUTFChars(env, filename, NULL);
icculus@10032
   265
    SDL_SendDropFile(NULL, path);
icculus@9640
   266
    (*env)->ReleaseStringUTFChars(env, filename, path);
icculus@10032
   267
    SDL_SendDropComplete(NULL);
icculus@9640
   268
}
icculus@9640
   269
gabomdq@7663
   270
/* Resize */
slouken@10672
   271
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeResize)(
slouken@4998
   272
                                    JNIEnv* env, jclass jcls,
philipp@9314
   273
                                    jint width, jint height, jint format, jfloat rate)
slouken@4995
   274
{
philipp@9314
   275
    Android_SetScreenResolution(width, height, format, rate);
slouken@4995
   276
}
slouken@4995
   277
philipp@8776
   278
/* Paddown */
slouken@10672
   279
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadDown)(
gabomdq@7907
   280
                                    JNIEnv* env, jclass jcls,
gabomdq@8057
   281
                                    jint device_id, jint keycode)
gabomdq@7907
   282
{
gabomdq@8057
   283
    return Android_OnPadDown(device_id, keycode);
gabomdq@7907
   284
}
gabomdq@7907
   285
philipp@8776
   286
/* Padup */
slouken@10672
   287
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(onNativePadUp)(
slouken@10672
   288
                                    JNIEnv* env, jclass jcls,
slouken@10672
   289
                                    jint device_id, jint keycode)
gabomdq@7907
   290
{
gabomdq@8057
   291
    return Android_OnPadUp(device_id, keycode);
gabomdq@7907
   292
}
gabomdq@7907
   293
philipp@7926
   294
/* Joy */
slouken@10672
   295
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeJoy)(
gabomdq@7907
   296
                                    JNIEnv* env, jclass jcls,
gabomdq@8057
   297
                                    jint device_id, jint axis, jfloat value)
gabomdq@7907
   298
{
gabomdq@8057
   299
    Android_OnJoy(device_id, axis, value);
gabomdq@8057
   300
}
gabomdq@8057
   301
dbrady@8140
   302
/* POV Hat */
slouken@10672
   303
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeHat)(
dbrady@8140
   304
                                    JNIEnv* env, jclass jcls,
dbrady@8140
   305
                                    jint device_id, jint hat_id, jint x, jint y)
dbrady@8140
   306
{
dbrady@8140
   307
    Android_OnHat(device_id, hat_id, x, y);
dbrady@8140
   308
}
dbrady@8140
   309
gabomdq@8057
   310
slouken@10672
   311
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeAddJoystick)(
slouken@10672
   312
                                    JNIEnv* env, jclass jcls,
slouken@10672
   313
                                    jint device_id, jstring device_name, jint is_accelerometer, 
slouken@10672
   314
                                    jint nbuttons, jint naxes, jint nhats, jint nballs)
gabomdq@8057
   315
{
gabomdq@8057
   316
    int retval;
gabomdq@8057
   317
    const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
gabomdq@8057
   318
gabomdq@8057
   319
    retval = Android_AddJoystick(device_id, name, (SDL_bool) is_accelerometer, nbuttons, naxes, nhats, nballs);
gabomdq@8057
   320
gabomdq@8057
   321
    (*env)->ReleaseStringUTFChars(env, device_name, name);
gabomdq@8057
   322
    
gabomdq@8057
   323
    return retval;
gabomdq@8057
   324
}
gabomdq@8057
   325
slouken@10672
   326
JNIEXPORT jint JNICALL SDL_JAVA_INTERFACE(nativeRemoveJoystick)(
slouken@10672
   327
                                    JNIEnv* env, jclass jcls,
slouken@10672
   328
                                    jint device_id)
gabomdq@8057
   329
{
gabomdq@8057
   330
    return Android_RemoveJoystick(device_id);
gabomdq@7907
   331
}
gabomdq@7907
   332
slouken@11238
   333
JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_nativeAddHaptic(
slouken@11238
   334
    JNIEnv* env, jclass jcls, jint device_id, jstring device_name)
slouken@11238
   335
{
slouken@11238
   336
    int retval;
slouken@11238
   337
    const char *name = (*env)->GetStringUTFChars(env, device_name, NULL);
slouken@11238
   338
slouken@11238
   339
    retval = Android_AddHaptic(device_id, name);
slouken@11238
   340
slouken@11238
   341
    (*env)->ReleaseStringUTFChars(env, device_name, name);
slouken@11238
   342
slouken@11238
   343
    return retval;
slouken@11238
   344
}
slouken@11238
   345
slouken@11238
   346
JNIEXPORT jint JNICALL Java_org_libsdl_app_SDLActivity_nativeRemoveHaptic(
slouken@11238
   347
    JNIEnv* env, jclass jcls, jint device_id)
slouken@11238
   348
{
slouken@11238
   349
    return Android_RemoveHaptic(device_id);
slouken@11238
   350
}
slouken@11238
   351
gabomdq@7659
   352
gabomdq@7663
   353
/* Surface Created */
slouken@10672
   354
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceChanged)(JNIEnv* env, jclass jcls)
gabomdq@7659
   355
{
gabomdq@7659
   356
    SDL_WindowData *data;
gabomdq@7659
   357
    SDL_VideoDevice *_this;
gabomdq@7659
   358
gabomdq@7659
   359
    if (Android_Window == NULL || Android_Window->driverdata == NULL ) {
gabomdq@7659
   360
        return;
gabomdq@7659
   361
    }
gabomdq@7659
   362
    
gabomdq@7659
   363
    _this =  SDL_GetVideoDevice();
gabomdq@7659
   364
    data =  (SDL_WindowData *) Android_Window->driverdata;
gabomdq@7659
   365
    
gabomdq@7659
   366
    /* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
gabomdq@7659
   367
    if (data->egl_surface == EGL_NO_SURFACE) {
gabomdq@7659
   368
        if(data->native_window) {
gabomdq@7659
   369
            ANativeWindow_release(data->native_window);
gabomdq@7659
   370
        }
gabomdq@7659
   371
        data->native_window = Android_JNI_GetNativeWindow();
gabomdq@7659
   372
        data->egl_surface = SDL_EGL_CreateSurface(_this, (NativeWindowType) data->native_window);
gabomdq@7659
   373
    }
gabomdq@7659
   374
    
gabomdq@7659
   375
    /* GL Context handling is done in the event loop because this function is run from the Java thread */
gabomdq@7659
   376
    
gabomdq@7659
   377
}
gabomdq@7659
   378
gabomdq@7663
   379
/* Surface Destroyed */
slouken@10672
   380
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeSurfaceDestroyed)(JNIEnv* env, jclass jcls)
gabomdq@7659
   381
{
gabomdq@7659
   382
    /* We have to clear the current context and destroy the egl surface here
gabomdq@7659
   383
     * Otherwise there's BAD_NATIVE_WINDOW errors coming from eglCreateWindowSurface on resume
gabomdq@7659
   384
     * Ref: http://stackoverflow.com/questions/8762589/eglcreatewindowsurface-on-ics-and-switching-from-2d-to-3d
gabomdq@7659
   385
     */
gabomdq@7659
   386
    SDL_WindowData *data;
gabomdq@7659
   387
    SDL_VideoDevice *_this;
gabomdq@7659
   388
    
gabomdq@7659
   389
    if (Android_Window == NULL || Android_Window->driverdata == NULL ) {
gabomdq@7659
   390
        return;
gabomdq@7659
   391
    }
gabomdq@7659
   392
    
gabomdq@7659
   393
    _this =  SDL_GetVideoDevice();
gabomdq@7659
   394
    data = (SDL_WindowData *) Android_Window->driverdata;
gabomdq@7659
   395
    
gabomdq@7659
   396
    if (data->egl_surface != EGL_NO_SURFACE) {
gabomdq@7659
   397
        SDL_EGL_MakeCurrent(_this, NULL, NULL);
gabomdq@7659
   398
        SDL_EGL_DestroySurface(_this, data->egl_surface);
gabomdq@7659
   399
        data->egl_surface = EGL_NO_SURFACE;
gabomdq@7659
   400
    }
gabomdq@7659
   401
    
gabomdq@7659
   402
    /* GL Context handling is done in the event loop because this function is run from the Java thread */
gabomdq@7659
   403
gabomdq@7659
   404
}
gabomdq@7659
   405
gabomdq@7663
   406
/* Keydown */
slouken@10672
   407
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyDown)(
slouken@10672
   408
                                    JNIEnv* env, jclass jcls,
slouken@10672
   409
                                    jint keycode)
slouken@4964
   410
{
slouken@4980
   411
    Android_OnKeyDown(keycode);
slouken@4964
   412
}
slouken@4964
   413
gabomdq@7663
   414
/* Keyup */
slouken@10672
   415
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyUp)(
slouken@10672
   416
                                    JNIEnv* env, jclass jcls,
slouken@10672
   417
                                    jint keycode)
slouken@4964
   418
{
slouken@4980
   419
    Android_OnKeyUp(keycode);
slouken@4964
   420
}
slouken@4964
   421
gabomdq@7663
   422
/* Keyboard Focus Lost */
slouken@10672
   423
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeKeyboardFocusLost)(
gabomdq@7564
   424
                                    JNIEnv* env, jclass jcls)
gabomdq@7564
   425
{
gabomdq@7564
   426
    /* Calling SDL_StopTextInput will take care of hiding the keyboard and cleaning up the DummyText widget */
gabomdq@7564
   427
    SDL_StopTextInput();
gabomdq@7564
   428
}
gabomdq@7564
   429
gabomdq@7564
   430
gabomdq@7663
   431
/* Touch */
slouken@10672
   432
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeTouch)(
slouken@4998
   433
                                    JNIEnv* env, jclass jcls,
icculus@5982
   434
                                    jint touch_device_id_in, jint pointer_finger_id_in,
slouken@4995
   435
                                    jint action, jfloat x, jfloat y, jfloat p)
slouken@4964
   436
{
icculus@5982
   437
    Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p);
slouken@4964
   438
}
slouken@4964
   439
joseba@9438
   440
/* Mouse */
slouken@10672
   441
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeMouse)(
joseba@9438
   442
                                    JNIEnv* env, jclass jcls,
joseba@9438
   443
                                    jint button, jint action, jfloat x, jfloat y)
joseba@9438
   444
{
joseba@9438
   445
    Android_OnMouse(button, action, x, y);
joseba@9438
   446
}
joseba@9438
   447
gabomdq@7663
   448
/* Accelerometer */
slouken@10672
   449
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(onNativeAccel)(
slouken@4998
   450
                                    JNIEnv* env, jclass jcls,
slouken@4995
   451
                                    jfloat x, jfloat y, jfloat z)
slouken@4964
   452
{
slouken@4964
   453
    fLastAccelerometer[0] = x;
slouken@4964
   454
    fLastAccelerometer[1] = y;
slouken@6212
   455
    fLastAccelerometer[2] = z;
philipp@9271
   456
    bHasNewData = SDL_TRUE;
slouken@4964
   457
}
slouken@4964
   458
gabomdq@7663
   459
/* Low memory */
slouken@10672
   460
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeLowMemory)(
slouken@7190
   461
                                    JNIEnv* env, jclass cls)
slouken@7191
   462
{
slouken@7190
   463
    SDL_SendAppEvent(SDL_APP_LOWMEMORY);
slouken@7190
   464
}
slouken@7190
   465
gabomdq@7663
   466
/* Quit */
slouken@10672
   467
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeQuit)(
slouken@4998
   468
                                    JNIEnv* env, jclass cls)
slouken@7191
   469
{
gabomdq@7910
   470
    /* Discard previous events. The user should have handled state storage
gabomdq@7910
   471
     * in SDL_APP_WILLENTERBACKGROUND. After nativeQuit() is called, no
gabomdq@7910
   472
     * events other than SDL_QUIT and SDL_APP_TERMINATING should fire */
gabomdq@7910
   473
    SDL_FlushEvents(SDL_FIRSTEVENT, SDL_LASTEVENT);
gabomdq@7663
   474
    /* Inject a SDL_QUIT event */
slouken@4995
   475
    SDL_SendQuit();
slouken@7190
   476
    SDL_SendAppEvent(SDL_APP_TERMINATING);
gabomdq@7910
   477
    /* Resume the event loop so that the app can catch SDL_QUIT which
gabomdq@7910
   478
     * should now be the top event in the event queue. */
gabomdq@7910
   479
    if (!SDL_SemValue(Android_ResumeSem)) SDL_SemPost(Android_ResumeSem);
slouken@4995
   480
}
slouken@4995
   481
gabomdq@7663
   482
/* Pause */
slouken@10672
   483
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativePause)(
slouken@6186
   484
                                    JNIEnv* env, jclass cls)
slouken@6186
   485
{
gabomdq@8039
   486
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativePause()");
slouken@6186
   487
    if (Android_Window) {
slouken@6186
   488
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
slouken@6191
   489
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
gabomdq@8039
   490
        SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
gabomdq@8039
   491
        SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
gabomdq@8039
   492
    
gabomdq@8039
   493
        /* *After* sending the relevant events, signal the pause semaphore 
gabomdq@8039
   494
         * so the event loop knows to pause and (optionally) block itself */
gabomdq@8039
   495
        if (!SDL_SemValue(Android_PauseSem)) SDL_SemPost(Android_PauseSem);
slouken@6186
   496
    }
slouken@6186
   497
}
slouken@6186
   498
gabomdq@7663
   499
/* Resume */
slouken@10672
   500
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE(nativeResume)(
slouken@6186
   501
                                    JNIEnv* env, jclass cls)
slouken@6186
   502
{
slouken@7190
   503
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "nativeResume()");
slouken@7190
   504
slouken@6186
   505
    if (Android_Window) {
gabomdq@8047
   506
        SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
gabomdq@8047
   507
        SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
gabomdq@8047
   508
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
gabomdq@8047
   509
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0);
gabomdq@6330
   510
        /* Signal the resume semaphore so the event loop knows to resume and restore the GL Context
gabomdq@6330
   511
         * We can't restore the GL Context here because it needs to be done on the SDL main thread
gabomdq@6330
   512
         * and this function will be called from the Java thread instead.
gabomdq@6330
   513
         */
gabomdq@6330
   514
        if (!SDL_SemValue(Android_ResumeSem)) SDL_SemPost(Android_ResumeSem);
slouken@6186
   515
    }
slouken@6186
   516
}
slouken@6186
   517
slouken@10672
   518
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeCommitText)(
slouken@6555
   519
                                    JNIEnv* env, jclass cls,
slouken@6555
   520
                                    jstring text, jint newCursorPosition)
slouken@6555
   521
{
ewing@7501
   522
    const char *utftext = (*env)->GetStringUTFChars(env, text, NULL);
slouken@6555
   523
slouken@6555
   524
    SDL_SendKeyboardText(utftext);
slouken@6555
   525
ewing@7501
   526
    (*env)->ReleaseStringUTFChars(env, text, utftext);
slouken@6555
   527
}
slouken@6555
   528
slouken@10672
   529
JNIEXPORT void JNICALL SDL_JAVA_INTERFACE_INPUT_CONNECTION(nativeSetComposingText)(
slouken@6555
   530
                                    JNIEnv* env, jclass cls,
slouken@6555
   531
                                    jstring text, jint newCursorPosition)
slouken@6555
   532
{
ewing@7501
   533
    const char *utftext = (*env)->GetStringUTFChars(env, text, NULL);
slouken@6555
   534
slouken@6555
   535
    SDL_SendEditingText(utftext, 0, 0);
slouken@6555
   536
ewing@7501
   537
    (*env)->ReleaseStringUTFChars(env, text, utftext);
slouken@6555
   538
}
slouken@6555
   539
slouken@10672
   540
JNIEXPORT jstring JNICALL SDL_JAVA_INTERFACE(nativeGetHint)(
slouken@10672
   541
                                    JNIEnv* env, jclass cls,
slouken@10672
   542
                                    jstring name)
slouken@10672
   543
{
alexey@8896
   544
    const char *utfname = (*env)->GetStringUTFChars(env, name, NULL);
alexey@8896
   545
    const char *hint = SDL_GetHint(utfname);
slouken@6555
   546
alexey@8896
   547
    jstring result = (*env)->NewStringUTF(env, hint);
alexey@8896
   548
    (*env)->ReleaseStringUTFChars(env, name, utfname);
alexey@8896
   549
alexey@8896
   550
    return result;
alexey@8896
   551
}
slouken@6555
   552
slouken@4964
   553
/*******************************************************************************
slouken@4964
   554
             Functions called by SDL into Java
slouken@4964
   555
*******************************************************************************/
slouken@6284
   556
ewing@7501
   557
static int s_active = 0;
ewing@7501
   558
struct LocalReferenceHolder
slouken@6284
   559
{
slouken@6284
   560
    JNIEnv *m_env;
slouken@6650
   561
    const char *m_func;
slouken@6284
   562
};
slouken@6284
   563
ewing@7501
   564
static struct LocalReferenceHolder LocalReferenceHolder_Setup(const char *func)
ewing@7501
   565
{
ewing@7501
   566
    struct LocalReferenceHolder refholder;
ewing@7501
   567
    refholder.m_env = NULL;
ewing@7501
   568
    refholder.m_func = func;
ewing@7501
   569
#ifdef DEBUG_JNI
ewing@7501
   570
    SDL_Log("Entering function %s", func);
ewing@7501
   571
#endif
ewing@7501
   572
    return refholder;
ewing@7501
   573
}
ewing@7501
   574
ewing@7501
   575
static SDL_bool LocalReferenceHolder_Init(struct LocalReferenceHolder *refholder, JNIEnv *env)
ewing@7501
   576
{
ewing@7501
   577
    const int capacity = 16;
ewing@7501
   578
    if ((*env)->PushLocalFrame(env, capacity) < 0) {
ewing@7501
   579
        SDL_SetError("Failed to allocate enough JVM local references");
philipp@7516
   580
        return SDL_FALSE;
ewing@7501
   581
    }
ewing@7501
   582
    ++s_active;
ewing@7501
   583
    refholder->m_env = env;
ewing@7501
   584
    return SDL_TRUE;
ewing@7501
   585
}
ewing@7501
   586
ewing@7501
   587
static void LocalReferenceHolder_Cleanup(struct LocalReferenceHolder *refholder)
ewing@7501
   588
{
ewing@7501
   589
#ifdef DEBUG_JNI
ewing@7501
   590
    SDL_Log("Leaving function %s", refholder->m_func);
ewing@7501
   591
#endif
ewing@7501
   592
    if (refholder->m_env) {
ewing@7501
   593
        JNIEnv* env = refholder->m_env;
ewing@7501
   594
        (*env)->PopLocalFrame(env, NULL);
ewing@7501
   595
        --s_active;
ewing@7501
   596
    }
ewing@7501
   597
}
ewing@7501
   598
philipp@9594
   599
static SDL_bool LocalReferenceHolder_IsActive(void)
ewing@7501
   600
{
gabomdq@9173
   601
    return s_active > 0;
gabomdq@9173
   602
}
gabomdq@9173
   603
gabomdq@7659
   604
ANativeWindow* Android_JNI_GetNativeWindow(void)
slouken@4964
   605
{
gabomdq@7659
   606
    ANativeWindow* anw;
gabomdq@7659
   607
    jobject s;
slouken@6792
   608
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6792
   609
gabomdq@7659
   610
    s = (*env)->CallStaticObjectMethod(env, mActivityClass, midGetNativeSurface);
gabomdq@7659
   611
    anw = ANativeWindow_fromSurface(env, s);
gabomdq@7659
   612
    (*env)->DeleteLocalRef(env, s);
gabomdq@7659
   613
  
gabomdq@7659
   614
    return anw;
gabomdq@7567
   615
}
gabomdq@7567
   616
ewing@7501
   617
void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   618
{
slouken@4998
   619
    jmethodID mid;
gabomdq@6354
   620
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   621
    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,"setActivityTitle","(Ljava/lang/String;)Z");
slouken@4998
   622
    if (mid) {
ewing@7501
   623
        jstring jtitle = (jstring)((*mEnv)->NewStringUTF(mEnv, title));
ewing@7501
   624
        (*mEnv)->CallStaticBooleanMethod(mEnv, mActivityClass, mid, jtitle);
ewing@7501
   625
        (*mEnv)->DeleteLocalRef(mEnv, jtitle);
slouken@4998
   626
    }
slouken@4964
   627
}
slouken@4964
   628
ewing@7501
   629
SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   630
{
slouken@5000
   631
    int i;
slouken@6212
   632
    SDL_bool retval = SDL_FALSE;
slouken@6212
   633
slouken@6212
   634
    if (bHasNewData) {
slouken@6212
   635
        for (i = 0; i < 3; ++i) {
slouken@6212
   636
            values[i] = fLastAccelerometer[i];
slouken@6212
   637
        }
philipp@9271
   638
        bHasNewData = SDL_FALSE;
slouken@6212
   639
        retval = SDL_TRUE;
slouken@5000
   640
    }
slouken@6212
   641
slouken@6212
   642
    return retval;
slouken@5000
   643
}
slouken@5000
   644
slouken@8055
   645
static void Android_JNI_ThreadDestroyed(void* value)
slouken@8055
   646
{
gabomdq@6354
   647
    /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
gabomdq@6354
   648
    JNIEnv *env = (JNIEnv*) value;
gabomdq@6354
   649
    if (env != NULL) {
ewing@7501
   650
        (*mJavaVM)->DetachCurrentThread(mJavaVM);
gabomdq@6354
   651
        pthread_setspecific(mThreadKey, NULL);
gabomdq@6354
   652
    }
gabomdq@6354
   653
}
gabomdq@6354
   654
slouken@8055
   655
JNIEnv* Android_JNI_GetEnv(void)
slouken@8055
   656
{
gabomdq@6354
   657
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   658
     * All threads are Linux threads, scheduled by the kernel.
gabomdq@6354
   659
     * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
gabomdq@6354
   660
     * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
gabomdq@6354
   661
     * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
gabomdq@6354
   662
     * and cannot make JNI calls.
gabomdq@6354
   663
     * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
gabomdq@6354
   664
     * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
gabomdq@6354
   665
     * is a no-op.
gabomdq@6354
   666
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   667
     */
gabomdq@6354
   668
gabomdq@6354
   669
    JNIEnv *env;
ewing@7501
   670
    int status = (*mJavaVM)->AttachCurrentThread(mJavaVM, &env, NULL);
gabomdq@6354
   671
    if(status < 0) {
gabomdq@6354
   672
        LOGE("failed to attach current thread");
gabomdq@6354
   673
        return 0;
gabomdq@6354
   674
    }
gabomdq@6354
   675
gabomdq@6354
   676
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   677
     * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
gabomdq@6354
   678
     * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
gabomdq@6354
   679
     * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
gabomdq@6354
   680
     * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
gabomdq@6354
   681
     * Note: The destructor is not called unless the stored value is != NULL
gabomdq@6354
   682
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   683
     *       (except for some lost CPU cycles)
gabomdq@6354
   684
     */
gabomdq@6354
   685
    pthread_setspecific(mThreadKey, (void*) env);
slouken@8055
   686
slouken@8055
   687
    return env;
slouken@8055
   688
}
slouken@8055
   689
slouken@8055
   690
int Android_JNI_SetupThread(void)
slouken@8055
   691
{
slouken@8055
   692
    Android_JNI_GetEnv();
gabomdq@6354
   693
    return 1;
gabomdq@6354
   694
}
gabomdq@6354
   695
philipp@11061
   696
jclass Android_JNI_GetActivityClass(void)
philipp@11061
   697
{
philipp@11061
   698
    return mActivityClass;
philipp@11061
   699
}
philipp@11061
   700
gabomdq@7663
   701
/*
gabomdq@7663
   702
 * Audio support
gabomdq@7663
   703
 */
slouken@4996
   704
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   705
static jobject audioBuffer = NULL;
slouken@4996
   706
static void* audioBufferPinned = NULL;
icculus@10280
   707
static jboolean captureBuffer16Bit = JNI_FALSE;
icculus@10280
   708
static jobject captureBuffer = NULL;
slouken@4995
   709
icculus@10280
   710
int Android_JNI_OpenAudioDevice(int iscapture, int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   711
{
philipp@9322
   712
    jboolean audioBufferStereo;
slouken@4996
   713
    int audioBufferFrames;
icculus@10280
   714
    jobject jbufobj = NULL;
ewing@10080
   715
    jboolean isCopy;
slouken@4964
   716
gabomdq@6354
   717
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   718
gabomdq@6354
   719
    if (!env) {
gabomdq@6354
   720
        LOGE("callback_handler: failed to attach current thread");
icculus@5996
   721
    }
gabomdq@6354
   722
    Android_JNI_SetupThread();
icculus@5996
   723
slouken@4996
   724
    audioBufferStereo = channelCount > 1;
slouken@4964
   725
icculus@10280
   726
    if (iscapture) {
icculus@10280
   727
        __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device for capture");
icculus@10280
   728
        captureBuffer16Bit = is16Bit;
icculus@10280
   729
        if ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureOpen, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames) != 0) {
icculus@10280
   730
            /* Error during audio initialization */
icculus@10280
   731
            __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: error on AudioRecord initialization!");
icculus@10280
   732
            return 0;
icculus@10280
   733
        }
icculus@10280
   734
    } else {
icculus@10280
   735
        __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device for output");
icculus@10280
   736
        audioBuffer16Bit = is16Bit;
icculus@10280
   737
        if ((*env)->CallStaticIntMethod(env, mActivityClass, midAudioOpen, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames) != 0) {
icculus@10280
   738
            /* Error during audio initialization */
icculus@10280
   739
            __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: error on AudioTrack initialization!");
icculus@10280
   740
            return 0;
icculus@10280
   741
        }
gabomdq@7552
   742
    }
gabomdq@6802
   743
gabomdq@6802
   744
    /* Allocating the audio buffer from the Java side and passing it as the return value for audioInit no longer works on
gabomdq@6802
   745
     * Android >= 4.2 due to a "stale global reference" error. So now we allocate this buffer directly from this side. */
slouken@7191
   746
gabomdq@6802
   747
    if (is16Bit) {
ewing@7501
   748
        jshortArray audioBufferLocal = (*env)->NewShortArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   749
        if (audioBufferLocal) {
icculus@10280
   750
            jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
ewing@7501
   751
            (*env)->DeleteLocalRef(env, audioBufferLocal);
gabomdq@6802
   752
        }
gabomdq@6802
   753
    }
gabomdq@6802
   754
    else {
ewing@7501
   755
        jbyteArray audioBufferLocal = (*env)->NewByteArray(env, desiredBufferFrames * (audioBufferStereo ? 2 : 1));
gabomdq@6802
   756
        if (audioBufferLocal) {
icculus@10280
   757
            jbufobj = (*env)->NewGlobalRef(env, audioBufferLocal);
ewing@7501
   758
            (*env)->DeleteLocalRef(env, audioBufferLocal);
gabomdq@6802
   759
        }
gabomdq@6802
   760
    }
slouken@4995
   761
icculus@10280
   762
    if (jbufobj == NULL) {
gabomdq@6802
   763
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: could not allocate an audio buffer!");
slouken@4996
   764
        return 0;
slouken@4996
   765
    }
slouken@4995
   766
icculus@10280
   767
    if (iscapture) {
icculus@10280
   768
        captureBuffer = jbufobj;
icculus@10280
   769
    } else {
icculus@10280
   770
        audioBuffer = jbufobj;
icculus@10280
   771
    }
icculus@10280
   772
ewing@10080
   773
    isCopy = JNI_FALSE;
icculus@10280
   774
icculus@10280
   775
    if (is16Bit) {
icculus@10280
   776
        if (!iscapture) {
icculus@10280
   777
            audioBufferPinned = (*env)->GetShortArrayElements(env, (jshortArray)audioBuffer, &isCopy);
icculus@10280
   778
        }
ewing@7501
   779
        audioBufferFrames = (*env)->GetArrayLength(env, (jshortArray)audioBuffer);
slouken@4996
   780
    } else {
icculus@10280
   781
        if (!iscapture) {
icculus@10280
   782
            audioBufferPinned = (*env)->GetByteArrayElements(env, (jbyteArray)audioBuffer, &isCopy);
icculus@10280
   783
        }
ewing@7501
   784
        audioBufferFrames = (*env)->GetArrayLength(env, (jbyteArray)audioBuffer);
slouken@4996
   785
    }
icculus@10280
   786
slouken@4996
   787
    if (audioBufferStereo) {
slouken@4996
   788
        audioBufferFrames /= 2;
slouken@4996
   789
    }
gabomdq@6864
   790
slouken@4996
   791
    return audioBufferFrames;
slouken@4995
   792
}
slouken@4995
   793
philipp@9594
   794
void * Android_JNI_GetAudioBuffer(void)
slouken@4995
   795
{
slouken@4996
   796
    return audioBufferPinned;
slouken@4995
   797
}
slouken@4995
   798
philipp@9594
   799
void Android_JNI_WriteAudioBuffer(void)
slouken@4995
   800
{
gabomdq@6354
   801
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   802
slouken@4996
   803
    if (audioBuffer16Bit) {
ewing@7501
   804
        (*mAudioEnv)->ReleaseShortArrayElements(mAudioEnv, (jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
ewing@7501
   805
        (*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   806
    } else {
ewing@7501
   807
        (*mAudioEnv)->ReleaseByteArrayElements(mAudioEnv, (jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
ewing@7501
   808
        (*mAudioEnv)->CallStaticVoidMethod(mAudioEnv, mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   809
    }
slouken@4995
   810
slouken@4996
   811
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   812
}
slouken@4995
   813
icculus@10280
   814
int Android_JNI_CaptureAudioBuffer(void *buffer, int buflen)
icculus@10280
   815
{
icculus@10280
   816
    JNIEnv *env = Android_JNI_GetEnv();
icculus@10280
   817
    jboolean isCopy = JNI_FALSE;
icculus@10280
   818
    jint br;
icculus@10280
   819
icculus@10280
   820
    if (captureBuffer16Bit) {
icculus@10280
   821
        SDL_assert((*env)->GetArrayLength(env, (jshortArray)captureBuffer) == (buflen / 2));
icculus@10280
   822
        br = (*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_TRUE);
icculus@10280
   823
        if (br > 0) {
icculus@10280
   824
            jshort *ptr = (*env)->GetShortArrayElements(env, (jshortArray)captureBuffer, &isCopy);
icculus@10280
   825
            br *= 2;
icculus@10280
   826
            SDL_memcpy(buffer, ptr, br);
icculus@10280
   827
            (*env)->ReleaseShortArrayElements(env, (jshortArray)captureBuffer, (jshort *)ptr, JNI_ABORT);
icculus@10280
   828
        }
icculus@10280
   829
    } else {
icculus@10280
   830
        SDL_assert((*env)->GetArrayLength(env, (jshortArray)captureBuffer) == buflen);
icculus@10280
   831
        br = (*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_TRUE);
icculus@10280
   832
        if (br > 0) {
icculus@10280
   833
            jbyte *ptr = (*env)->GetByteArrayElements(env, (jbyteArray)captureBuffer, &isCopy);
icculus@10280
   834
            SDL_memcpy(buffer, ptr, br);
icculus@10280
   835
            (*env)->ReleaseByteArrayElements(env, (jbyteArray)captureBuffer, (jbyte *)ptr, JNI_ABORT);
icculus@10280
   836
        }
icculus@10280
   837
    }
icculus@10280
   838
icculus@10280
   839
    return (int) br;
icculus@10280
   840
}
icculus@10280
   841
icculus@10280
   842
void Android_JNI_FlushCapturedAudio(void)
icculus@10280
   843
{
icculus@10280
   844
    JNIEnv *env = Android_JNI_GetEnv();
icculus@10280
   845
    #if 0  /* !!! FIXME: this needs API 23, or it'll do blocking reads and never end. */
icculus@10280
   846
    if (captureBuffer16Bit) {
icculus@10280
   847
        const jint len = (*env)->GetArrayLength(env, (jshortArray)captureBuffer);
icculus@10280
   848
        while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
icculus@10280
   849
    } else {
icculus@10280
   850
        const jint len = (*env)->GetArrayLength(env, (jbyteArray)captureBuffer);
icculus@10280
   851
        while ((*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE) == len) { /* spin */ }
icculus@10280
   852
    }
icculus@10280
   853
    #else
icculus@10280
   854
    if (captureBuffer16Bit) {
icculus@10280
   855
        (*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadShortBuffer, (jshortArray)captureBuffer, JNI_FALSE);
icculus@10280
   856
    } else {
icculus@10280
   857
        (*env)->CallStaticIntMethod(env, mActivityClass, midCaptureReadByteBuffer, (jbyteArray)captureBuffer, JNI_FALSE);
icculus@10280
   858
    }
icculus@10280
   859
    #endif
icculus@10280
   860
}
icculus@10280
   861
icculus@10280
   862
void Android_JNI_CloseAudioDevice(const int iscapture)
slouken@4995
   863
{
gabomdq@6354
   864
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   865
icculus@10280
   866
    if (iscapture) {
icculus@10280
   867
        (*env)->CallStaticVoidMethod(env, mActivityClass, midCaptureClose);
icculus@10280
   868
        if (captureBuffer) {
icculus@10280
   869
            (*env)->DeleteGlobalRef(env, captureBuffer);
icculus@10280
   870
            captureBuffer = NULL;
icculus@10280
   871
        }
icculus@10280
   872
    } else {
icculus@10280
   873
        (*env)->CallStaticVoidMethod(env, mActivityClass, midAudioClose);
icculus@10280
   874
        if (audioBuffer) {
icculus@10280
   875
            (*env)->DeleteGlobalRef(env, audioBuffer);
icculus@10280
   876
            audioBuffer = NULL;
icculus@10280
   877
            audioBufferPinned = NULL;
icculus@10280
   878
        }
slouken@4997
   879
    }
slouken@4964
   880
}
slouken@4981
   881
gabomdq@7663
   882
/* Test for an exception and call SDL_SetError with its detail if one occurs */
gabomdq@7663
   883
/* If the parameter silent is truthy then SDL_SetError() will not be called. */
philipp@9271
   884
static SDL_bool Android_JNI_ExceptionOccurred(SDL_bool silent)
tim@5650
   885
{
ewing@10080
   886
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@10080
   887
    jthrowable exception;
ewing@10080
   888
ewing@7501
   889
    SDL_assert(LocalReferenceHolder_IsActive());
slouken@6284
   890
ewing@10080
   891
    exception = (*mEnv)->ExceptionOccurred(mEnv);
tim@5650
   892
    if (exception != NULL) {
tim@5650
   893
        jmethodID mid;
tim@5650
   894
gabomdq@7663
   895
        /* Until this happens most JNI operations have undefined behaviour */
ewing@7501
   896
        (*mEnv)->ExceptionClear(mEnv);
tim@5650
   897
slouken@7045
   898
        if (!silent) {
ewing@7501
   899
            jclass exceptionClass = (*mEnv)->GetObjectClass(mEnv, exception);
ewing@7501
   900
            jclass classClass = (*mEnv)->FindClass(mEnv, "java/lang/Class");
ewing@10080
   901
            jstring exceptionName;
ewing@10080
   902
            const char* exceptionNameUTF8;
ewing@10080
   903
            jstring exceptionMessage;
tim@5650
   904
ewing@7501
   905
            mid = (*mEnv)->GetMethodID(mEnv, classClass, "getName", "()Ljava/lang/String;");
ewing@10080
   906
            exceptionName = (jstring)(*mEnv)->CallObjectMethod(mEnv, exceptionClass, mid);
ewing@10080
   907
            exceptionNameUTF8 = (*mEnv)->GetStringUTFChars(mEnv, exceptionName, 0);
tim@5650
   908
ewing@7501
   909
            mid = (*mEnv)->GetMethodID(mEnv, exceptionClass, "getMessage", "()Ljava/lang/String;");
ewing@10080
   910
            exceptionMessage = (jstring)(*mEnv)->CallObjectMethod(mEnv, exception, mid);
tim@5650
   911
slouken@7045
   912
            if (exceptionMessage != NULL) {
ewing@7501
   913
                const char* exceptionMessageUTF8 = (*mEnv)->GetStringUTFChars(mEnv, exceptionMessage, 0);
slouken@7045
   914
                SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
ewing@7501
   915
                (*mEnv)->ReleaseStringUTFChars(mEnv, exceptionMessage, exceptionMessageUTF8);
slouken@7045
   916
            } else {
slouken@7045
   917
                SDL_SetError("%s", exceptionNameUTF8);
slouken@7045
   918
            }
slouken@7045
   919
ewing@7501
   920
            (*mEnv)->ReleaseStringUTFChars(mEnv, exceptionName, exceptionNameUTF8);
tim@5650
   921
        }
tim@5650
   922
philipp@9271
   923
        return SDL_TRUE;
tim@5650
   924
    }
tim@5650
   925
philipp@9271
   926
    return SDL_FALSE;
tim@5650
   927
}
tim@5650
   928
ewing@7501
   929
static int Internal_Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   930
{
ewing@7501
   931
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
ewing@7501
   932
tim@5650
   933
    int result = 0;
tim@5650
   934
tim@5650
   935
    jmethodID mid;
tim@5650
   936
    jobject context;
tim@5650
   937
    jobject assetManager;
tim@5650
   938
    jobject inputStream;
tim@5650
   939
    jclass channels;
tim@5650
   940
    jobject readableByteChannel;
tim@5650
   941
    jstring fileNameJString;
gabomdq@6806
   942
    jobject fd;
gabomdq@6806
   943
    jclass fdCls;
gabomdq@6806
   944
    jfieldID descriptor;
tim@5650
   945
gabomdq@6354
   946
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
   947
    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
tim@5650
   948
        goto failure;
tim@5650
   949
    }
tim@5650
   950
gabomdq@6308
   951
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
gabomdq@6806
   952
    ctx->hidden.androidio.position = 0;
icculus@5582
   953
gabomdq@7663
   954
    /* context = SDLActivity.getContext(); */
ewing@7501
   955
    mid = (*mEnv)->GetStaticMethodID(mEnv, mActivityClass,
icculus@5582
   956
            "getContext","()Landroid/content/Context;");
ewing@7501
   957
    context = (*mEnv)->CallStaticObjectMethod(mEnv, mActivityClass, mid);
slouken@7191
   958
icculus@5582
   959
gabomdq@7663
   960
    /* assetManager = context.getAssets(); */
ewing@7501
   961
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, context),
tim@5650
   962
            "getAssets", "()Landroid/content/res/AssetManager;");
ewing@7501
   963
    assetManager = (*mEnv)->CallObjectMethod(mEnv, context, mid);
icculus@5582
   964
gabomdq@6806
   965
    /* First let's try opening the file to obtain an AssetFileDescriptor.
gabomdq@6806
   966
    * This method reads the files directly from the APKs using standard *nix calls
gabomdq@6806
   967
    */
ewing@7501
   968
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, assetManager), "openFd", "(Ljava/lang/String;)Landroid/content/res/AssetFileDescriptor;");
ewing@7501
   969
    inputStream = (*mEnv)->CallObjectMethod(mEnv, assetManager, mid, fileNameJString);
philipp@9271
   970
    if (Android_JNI_ExceptionOccurred(SDL_TRUE)) {
gabomdq@6806
   971
        goto fallback;
icculus@5582
   972
    }
icculus@5582
   973
ewing@7501
   974
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getStartOffset", "()J");
ewing@7501
   975
    ctx->hidden.androidio.offset = (*mEnv)->CallLongMethod(mEnv, inputStream, mid);
philipp@9271
   976
    if (Android_JNI_ExceptionOccurred(SDL_TRUE)) {
gabomdq@6806
   977
        goto fallback;
icculus@5582
   978
    }
icculus@5582
   979
ewing@7501
   980
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getDeclaredLength", "()J");
ewing@7501
   981
    ctx->hidden.androidio.size = (*mEnv)->CallLongMethod(mEnv, inputStream, mid);
philipp@9271
   982
    if (Android_JNI_ExceptionOccurred(SDL_TRUE)) {
gabomdq@6806
   983
        goto fallback;
icculus@5582
   984
    }
icculus@5582
   985
ewing@7501
   986
    mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream), "getFileDescriptor", "()Ljava/io/FileDescriptor;");
ewing@7501
   987
    fd = (*mEnv)->CallObjectMethod(mEnv, inputStream, mid);
ewing@7501
   988
    fdCls = (*mEnv)->GetObjectClass(mEnv, fd);
ewing@7501
   989
    descriptor = (*mEnv)->GetFieldID(mEnv, fdCls, "descriptor", "I");
ewing@7501
   990
    ctx->hidden.androidio.fd = (*mEnv)->GetIntField(mEnv, fd, descriptor);
ewing@7501
   991
    ctx->hidden.androidio.assetFileDescriptorRef = (*mEnv)->NewGlobalRef(mEnv, inputStream);
tim@5650
   992
gabomdq@7663
   993
    /* Seek to the correct offset in the file. */
gabomdq@6816
   994
    lseek(ctx->hidden.androidio.fd, (off_t)ctx->hidden.androidio.offset, SEEK_SET);
gabomdq@6816
   995
philipp@9271
   996
    if (0) {
gabomdq@6806
   997
fallback:
gabomdq@7663
   998
        /* Disabled log message because of spam on the Nexus 7 */
gabomdq@7678
   999
        /* __android_log_print(ANDROID_LOG_DEBUG, "SDL", "Falling back to legacy InputStream method for opening file"); */
slouken@7190
  1000
gabomdq@6806
  1001
        /* Try the old method using InputStream */
gabomdq@6806
  1002
        ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
  1003
gabomdq@7663
  1004
        /* inputStream = assetManager.open(<filename>); */
ewing@7501
  1005
        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, assetManager),
gabomdq@6806
  1006
                "open", "(Ljava/lang/String;I)Ljava/io/InputStream;");
gabomdq@7678
  1007
        inputStream = (*mEnv)->CallObjectMethod(mEnv, assetManager, mid, fileNameJString, 1 /* ACCESS_RANDOM */);
philipp@9271
  1008
        if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
philipp@9869
  1009
            /* Try fallback to APK expansion files */
alexey@8896
  1010
            mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, context),
philipp@9869
  1011
                "openAPKExpansionInputStream", "(Ljava/lang/String;)Ljava/io/InputStream;");
philipp@9873
  1012
            if (!mid) {
philipp@9873
  1013
                SDL_SetError("No openAPKExpansionInputStream() in Java class");
philipp@9873
  1014
                goto failure; /* Java class is missing the required method */
philipp@9873
  1015
            }
alexey@8896
  1016
            inputStream = (*mEnv)->CallObjectMethod(mEnv, context, mid, fileNameJString);
alexey@8896
  1017
philipp@9870
  1018
            /* Exception is checked first because it always needs to be cleared.
philipp@9870
  1019
             * If no exception occurred then the last SDL error message is kept.
philipp@9870
  1020
             */
philipp@9870
  1021
            if (Android_JNI_ExceptionOccurred(SDL_FALSE) || !inputStream) {
alexey@8896
  1022
                goto failure;
alexey@8896
  1023
            }
gabomdq@6806
  1024
        }
gabomdq@6806
  1025
ewing@7501
  1026
        ctx->hidden.androidio.inputStreamRef = (*mEnv)->NewGlobalRef(mEnv, inputStream);
gabomdq@6806
  1027
gabomdq@7663
  1028
        /* Despite all the visible documentation on [Asset]InputStream claiming
gabomdq@7663
  1029
         * that the .available() method is not guaranteed to return the entire file
gabomdq@7663
  1030
         * size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
gabomdq@7663
  1031
         * android/apis/content/ReadAsset.java imply that Android's
gabomdq@7663
  1032
         * AssetInputStream.available() /will/ always return the total file size
gabomdq@7663
  1033
        */
gabomdq@7663
  1034
        
gabomdq@7663
  1035
        /* size = inputStream.available(); */
ewing@7501
  1036
        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
gabomdq@6806
  1037
                "available", "()I");
ewing@7501
  1038
        ctx->hidden.androidio.size = (long)(*mEnv)->CallIntMethod(mEnv, inputStream, mid);
philipp@9271
  1039
        if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
gabomdq@6806
  1040
            goto failure;
gabomdq@6806
  1041
        }
gabomdq@6806
  1042
gabomdq@7663
  1043
        /* readableByteChannel = Channels.newChannel(inputStream); */
ewing@7501
  1044
        channels = (*mEnv)->FindClass(mEnv, "java/nio/channels/Channels");
ewing@7501
  1045
        mid = (*mEnv)->GetStaticMethodID(mEnv, channels,
gabomdq@6806
  1046
                "newChannel",
gabomdq@6806
  1047
                "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
ewing@7501
  1048
        readableByteChannel = (*mEnv)->CallStaticObjectMethod(
ewing@7501
  1049
                mEnv, channels, mid, inputStream);
philipp@9271
  1050
        if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
gabomdq@6806
  1051
            goto failure;
gabomdq@6806
  1052
        }
gabomdq@6806
  1053
gabomdq@6806
  1054
        ctx->hidden.androidio.readableByteChannelRef =
ewing@7501
  1055
            (*mEnv)->NewGlobalRef(mEnv, readableByteChannel);
gabomdq@6806
  1056
gabomdq@7663
  1057
        /* Store .read id for reading purposes */
ewing@7501
  1058
        mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, readableByteChannel),
gabomdq@6806
  1059
                "read", "(Ljava/nio/ByteBuffer;)I");
gabomdq@6806
  1060
        ctx->hidden.androidio.readMethod = mid;
gabomdq@6806
  1061
    }
icculus@5582
  1062
philipp@9271
  1063
    if (0) {
tim@5650
  1064
failure:
tim@5650
  1065
        result = -1;
tim@5650
  1066
ewing@7501
  1067
        (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
  1068
tim@5650
  1069
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
ewing@7501
  1070
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
  1071
        }
gabomdq@6308
  1072
gabomdq@6308
  1073
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
ewing@7501
  1074
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
  1075
        }
gabomdq@6308
  1076
gabomdq@6806
  1077
        if(ctx->hidden.androidio.assetFileDescriptorRef != NULL) {
ewing@7501
  1078
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.assetFileDescriptorRef);
gabomdq@6806
  1079
        }
gabomdq@6806
  1080
tim@5650
  1081
    }
ewing@7501
  1082
    
ewing@7501
  1083
    LocalReferenceHolder_Cleanup(&refs);
tim@5650
  1084
    return result;
icculus@5582
  1085
}
icculus@5582
  1086
ewing@7501
  1087
int Android_JNI_FileOpen(SDL_RWops* ctx,
ewing@7501
  1088
        const char* fileName, const char* mode)
icculus@5582
  1089
{
ewing@7501
  1090
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
gabomdq@6354
  1091
    JNIEnv *mEnv = Android_JNI_GetEnv();
ewing@7501
  1092
    int retval;
ewing@10080
  1093
    jstring fileNameJString;
slouken@6284
  1094
ewing@7501
  1095
    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
ewing@7501
  1096
        LocalReferenceHolder_Cleanup(&refs);        
slouken@6284
  1097
        return -1;
slouken@6284
  1098
    }
slouken@6284
  1099
icculus@5582
  1100
    if (!ctx) {
ewing@7501
  1101
        LocalReferenceHolder_Cleanup(&refs);
icculus@5582
  1102
        return -1;
icculus@5582
  1103
    }
icculus@5582
  1104
ewing@10080
  1105
    fileNameJString = (*mEnv)->NewStringUTF(mEnv, fileName);
ewing@7501
  1106
    ctx->hidden.androidio.fileNameRef = (*mEnv)->NewGlobalRef(mEnv, fileNameJString);
tim@5650
  1107
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
  1108
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
  1109
    ctx->hidden.androidio.readMethod = NULL;
gabomdq@6806
  1110
    ctx->hidden.androidio.assetFileDescriptorRef = NULL;
icculus@5582
  1111
ewing@7501
  1112
    retval = Internal_Android_JNI_FileOpen(ctx);
ewing@7501
  1113
    LocalReferenceHolder_Cleanup(&refs);
ewing@7501
  1114
    return retval;
icculus@5582
  1115
}
icculus@5582
  1116
ewing@7501
  1117
size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
  1118
        size_t size, size_t maxnum)
icculus@5582
  1119
{
ewing@7501
  1120
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
icculus@5582
  1121
gabomdq@6806
  1122
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
  1123
        size_t bytesMax = size * maxnum;
ewing@10080
  1124
        size_t result;
gabomdq@7678
  1125
        if (ctx->hidden.androidio.size != -1 /* UNKNOWN_LENGTH */ && ctx->hidden.androidio.position + bytesMax > ctx->hidden.androidio.size) {
gabomdq@6806
  1126
            bytesMax = ctx->hidden.androidio.size - ctx->hidden.androidio.position;
gabomdq@6806
  1127
        }
ewing@10080
  1128
        result = read(ctx->hidden.androidio.fd, buffer, bytesMax );
gabomdq@6806
  1129
        if (result > 0) {
gabomdq@6806
  1130
            ctx->hidden.androidio.position += result;
ewing@7501
  1131
            LocalReferenceHolder_Cleanup(&refs);
gabomdq@6806
  1132
            return result / size;
gabomdq@6806
  1133
        }
ewing@7501
  1134
        LocalReferenceHolder_Cleanup(&refs);
gabomdq@6806
  1135
        return 0;
gabomdq@6806
  1136
    } else {
gabomdq@6806
  1137
        jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6806
  1138
        jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
gabomdq@6806
  1139
        int bytesRead = 0;
ewing@10080
  1140
        JNIEnv *mEnv;
ewing@10080
  1141
        jobject readableByteChannel;
ewing@10080
  1142
        jmethodID readMethod;
ewing@10080
  1143
        jobject byteBuffer;
gabomdq@6377
  1144
gabomdq@6806
  1145
        /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6806
  1146
        if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
slouken@6284
  1147
ewing@10080
  1148
        mEnv = Android_JNI_GetEnv();
ewing@7501
  1149
        if (!LocalReferenceHolder_Init(&refs, mEnv)) {
ewing@7501
  1150
            LocalReferenceHolder_Cleanup(&refs);            
philipp@7368
  1151
            return 0;
icculus@5582
  1152
        }
icculus@5582
  1153
ewing@10080
  1154
        readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
ewing@10080
  1155
        readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
ewing@10080
  1156
        byteBuffer = (*mEnv)->NewDirectByteBuffer(mEnv, buffer, bytesRemaining);
gabomdq@6806
  1157
gabomdq@6806
  1158
        while (bytesRemaining > 0) {
gabomdq@7663
  1159
            /* result = readableByteChannel.read(...); */
ewing@7501
  1160
            int result = (*mEnv)->CallIntMethod(mEnv, readableByteChannel, readMethod, byteBuffer);
gabomdq@6806
  1161
philipp@9271
  1162
            if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
ewing@7501
  1163
                LocalReferenceHolder_Cleanup(&refs);            
gabomdq@6806
  1164
                return 0;
gabomdq@6806
  1165
            }
gabomdq@6806
  1166
gabomdq@6806
  1167
            if (result < 0) {
gabomdq@6806
  1168
                break;
gabomdq@6806
  1169
            }
gabomdq@6806
  1170
gabomdq@6806
  1171
            bytesRemaining -= result;
gabomdq@6806
  1172
            bytesRead += result;
gabomdq@6806
  1173
            ctx->hidden.androidio.position += result;
icculus@5582
  1174
        }
ewing@7501
  1175
        LocalReferenceHolder_Cleanup(&refs);                    
gabomdq@6806
  1176
        return bytesRead / size;
slouken@7191
  1177
    }
icculus@5582
  1178
}
icculus@5582
  1179
ewing@7501
  1180
size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
  1181
        size_t size, size_t num)
icculus@5582
  1182
{
icculus@5582
  1183
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
  1184
    return 0;
icculus@5582
  1185
}
icculus@5582
  1186
philipp@9271
  1187
static int Internal_Android_JNI_FileClose(SDL_RWops* ctx, SDL_bool release)
icculus@5582
  1188
{
ewing@7501
  1189
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
ewing@7501
  1190
icculus@5582
  1191
    int result = 0;
gabomdq@6354
  1192
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
  1193
ewing@7501
  1194
    if (!LocalReferenceHolder_Init(&refs, mEnv)) {
ewing@7501
  1195
        LocalReferenceHolder_Cleanup(&refs);
icculus@7037
  1196
        return SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
  1197
    }
slouken@6284
  1198
icculus@5582
  1199
    if (ctx) {
icculus@5582
  1200
        if (release) {
ewing@7501
  1201
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
  1202
        }
icculus@5582
  1203
gabomdq@6806
  1204
        if (ctx->hidden.androidio.assetFileDescriptorRef) {
gabomdq@6806
  1205
            jobject inputStream = (jobject)ctx->hidden.androidio.assetFileDescriptorRef;
ewing@7501
  1206
            jmethodID mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
gabomdq@6806
  1207
                    "close", "()V");
ewing@7501
  1208
            (*mEnv)->CallVoidMethod(mEnv, inputStream, mid);
ewing@7501
  1209
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.assetFileDescriptorRef);
philipp@9271
  1210
            if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
gabomdq@6806
  1211
                result = -1;
gabomdq@6806
  1212
            }
gabomdq@6806
  1213
        }
gabomdq@6806
  1214
        else {
gabomdq@6806
  1215
            jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
  1216
gabomdq@7677
  1217
            /* inputStream.close(); */
ewing@7501
  1218
            jmethodID mid = (*mEnv)->GetMethodID(mEnv, (*mEnv)->GetObjectClass(mEnv, inputStream),
gabomdq@6806
  1219
                    "close", "()V");
ewing@7501
  1220
            (*mEnv)->CallVoidMethod(mEnv, inputStream, mid);
ewing@7501
  1221
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.inputStreamRef);
ewing@7501
  1222
            (*mEnv)->DeleteGlobalRef(mEnv, (jobject)ctx->hidden.androidio.readableByteChannelRef);
philipp@9271
  1223
            if (Android_JNI_ExceptionOccurred(SDL_FALSE)) {
gabomdq@6806
  1224
                result = -1;
gabomdq@6806
  1225
            }
icculus@5582
  1226
        }
icculus@5582
  1227
icculus@5582
  1228
        if (release) {
icculus@5582
  1229
            SDL_FreeRW(ctx);
icculus@5582
  1230
        }
icculus@5582
  1231
    }
icculus@5582
  1232
ewing@7501
  1233
    LocalReferenceHolder_Cleanup(&refs);
icculus@5582
  1234
    return result;
icculus@5582
  1235
}
icculus@5582
  1236
icculus@5582
  1237
ewing@7501
  1238
Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
  1239
{
slouken@6642
  1240
    return ctx->hidden.androidio.size;
slouken@6642
  1241
}
slouken@6642
  1242
ewing@7501
  1243
Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
  1244
{
gabomdq@6806
  1245
    if (ctx->hidden.androidio.assetFileDescriptorRef) {
ewing@10080
  1246
        off_t ret;
gabomdq@6806
  1247
        switch (whence) {
gabomdq@6806
  1248
            case RW_SEEK_SET:
gabomdq@7678
  1249
                if (ctx->hidden.androidio.size != -1 /* UNKNOWN_LENGTH */ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
  1250
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
  1251
                break;
gabomdq@6806
  1252
            case RW_SEEK_CUR:
gabomdq@6806
  1253
                offset += ctx->hidden.androidio.position;
gabomdq@7678
  1254
                if (ctx->hidden.androidio.size != -1 /* UNKNOWN_LENGTH */ && offset > ctx->hidden.androidio.size) offset = ctx->hidden.androidio.size;
gabomdq@6806
  1255
                offset += ctx->hidden.androidio.offset;
gabomdq@6806
  1256
                break;
gabomdq@6806
  1257
            case RW_SEEK_END:
gabomdq@6806
  1258
                offset = ctx->hidden.androidio.offset + ctx->hidden.androidio.size + offset;
gabomdq@6806
  1259
                break;
gabomdq@6806
  1260
            default:
icculus@7037
  1261
                return SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
  1262
        }
gabomdq@6806
  1263
        whence = SEEK_SET;
icculus@5582
  1264
ewing@10080
  1265
        ret = lseek(ctx->hidden.androidio.fd, (off_t)offset, SEEK_SET);
gabomdq@6806
  1266
        if (ret == -1) return -1;
gabomdq@6806
  1267
        ctx->hidden.androidio.position = ret - ctx->hidden.androidio.offset;
gabomdq@6806
  1268
    } else {
gabomdq@6806
  1269
        Sint64 newPosition;
ewing@10080
  1270
        Sint64 movement;
gabomdq@6806
  1271
gabomdq@6806
  1272
        switch (whence) {
gabomdq@6806
  1273
            case RW_SEEK_SET:
gabomdq@6806
  1274
                newPosition = offset;
gabomdq@6806
  1275
                break;
gabomdq@6806
  1276
            case RW_SEEK_CUR:
gabomdq@6806
  1277
                newPosition = ctx->hidden.androidio.position + offset;
gabomdq@6806
  1278
                break;
gabomdq@6806
  1279
            case RW_SEEK_END:
gabomdq@6806
  1280
                newPosition = ctx->hidden.androidio.size + offset;
gabomdq@6806
  1281
                break;
gabomdq@6806
  1282
            default:
icculus@7037
  1283
                return SDL_SetError("Unknown value for 'whence'");
gabomdq@6806
  1284
        }
gabomdq@6806
  1285
gabomdq@6806
  1286
        /* Validate the new position */
gabomdq@6806
  1287
        if (newPosition < 0) {
icculus@7037
  1288
            return SDL_Error(SDL_EFSEEK);
gabomdq@6806
  1289
        }
gabomdq@6806
  1290
        if (newPosition > ctx->hidden.androidio.size) {
gabomdq@6806
  1291
            newPosition = ctx->hidden.androidio.size;
gabomdq@6806
  1292
        }
slouken@6642
  1293
ewing@10080
  1294
        movement = newPosition - ctx->hidden.androidio.position;
gabomdq@6806
  1295
        if (movement > 0) {
gabomdq@6806
  1296
            unsigned char buffer[4096];
icculus@5582
  1297
gabomdq@7663
  1298
            /* The easy case where we're seeking forwards */
gabomdq@6806
  1299
            while (movement > 0) {
gabomdq@6806
  1300
                Sint64 amount = sizeof (buffer);
ewing@10080
  1301
                size_t result;
gabomdq@6806
  1302
                if (amount > movement) {
gabomdq@6806
  1303
                    amount = movement;
gabomdq@6806
  1304
                }
ewing@10080
  1305
                result = Android_JNI_FileRead(ctx, buffer, 1, amount);
gabomdq@6806
  1306
                if (result <= 0) {
gabomdq@7663
  1307
                    /* Failed to read/skip the required amount, so fail */
gabomdq@6806
  1308
                    return -1;
gabomdq@6806
  1309
                }
tim@5993
  1310
gabomdq@6806
  1311
                movement -= result;
icculus@5582
  1312
            }
tim@5993
  1313
gabomdq@6806
  1314
        } else if (movement < 0) {
gabomdq@7663
  1315
            /* We can't seek backwards so we have to reopen the file and seek */
gabomdq@7663
  1316
            /* forwards which obviously isn't very efficient */
philipp@9271
  1317
            Internal_Android_JNI_FileClose(ctx, SDL_FALSE);
ewing@7501
  1318
            Internal_Android_JNI_FileOpen(ctx);
gabomdq@6806
  1319
            Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
  1320
        }
icculus@5582
  1321
    }
icculus@5582
  1322
icculus@5582
  1323
    return ctx->hidden.androidio.position;
slouken@7191
  1324
icculus@5582
  1325
}
icculus@5582
  1326
ewing@7501
  1327
int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
  1328
{
philipp@9271
  1329
    return Internal_Android_JNI_FileClose(ctx, SDL_TRUE);
icculus@5582
  1330
}
icculus@5582
  1331
gabomdq@7663
  1332
/* returns a new global reference which needs to be released later */
slouken@6464
  1333
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
  1334
{
ewing@7501
  1335
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6464
  1336
    JNIEnv* env = Android_JNI_GetEnv();
ewing@7501
  1337
    jobject retval = NULL;
ewing@10080
  1338
    jstring service;
ewing@10080
  1339
    jmethodID mid;
ewing@10080
  1340
    jobject context;
ewing@10080
  1341
    jobject manager;
ewing@7501
  1342
ewing@7501
  1343
    if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1344
        LocalReferenceHolder_Cleanup(&refs);
slouken@6464
  1345
        return NULL;
slouken@6464
  1346
    }
slouken@6464
  1347
ewing@10080
  1348
    service = (*env)->NewStringUTF(env, name);
slouken@6464
  1349
ewing@7501
  1350
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
ewing@10080
  1351
    context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6464
  1352
philipp@8029
  1353
    mid = (*env)->GetMethodID(env, mActivityClass, "getSystemServiceFromUiThread", "(Ljava/lang/String;)Ljava/lang/Object;");
ewing@10080
  1354
    manager = (*env)->CallObjectMethod(env, context, mid, service);
slouken@6464
  1355
ewing@7501
  1356
    (*env)->DeleteLocalRef(env, service);
slouken@6464
  1357
ewing@7501
  1358
    retval = manager ? (*env)->NewGlobalRef(env, manager) : NULL;
ewing@7501
  1359
    LocalReferenceHolder_Cleanup(&refs);
ewing@7501
  1360
    return retval;
slouken@6464
  1361
}
slouken@6464
  1362
slouken@6464
  1363
#define SETUP_CLIPBOARD(error) \
ewing@7501
  1364
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__); \
slouken@6464
  1365
    JNIEnv* env = Android_JNI_GetEnv(); \
ewing@10080
  1366
    jobject clipboard; \
ewing@7501
  1367
    if (!LocalReferenceHolder_Init(&refs, env)) { \
ewing@7501
  1368
        LocalReferenceHolder_Cleanup(&refs); \
slouken@6464
  1369
        return error; \
slouken@6464
  1370
    } \
ewing@10080
  1371
    clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
  1372
    if (!clipboard) { \
ewing@7501
  1373
        LocalReferenceHolder_Cleanup(&refs); \
slouken@6464
  1374
        return error; \
slouken@6464
  1375
    }
slouken@6464
  1376
ewing@7501
  1377
#define CLEANUP_CLIPBOARD() \
ewing@7501
  1378
    LocalReferenceHolder_Cleanup(&refs);
ewing@7501
  1379
ewing@7501
  1380
int Android_JNI_SetClipboardText(const char* text)
slouken@6464
  1381
{
ewing@10080
  1382
    /* Watch out for C89 scoping rules because of the macro */
slouken@6464
  1383
    SETUP_CLIPBOARD(-1)
slouken@6464
  1384
ewing@10080
  1385
    /* Nest the following in a scope to avoid C89 declaration rules triggered by the macro */
ewing@10080
  1386
    {
ewing@10080
  1387
        jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "setText", "(Ljava/lang/CharSequence;)V");
ewing@10080
  1388
        jstring string = (*env)->NewStringUTF(env, text);
ewing@10080
  1389
        (*env)->CallVoidMethod(env, clipboard, mid, string);
ewing@10080
  1390
        (*env)->DeleteGlobalRef(env, clipboard);
ewing@10080
  1391
        (*env)->DeleteLocalRef(env, string);
ewing@10080
  1392
    }
ewing@7501
  1393
    CLEANUP_CLIPBOARD();
ewing@7501
  1394
slouken@6464
  1395
    return 0;
slouken@6464
  1396
}
slouken@6464
  1397
philipp@9594
  1398
char* Android_JNI_GetClipboardText(void)
slouken@6464
  1399
{
ewing@10080
  1400
    /* Watch out for C89 scoping rules because of the macro */
slouken@6464
  1401
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
  1402
ewing@10080
  1403
    /* Nest the following in a scope to avoid C89 declaration rules triggered by the macro */
ewing@10080
  1404
    {
ewing@10080
  1405
        jmethodID mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "getText", "()Ljava/lang/CharSequence;");
ewing@10080
  1406
        jobject sequence = (*env)->CallObjectMethod(env, clipboard, mid);
ewing@10080
  1407
        (*env)->DeleteGlobalRef(env, clipboard);
ewing@10080
  1408
        if (sequence) {
ewing@10080
  1409
            jstring string;
ewing@10080
  1410
            const char* utf;
ewing@10080
  1411
            mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, sequence), "toString", "()Ljava/lang/String;");
ewing@10080
  1412
            string = (jstring)((*env)->CallObjectMethod(env, sequence, mid));
ewing@10080
  1413
            utf = (*env)->GetStringUTFChars(env, string, 0);
ewing@10080
  1414
            if (utf) {
ewing@10080
  1415
                char* text = SDL_strdup(utf);
ewing@10080
  1416
                (*env)->ReleaseStringUTFChars(env, string, utf);
ewing@7501
  1417
ewing@10080
  1418
                CLEANUP_CLIPBOARD();
ewing@7501
  1419
ewing@10080
  1420
                return text;
ewing@10080
  1421
            }
slouken@6464
  1422
        }
slouken@6464
  1423
    }
ewing@7501
  1424
    CLEANUP_CLIPBOARD();    
ewing@7501
  1425
slouken@6464
  1426
    return SDL_strdup("");
slouken@6464
  1427
}
slouken@6464
  1428
philipp@9594
  1429
SDL_bool Android_JNI_HasClipboardText(void)
slouken@6464
  1430
{
ewing@10080
  1431
    jmethodID mid;
ewing@10080
  1432
    jboolean has;
ewing@10080
  1433
    /* Watch out for C89 scoping rules because of the macro */
slouken@6464
  1434
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
  1435
ewing@10080
  1436
    mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, clipboard), "hasText", "()Z");
ewing@10080
  1437
    has = (*env)->CallBooleanMethod(env, clipboard, mid);
ewing@7501
  1438
    (*env)->DeleteGlobalRef(env, clipboard);
ewing@7501
  1439
ewing@7501
  1440
    CLEANUP_CLIPBOARD();
ewing@7501
  1441
    
slouken@6464
  1442
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
  1443
}
slouken@6464
  1444
slouken@6464
  1445
gabomdq@7663
  1446
/* returns 0 on success or -1 on error (others undefined then)
gabomdq@7663
  1447
 * returns truthy or falsy value in plugged, charged and battery
gabomdq@7663
  1448
 * returns the value in seconds and percent or -1 if not available
gabomdq@7663
  1449
 */
ewing@7501
  1450
int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
  1451
{
ewing@7501
  1452
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6448
  1453
    JNIEnv* env = Android_JNI_GetEnv();
ewing@10080
  1454
    jmethodID mid;
ewing@10080
  1455
    jobject context;
ewing@10080
  1456
    jstring action;
ewing@10080
  1457
    jclass cls;
ewing@10080
  1458
    jobject filter;
ewing@10080
  1459
    jobject intent;
ewing@10080
  1460
    jstring iname;
ewing@10080
  1461
    jmethodID imid;
ewing@10080
  1462
    jstring bname;
ewing@10080
  1463
    jmethodID bmid;
ewing@7501
  1464
    if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1465
        LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1466
        return -1;
slouken@6448
  1467
    }
slouken@6448
  1468
slouken@6448
  1469
ewing@7501
  1470
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext", "()Landroid/content/Context;");
ewing@10080
  1471
    context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6448
  1472
ewing@10080
  1473
    action = (*env)->NewStringUTF(env, "android.intent.action.BATTERY_CHANGED");
slouken@6448
  1474
ewing@10080
  1475
    cls = (*env)->FindClass(env, "android/content/IntentFilter");
slouken@6448
  1476
ewing@7501
  1477
    mid = (*env)->GetMethodID(env, cls, "<init>", "(Ljava/lang/String;)V");
ewing@10080
  1478
    filter = (*env)->NewObject(env, cls, mid, action);
slouken@6448
  1479
ewing@7501
  1480
    (*env)->DeleteLocalRef(env, action);
slouken@6448
  1481
ewing@7501
  1482
    mid = (*env)->GetMethodID(env, mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
ewing@10080
  1483
    intent = (*env)->CallObjectMethod(env, context, mid, NULL, filter);
slouken@6448
  1484
ewing@7501
  1485
    (*env)->DeleteLocalRef(env, filter);
slouken@6448
  1486
ewing@7501
  1487
    cls = (*env)->GetObjectClass(env, intent);
slouken@6448
  1488
ewing@10080
  1489
    imid = (*env)->GetMethodID(env, cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
  1490
ewing@10080
  1491
    /* Watch out for C89 scoping rules because of the macro */
slouken@6448
  1492
#define GET_INT_EXTRA(var, key) \
ewing@10080
  1493
    int var; \
ewing@7501
  1494
    iname = (*env)->NewStringUTF(env, key); \
ewing@10080
  1495
    var = (*env)->CallIntMethod(env, intent, imid, iname, -1); \
ewing@7501
  1496
    (*env)->DeleteLocalRef(env, iname);
slouken@6448
  1497
ewing@10080
  1498
    bmid = (*env)->GetMethodID(env, cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
  1499
ewing@10080
  1500
    /* Watch out for C89 scoping rules because of the macro */
slouken@6448
  1501
#define GET_BOOL_EXTRA(var, key) \
ewing@10080
  1502
    int var; \
ewing@7501
  1503
    bname = (*env)->NewStringUTF(env, key); \
ewing@10080
  1504
    var = (*env)->CallBooleanMethod(env, intent, bmid, bname, JNI_FALSE); \
ewing@7501
  1505
    (*env)->DeleteLocalRef(env, bname);
slouken@6448
  1506
slouken@6448
  1507
    if (plugged) {
ewing@10080
  1508
        /* Watch out for C89 scoping rules because of the macro */
gabomdq@7663
  1509
        GET_INT_EXTRA(plug, "plugged") /* == BatteryManager.EXTRA_PLUGGED (API 5) */
slouken@6448
  1510
        if (plug == -1) {
ewing@7501
  1511
            LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1512
            return -1;
slouken@6448
  1513
        }
gabomdq@7663
  1514
        /* 1 == BatteryManager.BATTERY_PLUGGED_AC */
gabomdq@7663
  1515
        /* 2 == BatteryManager.BATTERY_PLUGGED_USB */
slouken@6448
  1516
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
  1517
    }
slouken@6448
  1518
slouken@6448
  1519
    if (charged) {
ewing@10080
  1520
        /* Watch out for C89 scoping rules because of the macro */
gabomdq@7663
  1521
        GET_INT_EXTRA(status, "status") /* == BatteryManager.EXTRA_STATUS (API 5) */
slouken@6448
  1522
        if (status == -1) {
ewing@7501
  1523
            LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1524
            return -1;
slouken@6448
  1525
        }
gabomdq@7663
  1526
        /* 5 == BatteryManager.BATTERY_STATUS_FULL */
slouken@6448
  1527
        *charged = (status == 5) ? 1 : 0;
slouken@6448
  1528
    }
slouken@6448
  1529
slouken@6448
  1530
    if (battery) {
gabomdq@7663
  1531
        GET_BOOL_EXTRA(present, "present") /* == BatteryManager.EXTRA_PRESENT (API 5) */
slouken@6448
  1532
        *battery = present ? 1 : 0;
slouken@6448
  1533
    }
slouken@6448
  1534
slouken@6448
  1535
    if (seconds) {
gabomdq@7663
  1536
        *seconds = -1; /* not possible */
slouken@6448
  1537
    }
slouken@6448
  1538
slouken@6448
  1539
    if (percent) {
ewing@10080
  1540
        int level;
ewing@10080
  1541
        int scale;
ewing@10080
  1542
        
ewing@10080
  1543
        /* Watch out for C89 scoping rules because of the macro */
ewing@10080
  1544
        {
ewing@10080
  1545
            GET_INT_EXTRA(level_temp, "level") /* == BatteryManager.EXTRA_LEVEL (API 5) */
ewing@10080
  1546
            level = level_temp;
ewing@10080
  1547
        }
ewing@10080
  1548
        /* Watch out for C89 scoping rules because of the macro */
ewing@10080
  1549
        {
ewing@10080
  1550
            GET_INT_EXTRA(scale_temp, "scale") /* == BatteryManager.EXTRA_SCALE (API 5) */
ewing@10080
  1551
            scale = scale_temp;
ewing@10080
  1552
        }
ewing@10080
  1553
        
slouken@6448
  1554
        if ((level == -1) || (scale == -1)) {
ewing@7501
  1555
            LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1556
            return -1;
slouken@6448
  1557
        }
slouken@6448
  1558
        *percent = level * 100 / scale;
slouken@6448
  1559
    }
slouken@6448
  1560
ewing@7501
  1561
    (*env)->DeleteLocalRef(env, intent);
slouken@6448
  1562
ewing@7501
  1563
    LocalReferenceHolder_Cleanup(&refs);
slouken@6448
  1564
    return 0;
slouken@6448
  1565
}
slouken@6448
  1566
philipp@7786
  1567
/* returns number of found touch devices as return value and ids in parameter ids */
philipp@7786
  1568
int Android_JNI_GetTouchDeviceIds(int **ids) {
philipp@7786
  1569
    JNIEnv *env = Android_JNI_GetEnv();
philipp@7786
  1570
    jint sources = 4098; /* == InputDevice.SOURCE_TOUCHSCREEN */
philipp@7786
  1571
    jmethodID mid = (*env)->GetStaticMethodID(env, mActivityClass, "inputGetInputDeviceIds", "(I)[I");
philipp@7786
  1572
    jintArray array = (jintArray) (*env)->CallStaticObjectMethod(env, mActivityClass, mid, sources);
philipp@7786
  1573
    int number = 0;
philipp@7786
  1574
    *ids = NULL;
philipp@7786
  1575
    if (array) {
philipp@7786
  1576
        number = (int) (*env)->GetArrayLength(env, array);
philipp@7786
  1577
        if (0 < number) {
philipp@7786
  1578
            jint* elements = (*env)->GetIntArrayElements(env, array, NULL);
philipp@7786
  1579
            if (elements) {
philipp@7786
  1580
                int i;
slouken@7863
  1581
                *ids = SDL_malloc(number * sizeof (**ids));
philipp@7786
  1582
                for (i = 0; i < number; ++i) { /* not assuming sizeof (jint) == sizeof (int) */
slouken@7863
  1583
                    (*ids)[i] = elements[i];
philipp@7786
  1584
                }
philipp@7786
  1585
                (*env)->ReleaseIntArrayElements(env, array, elements, JNI_ABORT);
philipp@7786
  1586
            }
philipp@7786
  1587
        }
philipp@7786
  1588
        (*env)->DeleteLocalRef(env, array);
philipp@7786
  1589
    }
philipp@7786
  1590
    return number;
philipp@7786
  1591
}
philipp@7786
  1592
philipp@9594
  1593
void Android_JNI_PollInputDevices(void)
gabomdq@7907
  1594
{
gabomdq@8057
  1595
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@8057
  1596
    (*env)->CallStaticVoidMethod(env, mActivityClass, midPollInputDevices);    
gabomdq@7907
  1597
}
gabomdq@7907
  1598
slouken@11238
  1599
void Android_JNI_PollHapticDevices(void)
slouken@11238
  1600
{
slouken@11238
  1601
    JNIEnv *env = Android_JNI_GetEnv();
slouken@11238
  1602
    (*env)->CallStaticVoidMethod(env, mActivityClass, midPollHapticDevices);
slouken@11238
  1603
}
slouken@11238
  1604
    
slouken@11238
  1605
void Android_JNI_HapticRun(int device_id, int length)
slouken@11238
  1606
{
slouken@11238
  1607
    JNIEnv *env = Android_JNI_GetEnv();
slouken@11238
  1608
    (*env)->CallStaticVoidMethod(env, mActivityClass, midHapticRun, device_id, length);
slouken@11238
  1609
}
slouken@11238
  1610
slouken@11238
  1611
philipp@9174
  1612
/* See SDLActivity.java for constants. */
philipp@9174
  1613
#define COMMAND_SET_KEEP_SCREEN_ON    5
philipp@9174
  1614
gabomdq@7663
  1615
/* sends message to be handled on the UI event dispatch thread */
ewing@7501
  1616
int Android_JNI_SendMessage(int command, int param)
slouken@6392
  1617
{
slouken@6392
  1618
    JNIEnv *env = Android_JNI_GetEnv();
ewing@10080
  1619
    jmethodID mid;
ewing@10080
  1620
    jboolean success;
slouken@6392
  1621
    if (!env) {
slouken@6392
  1622
        return -1;
slouken@6392
  1623
    }
ewing@10080
  1624
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "sendMessage", "(II)Z");
slouken@6392
  1625
    if (!mid) {
slouken@6392
  1626
        return -1;
slouken@6392
  1627
    }
ewing@10080
  1628
    success = (*env)->CallStaticBooleanMethod(env, mActivityClass, mid, command, param);
philipp@7149
  1629
    return success ? 0 : -1;
slouken@6392
  1630
}
slouken@6392
  1631
philipp@9174
  1632
void Android_JNI_SuspendScreenSaver(SDL_bool suspend)
philipp@9174
  1633
{
philipp@9174
  1634
    Android_JNI_SendMessage(COMMAND_SET_KEEP_SCREEN_ON, (suspend == SDL_FALSE) ? 0 : 1);
philipp@9174
  1635
}
philipp@9174
  1636
ewing@7501
  1637
void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
  1638
{
slouken@6555
  1639
    JNIEnv *env = Android_JNI_GetEnv();
ewing@10080
  1640
    jmethodID mid;
slouken@6555
  1641
    if (!env) {
slouken@6654
  1642
        return;
slouken@6555
  1643
    }
slouken@6555
  1644
ewing@10080
  1645
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "showTextInput", "(IIII)Z");
slouken@6555
  1646
    if (!mid) {
slouken@6654
  1647
        return;
slouken@6555
  1648
    }
ewing@7501
  1649
    (*env)->CallStaticBooleanMethod(env, mActivityClass, mid,
slouken@6555
  1650
                               inputRect->x,
slouken@6555
  1651
                               inputRect->y,
slouken@6555
  1652
                               inputRect->w,
slouken@6555
  1653
                               inputRect->h );
slouken@6555
  1654
}
slouken@6555
  1655
philipp@9594
  1656
void Android_JNI_HideTextInput(void)
slouken@6555
  1657
{
gabomdq@7663
  1658
    /* has to match Activity constant */
slouken@6654
  1659
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
  1660
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
  1661
}
slouken@6555
  1662
slouken@9135
  1663
int Android_JNI_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
slouken@9135
  1664
{
slouken@9135
  1665
    JNIEnv *env;
philipp@9231
  1666
    jclass clazz;
slouken@9135
  1667
    jmethodID mid;
slouken@9135
  1668
    jobject context;
slouken@9135
  1669
    jstring title;
slouken@9135
  1670
    jstring message;
slouken@9135
  1671
    jintArray button_flags;
slouken@9135
  1672
    jintArray button_ids;
slouken@9135
  1673
    jobjectArray button_texts;
slouken@9135
  1674
    jintArray colors;
philipp@9231
  1675
    jobject text;
slouken@9135
  1676
    jint temp;
slouken@9135
  1677
    int i;
slouken@9135
  1678
slouken@9135
  1679
    env = Android_JNI_GetEnv();
slouken@9135
  1680
slouken@9135
  1681
    /* convert parameters */
slouken@9135
  1682
philipp@9231
  1683
    clazz = (*env)->FindClass(env, "java/lang/String");
philipp@9231
  1684
slouken@9135
  1685
    title = (*env)->NewStringUTF(env, messageboxdata->title);
slouken@9135
  1686
    message = (*env)->NewStringUTF(env, messageboxdata->message);
slouken@9135
  1687
slouken@9135
  1688
    button_flags = (*env)->NewIntArray(env, messageboxdata->numbuttons);
slouken@9135
  1689
    button_ids = (*env)->NewIntArray(env, messageboxdata->numbuttons);
slouken@9135
  1690
    button_texts = (*env)->NewObjectArray(env, messageboxdata->numbuttons,
philipp@9231
  1691
        clazz, NULL);
slouken@9135
  1692
    for (i = 0; i < messageboxdata->numbuttons; ++i) {
slouken@9135
  1693
        temp = messageboxdata->buttons[i].flags;
slouken@9135
  1694
        (*env)->SetIntArrayRegion(env, button_flags, i, 1, &temp);
slouken@9135
  1695
        temp = messageboxdata->buttons[i].buttonid;
slouken@9135
  1696
        (*env)->SetIntArrayRegion(env, button_ids, i, 1, &temp);
philipp@9231
  1697
        text = (*env)->NewStringUTF(env, messageboxdata->buttons[i].text);
philipp@9231
  1698
        (*env)->SetObjectArrayElement(env, button_texts, i, text);
philipp@9231
  1699
        (*env)->DeleteLocalRef(env, text);
slouken@9135
  1700
    }
slouken@9135
  1701
slouken@9135
  1702
    if (messageboxdata->colorScheme) {
slouken@9135
  1703
        colors = (*env)->NewIntArray(env, SDL_MESSAGEBOX_COLOR_MAX);
slouken@9135
  1704
        for (i = 0; i < SDL_MESSAGEBOX_COLOR_MAX; ++i) {
slouken@9135
  1705
            temp = (0xFF << 24) |
slouken@9135
  1706
                   (messageboxdata->colorScheme->colors[i].r << 16) |
slouken@9135
  1707
                   (messageboxdata->colorScheme->colors[i].g << 8) |
slouken@9135
  1708
                   (messageboxdata->colorScheme->colors[i].b << 0);
slouken@9135
  1709
            (*env)->SetIntArrayRegion(env, colors, i, 1, &temp);
slouken@9135
  1710
        }
slouken@9135
  1711
    } else {
slouken@9135
  1712
        colors = NULL;
slouken@9135
  1713
    }
slouken@9135
  1714
philipp@9231
  1715
    (*env)->DeleteLocalRef(env, clazz);
philipp@9231
  1716
slouken@9135
  1717
    /* call function */
slouken@9135
  1718
slouken@9135
  1719
    mid = (*env)->GetStaticMethodID(env, mActivityClass, "getContext","()Landroid/content/Context;");
slouken@9135
  1720
slouken@9135
  1721
    context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@9135
  1722
philipp@9231
  1723
    clazz = (*env)->GetObjectClass(env, context);
philipp@9231
  1724
philipp@9231
  1725
    mid = (*env)->GetMethodID(env, clazz,
slouken@9135
  1726
        "messageboxShowMessageBox", "(ILjava/lang/String;Ljava/lang/String;[I[I[Ljava/lang/String;[I)I");
slouken@9135
  1727
    *buttonid = (*env)->CallIntMethod(env, context, mid,
slouken@9135
  1728
        messageboxdata->flags,
slouken@9135
  1729
        title,
slouken@9135
  1730
        message,
slouken@9135
  1731
        button_flags,
slouken@9135
  1732
        button_ids,
slouken@9135
  1733
        button_texts,
slouken@9135
  1734
        colors);
slouken@9135
  1735
philipp@9231
  1736
    (*env)->DeleteLocalRef(env, context);
philipp@9231
  1737
    (*env)->DeleteLocalRef(env, clazz);
philipp@9231
  1738
slouken@9135
  1739
    /* delete parameters */
slouken@9135
  1740
slouken@9135
  1741
    (*env)->DeleteLocalRef(env, title);
slouken@9135
  1742
    (*env)->DeleteLocalRef(env, message);
slouken@9135
  1743
    (*env)->DeleteLocalRef(env, button_flags);
slouken@9135
  1744
    (*env)->DeleteLocalRef(env, button_ids);
slouken@9135
  1745
    (*env)->DeleteLocalRef(env, button_texts);
slouken@9135
  1746
    (*env)->DeleteLocalRef(env, colors);
slouken@9135
  1747
slouken@9135
  1748
    return 0;
slouken@9135
  1749
}
slouken@9135
  1750
gabomdq@7663
  1751
/*
slouken@6630
  1752
//////////////////////////////////////////////////////////////////////////////
slouken@6630
  1753
//
slouken@6630
  1754
// Functions exposed to SDL applications in SDL_system.h
gabomdq@7663
  1755
//////////////////////////////////////////////////////////////////////////////
gabomdq@7663
  1756
*/
slouken@6630
  1757
philipp@11031
  1758
void *SDL_AndroidGetJNIEnv(void)
slouken@6630
  1759
{
slouken@6630
  1760
    return Android_JNI_GetEnv();
slouken@6630
  1761
}
slouken@6630
  1762
philipp@11031
  1763
void *SDL_AndroidGetActivity(void)
slouken@6630
  1764
{
gabomdq@7095
  1765
    /* See SDL_system.h for caveats on using this function. */
slouken@7191
  1766
slouken@6630
  1767
    jmethodID mid;
slouken@6630
  1768
slouken@6630
  1769
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@7083
  1770
    if (!env) {
slouken@6630
  1771
        return NULL;
slouken@6630
  1772
    }
slouken@6630
  1773
gabomdq@7663
  1774
    /* return SDLActivity.getContext(); */
ewing@7501
  1775
    mid = (*env)->GetStaticMethodID(env, mActivityClass,
slouken@6630
  1776
            "getContext","()Landroid/content/Context;");
ewing@7501
  1777
    return (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6630
  1778
}
slouken@6630
  1779
philipp@11031
  1780
const char * SDL_AndroidGetInternalStoragePath(void)
slouken@6630
  1781
{
slouken@6630
  1782
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1783
slouken@6630
  1784
    if (!s_AndroidInternalFilesPath) {
ewing@7501
  1785
        struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6630
  1786
        jmethodID mid;
slouken@6630
  1787
        jobject context;
slouken@6630
  1788
        jobject fileObject;
slouken@6630
  1789
        jstring pathString;
slouken@6630
  1790
        const char *path;
slouken@6630
  1791
slouken@6630
  1792
        JNIEnv *env = Android_JNI_GetEnv();
ewing@7501
  1793
        if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1794
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1795
            return NULL;
slouken@6630
  1796
        }
slouken@6630
  1797
gabomdq@7663
  1798
        /* context = SDLActivity.getContext(); */
ewing@7501
  1799
        mid = (*env)->GetStaticMethodID(env, mActivityClass,
slouken@6630
  1800
                "getContext","()Landroid/content/Context;");
ewing@7501
  1801
        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6630
  1802
gabomdq@7663
  1803
        /* fileObj = context.getFilesDir(); */
ewing@7501
  1804
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
slouken@6630
  1805
                "getFilesDir", "()Ljava/io/File;");
ewing@7501
  1806
        fileObject = (*env)->CallObjectMethod(env, context, mid);
slouken@6630
  1807
        if (!fileObject) {
slouken@6630
  1808
            SDL_SetError("Couldn't get internal directory");
ewing@7501
  1809
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1810
            return NULL;
slouken@6630
  1811
        }
slouken@6630
  1812
gabomdq@7663
  1813
        /* path = fileObject.getAbsolutePath(); */
ewing@7501
  1814
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
slouken@6630
  1815
                "getAbsolutePath", "()Ljava/lang/String;");
ewing@7501
  1816
        pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
slouken@6630
  1817
ewing@7501
  1818
        path = (*env)->GetStringUTFChars(env, pathString, NULL);
slouken@6630
  1819
        s_AndroidInternalFilesPath = SDL_strdup(path);
ewing@7501
  1820
        (*env)->ReleaseStringUTFChars(env, pathString, path);
ewing@7501
  1821
ewing@7501
  1822
        LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1823
    }
slouken@6630
  1824
    return s_AndroidInternalFilesPath;
slouken@6630
  1825
}
slouken@6630
  1826
philipp@11031
  1827
int SDL_AndroidGetExternalStorageState(void)
slouken@6630
  1828
{
ewing@7501
  1829
    struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6630
  1830
    jmethodID mid;
slouken@6630
  1831
    jclass cls;
slouken@6630
  1832
    jstring stateString;
slouken@6630
  1833
    const char *state;
slouken@6630
  1834
    int stateFlags;
slouken@6630
  1835
slouken@6630
  1836
    JNIEnv *env = Android_JNI_GetEnv();
ewing@7501
  1837
    if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1838
        LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1839
        return 0;
slouken@6630
  1840
    }
slouken@6630
  1841
ewing@7501
  1842
    cls = (*env)->FindClass(env, "android/os/Environment");
ewing@7501
  1843
    mid = (*env)->GetStaticMethodID(env, cls,
slouken@6630
  1844
            "getExternalStorageState", "()Ljava/lang/String;");
ewing@7501
  1845
    stateString = (jstring)(*env)->CallStaticObjectMethod(env, cls, mid);
slouken@6630
  1846
ewing@7501
  1847
    state = (*env)->GetStringUTFChars(env, stateString, NULL);
slouken@6630
  1848
gabomdq@7663
  1849
    /* Print an info message so people debugging know the storage state */
slouken@6630
  1850
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1851
slouken@6630
  1852
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1853
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1854
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1855
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1856
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1857
    } else {
slouken@6630
  1858
        stateFlags = 0;
slouken@6630
  1859
    }
ewing@7501
  1860
    (*env)->ReleaseStringUTFChars(env, stateString, state);
slouken@6630
  1861
ewing@7501
  1862
    LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1863
    return stateFlags;
slouken@6630
  1864
}
slouken@6630
  1865
philipp@11031
  1866
const char * SDL_AndroidGetExternalStoragePath(void)
slouken@6630
  1867
{
slouken@6630
  1868
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1869
slouken@6630
  1870
    if (!s_AndroidExternalFilesPath) {
ewing@7501
  1871
        struct LocalReferenceHolder refs = LocalReferenceHolder_Setup(__FUNCTION__);
slouken@6630
  1872
        jmethodID mid;
slouken@6630
  1873
        jobject context;
slouken@6630
  1874
        jobject fileObject;
slouken@6630
  1875
        jstring pathString;
slouken@6630
  1876
        const char *path;
slouken@6630
  1877
slouken@6630
  1878
        JNIEnv *env = Android_JNI_GetEnv();
ewing@7501
  1879
        if (!LocalReferenceHolder_Init(&refs, env)) {
ewing@7501
  1880
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1881
            return NULL;
slouken@6630
  1882
        }
slouken@6630
  1883
gabomdq@7663
  1884
        /* context = SDLActivity.getContext(); */
ewing@7501
  1885
        mid = (*env)->GetStaticMethodID(env, mActivityClass,
slouken@6630
  1886
                "getContext","()Landroid/content/Context;");
ewing@7501
  1887
        context = (*env)->CallStaticObjectMethod(env, mActivityClass, mid);
slouken@6630
  1888
gabomdq@7663
  1889
        /* fileObj = context.getExternalFilesDir(); */
ewing@7501
  1890
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, context),
slouken@6630
  1891
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
ewing@7501
  1892
        fileObject = (*env)->CallObjectMethod(env, context, mid, NULL);
slouken@6630
  1893
        if (!fileObject) {
slouken@6630
  1894
            SDL_SetError("Couldn't get external directory");
ewing@7501
  1895
            LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1896
            return NULL;
slouken@6630
  1897
        }
slouken@6630
  1898
gabomdq@7663
  1899
        /* path = fileObject.getAbsolutePath(); */
ewing@7501
  1900
        mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, fileObject),
slouken@6630
  1901
                "getAbsolutePath", "()Ljava/lang/String;");
ewing@7501
  1902
        pathString = (jstring)(*env)->CallObjectMethod(env, fileObject, mid);
slouken@6630
  1903
ewing@7501
  1904
        path = (*env)->GetStringUTFChars(env, pathString, NULL);
slouken@6630
  1905
        s_AndroidExternalFilesPath = SDL_strdup(path);
ewing@7501
  1906
        (*env)->ReleaseStringUTFChars(env, pathString, path);
ewing@7501
  1907
ewing@7501
  1908
        LocalReferenceHolder_Cleanup(&refs);
slouken@6630
  1909
    }
slouken@6630
  1910
    return s_AndroidExternalFilesPath;
slouken@6630
  1911
}
slouken@6630
  1912
slouken@6044
  1913
#endif /* __ANDROID__ */
slouken@6044
  1914
slouken@4981
  1915
/* vi: set ts=4 sw=4 expandtab: */