src/core/android/SDL_android.cpp
author Sam Lantinga <slouken@libsdl.org>
Sat, 03 Nov 2012 18:43:36 -0700
changeset 6642 b716011e53ce
parent 6630 55910871076b
child 6650 d36232135316
permissions -rw-r--r--
Added an API to get the size of a file - WARNING! ABI CHANGE!
slouken@4964
     1
/*
slouken@5535
     2
  Simple DirectMedia Layer
slouken@6138
     3
  Copyright (C) 1997-2012 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@4964
    24
slouken@6044
    25
#ifdef __ANDROID__
slouken@6044
    26
slouken@6630
    27
#include "SDL_system.h"
slouken@4989
    28
#include "SDL_android.h"
slouken@4989
    29
slouken@4980
    30
extern "C" {
slouken@5092
    31
#include "../../events/SDL_events_c.h"
slouken@5092
    32
#include "../../video/android/SDL_androidkeyboard.h"
slouken@5092
    33
#include "../../video/android/SDL_androidtouch.h"
slouken@5092
    34
#include "../../video/android/SDL_androidvideo.h"
slouken@4995
    35
icculus@5996
    36
#include <android/log.h>
gabomdq@6354
    37
#include <pthread.h>
icculus@5996
    38
#define LOG_TAG "SDL_android"
icculus@5996
    39
//#define LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
icculus@5996
    40
//#define LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
icculus@5996
    41
#define LOGI(...) do {} while (false)
icculus@5996
    42
#define LOGE(...) do {} while (false)
icculus@5996
    43
icculus@5996
    44
slouken@6191
    45
/* Implemented in audio/android/SDL_androidaudio.c */
slouken@4995
    46
extern void Android_RunAudioThread();
slouken@4995
    47
} // C
slouken@4980
    48
slouken@4964
    49
/*******************************************************************************
slouken@4964
    50
 This file links the Java side of Android with libsdl
slouken@4964
    51
*******************************************************************************/
slouken@4964
    52
#include <jni.h>
slouken@4964
    53
#include <android/log.h>
slouken@4964
    54
slouken@4964
    55
slouken@4964
    56
/*******************************************************************************
slouken@4964
    57
                               Globals
slouken@4964
    58
*******************************************************************************/
gabomdq@6354
    59
static pthread_key_t mThreadKey;
icculus@5996
    60
static JavaVM* mJavaVM;
slouken@4964
    61
slouken@4995
    62
// Main activity
slouken@4998
    63
static jclass mActivityClass;
slouken@4964
    64
slouken@4995
    65
// method signatures
slouken@4995
    66
static jmethodID midCreateGLContext;
slouken@4995
    67
static jmethodID midFlipBuffers;
slouken@4995
    68
static jmethodID midAudioInit;
slouken@4995
    69
static jmethodID midAudioWriteShortBuffer;
slouken@4995
    70
static jmethodID midAudioWriteByteBuffer;
slouken@4996
    71
static jmethodID midAudioQuit;
slouken@4964
    72
slouken@4995
    73
// Accelerometer data storage
slouken@5000
    74
static float fLastAccelerometer[3];
slouken@6212
    75
static bool bHasNewData;
slouken@4964
    76
slouken@4964
    77
/*******************************************************************************
slouken@4964
    78
                 Functions called by JNI
slouken@4964
    79
*******************************************************************************/
slouken@4964
    80
slouken@4964
    81
// Library init
slouken@4964
    82
extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)
slouken@4964
    83
{
icculus@5996
    84
    JNIEnv *env;
icculus@5996
    85
    mJavaVM = vm;
icculus@5996
    86
    LOGI("JNI_OnLoad called");
icculus@5996
    87
    if (mJavaVM->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
icculus@5996
    88
        LOGE("Failed to get the environment using GetEnv()");
icculus@5996
    89
        return -1;
icculus@5996
    90
    }
gabomdq@6354
    91
    /*
gabomdq@6354
    92
     * Create mThreadKey so we can keep track of the JNIEnv assigned to each thread
gabomdq@6354
    93
     * Refer to http://developer.android.com/guide/practices/design/jni.html for the rationale behind this
gabomdq@6354
    94
     */
gabomdq@6354
    95
    if (pthread_key_create(&mThreadKey, Android_JNI_ThreadDestroyed)) {
gabomdq@6354
    96
        __android_log_print(ANDROID_LOG_ERROR, "SDL", "Error initializing pthread key");
gabomdq@6354
    97
    }
gabomdq@6354
    98
    else {
gabomdq@6354
    99
        Android_JNI_SetupThread();
gabomdq@6354
   100
    }
icculus@5996
   101
slouken@4964
   102
    return JNI_VERSION_1_4;
slouken@4964
   103
}
slouken@4964
   104
slouken@4964
   105
// Called before SDL_main() to initialize JNI bindings
gabomdq@6354
   106
extern "C" void SDL_Android_Init(JNIEnv* mEnv, jclass cls)
slouken@4964
   107
{
slouken@4964
   108
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init()");
slouken@4964
   109
gabomdq@6354
   110
    Android_JNI_SetupThread();
gabomdq@6354
   111
gabomdq@6354
   112
    mActivityClass = (jclass)mEnv->NewGlobalRef(cls);
slouken@4998
   113
slouken@4998
   114
    midCreateGLContext = mEnv->GetStaticMethodID(mActivityClass,
slouken@5222
   115
                                "createGLContext","(II)Z");
slouken@4998
   116
    midFlipBuffers = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   117
                                "flipBuffers","()V");
slouken@4998
   118
    midAudioInit = mEnv->GetStaticMethodID(mActivityClass, 
slouken@4998
   119
                                "audioInit", "(IZZI)Ljava/lang/Object;");
slouken@4998
   120
    midAudioWriteShortBuffer = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   121
                                "audioWriteShortBuffer", "([S)V");
slouken@4998
   122
    midAudioWriteByteBuffer = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   123
                                "audioWriteByteBuffer", "([B)V");
slouken@4998
   124
    midAudioQuit = mEnv->GetStaticMethodID(mActivityClass,
slouken@4998
   125
                                "audioQuit", "()V");
slouken@4964
   126
slouken@6212
   127
    bHasNewData = false;
