src/core/android/SDL_android.c
author Philipp Wiesemann <philipp.wiesemann@arcor.de>
Sun, 17 Jul 2016 21:43:12 +0200
changeset 10199 6ab154366a9b
parent 10080 426de7645465
child 10280 985f92b2f8e9
permissions -rw-r--r--
Android: Fixed missing export of a JNI function (thanks, Andrii!).

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