src/core/android/SDL_android.c
author Philipp Wiesemann <philipp.wiesemann@arcor.de>
Tue, 30 Aug 2016 21:15:18 +0200
changeset 10296 80190c2a271d
parent 10280 985f92b2f8e9
child 10358 f46d780b6685
permissions -rw-r--r--
Android: Fixed misleading warning in log output (thanks, Sylvain!).

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