slouken@6212
   128
slouken@4995
   129
    if(!midCreateGLContext || !midFlipBuffers || !midAudioInit ||
slouken@4996
   130
       !midAudioWriteShortBuffer || !midAudioWriteByteBuffer || !midAudioQuit) {
slouken@4996
   131
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL: Couldn't locate Java callbacks, check that they're named and typed correctly");
slouken@4964
   132
    }
icculus@5996
   133
    __android_log_print(ANDROID_LOG_INFO, "SDL", "SDL_Android_Init() finished!");
slouken@4964
   134
}
slouken@4964
   135
slouken@4995
   136
// Resize
slouken@4995
   137
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeResize(
slouken@4998
   138
                                    JNIEnv* env, jclass jcls,
slouken@4995
   139
                                    jint width, jint height, jint format)
slouken@4995
   140
{
slouken@4995
   141
    Android_SetScreenResolution(width, height, format);
slouken@4995
   142
}
slouken@4995
   143
slouken@4964
   144
// Keydown
slouken@4995
   145
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyDown(
slouken@4998
   146
                                    JNIEnv* env, jclass jcls, jint keycode)
slouken@4964
   147
{
slouken@4980
   148
    Android_OnKeyDown(keycode);
slouken@4964
   149
}
slouken@4964
   150
slouken@4964
   151
// Keyup
slouken@4995
   152
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeKeyUp(
slouken@4998
   153
                                    JNIEnv* env, jclass jcls, jint keycode)
slouken@4964
   154
{
slouken@4980
   155
    Android_OnKeyUp(keycode);
slouken@4964
   156
}
slouken@4964
   157
slouken@4964
   158
// Touch
slouken@4995
   159
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeTouch(
slouken@4998
   160
                                    JNIEnv* env, jclass jcls,
icculus@5982
   161
                                    jint touch_device_id_in, jint pointer_finger_id_in,
slouken@4995
   162
                                    jint action, jfloat x, jfloat y, jfloat p)
slouken@4964
   163
{
icculus@5982
   164
    Android_OnTouch(touch_device_id_in, pointer_finger_id_in, action, x, y, p);
slouken@4964
   165
}
slouken@4964
   166
slouken@4995
   167
// Accelerometer
slouken@4964
   168
extern "C" void Java_org_libsdl_app_SDLActivity_onNativeAccel(
slouken@4998
   169
                                    JNIEnv* env, jclass jcls,
slouken@4995
   170
                                    jfloat x, jfloat y, jfloat z)
slouken@4964
   171
{
slouken@4964
   172
    fLastAccelerometer[0] = x;
slouken@4964
   173
    fLastAccelerometer[1] = y;
slouken@6212
   174
    fLastAccelerometer[2] = z;
slouken@6212
   175
    bHasNewData = true;
slouken@4964
   176
}
slouken@4964
   177
slouken@4995
   178
// Quit
slouken@4995
   179
extern "C" void Java_org_libsdl_app_SDLActivity_nativeQuit(
slouken@4998
   180
                                    JNIEnv* env, jclass cls)
slouken@4995
   181
{    
slouken@4995
   182
    // Inject a SDL_QUIT event
slouken@4995
   183
    SDL_SendQuit();
slouken@4995
   184
}
slouken@4995
   185
slouken@6186
   186
// Pause
slouken@6186
   187
extern "C" void Java_org_libsdl_app_SDLActivity_nativePause(
slouken@6186
   188
                                    JNIEnv* env, jclass cls)
slouken@6186
   189
{
slouken@6186
   190
    if (Android_Window) {
gabomdq@6330
   191
        /* Signal the pause semaphore so the event loop knows to pause and (optionally) block itself */
gabomdq@6330
   192
        if (!SDL_SemValue(Android_PauseSem)) SDL_SemPost(Android_PauseSem);
slouken@6186
   193
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_LOST, 0, 0);
slouken@6191
   194
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_MINIMIZED, 0, 0);
slouken@6186
   195
    }
slouken@6186
   196
}
slouken@6186
   197
slouken@6186
   198
// Resume
slouken@6186
   199
extern "C" void Java_org_libsdl_app_SDLActivity_nativeResume(
slouken@6186
   200
                                    JNIEnv* env, jclass cls)
slouken@6186
   201
{
slouken@6186
   202
    if (Android_Window) {
gabomdq@6330
   203
        /* Signal the resume semaphore so the event loop knows to resume and restore the GL Context
gabomdq@6330
   204
         * We can't restore the GL Context here because it needs to be done on the SDL main thread
gabomdq@6330
   205
         * and this function will be called from the Java thread instead.
gabomdq@6330
   206
         */
gabomdq@6330
   207
        if (!SDL_SemValue(Android_ResumeSem)) SDL_SemPost(Android_ResumeSem);
slouken@6186
   208
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_FOCUS_GAINED, 0, 0);
slouken@6191
   209
        SDL_SendWindowEvent(Android_Window, SDL_WINDOWEVENT_RESTORED, 0, 0);
slouken@6186
   210
    }
slouken@6186
   211
}
slouken@6186
   212
slouken@4995
   213
extern "C" void Java_org_libsdl_app_SDLActivity_nativeRunAudioThread(
slouken@4998
   214
                                    JNIEnv* env, jclass cls)
slouken@4995
   215
{
slouken@4998
   216
    /* This is the audio thread, with a different environment */
gabomdq@6354
   217
    Android_JNI_SetupThread();
slouken@4998
   218
slouken@4996
   219
    Android_RunAudioThread();
slouken@4995
   220
}
slouken@4964
   221
slouken@6555
   222
extern "C" void Java_org_libsdl_app_SDLInputConnection_nativeCommitText(
slouken@6555
   223
                                    JNIEnv* env, jclass cls,
slouken@6555
   224
                                    jstring text, jint newCursorPosition)
slouken@6555
   225
{
slouken@6555
   226
    const char *utftext = env->GetStringUTFChars(text, NULL);
slouken@6555
   227
slouken@6555
   228
    SDL_SendKeyboardText(utftext);
slouken@6555
   229
slouken@6555
   230
    env->ReleaseStringUTFChars(text, utftext);
slouken@6555
   231
}
slouken@6555
   232
slouken@6555
   233
