src/core/android/SDL_android.cpp
author Sam Lantinga <slouken@libsdl.org>
Sun, 04 Nov 2012 21:53:28 -0800
changeset 6654 2ecfb25be1e2
parent 6653 b73f8ee5f033
child 6792 a15821a3471f
permissions -rw-r--r--
Synchronized the on-screen keyboard state with whether we are accepting text input.
The functions to show/hide/toggle the on-screen keyboard have been folded into the text input state.
Calling SDL_StartTextInput() will automatically show the on-screen keyboard if it's available.
Calling SDL_StopTextInput() will automatically hide the on-screen keyboard if it's available.
There is a new API function SDL_IsTextInputActive() which will return whether text input is currently active.
Text input is disabled by default, you must call SDL_StartTextInput() when you are ready to accept text input.
SDL_HasScreenKeyboardSupport() no longer needs to be passed a window.
The iPhone-specific on-screen keyboard functions have been removed.
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
             Functions called by SDL into Java
slouken@4964
   251
*******************************************************************************/
slouken@6284
   252
slouken@6284
   253
class LocalReferenceHolder
slouken@6284
   254
{
slouken@6284
   255
private:
slouken@6284
   256
    static int s_active;
slouken@6284
   257
slouken@6284
   258
public:
slouken@6284
   259
    static bool IsActive() {
slouken@6284
   260
        return s_active > 0;
slouken@6284
   261
    }
slouken@6284
   262
slouken@6284
   263
public:
slouken@6650
   264
    LocalReferenceHolder(const char *func) : m_env(NULL), m_func(func) {
slouken@6650
   265
#ifdef DEBUG_JNI
slouken@6650
   266
        SDL_Log("Entering function %s", m_func);
slouken@6650
   267
#endif
slouken@6650
   268
    }
slouken@6284
   269
    ~LocalReferenceHolder() {
slouken@6650
   270
#ifdef DEBUG_JNI
slouken@6650
   271
        SDL_Log("Leaving function %s", m_func);
slouken@6650
   272
#endif
slouken@6284
   273
        if (m_env) {
slouken@6284
   274
            m_env->PopLocalFrame(NULL);
slouken@6284
   275
            --s_active;
slouken@6284
   276
        }
slouken@6284
   277
    }
slouken@6284
   278
slouken@6284
   279
    bool init(JNIEnv *env, jint capacity = 16) {
slouken@6284
   280
        if (env->PushLocalFrame(capacity) < 0) {
slouken@6284
   281
            SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   282
            return false;
slouken@6284
   283
        }
slouken@6284
   284
        ++s_active;
slouken@6284
   285
        m_env = env;
slouken@6284
   286
        return true;
slouken@6284
   287
    }
slouken@6284
   288
slouken@6284
   289
protected:
slouken@6284
   290
    JNIEnv *m_env;
slouken@6650
   291
    const char *m_func;
slouken@6284
   292
};
slouken@6284
   293
int LocalReferenceHolder::s_active;
slouken@6284
   294
slouken@5222
   295
extern "C" SDL_bool Android_JNI_CreateContext(int majorVersion, int minorVersion)
slouken@4964
   296
{
gabomdq@6354
   297
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@5222
   298
    if (mEnv->CallStaticBooleanMethod(mActivityClass, midCreateGLContext, majorVersion, minorVersion)) {
slouken@5222
   299
        return SDL_TRUE;
slouken@5222
   300
    } else {
slouken@5222
   301
        return SDL_FALSE;
slouken@5222
   302
    }
slouken@4964
   303
}
slouken@4964
   304
slouken@4989
   305
extern "C" void Android_JNI_SwapWindow()
slouken@4964
   306
{
gabomdq@6354
   307
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@4998
   308
    mEnv->CallStaticVoidMethod(mActivityClass, midFlipBuffers); 
slouken@4998
   309
}
slouken@4998
   310
slouken@4998
   311
extern "C" void Android_JNI_SetActivityTitle(const char *title)
slouken@4998
   312
{
slouken@4998
   313
    jmethodID mid;
gabomdq@6354
   314
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@4998
   315
    mid = mEnv->GetStaticMethodID(mActivityClass,"setActivityTitle","(Ljava/lang/String;)V");
slouken@4998
   316
    if (mid) {
gabomdq@6307
   317
        jstring jtitle = reinterpret_cast<jstring>(mEnv->NewStringUTF(title));
gabomdq@6307
   318
        mEnv->CallStaticVoidMethod(mActivityClass, mid, jtitle);
gabomdq@6307
   319
        mEnv->DeleteLocalRef(jtitle);
slouken@4998
   320
    }
slouken@4964
   321
}
slouken@4964
   322
slouken@6212
   323
extern "C" SDL_bool Android_JNI_GetAccelerometerValues(float values[3])
slouken@5000
   324
{
slouken@5000
   325
    int i;
slouken@6212
   326
    SDL_bool retval = SDL_FALSE;
slouken@6212
   327
slouken@6212
   328
    if (bHasNewData) {
slouken@6212
   329
        for (i = 0; i < 3; ++i) {
slouken@6212
   330
            values[i] = fLastAccelerometer[i];
slouken@6212
   331
        }
slouken@6212
   332
        bHasNewData = false;
slouken@6212
   333
        retval = SDL_TRUE;
slouken@5000
   334
    }
slouken@6212
   335
slouken@6212
   336
    return retval;
slouken@5000
   337
}
slouken@5000
   338
gabomdq@6354
   339
static void Android_JNI_ThreadDestroyed(void* value) {
gabomdq@6354
   340
    /* The thread is being destroyed, detach it from the Java VM and set the mThreadKey value to NULL as required */
gabomdq@6354
   341
    JNIEnv *env = (JNIEnv*) value;
gabomdq@6354
   342
    if (env != NULL) {
gabomdq@6354
   343
        mJavaVM->DetachCurrentThread();
gabomdq@6354
   344
        pthread_setspecific(mThreadKey, NULL);
gabomdq@6354
   345
    }
gabomdq@6354
   346
}
gabomdq@6354
   347
gabomdq@6354
   348
