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