extern "C" void Java_org_libsdl_app_SDLInputConnection_nativeSetComposingText(
slouken@6555
   234
                                    JNIEnv* env, jclass cls,
slouken@6555
   235
                                    jstring text, jint newCursorPosition)
slouken@6555
   236
{
slouken@6555
   237
    const char *utftext = env->GetStringUTFChars(text, NULL);
slouken@6555
   238
slouken@6555
   239
    SDL_SendEditingText(utftext, 0, 0);
slouken@6555
   240
slouken@6555
   241
    env->ReleaseStringUTFChars(text, utftext);
slouken@6555
   242
}
slouken@6555
   243
slouken@6555
   244
slouken@6555
   245
slouken@4964
   246
slouken@4964
   247
/*******************************************************************************
slouken@4964
   248
             Functions called by SDL into Java
slouken@4964
   249
*******************************************************************************/
slouken@6284
   250
slouken@6284
   251
class LocalReferenceHolder
slouken@6284
   252
{
slouken@6284
   253
private:
slouken@6284
   254
    static int s_active;
slouken@6284
   255
slouken@6284
   256
public:
slouken@6284
   257
    static bool IsActive() {
slouken@6284
   258
        return s_active > 0;
slouken@6284
   259
    }
slouken@6284
   260
slouken@6284
   261
public:
slouken@6284
   262
    LocalReferenceHolder() : m_env(NULL) { }
slouken@6284
   263
    ~LocalReferenceHolder() {
slouken@6284
   264
        if (m_env) {
slouken@6284
   265
            m_env->PopLocalFrame(NULL);
slouken@6284
   266
            --s_active;
slouken@6284
   267
        }
slouken@6284
   268
    }
slouken@6284
   269
slouken@6284
   270
    bool init(JNIEnv *env, jint capacity = 16) {
slouken@6284
   271
        if (env->PushLocalFrame(capacity) < 0) {
slouken@6284
   272
            SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   273
            return false;
slouken@6284
   274
        }
slouken@6284
   275
        ++s_active;
slouken@6284
   276
        m_env = env;
slouken@6284
   277
        return true;
slouken@6284
   278
    }
slouken@6284
   279
slouken@6284
   280
protected:
slouken@6284
   281
    JNIEnv *m_env;
slouken@6284
   282
};
slouken@6284
   283
int LocalReferenceHolder::s_active;
slouken@6284
   284
slouken@5222
   285
extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion)
slouken@4964
   286
{
gabomdq@6354
   287
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@5222
   288
    if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) {
slouken@5222
   289
        return SDL_TRUE;
slouken@5222
   290
    } else {
slouken@5222
   291
        return SDL_FALSE;
slouken@5222
   292
    }
slouken@4964
   293
}
slouken@4964
   294
slouken@4989
   295
extern "C" void Android_JNI_SwapWindow()
slouken@4964
   296
{
gabomdq@6354
   297
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@4998
   298
    mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); 
slouken@4998
   299
}
slouken@4998
   300
slouken@4998
   301
extern "C" void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   302
{
slouken@4998
   303
    jmethodID mid;
gabomdq@6354
   304
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@4998
   305
    mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V");
slouken@4998
   306
    if (mid) {
gabomdq@6307
   307
        jstring jtitle = reinterpret_cast<jstring>(mEnv->NewStringUTF(title));
gabomdq@6307
   308
        mEnv->CallStaticVoidMethod(mActivityClass, mid, jtitle);
gabomdq@6307
   309
        mEnv->DeleteLocalRef(jtitle);
slouken@4998
   310
    }
slouken@4964
   311
}
slouken@4964
   312
slouken@6212
   313
extern "C" SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   314
{
slouken@5000
   315
    int i;
slouken@6212
   316
    SDL_bool retval = SDL_FALSE;
slouken@6212
   317
slouken@6212
   318
    if (bHasNewData) {
slouken@6212
   319
        for (i = 0; i < 3; ++i) {
slouken@6212
   320
            values[i] = fLastAccelerometer[i];
slouken@6212
   321
        }
slouken@6212
   322
        bHasNewData = false;
slouken@6212
   323
        retval = SDL_TRUE;
slouken@5000
   324
    }
slouken@6212
   325
slouken@6212
   326
    return retval;
slouken@5000
   327
}
slouken@5000
   328
gabomdq@6354
   329
static void Android_JNI_ThreadDestroyed(void* value) {
gabomdq@6354
   330
    /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
gabomdq@6354
   331
    JNIEnv *env = (JNIEnv*) value;
gabomdq@6354
   332
    if (env != NULL) {
gabomdq@6354
   333
        mJavaVM->DetachCurrentThread();
gabomdq@6354
   334
        pthread_setspecific(mThreadKey, NULL);
gabomdq@6354
   335
    }
gabomdq@6354
   336
}
gabomdq@6354
   337
gabomdq@6354
   338
JNIEnv* Android_JNI_GetEnv(void) {
gabomdq@6354
   339
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   340
     * All threads are Linux threads, scheduled by the kernel.
gabomdq@6354
   341
     * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
gabomdq@6354
   342
     * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
gabomdq@6354
   343
     * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
gabomdq@6354
   344
     * and cannot make JNI calls.
gabomdq@6354
   345
     * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
gabomdq@6354
   346
     * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
gabomdq@6354
   347
     * is a no-op.
gabomdq@6354
   348
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   349
     */
gabomdq@6354
   350
gabomdq@6354
   351
    JNIEnv *env;
gabomdq@6354
   352
    int status = mJavaVM->AttachCurrentThread(&env, NULL);
gabomdq@6354
   353
    if(status < 0) {
gabomdq@6354
   354
        LOGE("failed to attach current thread");
gabomdq@6354
   355
        return 0;
gabomdq@6354
   356
    }
gabomdq@6354
   357
gabomdq@6354
   358
    return env;
gabomdq@6354
   359
}
gabomdq@6354
   360
gabomdq@6354
   361