JNIEnv* Android_JNI_GetEnv(void) {
gabomdq@6354
   349
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   350
     * All threads are Linux threads, scheduled by the kernel.
gabomdq@6354
   351
     * They're usually started from managed code (using Thread.start), but they can also be created elsewhere and then
gabomdq@6354
   352
     * attached to the JavaVM. For example, a thread started with pthread_create can be attached with the
gabomdq@6354
   353
     * JNI AttachCurrentThread or AttachCurrentThreadAsDaemon functions. Until a thread is attached, it has no JNIEnv,
gabomdq@6354
   354
     * and cannot make JNI calls.
gabomdq@6354
   355
     * Attaching a natively-created thread causes a java.lang.Thread object to be constructed and added to the "main"
gabomdq@6354
   356
     * ThreadGroup, making it visible to the debugger. Calling AttachCurrentThread on an already-attached thread
gabomdq@6354
   357
     * is a no-op.
gabomdq@6354
   358
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   359
     */
gabomdq@6354
   360
gabomdq@6354
   361
    JNIEnv *env;
gabomdq@6354
   362
    int status = mJavaVM->AttachCurrentThread(&env, NULL);
gabomdq@6354
   363
    if(status < 0) {
gabomdq@6354
   364
        LOGE("failed to attach current thread");
gabomdq@6354
   365
        return 0;
gabomdq@6354
   366
    }
gabomdq@6354
   367
gabomdq@6354
   368
    return env;
gabomdq@6354
   369
}
gabomdq@6354
   370
gabomdq@6354
   371
int Android_JNI_SetupThread(void) {
gabomdq@6354
   372
    /* From http://developer.android.com/guide/practices/jni.html
gabomdq@6354
   373
     * Threads attached through JNI must call DetachCurrentThread before they exit. If coding this directly is awkward,
gabomdq@6354
   374
     * in Android 2.0 (Eclair) and higher you can use pthread_key_create to define a destructor function that will be
gabomdq@6354
   375
     * called before the thread exits, and call DetachCurrentThread from there. (Use that key with pthread_setspecific
gabomdq@6354
   376
     * to store the JNIEnv in thread-local-storage; that way it'll be passed into your destructor as the argument.)
gabomdq@6354
   377
     * Note: The destructor is not called unless the stored value is != NULL
gabomdq@6354
   378
     * Note: You can call this function any number of times for the same thread, there's no harm in it
gabomdq@6354
   379
     *       (except for some lost CPU cycles)
gabomdq@6354
   380
     */
gabomdq@6354
   381
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   382
    pthread_setspecific(mThreadKey, (void*) env);
gabomdq@6354
   383
    return 1;
gabomdq@6354
   384
}
gabomdq@6354
   385
slouken@4995
   386
//
slouken@4995
   387
// Audio support
slouken@4995
   388
//
slouken@4996
   389
static jboolean audioBuffer16Bit = JNI_FALSE;
slouken@4996
   390
static jboolean audioBufferStereo = JNI_FALSE;
slouken@4996
   391
static jobject audioBuffer = NULL;
slouken@4996
   392
static void* audioBufferPinned = NULL;
slouken@4995
   393
slouken@4995
   394
extern "C" int Android_JNI_OpenAudioDevice(int sampleRate, int is16Bit, int channelCount, int desiredBufferFrames)
slouken@4964
   395
{
slouken@4996
   396
    int audioBufferFrames;
slouken@4964
   397
icculus@5996
   398
    int status;
gabomdq@6354
   399
    JNIEnv *env = Android_JNI_GetEnv();
gabomdq@6354
   400
gabomdq@6354
   401
    if (!env) {
gabomdq@6354
   402
        LOGE("callback_handler: failed to attach current thread");
icculus@5996
   403
    }
gabomdq@6354
   404
    Android_JNI_SetupThread();
icculus@5996
   405
icculus@5996
   406
    
slouken@4996
   407
    __android_log_print(ANDROID_LOG_VERBOSE, "SDL", "SDL audio: opening device");
slouken@4996
   408
    audioBuffer16Bit = is16Bit;
slouken@4996
   409
    audioBufferStereo = channelCount > 1;
slouken@4964
   410
icculus@5996
   411
    audioBuffer = env->CallStaticObjectMethod(mActivityClass, midAudioInit, sampleRate, audioBuffer16Bit, audioBufferStereo, desiredBufferFrames);
slouken@4995
   412
slouken@4996
   413
    if (audioBuffer == NULL) {
slouken@4996
   414
        __android_log_print(ANDROID_LOG_WARN, "SDL", "SDL audio: didn't get back a good audio buffer!");
slouken@4996
   415
        return 0;
slouken@4996
   416
    }
icculus@5996
   417
    audioBuffer = env->NewGlobalRef(audioBuffer);
slouken@4995
   418
slouken@4996
   419
    jboolean isCopy = JNI_FALSE;
slouken@4996
   420
    if (audioBuffer16Bit) {
icculus@5996
   421
        audioBufferPinned = env->GetShortArrayElements((jshortArray)audioBuffer, &isCopy);
icculus@5996
   422
        audioBufferFrames = env->GetArrayLength((jshortArray)audioBuffer);
slouken@4996
   423
    } else {
icculus@5996
   424
        audioBufferPinned = env->GetByteArrayElements((jbyteArray)audioBuffer, &isCopy);
icculus@5996
   425
        audioBufferFrames = env->GetArrayLength((jbyteArray)audioBuffer);
slouken@4996
   426
    }
slouken@4996
   427
    if (audioBufferStereo) {
slouken@4996
   428
        audioBufferFrames /= 2;
slouken@4996
   429
    }
icculus@5996
   430
 
slouken@4996
   431
    return audioBufferFrames;
slouken@4995
   432
}
slouken@4995
   433
slouken@4996
   434
extern "C" void * Android_JNI_GetAudioBuffer()
slouken@4995
   435
{
slouken@4996
   436
    return audioBufferPinned;
slouken@4995
   437
}
slouken@4995
   438
slouken@4996
   439
