src/core/android/SDL_android.c
author Sam Lantinga <slouken@libsdl.org>
Sat, 04 Nov 2017 22:03:28 -0700
changeset 11688 e4d90d54cb01
parent 11678 1f10a52295e3
child 11715 35da714ed287
permissions -rw-r--r--
Fixed bug 3917 - Android, issues with getManifestEnvironmentVariable

Sylvain

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