int Android_JNI_SetupThread(void) {
gabomdq@6354
   362
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   363
     * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
gabomdq@6354
   364
     * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
gabomdq@6354
   365
     * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
gabomdq@6354
   366
     * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
gabomdq@6354
   367
     * Note: The destructor is not called unless the stored value is != NULL
gabomdq@6354
   368
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   369
     *       (except for some lost CPU cycles)
gabomdq@6354
   370
     */
gabomdq@6354
   371
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   372
    pthread_setspecific(mThreadKey, (void*) env);
gabomdq@6354
   373
    return 1;
gabomdq@6354
   374
}
gabomdq@6354
   375
slouken@4995
   376
//
slouken@4995
   377
// Audio support
slouken@4995
   378
//
slouken@4996
   379
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   380
static jboolean audioBufferStereo = JNI_FALSE;
slouken@4996
   381
static jobject audioBuffer = NULL;
slouken@4996
   382
static void* audioBufferPinned = NULL;
slouken@4995
   383
slouken@4995
   384
extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   385
{
slouken@4996
   386
    int audioBufferFrames;
slouken@4964
   387
icculus@5996
   388
    int status;
gabomdq@6354
   389
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   390
gabomdq@6354
   391
    if (!env) {
gabomdq@6354
   392
        LOGE("callback_handler: failed to attach current thread");
icculus@5996
   393
    }
gabomdq@6354
   394
    Android_JNI_SetupThread();
icculus@5996
   395
icculus@5996
   396
    
slouken@4996
   397
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   398
    audioBuffer16Bit = is16Bit;
slouken@4996
   399
    audioBufferStereo = channelCount > 1;
slouken@4964
   400
icculus@5996
   401
    audioBuffer = env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
slouken@4995
   402
slouken@4996
   403
    if (audioBuffer == NULL) {
slouken@4996
   404
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!");
slouken@4996
   405
        return 0;
slouken@4996
   406
    }
icculus@5996
   407
    audioBuffer = env->NewGlobalRef(audioBuffer);
slouken@4995
   408
slouken@4996
   409
    jboolean isCopy = JNI_FALSE;
slouken@4996
   410
    if (audioBuffer16Bit) {
icculus@5996
   411
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   412
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   413
    } else {
icculus@5996
   414
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   415
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   416
    }
slouken@4996
   417
    if (audioBufferStereo) {
slouken@4996
   418
        audioBufferFrames /= 2;
slouken@4996
   419
    }
icculus@5996
   420
 
slouken@4996
   421
    return audioBufferFrames;
slouken@4995
   422
}
slouken@4995
   423
slouken@4996
   424
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   425
{
slouken@4996
   426
    return audioBufferPinned;
slouken@4995
   427
}
slouken@4995
   428
slouken@4996
   429
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   430
{
gabomdq@6354
   431
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   432
slouken@4996
   433
    if (audioBuffer16Bit) {
slouken@4996
   434
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   435
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   436
    } else {
slouken@4996
   437
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   438
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   439
    }
slouken@4995
   440
slouken@4996
   441
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   442
}
slouken@4995
   443
slouken@4995
   444
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   445
{
icculus@5996
   446
    int status;
gabomdq@6354
   447
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   448
icculus@5996
   449
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   450
slouken@4997
   451
    if (audioBuffer) {
icculus@5996
   452
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   453
        audioBuffer = NULL;
slouken@4997
   454
        audioBufferPinned = NULL;
slouken@4997
   455
    }
slouken@4964
   456
}
slouken@4981
   457
tim@5650
   458
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   459
static bool Android_JNI_ExceptionOccurred()
tim@5650
   460
{
slouken@6284
   461
    SDL_assert(LocalReferenceHolder::IsActive());
gabomdq@6354
   462
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   463
tim@5650
   464
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   465
    if (exception != NULL) {
tim@5650
   466
        jmethodID mid;
tim@5650
   467
tim@5650
   468
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   469
        mEnv->ExceptionClear();
tim@5650
   470
tim@5650
   471
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   472
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   473
tim@5650
   474
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   475
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   476
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   477
tim@5650
   478
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   479
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   480
tim@5650
   481
        if (exceptionMessage != NULL) {
tim@5650
   482
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   483
                    exceptionMessage, 0);
tim@5650
   484
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   485
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   486
        } else {
tim@5650
   487
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   488
        }
tim@5650
   489
tim@5650
   490
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   491
tim@5650
   492
        return true;
tim@5650
   493
    }
tim@5650
   494
tim@5650
   495
    return false;
tim@5650
   496
}
tim@5650
   497
icculus@5582
   498
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   499
{
slouken@6284
   500
    LocalReferenceHolder refs;
tim@5650
   501
    int result = 0;
tim@5650
   502
tim@5650
   503
    jmethodID mid;
tim@5650
   504
    jobject context;
tim@5650
   505
    jobject assetManager;
tim@5650
   506
    jobject inputStream;
tim@5650
   507
    jclass channels;
tim@5650
   508
    jobject readableByteChannel;
tim@5650
   509
    jstring fileNameJString;
tim@5650
   510
gabomdq@6354
   511
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   512
    if (!refs.init(mEnv)) {
tim@5650
   513
        goto failure;
tim@5650
   514
    }
tim@5650
   515
gabomdq@6308
   516
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
icculus@5582
   517
icculus@5582
   518
    // context = SDLActivity.getContext();
tim@5650
   519
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   520
            "getContext","()Landroid/content/Context;");
tim@5650
   521
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
icculus@5582
   522
icculus@5582
   523
    // assetManager = context.getAssets();
icculus@5582
   524
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   525
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   526
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   527
icculus@5582
   528
    // inputStream = assetManager.open(<filename>);
icculus@5582
   529
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
icculus@5582
   530
            "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
tim@5650
   531
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   532
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   533
        goto failure;
icculus@5582
   534
    }
icculus@5582
   535
tim@5650
   536
    ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
tim@5650
   537
icculus@5582
   538
    // Despite all the visible documentation on [Asset]InputStream claiming
icculus@5582
   539
    // that the .available() method is not guaranteed to return the entire file
icculus@5582
   540
    // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
icculus@5582
   541
    // android/apis/content/ReadAsset.java imply that Android's
icculus@5582
   542
    // AssetInputStream.available() /will/ always return the total file size
icculus@5582
   543
icculus@5582
   544
    // size = inputStream.available();
icculus@5582
   545
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   546
            "available", "()I");
icculus@5582
   547
    ctx->hidden.androidio.size = mEnv->CallIntMethod(inputStream, mid);