extern "C" void Android_JNI_WriteAudioBuffer()
slouken@4995
   440
{
gabomdq@6354
   441
    JNIEnv *mAudioEnv = Android_JNI_GetEnv();
gabomdq@6354
   442
slouken@4996
   443
    if (audioBuffer16Bit) {
slouken@4996
   444
        mAudioEnv->ReleaseShortArrayElements((jshortArray)audioBuffer, (jshort *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   445
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteShortBuffer, (jshortArray)audioBuffer);
slouken@4996
   446
    } else {
slouken@4996
   447
        mAudioEnv->ReleaseByteArrayElements((jbyteArray)audioBuffer, (jbyte *)audioBufferPinned, JNI_COMMIT);
slouken@4998
   448
        mAudioEnv->CallStaticVoidMethod(mActivityClass, midAudioWriteByteBuffer, (jbyteArray)audioBuffer);
slouken@4996
   449
    }
slouken@4995
   450
slouken@4996
   451
    /* JNI_COMMIT means the changes are committed to the VM but the buffer remains pinned */
slouken@4995
   452
}
slouken@4995
   453
slouken@4995
   454
extern "C" void Android_JNI_CloseAudioDevice()
slouken@4995
   455
{
icculus@5996
   456
    int status;
gabomdq@6354
   457
    JNIEnv *env = Android_JNI_GetEnv();
icculus@5996
   458
icculus@5996
   459
    env->CallStaticVoidMethod(mActivityClass, midAudioQuit); 
slouken@4964
   460
slouken@4997
   461
    if (audioBuffer) {
icculus@5996
   462
        env->DeleteGlobalRef(audioBuffer);
slouken@4997
   463
        audioBuffer = NULL;
slouken@4997
   464
        audioBufferPinned = NULL;
slouken@4997
   465
    }
slouken@4964
   466
}
slouken@4981
   467
tim@5650
   468
// Test for an exception and call SDL_SetError with its detail if one occurs
tim@5650
   469
static bool Android_JNI_ExceptionOccurred()
tim@5650
   470
{
slouken@6284
   471
    SDL_assert(LocalReferenceHolder::IsActive());
gabomdq@6354
   472
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   473
tim@5650
   474
    jthrowable exception = mEnv->ExceptionOccurred();
tim@5650
   475
    if (exception != NULL) {
tim@5650
   476
        jmethodID mid;
tim@5650
   477
tim@5650
   478
        // Until this happens most JNI operations have undefined behaviour
tim@5650
   479
        mEnv->ExceptionClear();
tim@5650
   480
tim@5650
   481
        jclass exceptionClass = mEnv->GetObjectClass(exception);
tim@5650
   482
        jclass classClass = mEnv->FindClass("java/lang/Class");
tim@5650
   483
tim@5650
   484
        mid = mEnv->GetMethodID(classClass, "getName", "()Ljava/lang/String;");
tim@5650
   485
        jstring exceptionName = (jstring)mEnv->CallObjectMethod(exceptionClass, mid);
tim@5650
   486
        const char* exceptionNameUTF8 = mEnv->GetStringUTFChars(exceptionName, 0);
tim@5650
   487
tim@5650
   488
        mid = mEnv->GetMethodID(exceptionClass, "getMessage", "()Ljava/lang/String;");
icculus@5860
   489
        jstring exceptionMessage = (jstring)mEnv->CallObjectMethod(exception, mid);
tim@5650
   490
tim@5650
   491
        if (exceptionMessage != NULL) {
tim@5650
   492
            const char* exceptionMessageUTF8 = mEnv->GetStringUTFChars(
tim@5650
   493
                    exceptionMessage, 0);
tim@5650
   494
            SDL_SetError("%s: %s", exceptionNameUTF8, exceptionMessageUTF8);
tim@5650
   495
            mEnv->ReleaseStringUTFChars(exceptionMessage, exceptionMessageUTF8);
tim@5650
   496
        } else {
tim@5650
   497
            SDL_SetError("%s", exceptionNameUTF8);
tim@5650
   498
        }
tim@5650
   499
tim@5650
   500
        mEnv->ReleaseStringUTFChars(exceptionName, exceptionNameUTF8);
tim@5650
   501
tim@5650
   502
        return true;
tim@5650
   503
    }
tim@5650
   504
tim@5650
   505
    return false;
tim@5650
   506
}
tim@5650
   507
icculus@5582
   508
static int Android_JNI_FileOpen(SDL_RWops* ctx)
icculus@5582
   509
{
slouken@6650
   510
    LocalReferenceHolder refs(__FUNCTION__);
tim@5650
   511
    int result = 0;
tim@5650
   512
tim@5650
   513
    jmethodID mid;
tim@5650
   514
    jobject context;
tim@5650
   515
    jobject assetManager;
tim@5650
   516
    jobject inputStream;
tim@5650
   517
    jclass channels;
tim@5650
   518
    jobject readableByteChannel;
tim@5650
   519
    jstring fileNameJString;
tim@5650
   520
gabomdq@6354
   521
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   522
    if (!refs.init(mEnv)) {
tim@5650
   523
        goto failure;
tim@5650
   524
    }
tim@5650
   525
gabomdq@6308
   526
    fileNameJString = (jstring)ctx->hidden.androidio.fileNameRef;
icculus@5582
   527
icculus@5582
   528
    // context = SDLActivity.getContext();
tim@5650
   529
    mid = mEnv->GetStaticMethodID(mActivityClass,
icculus@5582
   530
            "getContext","()Landroid/content/Context;");
tim@5650
   531
    context = mEnv->CallStaticObjectMethod(mActivityClass, mid);
icculus@5582
   532
icculus@5582
   533
    // assetManager = context.getAssets();
icculus@5582
   534
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(context),
tim@5650
   535
            "getAssets", "()Landroid/content/res/AssetManager;");
tim@5650
   536
    assetManager = mEnv->CallObjectMethod(context, mid);
icculus@5582
   537
icculus@5582
   538
    // inputStream = assetManager.open(<filename>);
icculus@5582
   539
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(assetManager),
icculus@5582
   540
            "open", "(Ljava/lang/String;)Ljava/io/InputStream;");
tim@5650
   541
    inputStream = mEnv->CallObjectMethod(assetManager, mid, fileNameJString);
tim@5650
   542
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   543
        goto failure;
icculus@5582
   544
    }
icculus@5582
   545
tim@5650
   546
    ctx->hidden.androidio.inputStreamRef = mEnv->NewGlobalRef(inputStream);
tim@5650
   547
icculus@5582
   548
    // Despite all the visible documentation on [Asset]InputStream claiming
icculus@5582
   549
    // that the .available() method is not guaranteed to return the entire file
icculus@5582
   550
    // size, comments in <sdk>/samples/<ver>/ApiDemos/src/com/example/ ...
icculus@5582
   551
    // android/apis/content/ReadAsset.java imply that Android's
icculus@5582
   552
    // AssetInputStream.available() /will/ always return the total file size
icculus@5582
   553
icculus@5582
   554
    // size = inputStream.available();
