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