src/core/android/SDL_android.c
author Philipp Wiesemann <philipp.wiesemann@arcor.de>
Sat, 05 Oct 2013 17:08:19 +0200
changeset 7786 cfc1285375e1
parent 7678 286c42d7c5ed
child 7863 c6b33210e610
permissions -rw-r--r--
Added detection of touch devices before first touch events happen on Android.

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