icculus@5582
   555
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   556
            "available", "()I");
icculus@5582
   557
    ctx->hidden.androidio.size = mEnv->CallIntMethod(inputStream, mid);
tim@5650
   558
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   559
        goto failure;
icculus@5582
   560
    }
icculus@5582
   561
icculus@5582
   562
    // readableByteChannel = Channels.newChannel(inputStream);
tim@5650
   563
    channels = mEnv->FindClass("java/nio/channels/Channels");
icculus@5582
   564
    mid = mEnv->GetStaticMethodID(channels,
icculus@5582
   565
            "newChannel",
icculus@5582
   566
            "(Ljava/io/InputStream;)Ljava/nio/channels/ReadableByteChannel;");
tim@5650
   567
    readableByteChannel = mEnv->CallStaticObjectMethod(
icculus@5582
   568
            channels, mid, inputStream);
tim@5650
   569
    if (Android_JNI_ExceptionOccurred()) {
tim@5650
   570
        goto failure;
icculus@5582
   571
    }
icculus@5582
   572
tim@5650
   573
    ctx->hidden.androidio.readableByteChannelRef =
tim@5650
   574
        mEnv->NewGlobalRef(readableByteChannel);
tim@5650
   575
icculus@5582
   576
    // Store .read id for reading purposes
icculus@5582
   577
    mid = mEnv->GetMethodID(mEnv->GetObjectClass(readableByteChannel),
icculus@5582
   578
            "read", "(Ljava/nio/ByteBuffer;)I");
icculus@5582
   579
    ctx->hidden.androidio.readMethod = mid;
icculus@5582
   580
icculus@5582
   581
    ctx->hidden.androidio.position = 0;
icculus@5582
   582
tim@5650
   583
    if (false) {
tim@5650
   584
failure:
tim@5650
   585
        result = -1;
tim@5650
   586
tim@5650
   587
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
tim@5650
   588
tim@5650
   589
        if(ctx->hidden.androidio.inputStreamRef != NULL) {
tim@5650
   590
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
tim@5650
   591
        }
gabomdq@6308
   592
gabomdq@6308
   593
        if(ctx->hidden.androidio.readableByteChannelRef != NULL) {
gabomdq@6308
   594
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
gabomdq@6308
   595
        }
gabomdq@6308
   596
tim@5650
   597
    }
tim@5650
   598
tim@5650
   599
    return result;
icculus@5582
   600
}
icculus@5582
   601
icculus@5582
   602
extern "C" int Android_JNI_FileOpen(SDL_RWops* ctx,
icculus@5582
   603
        const char* fileName, const char*)
icculus@5582
   604
{
slouken@6650
   605
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6354
   606
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   607
slouken@6284
   608
    if (!refs.init(mEnv)) {
slouken@6284
   609
        return -1;
slouken@6284
   610
    }
slouken@6284
   611
icculus@5582
   612
    if (!ctx) {
icculus@5582
   613
        return -1;
icculus@5582
   614
    }
icculus@5582
   615
icculus@5582
   616
    jstring fileNameJString = mEnv->NewStringUTF(fileName);
icculus@5582
   617
    ctx->hidden.androidio.fileNameRef = mEnv->NewGlobalRef(fileNameJString);
tim@5650
   618
    ctx->hidden.androidio.inputStreamRef = NULL;
gabomdq@6335
   619
    ctx->hidden.androidio.readableByteChannelRef = NULL;
gabomdq@6335
   620
    ctx->hidden.androidio.readMethod = NULL;
icculus@5582
   621
icculus@5582
   622
    return Android_JNI_FileOpen(ctx);
icculus@5582
   623
}
icculus@5582
   624
icculus@5582
   625
extern "C" size_t Android_JNI_FileRead(SDL_RWops* ctx, void* buffer,
icculus@5582
   626
        size_t size, size_t maxnum)
icculus@5582
   627
{
slouken@6650
   628
    LocalReferenceHolder refs(__FUNCTION__);
gabomdq@6377
   629
    jlong bytesRemaining = (jlong) (size * maxnum);
gabomdq@6377
   630
    jlong bytesMax = (jlong) (ctx->hidden.androidio.size -  ctx->hidden.androidio.position);
icculus@5582
   631
    int bytesRead = 0;
icculus@5582
   632
gabomdq@6377
   633
    /* Don't read more bytes than those that remain in the file, otherwise we get an exception */
gabomdq@6377
   634
    if (bytesRemaining >  bytesMax) bytesRemaining = bytesMax;
gabomdq@6377
   635
gabomdq@6354
   636
    JNIEnv *mEnv = Android_JNI_GetEnv();
slouken@6284
   637
    if (!refs.init(mEnv)) {
slouken@6284
   638
        return -1;
slouken@6284
   639
    }
slouken@6284
   640
gabomdq@6308
   641
    jobject readableByteChannel = (jobject)ctx->hidden.androidio.readableByteChannelRef;
icculus@5582
   642
    jmethodID readMethod = (jmethodID)ctx->hidden.androidio.readMethod;
icculus@5582
   643
    jobject byteBuffer = mEnv->NewDirectByteBuffer(buffer, bytesRemaining);
icculus@5582
   644
icculus@5582
   645
    while (bytesRemaining > 0) {
icculus@5582
   646
        // result = readableByteChannel.read(...);
icculus@5582
   647
        int result = mEnv->CallIntMethod(readableByteChannel, readMethod, byteBuffer);
icculus@5582
   648
tim@5650
   649
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   650
            return 0;
icculus@5582
   651
        }
icculus@5582
   652
icculus@5582
   653
        if (result < 0) {
icculus@5582
   654
            break;
icculus@5582
   655
        }
icculus@5582
   656
icculus@5582
   657
        bytesRemaining -= result;
icculus@5582
   658
        bytesRead += result;
icculus@5582
   659
        ctx->hidden.androidio.position += result;
icculus@5582
   660
    }
icculus@5582
   661
icculus@5582
   662
    return bytesRead / size;
icculus@5582
   663
}
icculus@5582
   664
icculus@5582
   665
extern "C" size_t Android_JNI_FileWrite(SDL_RWops* ctx, const void* buffer,
icculus@5582
   666
        size_t size, size_t num)
icculus@5582
   667
{
icculus@5582
   668
    SDL_SetError("Cannot write to Android package filesystem");
icculus@5582
   669
    return 0;
icculus@5582
   670
}
icculus@5582
   671
