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