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