tim@5650
   548
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   549
        goto failure;
icculus@5582
   550
    }
icculus@5582
   551
icculus@5582
   552
    // readableByteChannel = Channels.newChannel(inputStream);
tim@5650
   553
    channels = mEnv->FindClass("java/nio/channels/Channels");
icculus@5582
   554
    mid = mEnv->GetStaticMethodID(channels,
icculus@5582
   555
            "newChannel",
icculus@5582
   556
            "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
tim@5650
   557
    readableByteChannel = mEnv->CallStaticObjectMethod(
icculus@5582
   558
            channels, mid, inputStream);
tim@5650
   559
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   560
        goto failure;
icculus@5582
   561
    }
icculus@5582
   562
tim@5650
   563
    ctx->hidden.androidio.readableByteChannelRef =
tim@5650
   564
        mEnv->NewGlobalRef(readableByteChannel);
tim@5650
   565
icculus@5582
   566
    // Store .read id for reading purposes
icculus@5582
   567
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
icculus@5582
   568
            "read", "(Ljava/nio/ByteBuffer;)I");
icculus@5582
   569
    ctx->hidden.androidio.readMethod = mid;
icculus@5582
   570
icculus@5582
   571
    ctx->hidden.androidio.position = 0;
icculus@5582
   572
tim@5650
   573
    if (false) {
tim@5650
   574
failure:
tim@5650
   575
        result = -1;
tim@5650
   576
tim@5650
   577
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   578
tim@5650
   579
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   580
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   581
        }
gabomdq@6308
   582
gabomdq@6308
   583
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   584
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   585
        }
gabomdq@6308
   586
tim@5650
   587
    }
tim@5650
   588
tim@5650
   589
    return result;
icculus@5582
   590
}
icculus@5582
   591
icculus@5582
   592
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   593
        const char* fileName, const char*)
icculus@5582
   594
{
slouken@6284
   595
    LocalReferenceHolder refs;
gabomdq@6354
   596
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   597
slouken@6284
   598
    if (!refs.init(mEnv)) {
slouken@6284
   599
        return -1;
slouken@6284
   600
    }
slouken@6284
   601
icculus@5582
   602
    if (!ctx) {
icculus@5582
   603
        return -1;
icculus@5582
   604
    }
icculus@5582
   605
icculus@5582
   606
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   607
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   608
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   609
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   610
    ctx->hidden.androidio.readMethod = NULL;
icculus@5582
   611
icculus@5582
   612
    return Android_JNI_FileOpen(ctx);
icculus@5582
   613
}
icculus@5582
   614
icculus@5582
   615
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   616
        size_t size, size_t maxnum)
icculus@5582
   617
{
slouken@6284
   618
    LocalReferenceHolder refs;
gabomdq@6377
   619
    jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6377
   620
    jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
icculus@5582
   621
    int bytesRead = 0;
icculus@5582
   622
gabomdq@6377
   623
    /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6377
   624
    if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
gabomdq@6377
   625
gabomdq@6354
   626
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   627
    if (!refs.init(mEnv)) {
slouken@6284
   628
        return -1;
slouken@6284
   629
    }
slouken@6284
   630
gabomdq@6308
   631
    jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
icculus@5582
   632
    jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
icculus@5582
   633
    jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
icculus@5582
   634
icculus@5582
   635
    while (bytesRemaining > 0) {
icculus@5582
   636
        // result = readableByteChannel.read(...);
icculus@5582
   637
        int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
icculus@5582
   638
tim@5650
   639
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   640
            return 0;
icculus@5582
   641
        }
icculus@5582
   642
icculus@5582
   643
        if (result < 0) {
icculus@5582
   644
            break;
icculus@5582
   645
        }
icculus@5582
   646
icculus@5582
   647
        bytesRemaining -= result;
icculus@5582
   648
        bytesRead += result;
icculus@5582
   649
        ctx->hidden.androidio.position += result;
icculus@5582
   650
    }
icculus@5582
   651
icculus@5582
   652
    return bytesRead / size;
icculus@5582
   653
}
icculus@5582
   654
icculus@5582
   655
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   656
        size_t size, size_t num)
icculus@5582
   657
{
icculus@5582
   658
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   659
    return 0;
icculus@5582
   660
}
icculus@5582
   661
icculus@5582
   662
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   663
{
slouken@6284
   664
    LocalReferenceHolder refs;
icculus@5582
   665
    int result = 0;
gabomdq@6354
   666
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   667
slouken@6284
   668
    if (!refs.init(mEnv)) {
slouken@6284
   669
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   670
        return -1;
slouken@6284
   671
    }
slouken@6284
   672
icculus@5582
   673
    if (ctx) {
icculus@5582
   674
        if (release) {
icculus@5582
   675
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   676
        }
icculus@5582
   677
gabomdq@6308
   678
        jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   679
icculus@5582
   680
        // inputStream.close();
icculus@5582
   681
        jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   682
                "close", "()V");
icculus@5582
   683
        mEnv->CallVoidMethod(inputStream, mid);
icculus@5582
   684
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
icculus@5582
   685
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
tim@5650
   686
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   687
            result = -1;
icculus@5582
   688
        }
icculus@5582
   689
icculus@5582
   690
        if (release) {
icculus@5582
   691
            SDL_FreeRW(ctx);
icculus@5582
   692
        }
icculus@5582
   693
    }
icculus@5582
   694
icculus@5582
   695
    return result;
icculus@5582
   696
}
icculus@5582
   697
icculus@5582
   698
slouken@6642
   699
extern "C" Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   700
{
slouken@6642
   701
    return ctx->hidden.androidio.size;
slouken@6642
   702
}
slouken@6642
   703
