src/core/android/SDL_android.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 27 Aug 2017 18:43:52 -0700
changeset 11355 6185fb86f046
parent 11292 df399ea01ee5
child 11393 3e57ce45a890
permissions -rw-r--r--
Fixed bug 2266 - please add notifications for clipboard updates on Android

Sylvain

Hi! here's a patch for that with two class loaded regarding API level.
Test both case : before API 11 and after.

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