src/core/android/SDL_android.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 13 Aug 2017 20:55:59 -0700
changeset 11270 31ce9a8ce2bd
parent 11239 856e5e3c1e86
child 11271 ab3f2402a777
permissions -rw-r--r--
Fixed bug 3235 - Make the Android window creation similar to iOS' window creation

Sylvain

Here's a patch.
It tries to get the hint first. Resizable will allow any orientation. Otherwise it uses width/height window.

setOrientation method is splitted in static and non-static, so that it can be overloaded in a user subclass.

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