slouken@6642
   704
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   705
{
slouken@6642
   706
    Sint64 newPosition;
icculus@5582
   707
icculus@5582
   708
    switch (whence) {
icculus@5582
   709
        case RW_SEEK_SET:
icculus@5582
   710
            newPosition = offset;
icculus@5582
   711
            break;
icculus@5582
   712
        case RW_SEEK_CUR:
icculus@5582
   713
            newPosition = ctx->hidden.androidio.position + offset;
icculus@5582
   714
            break;
icculus@5582
   715
        case RW_SEEK_END:
icculus@5582
   716
            newPosition = ctx->hidden.androidio.size + offset;
icculus@5582
   717
            break;
icculus@5582
   718
        default:
icculus@5582
   719
            SDL_SetError("Unknown value for 'whence'");
icculus@5582
   720
            return -1;
icculus@5582
   721
    }
slouken@6642
   722
slouken@6642
   723
    /* Validate the new position */
icculus@5582
   724
    if (newPosition < 0) {
slouken@6642
   725
        SDL_Error(SDL_EFSEEK);
slouken@6642
   726
        return -1;
icculus@5582
   727
    }
icculus@5582
   728
    if (newPosition > ctx->hidden.androidio.size) {
icculus@5582
   729
        newPosition = ctx->hidden.androidio.size;
icculus@5582
   730
    }
icculus@5582
   731
slouken@6642
   732
    Sint64 movement = newPosition - ctx->hidden.androidio.position;
icculus@5582
   733
    if (movement > 0) {
tim@5993
   734
        unsigned char buffer[1024];
tim@5993
   735
icculus@5582
   736
        // The easy case where we're seeking forwards
icculus@5582
   737
        while (movement > 0) {
slouken@6642
   738
            Sint64 amount = sizeof (buffer);
icculus@5994
   739
            if (amount > movement) {
icculus@5994
   740
                amount = movement;
icculus@5994
   741
            }
icculus@5994
   742
            size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
tim@5993
   743
            if (result <= 0) {
tim@5993
   744
                // Failed to read/skip the required amount, so fail
icculus@5582
   745
                return -1;
icculus@5582
   746
            }
tim@5993
   747
tim@5993
   748
            movement -= result;
icculus@5582
   749
        }
slouken@6642
   750
icculus@5582
   751
    } else if (movement < 0) {
icculus@5582
   752
        // We can't seek backwards so we have to reopen the file and seek
icculus@5582
   753
        // forwards which obviously isn't very efficient
icculus@5582
   754
        Android_JNI_FileClose(ctx, false);
icculus@5582
   755
        Android_JNI_FileOpen(ctx);
icculus@5582
   756
        Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   757
    }
icculus@5582
   758
icculus@5582
   759
    return ctx->hidden.androidio.position;
icculus@5582
   760
}
icculus@5582
   761
icculus@5582
   762
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   763
{
icculus@5582
   764
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   765
}
icculus@5582
   766
slouken@6464
   767
// returns a new global reference which needs to be released later
slouken@6464
   768
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   769
{
slouken@6464
   770
    LocalReferenceHolder refs;
slouken@6464
   771
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6464
   772
    if (!refs.init(env)) {
slouken@6464
   773
        return NULL;
slouken@6464
   774
    }
slouken@6464
   775
slouken@6464
   776
    jstring service = env->NewStringUTF(name);
slouken@6464
   777
slouken@6464
   778
    jmethodID mid;
slouken@6464
   779
slouken@6464
   780
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6464
   781
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6464
   782
slouken@6464
   783
    mid = env->GetMethodID(mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
slouken@6464
   784
    jobject manager = env->CallObjectMethod(context, mid, service);
slouken@6464
   785
slouken@6464
   786
    env->DeleteLocalRef(service);
slouken@6464
   787
slouken@6464
   788
    return manager ? env->NewGlobalRef(manager) : NULL;
slouken@6464
   789
}
slouken@6464
   790
slouken@6464
   791
#define SETUP_CLIPBOARD(error) \
slouken@6464
   792
    LocalReferenceHolder refs; \
slouken@6464
   793
    JNIEnv* env = Android_JNI_GetEnv(); \
slouken@6464
   794
    if (!refs.init(env)) { \
slouken@6464
   795
        return error; \
slouken@6464
   796
    } \
slouken@6464
   797
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
   798
    if (!clipboard) { \
slouken@6464
   799
        return error; \
slouken@6464
   800
    }
slouken@6464
   801
slouken@6464
   802
extern "C" int Android_JNI_SetClipboardText(const char* text)
slouken@6464
   803
{
slouken@6464
   804
    SETUP_CLIPBOARD(-1)
slouken@6464
   805
slouken@6464
   806
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "setText", "(Ljava/lang/CharSequence;)V");
slouken@6464
   807
    jstring string = env->NewStringUTF(text);
slouken@6464
   808
    env->CallVoidMethod(clipboard, mid, string);
slouken@6464
   809
    env->DeleteGlobalRef(clipboard);
slouken@6464
   810
    env->DeleteLocalRef(string);
slouken@6464
   811
    return 0;
slouken@6464
   812
}
slouken@6464
   813
slouken@6464
   814
extern "C" char* Android_JNI_GetClipboardText()
slouken@6464
   815
{
slouken@6464
   816
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
   817
slouken@6464
   818
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "getText", "()Ljava/lang/CharSequence;");
slouken@6464
   819
    jobject sequence = env->CallObjectMethod(clipboard, mid);
slouken@6464
   820
    env->DeleteGlobalRef(clipboard);
slouken@6464
   821
    if (sequence) {
slouken@6464
   822
        mid = env->GetMethodID(env->GetObjectClass(sequence), "toString", "()Ljava/lang/String;");
slouken@6464
   823
        jstring string = reinterpret_cast<jstring>(env->CallObjectMethod(sequence, mid));
slouken@6464
   824
        const char* utf = env->GetStringUTFChars(string, 0);
slouken@6464
   825
        if (utf) {
slouken@6464
   826
            char* text = SDL_strdup(utf);
slouken@6464
   827
            env->ReleaseStringUTFChars(string, utf);
slouken@6464
   828
            return text;
slouken@6464
   829
        }
slouken@6464
   830
    }
slouken@6464
   831
    return SDL_strdup("");
slouken@6464
   832
}
slouken@6464
   833
slouken@6464
   834
extern "C" SDL_bool Android_JNI_HasClipboardText()
slouken@6464
   835
{
slouken@6464
   836
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
   837
slouken@6464
   838
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "hasText", "()Z");
slouken@6464
   839
    jboolean has = env->CallBooleanMethod(clipboard, mid);
slouken@6464
   840
    env->DeleteGlobalRef(clipboard);