icculus@5582
   672
static int Android_JNI_FileClose(SDL_RWops* ctx, bool release)
icculus@5582
   673
{
slouken@6650
   674
    LocalReferenceHolder refs(__FUNCTION__);
icculus@5582
   675
    int result = 0;
gabomdq@6354
   676
    JNIEnv *mEnv = Android_JNI_GetEnv();
icculus@5582
   677
slouken@6284
   678
    if (!refs.init(mEnv)) {
slouken@6284
   679
        SDL_SetError("Failed to allocate enough JVM local references");
slouken@6284
   680
        return -1;
slouken@6284
   681
    }
slouken@6284
   682
icculus@5582
   683
    if (ctx) {
icculus@5582
   684
        if (release) {
icculus@5582
   685
            mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.fileNameRef);
icculus@5582
   686
        }
icculus@5582
   687
gabomdq@6308
   688
        jobject inputStream = (jobject)ctx->hidden.androidio.inputStreamRef;
icculus@5582
   689
icculus@5582
   690
        // inputStream.close();
icculus@5582
   691
        jmethodID mid = mEnv->GetMethodID(mEnv->GetObjectClass(inputStream),
icculus@5582
   692
                "close", "()V");
icculus@5582
   693
        mEnv->CallVoidMethod(inputStream, mid);
icculus@5582
   694
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.inputStreamRef);
icculus@5582
   695
        mEnv->DeleteGlobalRef((jobject)ctx->hidden.androidio.readableByteChannelRef);
tim@5650
   696
        if (Android_JNI_ExceptionOccurred()) {
icculus@5582
   697
            result = -1;
icculus@5582
   698
        }
icculus@5582
   699
icculus@5582
   700
        if (release) {
icculus@5582
   701
            SDL_FreeRW(ctx);
icculus@5582
   702
        }
icculus@5582
   703
    }
icculus@5582
   704
icculus@5582
   705
    return result;
icculus@5582
   706
}
icculus@5582
   707
icculus@5582
   708
slouken@6642
   709
extern "C" Sint64 Android_JNI_FileSize(SDL_RWops* ctx)
icculus@5582
   710
{
slouken@6642
   711
    return ctx->hidden.androidio.size;
slouken@6642
   712
}
slouken@6642
   713
slouken@6642
   714
extern "C" Sint64 Android_JNI_FileSeek(SDL_RWops* ctx, Sint64 offset, int whence)
slouken@6642
   715
{
slouken@6642
   716
    Sint64 newPosition;
icculus@5582
   717
icculus@5582
   718
    switch (whence) {
icculus@5582
   719
        case RW_SEEK_SET:
icculus@5582
   720
            newPosition = offset;
icculus@5582
   721
            break;
icculus@5582
   722
        case RW_SEEK_CUR:
icculus@5582
   723
            newPosition = ctx->hidden.androidio.position + offset;
icculus@5582
   724
            break;
icculus@5582
   725
        case RW_SEEK_END:
icculus@5582
   726
            newPosition = ctx->hidden.androidio.size + offset;
icculus@5582
   727
            break;
icculus@5582
   728
        default:
icculus@5582
   729
            SDL_SetError("Unknown value for 'whence'");
icculus@5582
   730
            return -1;
icculus@5582
   731
    }
slouken@6642
   732
slouken@6642
   733
    /* Validate the new position */
icculus@5582
   734
    if (newPosition < 0) {
slouken@6642
   735
        SDL_Error(SDL_EFSEEK);
slouken@6642
   736
        return -1;
icculus@5582
   737
    }
icculus@5582
   738
    if (newPosition > ctx->hidden.androidio.size) {
icculus@5582
   739
        newPosition = ctx->hidden.androidio.size;
icculus@5582
   740
    }
icculus@5582
   741
slouken@6642
   742
    Sint64 movement = newPosition - ctx->hidden.androidio.position;
icculus@5582
   743
    if (movement > 0) {
slouken@6650
   744
        unsigned char buffer[4096];
tim@5993
   745
icculus@5582
   746
        // The easy case where we're seeking forwards
icculus@5582
   747
        while (movement > 0) {
slouken@6642
   748
            Sint64 amount = sizeof (buffer);
icculus@5994
   749
            if (amount > movement) {
icculus@5994
   750
                amount = movement;
icculus@5994
   751
            }
icculus@5994
   752
            size_t result = Android_JNI_FileRead(ctx, buffer, 1, amount);
tim@5993
   753
            if (result <= 0) {
tim@5993
   754
                // Failed to read/skip the required amount, so fail
icculus@5582
   755
                return -1;
icculus@5582
   756
            }
tim@5993
   757
tim@5993
   758
            movement -= result;
icculus@5582
   759
        }
slouken@6642
   760
icculus@5582
   761
    } else if (movement < 0) {
icculus@5582
   762
        // We can't seek backwards so we have to reopen the file and seek
icculus@5582
   763
        // forwards which obviously isn't very efficient
icculus@5582
   764
        Android_JNI_FileClose(ctx, false);
icculus@5582
   765
        Android_JNI_FileOpen(ctx);
icculus@5582
   766
        Android_JNI_FileSeek(ctx, newPosition, RW_SEEK_SET);
icculus@5582
   767
    }
icculus@5582
   768
icculus@5582
   769
    return ctx->hidden.androidio.position;
icculus@5582
   770
}
icculus@5582
   771
icculus@5582
   772
extern "C" int Android_JNI_FileClose(SDL_RWops* ctx)
icculus@5582
   773
{
icculus@5582
   774
    return Android_JNI_FileClose(ctx, true);
icculus@5582
   775
}
icculus@5582
   776
slouken@6464
   777
// returns a new global reference which needs to be released later
slouken@6464
   778
