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