slouken@6464
   841
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
   842
}
slouken@6464
   843
slouken@6464
   844
slouken@6448
   845
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
   846
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
   847
// returns the value in seconds and percent or -1 if not available
slouken@6448
   848
extern "C" int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
   849
{
slouken@6448
   850
    LocalReferenceHolder refs;
slouken@6448
   851
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6448
   852
    if (!refs.init(env)) {
slouken@6448
   853
        return -1;
slouken@6448
   854
    }
slouken@6448
   855
slouken@6448
   856
    jmethodID mid;
slouken@6448
   857
slouken@6448
   858
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6448
   859
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6448
   860
slouken@6448
   861
    jstring action = env->NewStringUTF("android.intent.action.BATTERY_CHANGED");
slouken@6448
   862
slouken@6448
   863
    jclass cls = env->FindClass("android/content/IntentFilter");
slouken@6448
   864
slouken@6448
   865
    mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
slouken@6448
   866
    jobject filter = env->NewObject(cls, mid, action);
slouken@6448
   867
slouken@6448
   868
    env->DeleteLocalRef(action);
slouken@6448
   869
slouken@6448
   870
    mid = env->GetMethodID(mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
slouken@6448
   871
    jobject intent = env->CallObjectMethod(context, mid, NULL, filter);
slouken@6448
   872
slouken@6448
   873
    env->DeleteLocalRef(filter);
slouken@6448
   874
slouken@6448
   875
    cls = env->GetObjectClass(intent);
slouken@6448
   876
slouken@6448
   877
    jstring iname;
slouken@6448
   878
    jmethodID imid = env->GetMethodID(cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
   879
slouken@6448
   880
#define GET_INT_EXTRA(var, key) \
slouken@6448
   881
    iname = env->NewStringUTF(key); \
slouken@6448
   882
    int var = env->CallIntMethod(intent, imid, iname, -1); \
slouken@6448
   883
    env->DeleteLocalRef(iname);
slouken@6448
   884
slouken@6448
   885
    jstring bname;
slouken@6448
   886
    jmethodID bmid = env->GetMethodID(cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
   887
slouken@6448
   888
#define GET_BOOL_EXTRA(var, key) \
slouken@6448
   889
    bname = env->NewStringUTF(key); \
slouken@6448
   890
    int var = env->CallBooleanMethod(intent, bmid, bname, JNI_FALSE); \
slouken@6448
   891
    env->DeleteLocalRef(bname);
slouken@6448
   892
slouken@6448
   893
    if (plugged) {
slouken@6448
   894
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
   895
        if (plug == -1) {
slouken@6448
   896
            return -1;
slouken@6448
   897
        }
slouken@6448
   898
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
   899
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
   900
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
   901
    }
slouken@6448
   902
slouken@6448
   903
    if (charged) {
slouken@6448
   904
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
   905
        if (status == -1) {
slouken@6448
   906
            return -1;
slouken@6448
   907
        }
slouken@6448
   908
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
   909
        *charged = (status == 5) ? 1 : 0;
slouken@6448
   910
    }
slouken@6448
   911
slouken@6448
   912
    if (battery) {
slouken@6448
   913
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
   914
        *battery = present ? 1 : 0;
slouken@6448
   915
    }
slouken@6448
   916
slouken@6448
   917
    if (seconds) {
slouken@6448
   918
        *seconds = -1; // not possible
slouken@6448
   919
    }
slouken@6448
   920
slouken@6448
   921
    if (percent) {
slouken@6448
   922
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
   923
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
   924
        if ((level == -1) || (scale == -1)) {
slouken@6448
   925
            return -1;
slouken@6448
   926
        }
slouken@6448
   927
        *percent = level * 100 / scale;
slouken@6448
   928
    }
slouken@6448
   929
slouken@6448
   930
    env->DeleteLocalRef(intent);
slouken@6448
   931
slouken@6448
   932
    return 0;
slouken@6448
   933
}
slouken@6448
   934
slouken@6392
   935
// sends message to be handled on the UI event dispatch thread
slouken@6392
   936
extern "C" int Android_JNI_SendMessage(int command, int param)
slouken@6392
   937
{
slouken@6392
   938
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
   939
    if (!env) {
slouken@6392
   940
        return -1;
slouken@6392
   941
    }
slouken@6392
   942
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "sendMessage", "(II)V");
slouken@6392
   943
    if (!mid) {
slouken@6392
   944
        return -1;
slouken@6392
   945
    }
slouken@6392
   946
    env->CallStaticVoidMethod(mActivityClass, mid, command, param);
slouken@6392
   947
    return 0;
slouken@6392
   948
}
slouken@6392
   949
slouken@6555
   950
extern "C" int Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
   951
{
slouken@6555
   952
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
   953
    if (!env) {
slouken@6555
   954
        return -1;
slouken@6555
   955
    }
slouken@6555
   956
slouken@6555
   957
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "showTextInput", "(IIII)V");
slouken@6555
   958
    if (!mid) {
slouken@6555
   959
        return -1;
slouken@6555
   960
    }
slouken@6555
   961
    env->CallStaticVoidMethod( mActivityClass, mid,
slouken@6555
   962
                               inputRect->x,
slouken@6555
   963
                               inputRect->y,
slouken@6555
   964
                               inputRect->w,
slouken@6555
   965
                               inputRect->h );
slouken@6555
   966
    return 0;
slouken@6555
   967
}
slouken@6555
   968
slouken@6555
   969
/*extern "C" int Android_JNI_HideTextInput()
slouken@6555
   970
{
slouken@6555
   971
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
   972
    if (!env) {
slouken@6555
   973
        return -1;
slouken@6555
   974
    }
slouken@6555
   975
slouken@6555
   976
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "hideTextInput", "()V");
slouken@6555
   977
    if (!mid) {
slouken@6555
   978
        return -1;
slouken@6555
   979
    }
slouken@6555
   980
    env->CallStaticVoidMethod(mActivityClass, mid);
slouken@6555
   981
    return 0;
slouken@6555
   982
}*/
slouken@6555
   983
slouken@6630
   984
//////////////////////////////////////////////////////////////////////////////
slouken@6630
   985
//
slouken@6630
   986
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
   987
//
slouken@6630
   988
slouken@6630
   989
extern "C" void *SDL_AndroidGetJNIEnv()
slouken@6630
   990
{
slouken@6630
   991
    return Android_JNI_GetEnv();
slouken@6630
   992
}
slouken@6630
   993
slouken@6630
   994
extern "C" void *SDL_AndroidGetActivity()
slouken@6630
   995
{
slouken@6630
   996
    LocalReferenceHolder refs;
slouken@6630
   997
    jmethodID mid;
slouken@6630
   998
slouken@6630
   999
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1000
    if (!refs.init(env)) {
slouken@6630
  1001
        return NULL;
slouken@6630
  1002
    }
slouken@6630
  1003
slouken@6630
  1004
    // return SDLActivity.getContext();
slouken@6630
  1005
    mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1006
            "getContext","()Landroid/content/Context;");
slouken@6630
  1007
    return env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1008
}
slouken@6630
  1009