static jobject Android_JNI_GetSystemServiceObject(const char* name)
slouken@6464
   779
{
slouken@6650
   780
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6464
   781
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6464
   782
    if (!refs.init(env)) {
slouken@6464
   783
        return NULL;
slouken@6464
   784
    }
slouken@6464
   785
slouken@6464
   786
    jstring service = env->NewStringUTF(name);
slouken@6464
   787
slouken@6464
   788
    jmethodID mid;
slouken@6464
   789
slouken@6464
   790
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6464
   791
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6464
   792
slouken@6464
   793
    mid = env->GetMethodID(mActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");
slouken@6464
   794
    jobject manager = env->CallObjectMethod(context, mid, service);
slouken@6464
   795
slouken@6464
   796
    env->DeleteLocalRef(service);
slouken@6464
   797
slouken@6464
   798
    return manager ? env->NewGlobalRef(manager) : NULL;
slouken@6464
   799
}
slouken@6464
   800
slouken@6464
   801
#define SETUP_CLIPBOARD(error) \
slouken@6650
   802
    LocalReferenceHolder refs(__FUNCTION__); \
slouken@6464
   803
    JNIEnv* env = Android_JNI_GetEnv(); \
slouken@6464
   804
    if (!refs.init(env)) { \
slouken@6464
   805
        return error; \
slouken@6464
   806
    } \
slouken@6464
   807
    jobject clipboard = Android_JNI_GetSystemServiceObject("clipboard"); \
slouken@6464
   808
    if (!clipboard) { \
slouken@6464
   809
        return error; \
slouken@6464
   810
    }
slouken@6464
   811
slouken@6464
   812
extern "C" int Android_JNI_SetClipboardText(const char* text)
slouken@6464
   813
{
slouken@6464
   814
    SETUP_CLIPBOARD(-1)
slouken@6464
   815
slouken@6464
   816
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "setText", "(Ljava/lang/CharSequence;)V");
slouken@6464
   817
    jstring string = env->NewStringUTF(text);
slouken@6464
   818
    env->CallVoidMethod(clipboard, mid, string);
slouken@6464
   819
    env->DeleteGlobalRef(clipboard);
slouken@6464
   820
    env->DeleteLocalRef(string);
slouken@6464
   821
    return 0;
slouken@6464
   822
}
slouken@6464
   823
slouken@6464
   824
extern "C" char* Android_JNI_GetClipboardText()
slouken@6464
   825
{
slouken@6464
   826
    SETUP_CLIPBOARD(SDL_strdup(""))
slouken@6464
   827
slouken@6464
   828
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "getText", "()Ljava/lang/CharSequence;");
slouken@6464
   829
    jobject sequence = env->CallObjectMethod(clipboard, mid);
slouken@6464
   830
    env->DeleteGlobalRef(clipboard);
slouken@6464
   831
    if (sequence) {
slouken@6464
   832
        mid = env->GetMethodID(env->GetObjectClass(sequence), "toString", "()Ljava/lang/String;");
slouken@6464
   833
        jstring string = reinterpret_cast<jstring>(env->CallObjectMethod(sequence, mid));
slouken@6464
   834
        const char* utf = env->GetStringUTFChars(string, 0);
slouken@6464
   835
        if (utf) {
slouken@6464
   836
            char* text = SDL_strdup(utf);
slouken@6464
   837
            env->ReleaseStringUTFChars(string, utf);
slouken@6464
   838
            return text;
slouken@6464
   839
        }
slouken@6464
   840
    }
slouken@6464
   841
    return SDL_strdup("");
slouken@6464
   842
}
slouken@6464
   843
slouken@6464
   844
extern "C" SDL_bool Android_JNI_HasClipboardText()
slouken@6464
   845
{
slouken@6464
   846
    SETUP_CLIPBOARD(SDL_FALSE)
slouken@6464
   847
slouken@6464
   848
    jmethodID mid = env->GetMethodID(env->GetObjectClass(clipboard), "hasText", "()Z");
slouken@6464
   849
    jboolean has = env->CallBooleanMethod(clipboard, mid);
slouken@6464
   850
    env->DeleteGlobalRef(clipboard);
slouken@6464
   851
    return has ? SDL_TRUE : SDL_FALSE;
slouken@6464
   852
}
slouken@6464
   853
slouken@6464
   854
slouken@6448
   855
// returns 0 on success or -1 on error (others undefined then)
slouken@6448
   856
// returns truthy or falsy value in plugged, charged and battery
slouken@6448
   857
// returns the value in seconds and percent or -1 if not available
slouken@6448
   858
