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