slouken@6630
  1010
extern "C" const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1011
{
slouken@6630
  1012
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1013
slouken@6630
  1014
    if (!s_AndroidInternalFilesPath) {
slouken@6630
  1015
        LocalReferenceHolder refs;
slouken@6630
  1016
        jmethodID mid;
slouken@6630
  1017
        jobject context;
slouken@6630
  1018
        jobject fileObject;
slouken@6630
  1019
        jstring pathString;
slouken@6630
  1020
        const char *path;
slouken@6630
  1021
slouken@6630
  1022
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1023
        if (!refs.init(env)) {
slouken@6630
  1024
            return NULL;
slouken@6630
  1025
        }
slouken@6630
  1026
slouken@6630
  1027
        // context = SDLActivity.getContext();
slouken@6630
  1028
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1029
                "getContext","()Landroid/content/Context;");
slouken@6630
  1030
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1031
slouken@6630
  1032
        // fileObj = context.getFilesDir();
slouken@6630
  1033
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1034
                "getFilesDir", "()Ljava/io/File;");
slouken@6630
  1035
        fileObject = env->CallObjectMethod(context, mid);
slouken@6630
  1036
        if (!fileObject) {
slouken@6630
  1037
            SDL_SetError("Couldn't get internal directory");
slouken@6630
  1038
            return NULL;
slouken@6630
  1039
        }
slouken@6630
  1040
slouken@6630
  1041
        // path = fileObject.getAbsolutePath();
slouken@6630
  1042
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1043
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1044
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1045
slouken@6630
  1046
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1047
        s_AndroidInternalFilesPath = SDL_strdup(path);
slouken@6630
  1048
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1049
    }
slouken@6630
  1050
    return s_AndroidInternalFilesPath;
slouken@6630
  1051
}
slouken@6630
  1052
slouken@6630
  1053
extern "C" int SDL_AndroidGetExternalStorageState()
slouken@6630
  1054
{
slouken@6630
  1055
    LocalReferenceHolder refs;
slouken@6630
  1056
    jmethodID mid;
slouken@6630
  1057
    jclass cls;
slouken@6630
  1058
    jstring stateString;
slouken@6630
  1059
    const char *state;
slouken@6630
  1060
    int stateFlags;
slouken@6630
  1061
slouken@6630
  1062
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1063
    if (!refs.init(env)) {
slouken@6630
  1064
        return 0;
slouken@6630
  1065
    }
slouken@6630
  1066
slouken@6630
  1067
    cls = env->FindClass("android/os/Environment");
slouken@6630
  1068
    mid = env->GetStaticMethodID(cls,
slouken@6630
  1069
            "getExternalStorageState", "()Ljava/lang/String;");
slouken@6630
  1070
    stateString = (jstring)env->CallStaticObjectMethod(cls, mid);
slouken@6630
  1071
slouken@6630
  1072
    state = env->GetStringUTFChars(stateString, NULL);
slouken@6630
  1073
slouken@6630
  1074
    // Print an info message so people debugging know the storage state
slouken@6630
  1075
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1076
slouken@6630
  1077
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1078
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1079
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1080
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1081
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1082
    } else {
slouken@6630
  1083
        stateFlags = 0;
slouken@6630
  1084
    }
slouken@6630
  1085
    env->ReleaseStringUTFChars(stateString, state);
slouken@6630
  1086
slouken@6630
  1087
    return stateFlags;
slouken@6630
  1088
}
slouken@6630
  1089
slouken@6630
  1090
extern "C" const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1091
{
slouken@6630
  1092
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1093
slouken@6630
  1094
    if (!s_AndroidExternalFilesPath) {
slouken@6630
  1095
        LocalReferenceHolder refs;
slouken@6630
  1096
        jmethodID mid;
slouken@6630
  1097
        jobject context;
slouken@6630
  1098
        jobject fileObject;
slouken@6630
  1099
        jstring pathString;
slouken@6630
  1100
        const char *path;
slouken@6630
  1101
slouken@6630
  1102
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1103
        if (!refs.init(env)) {
slouken@6630
  1104
            return NULL;
slouken@6630
  1105
        }
slouken@6630
  1106
slouken@6630
  1107
        // context = SDLActivity.getContext();
slouken@6630
  1108
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1109
                "getContext","()Landroid/content/Context;");
slouken@6630
  1110
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1111
slouken@6630
  1112
        // fileObj = context.getExternalFilesDir();
slouken@6630
  1113
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1114
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
slouken@6630
  1115
        fileObject = env->CallObjectMethod(context, mid, NULL);
slouken@6630
  1116
        if (!fileObject) {
slouken@6630
  1117
            SDL_SetError("Couldn't get external directory");
slouken@6630
  1118
            return NULL;
slouken@6630
  1119
        }
slouken@6630
  1120
slouken@6630
  1121
        // path = fileObject.getAbsolutePath();
slouken@6630
  1122
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1123
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1124
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1125
slouken@6630
  1126
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1127
        s_AndroidExternalFilesPath = SDL_strdup(path);
slouken@6630
  1128
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1129
    }
slouken@6630
  1130
    return s_AndroidExternalFilesPath;
slouken@6630
  1131
}
slouken@6630
  1132
slouken@6044
  1133
#endif /* __ANDROID__ */
slouken@6044
  1134
slouken@4981
  1135
/* vi: set ts=4 sw=4 expandtab: */