extern "C" int Android_JNI_GetPowerInfo(int* plugged, int* charged, int* battery, int* seconds, int* percent)
slouken@6448
   859
{
slouken@6650
   860
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6448
   861
    JNIEnv* env = Android_JNI_GetEnv();
slouken@6448
   862
    if (!refs.init(env)) {
slouken@6448
   863
        return -1;
slouken@6448
   864
    }
slouken@6448
   865
slouken@6448
   866
    jmethodID mid;
slouken@6448
   867
slouken@6448
   868
    mid = env->GetStaticMethodID(mActivityClass, "getContext", "()Landroid/content/Context;");
slouken@6448
   869
    jobject context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6448
   870
slouken@6448
   871
    jstring action = env->NewStringUTF("android.intent.action.BATTERY_CHANGED");
slouken@6448
   872
slouken@6448
   873
    jclass cls = env->FindClass("android/content/IntentFilter");
slouken@6448
   874
slouken@6448
   875
    mid = env->GetMethodID(cls, "<init>", "(Ljava/lang/String;)V");
slouken@6448
   876
    jobject filter = env->NewObject(cls, mid, action);
slouken@6448
   877
slouken@6448
   878
    env->DeleteLocalRef(action);
slouken@6448
   879
slouken@6448
   880
    mid = env->GetMethodID(mActivityClass, "registerReceiver", "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;");
slouken@6448
   881
    jobject intent = env->CallObjectMethod(context, mid, NULL, filter);
slouken@6448
   882
slouken@6448
   883
    env->DeleteLocalRef(filter);
slouken@6448
   884
slouken@6448
   885
    cls = env->GetObjectClass(intent);
slouken@6448
   886
slouken@6448
   887
    jstring iname;
slouken@6448
   888
    jmethodID imid = env->GetMethodID(cls, "getIntExtra", "(Ljava/lang/String;I)I");
slouken@6448
   889
slouken@6448
   890
#define GET_INT_EXTRA(var, key) \
slouken@6448
   891
    iname = env->NewStringUTF(key); \
slouken@6448
   892
    int var = env->CallIntMethod(intent, imid, iname, -1); \
slouken@6448
   893
    env->DeleteLocalRef(iname);
slouken@6448
   894
slouken@6448
   895
    jstring bname;
slouken@6448
   896
    jmethodID bmid = env->GetMethodID(cls, "getBooleanExtra", "(Ljava/lang/String;Z)Z");
slouken@6448
   897
slouken@6448
   898
#define GET_BOOL_EXTRA(var, key) \
slouken@6448
   899
    bname = env->NewStringUTF(key); \
slouken@6448
   900
    int var = env->CallBooleanMethod(intent, bmid, bname, JNI_FALSE); \
slouken@6448
   901
    env->DeleteLocalRef(bname);
slouken@6448
   902
slouken@6448
   903
    if (plugged) {
slouken@6448
   904
        GET_INT_EXTRA(plug, "plugged") // == BatteryManager.EXTRA_PLUGGED (API 5)
slouken@6448
   905
        if (plug == -1) {
slouken@6448
   906
            return -1;
slouken@6448
   907
        }
slouken@6448
   908
        // 1 == BatteryManager.BATTERY_PLUGGED_AC
slouken@6448
   909
        // 2 == BatteryManager.BATTERY_PLUGGED_USB
slouken@6448
   910
        *plugged = (0 < plug) ? 1 : 0;
slouken@6448
   911
    }
slouken@6448
   912
slouken@6448
   913
    if (charged) {
slouken@6448
   914
        GET_INT_EXTRA(status, "status") // == BatteryManager.EXTRA_STATUS (API 5)
slouken@6448
   915
        if (status == -1) {
slouken@6448
   916
            return -1;
slouken@6448
   917
        }
slouken@6448
   918
        // 5 == BatteryManager.BATTERY_STATUS_FULL
slouken@6448
   919
        *charged = (status == 5) ? 1 : 0;
slouken@6448
   920
    }
slouken@6448
   921
slouken@6448
   922
    if (battery) {
slouken@6448
   923
        GET_BOOL_EXTRA(present, "present") // == BatteryManager.EXTRA_PRESENT (API 5)
slouken@6448
   924
        *battery = present ? 1 : 0;
slouken@6448
   925
    }
slouken@6448
   926
slouken@6448
   927
    if (seconds) {
slouken@6448
   928
        *seconds = -1; // not possible
slouken@6448
   929
    }
slouken@6448
   930
slouken@6448
   931
    if (percent) {
slouken@6448
   932
        GET_INT_EXTRA(level, "level") // == BatteryManager.EXTRA_LEVEL (API 5)
slouken@6448
   933
        GET_INT_EXTRA(scale, "scale") // == BatteryManager.EXTRA_SCALE (API 5)
slouken@6448
   934
        if ((level == -1) || (scale == -1)) {
slouken@6448
   935
            return -1;
slouken@6448
   936
        }
slouken@6448
   937
        *percent = level * 100 / scale;
slouken@6448
   938
    }
slouken@6448
   939
slouken@6448
   940
    env->DeleteLocalRef(intent);
slouken@6448
   941
slouken@6448
   942
    return 0;
slouken@6448
   943
}
slouken@6448
   944
slouken@6392
   945
// sends message to be handled on the UI event dispatch thread
slouken@6392
   946
extern "C" int Android_JNI_SendMessage(int command, int param)
slouken@6392
   947
{
slouken@6392
   948
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6392
   949
    if (!env) {
slouken@6392
   950
        return -1;
slouken@6392
   951
    }
slouken@6392
   952
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "sendMessage", "(II)V");
slouken@6392
   953
    if (!mid) {
slouken@6392
   954
        return -1;
slouken@6392
   955
    }
slouken@6392
   956
    env->CallStaticVoidMethod(mActivityClass, mid, command, param);
slouken@6392
   957
    return 0;
slouken@6392
   958
}
slouken@6392
   959
slouken@6654
   960
extern "C" void Android_JNI_ShowTextInput(SDL_Rect *inputRect)
slouken@6555
   961
{
slouken@6555
   962
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6555
   963
    if (!env) {
slouken@6654
   964
        return;
slouken@6555
   965
    }
slouken@6555
   966
slouken@6555
   967
    jmethodID mid = env->GetStaticMethodID(mActivityClass, "showTextInput", "(IIII)V");
slouken@6555
   968
    if (!mid) {
slouken@6654
   969
        return;
slouken@6555
   970
    }
slouken@6555
   971
    env->CallStaticVoidMethod( mActivityClass, mid,
slouken@6555
   972
                               inputRect->x,
slouken@6555
   973
                               inputRect->y,
slouken@6555
   974
                               inputRect->w,
slouken@6555
   975
                               inputRect->h );
slouken@6555
   976
}
slouken@6555
   977
slouken@6654
   978
extern "C" void Android_JNI_HideTextInput()
slouken@6555
   979
{
slouken@6654
   980
    // has to match Activity constant
slouken@6654
   981
    const int COMMAND_TEXTEDIT_HIDE = 3;
slouken@6654
   982
    Android_JNI_SendMessage(COMMAND_TEXTEDIT_HIDE, 0);
slouken@6654
   983
}
slouken@6555
   984
slouken@6630
   985
//////////////////////////////////////////////////////////////////////////////
slouken@6630
   986
//
slouken@6630
   987
// Functions exposed to SDL applications in SDL_system.h
slouken@6630
   988
//
slouken@6630
   989
slouken@6630
   990
extern "C" void *SDL_AndroidGetJNIEnv()
slouken@6630
   991
{
slouken@6630
   992
    return Android_JNI_GetEnv();
slouken@6630
   993
}
slouken@6630
   994
slouken@6630
   995
extern "C" void *SDL_AndroidGetActivity()
slouken@6630
   996
{
slouken@6650
   997
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
   998
    jmethodID mid;
slouken@6630
   999
slouken@6630
  1000
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1001
    if (!refs.init(env)) {
slouken@6630
  1002
        return NULL;
slouken@6630
  1003
    }
slouken@6630
  1004
slouken@6630
  1005
    // return SDLActivity.getContext();
slouken@6630
  1006
    mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1007
            "getContext","()Landroid/content/Context;");
slouken@6630
  1008
    return env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1009
}
slouken@6630
  1010
slouken@6630
  1011
