src/core/android/SDL_android.c
author Sam Lantinga <slouken@libsdl.org>
Sun, 02 Feb 2014 00:53:27 -0800
changeset 8149 681eb46b8ac4
parent 8140 8372466c003c
child 8760 27eedcca604d
child 8896 d931167c375a
permissions -rw-r--r--
Fixed bug 2374 - Update copyright for 2014...

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