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