extern "C" const char * SDL_AndroidGetInternalStoragePath()
slouken@6630
  1012
{
slouken@6630
  1013
    static char *s_AndroidInternalFilesPath = NULL;
slouken@6630
  1014
slouken@6630
  1015
    if (!s_AndroidInternalFilesPath) {
slouken@6650
  1016
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1017
        jmethodID mid;
slouken@6630
  1018
        jobject context;
slouken@6630
  1019
        jobject fileObject;
slouken@6630
  1020
        jstring pathString;
slouken@6630
  1021
        const char *path;
slouken@6630
  1022
slouken@6630
  1023
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1024
        if (!refs.init(env)) {
slouken@6630
  1025
            return NULL;
slouken@6630
  1026
        }
slouken@6630
  1027
slouken@6630
  1028
        // context = SDLActivity.getContext();
slouken@6630
  1029
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1030
                "getContext","()Landroid/content/Context;");
slouken@6630
  1031
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1032
slouken@6630
  1033
        // fileObj = context.getFilesDir();
slouken@6630
  1034
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1035
                "getFilesDir", "()Ljava/io/File;");
slouken@6630
  1036
        fileObject = env->CallObjectMethod(context, mid);
slouken@6630
  1037
        if (!fileObject) {
slouken@6630
  1038
            SDL_SetError("Couldn't get internal directory");
slouken@6630
  1039
            return NULL;
slouken@6630
  1040
        }
slouken@6630
  1041
slouken@6630
  1042
        // path = fileObject.getAbsolutePath();
slouken@6630
  1043
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1044
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1045
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1046
slouken@6630
  1047
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1048
        s_AndroidInternalFilesPath = SDL_strdup(path);
slouken@6630
  1049
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1050
    }
slouken@6630
  1051
    return s_AndroidInternalFilesPath;
slouken@6630
  1052
}
slouken@6630
  1053
slouken@6630
  1054
extern "C" int SDL_AndroidGetExternalStorageState()
slouken@6630
  1055
{
slouken@6650
  1056
    LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1057
    jmethodID mid;
slouken@6630
  1058
    jclass cls;
slouken@6630
  1059
    jstring stateString;
slouken@6630
  1060
    const char *state;
slouken@6630
  1061
    int stateFlags;
slouken@6630
  1062
slouken@6630
  1063
    JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1064
    if (!refs.init(env)) {
slouken@6630
  1065
        return 0;
slouken@6630
  1066
    }
slouken@6630
  1067
slouken@6630
  1068
    cls = env->FindClass("android/os/Environment");
slouken@6630
  1069
    mid = env->GetStaticMethodID(cls,
slouken@6630
  1070
            "getExternalStorageState", "()Ljava/lang/String;");
slouken@6630
  1071
    stateString = (jstring)env->CallStaticObjectMethod(cls, mid);
slouken@6630
  1072
slouken@6630
  1073
    state = env->GetStringUTFChars(stateString, NULL);
slouken@6630
  1074
slouken@6630
  1075
    // Print an info message so people debugging know the storage state
slouken@6630
  1076
    __android_log_print(ANDROID_LOG_INFO, "SDL", "external storage state: %s", state);
slouken@6630
  1077
slouken@6630
  1078
    if (SDL_strcmp(state, "mounted") == 0) {
slouken@6630
  1079
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ |
slouken@6630
  1080
                     SDL_ANDROID_EXTERNAL_STORAGE_WRITE;
slouken@6630
  1081
    } else if (SDL_strcmp(state, "mounted_ro") == 0) {
slouken@6630
  1082
        stateFlags = SDL_ANDROID_EXTERNAL_STORAGE_READ;
slouken@6630
  1083
    } else {
slouken@6630
  1084
        stateFlags = 0;
slouken@6630
  1085
    }
slouken@6630
  1086
    env->ReleaseStringUTFChars(stateString, state);
slouken@6630
  1087
slouken@6630
  1088
    return stateFlags;
slouken@6630
  1089
}
slouken@6630
  1090
slouken@6630
  1091
extern "C" const char * SDL_AndroidGetExternalStoragePath()
slouken@6630
  1092
{
slouken@6630
  1093
    static char *s_AndroidExternalFilesPath = NULL;
slouken@6630
  1094
slouken@6630
  1095
    if (!s_AndroidExternalFilesPath) {
slouken@6650
  1096
        LocalReferenceHolder refs(__FUNCTION__);
slouken@6630
  1097
        jmethodID mid;
slouken@6630
  1098
        jobject context;
slouken@6630
  1099
        jobject fileObject;
slouken@6630
  1100
        jstring pathString;
slouken@6630
  1101
        const char *path;
slouken@6630
  1102
slouken@6630
  1103
        JNIEnv *env = Android_JNI_GetEnv();
slouken@6630
  1104
        if (!refs.init(env)) {
slouken@6630
  1105
            return NULL;
slouken@6630
  1106
        }
slouken@6630
  1107
slouken@6630
  1108
        // context = SDLActivity.getContext();
slouken@6630
  1109
        mid = env->GetStaticMethodID(mActivityClass,
slouken@6630
  1110
                "getContext","()Landroid/content/Context;");
slouken@6630
  1111
        context = env->CallStaticObjectMethod(mActivityClass, mid);
slouken@6630
  1112
slouken@6630
  1113
        // fileObj = context.getExternalFilesDir();
slouken@6630
  1114
        mid = env->GetMethodID(env->GetObjectClass(context),
slouken@6630
  1115
                "getExternalFilesDir", "(Ljava/lang/String;)Ljava/io/File;");
slouken@6630
  1116
        fileObject = env->CallObjectMethod(context, mid, NULL);
slouken@6630
  1117
        if (!fileObject) {
slouken@6630
  1118
            SDL_SetError("Couldn't get external directory");
slouken@6630
  1119
            return NULL;
slouken@6630
  1120
        }
slouken@6630
  1121
slouken@6630
  1122
        // path = fileObject.getAbsolutePath();
slouken@6630
  1123
        mid = env->GetMethodID(env->GetObjectClass(fileObject),
slouken@6630
  1124
                "getAbsolutePath", "()Ljava/lang/String;");
slouken@6630
  1125
        pathString = (jstring)env->CallObjectMethod(fileObject, mid);
slouken@6630
  1126
slouken@6630
  1127
        path = env->GetStringUTFChars(pathString, NULL);
slouken@6630
  1128
        s_AndroidExternalFilesPath = SDL_strdup(path);
slouken@6630
  1129
        env->ReleaseStringUTFChars(pathString, path);
slouken@6630
  1130
    }
slouken@6630
  1131
    return s_AndroidExternalFilesPath;
slouken@6630
  1132
}
slouken@6630
  1133
slouken@6044
  1134
#endif /* __ANDROID__ */
slouken@6044
  1135
slouken@4981
  1136
/* vi: set ts=4 sw=4 expandtab: */