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