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