src/core/android/SDL_android.c
author Gabriel Jacobo <gabomdq@gmail.com>
Tue, 05 Nov 2013 20:07:39 -0300
changeset 7907 24b4e98c6010
parent 7863 c6b33210e610
child 7910 261addaa47d0
permissions -rw-r--r--
Adds Joystick support for Android

This bumps the build SDK level to 12 (up from 10). Runtime requirements remain
the same (at API level < 12 joystick support is disabled).

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