- moving to a new way of handling window changes (position, size, visibility)
[freeglut] / src / android / fg_main_android.c
index 15d31e6..ce3f585 100644 (file)
-/*
- * fg_main_android.c
- *
- * The Android-specific windows message processing methods.
- *
- * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.
- * Written by Pawel W. Olszta, <olszta@sourceforge.net>
- * Copied for Platform code by Evan Felix <karcaw at gmail.com>
- * Copyright (C) 2012  Sylvain Beucler
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the "Software"),
- * to deal in the Software without restriction, including without limitation
- * the rights to use, copy, modify, merge, publish, distribute, sublicense,
- * and/or sell copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
- * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
- * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
- * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
-#include <GL/freeglut.h>
-#include "fg_internal.h"
-#include "egl/fg_window_egl.h"
-
-#include <android/log.h>
-#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "FreeGLUT", __VA_ARGS__))
-#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "FreeGLUT", __VA_ARGS__))
-#include <android/native_app_glue/android_native_app_glue.h>
-#include <android/keycodes.h>
-
-static struct touchscreen touchscreen;
-static unsigned char key_a2fg[256];
-
-/* Cf. http://developer.android.com/reference/android/view/KeyEvent.html */
-/* These codes are missing in <android/keycodes.h> */
-/* Don't convert to enum, since it may conflict with future version of
-   that <android/keycodes.h> */
-#define AKEYCODE_FORWARD_DEL 112
-#define AKEYCODE_CTRL_LEFT 113
-#define AKEYCODE_CTRL_RIGHT 114
-#define AKEYCODE_MOVE_HOME 122
-#define AKEYCODE_MOVE_END 123
-#define AKEYCODE_INSERT 124
-#define AKEYCODE_ESCAPE 127
-#define AKEYCODE_F1 131
-#define AKEYCODE_F2 132
-#define AKEYCODE_F3 133
-#define AKEYCODE_F4 134
-#define AKEYCODE_F5 135
-#define AKEYCODE_F6 136
-#define AKEYCODE_F7 137
-#define AKEYCODE_F8 138
-#define AKEYCODE_F9 139
-#define AKEYCODE_F10 140
-#define AKEYCODE_F11 141
-#define AKEYCODE_F12 142
-
-#define EVENT_HANDLED 1
-#define EVENT_NOT_HANDLED 0
-
-/**
- * Initialize Android keycode to GLUT keycode mapping
- */
-static void key_init() {
-  memset(key_a2fg, 0, sizeof(key_a2fg));
-
-  key_a2fg[AKEYCODE_F1]  = GLUT_KEY_F1;
-  key_a2fg[AKEYCODE_F2]  = GLUT_KEY_F2;
-  key_a2fg[AKEYCODE_F3]  = GLUT_KEY_F3;
-  key_a2fg[AKEYCODE_F4]  = GLUT_KEY_F4;
-  key_a2fg[AKEYCODE_F5]  = GLUT_KEY_F5;
-  key_a2fg[AKEYCODE_F6]  = GLUT_KEY_F6;
-  key_a2fg[AKEYCODE_F7]  = GLUT_KEY_F7;
-  key_a2fg[AKEYCODE_F8]  = GLUT_KEY_F8;
-  key_a2fg[AKEYCODE_F9]  = GLUT_KEY_F9;
-  key_a2fg[AKEYCODE_F10] = GLUT_KEY_F10;
-  key_a2fg[AKEYCODE_F11] = GLUT_KEY_F11;
-  key_a2fg[AKEYCODE_F12] = GLUT_KEY_F12;
-
-  key_a2fg[AKEYCODE_PAGE_UP]   = GLUT_KEY_PAGE_UP;
-  key_a2fg[AKEYCODE_PAGE_DOWN] = GLUT_KEY_PAGE_DOWN;
-  key_a2fg[AKEYCODE_MOVE_HOME] = GLUT_KEY_HOME;
-  key_a2fg[AKEYCODE_MOVE_END]  = GLUT_KEY_END;
-  key_a2fg[AKEYCODE_INSERT]    = GLUT_KEY_INSERT;
-
-  key_a2fg[AKEYCODE_DPAD_UP]    = GLUT_KEY_UP;
-  key_a2fg[AKEYCODE_DPAD_DOWN]  = GLUT_KEY_DOWN;
-  key_a2fg[AKEYCODE_DPAD_LEFT]  = GLUT_KEY_LEFT;
-  key_a2fg[AKEYCODE_DPAD_RIGHT] = GLUT_KEY_RIGHT;
-
-  key_a2fg[AKEYCODE_ALT_LEFT]    = GLUT_KEY_ALT_L;
-  key_a2fg[AKEYCODE_ALT_RIGHT]   = GLUT_KEY_ALT_R;
-  key_a2fg[AKEYCODE_SHIFT_LEFT]  = GLUT_KEY_SHIFT_L;
-  key_a2fg[AKEYCODE_SHIFT_RIGHT] = GLUT_KEY_SHIFT_R;
-  key_a2fg[AKEYCODE_CTRL_LEFT]   = GLUT_KEY_CTRL_L;
-  key_a2fg[AKEYCODE_CTRL_RIGHT]  = GLUT_KEY_CTRL_R;
-}
-
-/**
- * Convert an Android key event to ASCII.
- */
-static unsigned char key_ascii(struct android_app* app, AInputEvent* event) {
-  int32_t code = AKeyEvent_getKeyCode(event);
-
-  /* Handle a few special cases: */
-  switch (code) {
-  case AKEYCODE_DEL:
-    return 8;
-  case AKEYCODE_FORWARD_DEL:
-    return 127;
-  case AKEYCODE_ESCAPE:
-    return 27;
-  }
-
-  /* Get usable JNI context */
-  JNIEnv* env = app->activity->env;
-  JavaVM* vm = app->activity->vm;
-  (*vm)->AttachCurrentThread(vm, &env, NULL);
-
-  jclass KeyEventClass = (*env)->FindClass(env, "android/view/KeyEvent");
-  jmethodID KeyEventConstructor = (*env)->GetMethodID(env, KeyEventClass, "<init>", "(II)V");
-  jobject keyEvent = (*env)->NewObject(env, KeyEventClass, KeyEventConstructor,
-                                      AKeyEvent_getAction(event), AKeyEvent_getKeyCode(event));
-  jmethodID KeyEvent_getUnicodeChar = (*env)->GetMethodID(env, KeyEventClass, "getUnicodeChar", "(I)I");
-  int ascii = (*env)->CallIntMethod(env, keyEvent, KeyEvent_getUnicodeChar, AKeyEvent_getMetaState(event));
-
-  /* LOGI("getUnicodeChar(%d) = %d ('%c')", AKeyEvent_getKeyCode(event), ascii, ascii); */
-  (*vm)->DetachCurrentThread(vm);
-
-  return ascii;
-}
-
-unsigned long fgPlatformSystemTime ( void )
-{
-  struct timeval now;
-  gettimeofday( &now, NULL );
-  return now.tv_usec/1000 + now.tv_sec*1000;
-}
-
-/*
- * Does the magic required to relinquish the CPU until something interesting
- * happens.
- */
-void fgPlatformSleepForEvents( long msec )
-{
-    /* Android's NativeActivity relies on a Looper/ALooper object to
-       notify about events.  The Looper object is plugged on two
-       internal pipe(2)s to detect system and input events.  Sadly you
-       can only ask the Looper for an event, not just ask whether
-       there is a pending event (and process it later).  Consequently,
-       short of redesigning NativeActivity, we cannot
-       SleepForEvents. */
-}
-
-/**
- * Process the next input event.
- */
-int32_t handle_input(struct android_app* app, AInputEvent* event) {
-  SFG_Window* window = fgWindowByHandle(app->window);
-  if (window == NULL)
-    return EVENT_NOT_HANDLED;
-
-  /* FIXME: in Android, when a key is repeated, down
-     and up events happen most often at the exact same time.  This
-     makes it impossible to animate based on key press time. */
-  /* e.g. down/up/wait/down/up rather than down/wait/down/wait/up */ 
-  /* This looks like a bug in the Android virtual keyboard system :/
-     Real buttons such as the Back button appear to work correctly
-     (series of down events with proper getRepeatCount value). */
-  
-  if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) {
-    /* LOGI("action: %d", AKeyEvent_getAction(event)); */
-    /* LOGI("keycode: %d", code); */
-    int32_t code = AKeyEvent_getKeyCode(event);
-
-    if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN) {
-      int32_t keypress = 0;
-      unsigned char ascii = 0;
-      if ((keypress = key_a2fg[code]) && FETCH_WCB(*window, Special)) {
-       INVOKE_WCB(*window, Special, (keypress, window->State.MouseX, window->State.MouseY));
-       return EVENT_HANDLED;
-      } else if ((ascii = key_ascii(app, event)) && FETCH_WCB(*window, Keyboard)) {
-       INVOKE_WCB(*window, Keyboard, (ascii, window->State.MouseX, window->State.MouseY));
-       return EVENT_HANDLED;
-      }
-    }
-    else if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) {
-      int32_t keypress = 0;
-      unsigned char ascii = 0;
-      if ((keypress = key_a2fg[code]) && FETCH_WCB(*window, Special)) {
-       INVOKE_WCB(*window, SpecialUp, (keypress, window->State.MouseX, window->State.MouseY));
-       return EVENT_HANDLED;
-      } else if ((ascii = key_ascii(app, event)) && FETCH_WCB(*window, Keyboard)) {
-       INVOKE_WCB(*window, KeyboardUp, (ascii, window->State.MouseX, window->State.MouseY));
-       return EVENT_HANDLED;
-      }
-    }
-  }
-
-  int32_t source = AInputEvent_getSource(event);
-  if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION
-      && source == AINPUT_SOURCE_TOUCHSCREEN) {
-    int32_t action = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK;
-    /* Pointer ID for clicks */
-    int32_t pidx = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
-    /* TODO: Handle multi-touch; also handle multiple sources/devices */
-    /* cf. http://sourceforge.net/mailarchive/forum.php?thread_name=20120518071314.GA28061%40perso.beuc.net&forum_name=freeglut-developer */
-    if (0) {
-      LOGI("motion action=%d index=%d source=%d", action, pidx, source);
-      int count = AMotionEvent_getPointerCount(event);
-      int i;
-      for (i = 0; i < count; i++) {
-        LOGI("multi(%d): %.01f,%.01f",
-             AMotionEvent_getPointerId(event, i),
-             AMotionEvent_getX(event, i), AMotionEvent_getY(event, i));
-      }
-    }
-    float x = AMotionEvent_getX(event, 0);
-    float y = AMotionEvent_getY(event, 0);
-
-    /* Virtual arrows PAD */
-    /* Don't interfere with existing mouse move event */
-    if (!touchscreen.in_mmotion) {
-      struct vpad_state prev_vpad = touchscreen.vpad;
-      touchscreen.vpad.left = touchscreen.vpad.right
-       = touchscreen.vpad.up = touchscreen.vpad.down = false;
-
-      /* int32_t width = ANativeWindow_getWidth(window->Window.Handle); */
-      int32_t height = ANativeWindow_getHeight(window->Window.Handle);
-      if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_MOVE) {
-       if ((x > 0 && x < 100) && (y > (height - 100) && y < height))
-         touchscreen.vpad.left = true;
-       if ((x > 200 && x < 300) && (y > (height - 100) && y < height))
-         touchscreen.vpad.right = true;
-       if ((x > 100 && x < 200) && (y > (height - 100) && y < height))
-         touchscreen.vpad.down = true;
-       if ((x > 100 && x < 200) && (y > (height - 200) && y < (height - 100)))
-         touchscreen.vpad.up = true;
-      }
-      if (action == AMOTION_EVENT_ACTION_DOWN && 
-         (touchscreen.vpad.left || touchscreen.vpad.right || touchscreen.vpad.down || touchscreen.vpad.up))
-       touchscreen.vpad.on = true;
-      if (action == AMOTION_EVENT_ACTION_UP)
-       touchscreen.vpad.on = false;
-      if (prev_vpad.left != touchscreen.vpad.left
-         || prev_vpad.right != touchscreen.vpad.right
-         || prev_vpad.up != touchscreen.vpad.up
-         || prev_vpad.down != touchscreen.vpad.down
-         || prev_vpad.on != touchscreen.vpad.on) {
-       if (FETCH_WCB(*window, Special)) {
-         if (prev_vpad.left == false && touchscreen.vpad.left == true)
-           INVOKE_WCB(*window, Special, (GLUT_KEY_LEFT, x, y));
-         else if (prev_vpad.right == false && touchscreen.vpad.right == true)
-           INVOKE_WCB(*window, Special, (GLUT_KEY_RIGHT, x, y));
-         else if (prev_vpad.up == false && touchscreen.vpad.up == true)
-           INVOKE_WCB(*window, Special, (GLUT_KEY_UP, x, y));
-         else if (prev_vpad.down == false && touchscreen.vpad.down == true)
-           INVOKE_WCB(*window, Special, (GLUT_KEY_DOWN, x, y));
-       }
-       if (FETCH_WCB(*window, SpecialUp)) {
-         if (prev_vpad.left == true && touchscreen.vpad.left == false)
-           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_LEFT, x, y));
-         if (prev_vpad.right == true && touchscreen.vpad.right == false)
-           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_RIGHT, x, y));
-         if (prev_vpad.up == true && touchscreen.vpad.up == false)
-           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_UP, x, y));
-         if (prev_vpad.down == true && touchscreen.vpad.down == false)
-           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_DOWN, x, y));
-       }
-       return EVENT_HANDLED;
-      }
-    }
-    
-    /* Normal mouse events */
-    if (!touchscreen.vpad.on) {
-      window->State.MouseX = x;
-      window->State.MouseY = y;
-      if (action == AMOTION_EVENT_ACTION_DOWN && FETCH_WCB(*window, Mouse)) {
-       touchscreen.in_mmotion = true;
-       INVOKE_WCB(*window, Mouse, (GLUT_LEFT_BUTTON, GLUT_DOWN, x, y));
-      } else if (action == AMOTION_EVENT_ACTION_UP && FETCH_WCB(*window, Mouse)) {
-       touchscreen.in_mmotion = false;
-       INVOKE_WCB(*window, Mouse, (GLUT_LEFT_BUTTON, GLUT_UP, x, y));
-      } else if (action == AMOTION_EVENT_ACTION_MOVE && FETCH_WCB(*window, Motion)) {
-       INVOKE_WCB(*window, Motion, (x, y));
-      }
-    }
-    
-    return EVENT_HANDLED;
-  }
-
-  /* Let Android handle other events (e.g. Back and Menu buttons) */
-  return EVENT_NOT_HANDLED;
-}
-
-/**
- * Process the next main command.
- */
-void handle_cmd(struct android_app* app, int32_t cmd) {
-  SFG_Window* window = fgWindowByHandle(app->window);  /* may be NULL */
-  switch (cmd) {
-  /* App life cycle, in that order: */
-  case APP_CMD_START:
-    LOGI("handle_cmd: APP_CMD_START");
-    break;
-  case APP_CMD_RESUME:
-    LOGI("handle_cmd: APP_CMD_RESUME");
-    /* Cf. fgPlatformProcessSingleEvent */
-    break;
-  case APP_CMD_INIT_WINDOW: /* surfaceCreated */
-    /* The window is being shown, get it ready. */
-    LOGI("handle_cmd: APP_CMD_INIT_WINDOW %p", app->window);
-    fgDisplay.pDisplay.single_native_window = app->window;
-    /* start|resume: glPlatformOpenWindow was waiting for Handle to be
-       defined and will now continue processing */
-    break;
-  case APP_CMD_GAINED_FOCUS:
-    LOGI("handle_cmd: APP_CMD_GAINED_FOCUS");
-    break;
-  case APP_CMD_WINDOW_RESIZED:
-    LOGI("handle_cmd: APP_CMD_WINDOW_RESIZED");
-    if (window->Window.pContext.egl.Surface != EGL_NO_SURFACE)
-      /* Make ProcessSingleEvent detect the new size, only available
-        after the next SwapBuffer */
-      glutPostRedisplay();
-    break;
-
-  case APP_CMD_SAVE_STATE: /* onSaveInstanceState */
-    /* The system has asked us to save our current state, when it
-       pauses the application without destroying it right after. */
-    app->savedState = strdup("Detect me as non-NULL on next android_main");
-    app->savedStateSize = strlen(app->savedState) + 1;
-    LOGI("handle_cmd: APP_CMD_SAVE_STATE");
-    break;
-  case APP_CMD_PAUSE:
-    LOGI("handle_cmd: APP_CMD_PAUSE");
-    /* Cf. fgPlatformProcessSingleEvent */
-    break;
-  case APP_CMD_LOST_FOCUS:
-    LOGI("handle_cmd: APP_CMD_LOST_FOCUS");
-    break;
-  case APP_CMD_TERM_WINDOW: /* surfaceDestroyed */
-    /* The application is being hidden, but may be restored */
-    LOGI("handle_cmd: APP_CMD_TERM_WINDOW");
-    fghPlatformCloseWindowEGL(window);
-    window->State.NeedToInitContext = GL_TRUE;
-    fgDisplay.pDisplay.single_native_window = NULL;
-    break;
-  case APP_CMD_STOP:
-    LOGI("handle_cmd: APP_CMD_STOP");
-    break;
-  case APP_CMD_DESTROY: /* Activity.onDestroy */
-    LOGI("handle_cmd: APP_CMD_DESTROY");
-    /* User closed the application for good, let's kill the window */
-    {
-      /* Can't use fgWindowByHandle as app->window is NULL */
-      SFG_Window* window = fgStructure.CurrentWindow;
-      if (window != NULL) {
-        fgDestroyWindow(window);
-      } else {
-        LOGI("APP_CMD_DESTROY: No current window");
-      }
-    }
-    /* glue has already set android_app->destroyRequested=1 */
-    break;
-
-  case APP_CMD_CONFIG_CHANGED:
-    /* Handle rotation / orientation change */
-    LOGI("handle_cmd: APP_CMD_CONFIG_CHANGED");
-    break;
-  case APP_CMD_LOW_MEMORY:
-    LOGI("handle_cmd: APP_CMD_LOW_MEMORY");
-    break;
-  default:
-    LOGI("handle_cmd: unhandled cmd=%d", cmd);
-  }
-}
-
-void fgPlatformOpenWindow( SFG_Window* window, const char* title,
-                           GLboolean positionUse, int x, int y,
-                           GLboolean sizeUse, int w, int h,
-                           GLboolean gameMode, GLboolean isSubWindow );
-
-void fgPlatformProcessSingleEvent ( void )
-{
-  /* When the screen is resized, the window handle still points to the
-     old window until the next SwapBuffer, while it's crucial to set
-     the size (onShape) correctly before the next onDisplay callback.
-     Plus we don't know if the next SwapBuffer already occurred at the
-     time we process the event (e.g. during onDisplay). */
-  /* So we do the check each time rather than on event. */
-  /* Interestingly, on a Samsung Galaxy S/PowerVR SGX540 GPU/Android
-     2.3, that next SwapBuffer is fake (but still necessary to get the
-     new size). */
-  SFG_Window* window = fgStructure.CurrentWindow;
-  if (window != NULL && window->Window.Handle != NULL) {
-    int32_t width = ANativeWindow_getWidth(window->Window.Handle);
-    int32_t height = ANativeWindow_getHeight(window->Window.Handle);
-    if (width != window->State.pWState.LastWidth || height != window->State.pWState.LastHeight) {
-      window->State.pWState.LastWidth = width;
-      window->State.pWState.LastHeight = height;
-      LOGI("width=%d, height=%d", width, height);
-      if( FETCH_WCB( *window, Reshape ) )
-       INVOKE_WCB( *window, Reshape, ( width, height ) );
-      else
-       glViewport( 0, 0, width, height );
-      glutPostRedisplay();
-    }
-  }
-
-  /* Read pending event. */
-  int ident;
-  int events;
-  struct android_poll_source* source;
-  /* This is called "ProcessSingleEvent" but this means we'd only
-     process ~60 (screen Hz) mouse events per second, plus other ports
-     are processing all events already.  So let's process all pending
-     events. */
-  /* if ((ident=ALooper_pollOnce(0, NULL, &events, (void**)&source)) >= 0) { */
-  while ((ident=ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0) {
-    /* Process this event. */
-    if (source != NULL) {
-      source->process(source->app, source);
-    }
-  }
-
-  /* If we're not in RESUME state, Android paused us, so wait */
-  struct android_app* app = fgDisplay.pDisplay.app;
-  if (app->destroyRequested != 1 && app->activityState != APP_CMD_RESUME) {
-      INVOKE_WCB(*window, Pause, ());
-
-    int FOREVER = -1;
-    while (app->destroyRequested != 1 && (app->activityState != APP_CMD_RESUME)) {
-      if ((ident=ALooper_pollOnce(FOREVER, NULL, &events, (void**)&source)) >= 0) {
-        /* Process this event. */
-        if (source != NULL) {
-          source->process(source->app, source);
-        }
-      }
-    }
-    /* Coming back from a pause: */
-    /* - Recreate window context and surface */
-    /* - Call user-defined hook to restore resources (textures...) */
-    /* - Exit pause looop */
-    if (app->destroyRequested != 1) {
-      /* Android is full-screen only, simplified call.. */
-      /* Ideally we'd have a fgPlatformReopenWindow() */
-      /* If we're hidden by a non-fullscreen or translucent activity,
-         we'll be paused but not stopped, and keep the current
-         surface; in which case fgPlatformOpenWindow will no-op. */
-      fgPlatformOpenWindow(window, "", GL_FALSE, 0, 0, GL_FALSE, 0, 0, GL_FALSE, GL_FALSE);
-
-      if (!FETCH_WCB(*window, InitContext))
-          fgWarning("Resuming application, but no callback to reload context resources (glutInitContextFunc)");
-    }
-
-    INVOKE_WCB(*window, Resume, ());
-  }
-}
-
-void fgPlatformMainLoopPreliminaryWork ( void )
-{
-  LOGI("fgPlatformMainLoopPreliminaryWork\n");
-
-  key_init();
-
-  /* Make sure glue isn't stripped. */
-  /* JNI entry points need to be bundled even when linking statically */
-  app_dummy();
-}
+/*\r
+ * fg_main_android.c\r
+ *\r
+ * The Android-specific windows message processing methods.\r
+ *\r
+ * Copyright (c) 1999-2000 Pawel W. Olszta. All Rights Reserved.\r
+ * Written by Pawel W. Olszta, <olszta@sourceforge.net>\r
+ * Copied for Platform code by Evan Felix <karcaw at gmail.com>\r
+ * Copyright (C) 2012  Sylvain Beucler\r
+ *\r
+ * Permission is hereby granted, free of charge, to any person obtaining a\r
+ * copy of this software and associated documentation files (the "Software"),\r
+ * to deal in the Software without restriction, including without limitation\r
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,\r
+ * and/or sell copies of the Software, and to permit persons to whom the\r
+ * Software is furnished to do so, subject to the following conditions:\r
+ *\r
+ * The above copyright notice and this permission notice shall be included\r
+ * in all copies or substantial portions of the Software.\r
+ *\r
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS\r
+ * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL\r
+ * PAWEL W. OLSZTA BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\r
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\r
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+ */\r
+\r
+#include <GL/freeglut.h>\r
+#include "fg_internal.h"\r
+#include "egl/fg_window_egl.h"\r
+\r
+#include <android/log.h>\r
+#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "FreeGLUT", __VA_ARGS__))\r
+#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "FreeGLUT", __VA_ARGS__))\r
+#include <android/native_app_glue/android_native_app_glue.h>\r
+#include <android/keycodes.h>\r
+\r
+extern void fghOnReshapeNotify(SFG_Window *window, int width, int height, GLboolean forceNotify);\r
+extern void fghOnPositionNotify(SFG_Window *window, int x, int y, GLboolean forceNotify);\r
+extern void fgPlatformFullScreenToggle( SFG_Window *win );\r
+extern void fgPlatformPositionWindow( SFG_Window *window, int x, int y );\r
+extern void fgPlatformReshapeWindow ( SFG_Window *window, int width, int height );\r
+extern void fgPlatformPushWindow( SFG_Window *window );\r
+extern void fgPlatformPopWindow( SFG_Window *window );\r
+extern void fgPlatformHideWindow( SFG_Window *window );\r
+extern void fgPlatformIconifyWindow( SFG_Window *window );\r
+extern void fgPlatformShowWindow( SFG_Window *window );\r
+\r
+static struct touchscreen touchscreen;\r
+static unsigned char key_a2fg[256];\r
+\r
+/* Cf. http://developer.android.com/reference/android/view/KeyEvent.html */\r
+/* These codes are missing in <android/keycodes.h> */\r
+/* Don't convert to enum, since it may conflict with future version of\r
+   that <android/keycodes.h> */\r
+#define AKEYCODE_FORWARD_DEL 112\r
+#define AKEYCODE_CTRL_LEFT 113\r
+#define AKEYCODE_CTRL_RIGHT 114\r
+#define AKEYCODE_MOVE_HOME 122\r
+#define AKEYCODE_MOVE_END 123\r
+#define AKEYCODE_INSERT 124\r
+#define AKEYCODE_ESCAPE 127\r
+#define AKEYCODE_F1 131\r
+#define AKEYCODE_F2 132\r
+#define AKEYCODE_F3 133\r
+#define AKEYCODE_F4 134\r
+#define AKEYCODE_F5 135\r
+#define AKEYCODE_F6 136\r
+#define AKEYCODE_F7 137\r
+#define AKEYCODE_F8 138\r
+#define AKEYCODE_F9 139\r
+#define AKEYCODE_F10 140\r
+#define AKEYCODE_F11 141\r
+#define AKEYCODE_F12 142\r
+\r
+#define EVENT_HANDLED 1\r
+#define EVENT_NOT_HANDLED 0\r
+\r
+/**\r
+ * Initialize Android keycode to GLUT keycode mapping\r
+ */\r
+static void key_init() {\r
+  memset(key_a2fg, 0, sizeof(key_a2fg));\r
+\r
+  key_a2fg[AKEYCODE_F1]  = GLUT_KEY_F1;\r
+  key_a2fg[AKEYCODE_F2]  = GLUT_KEY_F2;\r
+  key_a2fg[AKEYCODE_F3]  = GLUT_KEY_F3;\r
+  key_a2fg[AKEYCODE_F4]  = GLUT_KEY_F4;\r
+  key_a2fg[AKEYCODE_F5]  = GLUT_KEY_F5;\r
+  key_a2fg[AKEYCODE_F6]  = GLUT_KEY_F6;\r
+  key_a2fg[AKEYCODE_F7]  = GLUT_KEY_F7;\r
+  key_a2fg[AKEYCODE_F8]  = GLUT_KEY_F8;\r
+  key_a2fg[AKEYCODE_F9]  = GLUT_KEY_F9;\r
+  key_a2fg[AKEYCODE_F10] = GLUT_KEY_F10;\r
+  key_a2fg[AKEYCODE_F11] = GLUT_KEY_F11;\r
+  key_a2fg[AKEYCODE_F12] = GLUT_KEY_F12;\r
+\r
+  key_a2fg[AKEYCODE_PAGE_UP]   = GLUT_KEY_PAGE_UP;\r
+  key_a2fg[AKEYCODE_PAGE_DOWN] = GLUT_KEY_PAGE_DOWN;\r
+  key_a2fg[AKEYCODE_MOVE_HOME] = GLUT_KEY_HOME;\r
+  key_a2fg[AKEYCODE_MOVE_END]  = GLUT_KEY_END;\r
+  key_a2fg[AKEYCODE_INSERT]    = GLUT_KEY_INSERT;\r
+\r
+  key_a2fg[AKEYCODE_DPAD_UP]    = GLUT_KEY_UP;\r
+  key_a2fg[AKEYCODE_DPAD_DOWN]  = GLUT_KEY_DOWN;\r
+  key_a2fg[AKEYCODE_DPAD_LEFT]  = GLUT_KEY_LEFT;\r
+  key_a2fg[AKEYCODE_DPAD_RIGHT] = GLUT_KEY_RIGHT;\r
+\r
+  key_a2fg[AKEYCODE_ALT_LEFT]    = GLUT_KEY_ALT_L;\r
+  key_a2fg[AKEYCODE_ALT_RIGHT]   = GLUT_KEY_ALT_R;\r
+  key_a2fg[AKEYCODE_SHIFT_LEFT]  = GLUT_KEY_SHIFT_L;\r
+  key_a2fg[AKEYCODE_SHIFT_RIGHT] = GLUT_KEY_SHIFT_R;\r
+  key_a2fg[AKEYCODE_CTRL_LEFT]   = GLUT_KEY_CTRL_L;\r
+  key_a2fg[AKEYCODE_CTRL_RIGHT]  = GLUT_KEY_CTRL_R;\r
+}\r
+\r
+/**\r
+ * Convert an Android key event to ASCII.\r
+ */\r
+static unsigned char key_ascii(struct android_app* app, AInputEvent* event) {\r
+  int32_t code = AKeyEvent_getKeyCode(event);\r
+\r
+  /* Handle a few special cases: */\r
+  switch (code) {\r
+  case AKEYCODE_DEL:\r
+    return 8;\r
+  case AKEYCODE_FORWARD_DEL:\r
+    return 127;\r
+  case AKEYCODE_ESCAPE:\r
+    return 27;\r
+  }\r
+\r
+  /* Get usable JNI context */\r
+  JNIEnv* env = app->activity->env;\r
+  JavaVM* vm = app->activity->vm;\r
+  (*vm)->AttachCurrentThread(vm, &env, NULL);\r
+\r
+  jclass KeyEventClass = (*env)->FindClass(env, "android/view/KeyEvent");\r
+  jmethodID KeyEventConstructor = (*env)->GetMethodID(env, KeyEventClass, "<init>", "(II)V");\r
+  jobject keyEvent = (*env)->NewObject(env, KeyEventClass, KeyEventConstructor,\r
+                                      AKeyEvent_getAction(event), AKeyEvent_getKeyCode(event));\r
+  jmethodID KeyEvent_getUnicodeChar = (*env)->GetMethodID(env, KeyEventClass, "getUnicodeChar", "(I)I");\r
+  int ascii = (*env)->CallIntMethod(env, keyEvent, KeyEvent_getUnicodeChar, AKeyEvent_getMetaState(event));\r
+\r
+  /* LOGI("getUnicodeChar(%d) = %d ('%c')", AKeyEvent_getKeyCode(event), ascii, ascii); */\r
+  (*vm)->DetachCurrentThread(vm);\r
+\r
+  return ascii;\r
+}\r
+\r
+unsigned long fgPlatformSystemTime ( void )\r
+{\r
+  struct timeval now;\r
+  gettimeofday( &now, NULL );\r
+  return now.tv_usec/1000 + now.tv_sec*1000;\r
+}\r
+\r
+/*\r
+ * Does the magic required to relinquish the CPU until something interesting\r
+ * happens.\r
+ */\r
+void fgPlatformSleepForEvents( long msec )\r
+{\r
+    /* Android's NativeActivity relies on a Looper/ALooper object to\r
+       notify about events.  The Looper object is plugged on two\r
+       internal pipe(2)s to detect system and input events.  Sadly you\r
+       can only ask the Looper for an event, not just ask whether\r
+       there is a pending event (and process it later).  Consequently,\r
+       short of redesigning NativeActivity, we cannot\r
+       SleepForEvents. */\r
+}\r
+\r
+/**\r
+ * Process the next input event.\r
+ */\r
+int32_t handle_input(struct android_app* app, AInputEvent* event) {\r
+  SFG_Window* window = fgWindowByHandle(app->window);\r
+  if (window == NULL)\r
+    return EVENT_NOT_HANDLED;\r
+\r
+  /* FIXME: in Android, when a key is repeated, down\r
+     and up events happen most often at the exact same time.  This\r
+     makes it impossible to animate based on key press time. */\r
+  /* e.g. down/up/wait/down/up rather than down/wait/down/wait/up */ \r
+  /* This looks like a bug in the Android virtual keyboard system :/\r
+     Real buttons such as the Back button appear to work correctly\r
+     (series of down events with proper getRepeatCount value). */\r
+  \r
+  if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY) {\r
+    /* LOGI("action: %d", AKeyEvent_getAction(event)); */\r
+    /* LOGI("keycode: %d", code); */\r
+    int32_t code = AKeyEvent_getKeyCode(event);\r
+\r
+    if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_DOWN) {\r
+      int32_t keypress = 0;\r
+      unsigned char ascii = 0;\r
+      if ((keypress = key_a2fg[code]) && FETCH_WCB(*window, Special)) {\r
+       INVOKE_WCB(*window, Special, (keypress, window->State.MouseX, window->State.MouseY));\r
+       return EVENT_HANDLED;\r
+      } else if ((ascii = key_ascii(app, event)) && FETCH_WCB(*window, Keyboard)) {\r
+       INVOKE_WCB(*window, Keyboard, (ascii, window->State.MouseX, window->State.MouseY));\r
+       return EVENT_HANDLED;\r
+      }\r
+    }\r
+    else if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) {\r
+      int32_t keypress = 0;\r
+      unsigned char ascii = 0;\r
+      if ((keypress = key_a2fg[code]) && FETCH_WCB(*window, Special)) {\r
+       INVOKE_WCB(*window, SpecialUp, (keypress, window->State.MouseX, window->State.MouseY));\r
+       return EVENT_HANDLED;\r
+      } else if ((ascii = key_ascii(app, event)) && FETCH_WCB(*window, Keyboard)) {\r
+       INVOKE_WCB(*window, KeyboardUp, (ascii, window->State.MouseX, window->State.MouseY));\r
+       return EVENT_HANDLED;\r
+      }\r
+    }\r
+  }\r
+\r
+  int32_t source = AInputEvent_getSource(event);\r
+  if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION\r
+      && source == AINPUT_SOURCE_TOUCHSCREEN) {\r
+    int32_t action = AMotionEvent_getAction(event) & AMOTION_EVENT_ACTION_MASK;\r
+    /* Pointer ID for clicks */\r
+    int32_t pidx = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;\r
+    /* TODO: Handle multi-touch; also handle multiple sources/devices */\r
+    /* cf. http://sourceforge.net/mailarchive/forum.php?thread_name=20120518071314.GA28061%40perso.beuc.net&forum_name=freeglut-developer */\r
+    if (0) {\r
+      LOGI("motion action=%d index=%d source=%d", action, pidx, source);\r
+      int count = AMotionEvent_getPointerCount(event);\r
+      int i;\r
+      for (i = 0; i < count; i++) {\r
+        LOGI("multi(%d): %.01f,%.01f",\r
+             AMotionEvent_getPointerId(event, i),\r
+             AMotionEvent_getX(event, i), AMotionEvent_getY(event, i));\r
+      }\r
+    }\r
+    float x = AMotionEvent_getX(event, 0);\r
+    float y = AMotionEvent_getY(event, 0);\r
+\r
+    /* Virtual arrows PAD */\r
+    /* Don't interfere with existing mouse move event */\r
+    if (!touchscreen.in_mmotion) {\r
+      struct vpad_state prev_vpad = touchscreen.vpad;\r
+      touchscreen.vpad.left = touchscreen.vpad.right\r
+       = touchscreen.vpad.up = touchscreen.vpad.down = false;\r
+\r
+      /* int32_t width = ANativeWindow_getWidth(window->Window.Handle); */\r
+      int32_t height = ANativeWindow_getHeight(window->Window.Handle);\r
+      if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_MOVE) {\r
+       if ((x > 0 && x < 100) && (y > (height - 100) && y < height))\r
+         touchscreen.vpad.left = true;\r
+       if ((x > 200 && x < 300) && (y > (height - 100) && y < height))\r
+         touchscreen.vpad.right = true;\r
+       if ((x > 100 && x < 200) && (y > (height - 100) && y < height))\r
+         touchscreen.vpad.down = true;\r
+       if ((x > 100 && x < 200) && (y > (height - 200) && y < (height - 100)))\r
+         touchscreen.vpad.up = true;\r
+      }\r
+      if (action == AMOTION_EVENT_ACTION_DOWN && \r
+         (touchscreen.vpad.left || touchscreen.vpad.right || touchscreen.vpad.down || touchscreen.vpad.up))\r
+       touchscreen.vpad.on = true;\r
+      if (action == AMOTION_EVENT_ACTION_UP)\r
+       touchscreen.vpad.on = false;\r
+      if (prev_vpad.left != touchscreen.vpad.left\r
+         || prev_vpad.right != touchscreen.vpad.right\r
+         || prev_vpad.up != touchscreen.vpad.up\r
+         || prev_vpad.down != touchscreen.vpad.down\r
+         || prev_vpad.on != touchscreen.vpad.on) {\r
+       if (FETCH_WCB(*window, Special)) {\r
+         if (prev_vpad.left == false && touchscreen.vpad.left == true)\r
+           INVOKE_WCB(*window, Special, (GLUT_KEY_LEFT, x, y));\r
+         else if (prev_vpad.right == false && touchscreen.vpad.right == true)\r
+           INVOKE_WCB(*window, Special, (GLUT_KEY_RIGHT, x, y));\r
+         else if (prev_vpad.up == false && touchscreen.vpad.up == true)\r
+           INVOKE_WCB(*window, Special, (GLUT_KEY_UP, x, y));\r
+         else if (prev_vpad.down == false && touchscreen.vpad.down == true)\r
+           INVOKE_WCB(*window, Special, (GLUT_KEY_DOWN, x, y));\r
+       }\r
+       if (FETCH_WCB(*window, SpecialUp)) {\r
+         if (prev_vpad.left == true && touchscreen.vpad.left == false)\r
+           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_LEFT, x, y));\r
+         if (prev_vpad.right == true && touchscreen.vpad.right == false)\r
+           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_RIGHT, x, y));\r
+         if (prev_vpad.up == true && touchscreen.vpad.up == false)\r
+           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_UP, x, y));\r
+         if (prev_vpad.down == true && touchscreen.vpad.down == false)\r
+           INVOKE_WCB(*window, SpecialUp, (GLUT_KEY_DOWN, x, y));\r
+       }\r
+       return EVENT_HANDLED;\r
+      }\r
+    }\r
+    \r
+    /* Normal mouse events */\r
+    if (!touchscreen.vpad.on) {\r
+      window->State.MouseX = x;\r
+      window->State.MouseY = y;\r
+      if (action == AMOTION_EVENT_ACTION_DOWN && FETCH_WCB(*window, Mouse)) {\r
+       touchscreen.in_mmotion = true;\r
+       INVOKE_WCB(*window, Mouse, (GLUT_LEFT_BUTTON, GLUT_DOWN, x, y));\r
+      } else if (action == AMOTION_EVENT_ACTION_UP && FETCH_WCB(*window, Mouse)) {\r
+       touchscreen.in_mmotion = false;\r
+       INVOKE_WCB(*window, Mouse, (GLUT_LEFT_BUTTON, GLUT_UP, x, y));\r
+      } else if (action == AMOTION_EVENT_ACTION_MOVE && FETCH_WCB(*window, Motion)) {\r
+       INVOKE_WCB(*window, Motion, (x, y));\r
+      }\r
+    }\r
+    \r
+    return EVENT_HANDLED;\r
+  }\r
+\r
+  /* Let Android handle other events (e.g. Back and Menu buttons) */\r
+  return EVENT_NOT_HANDLED;\r
+}\r
+\r
+/**\r
+ * Process the next main command.\r
+ */\r
+void handle_cmd(struct android_app* app, int32_t cmd) {\r
+  SFG_Window* window = fgWindowByHandle(app->window);  /* may be NULL */\r
+  switch (cmd) {\r
+  /* App life cycle, in that order: */\r
+  case APP_CMD_START:\r
+    LOGI("handle_cmd: APP_CMD_START");\r
+    break;\r
+  case APP_CMD_RESUME:\r
+    LOGI("handle_cmd: APP_CMD_RESUME");\r
+    /* Cf. fgPlatformProcessSingleEvent */\r
+    break;\r
+  case APP_CMD_INIT_WINDOW: /* surfaceCreated */\r
+    /* The window is being shown, get it ready. */\r
+    LOGI("handle_cmd: APP_CMD_INIT_WINDOW %p", app->window);\r
+    fgDisplay.pDisplay.single_native_window = app->window;\r
+    window->State.WorkMask |= GLUT_INIT_WORK;\r
+    /* start|resume: glPlatformOpenWindow was waiting for Handle to be\r
+       defined and will now continue processing */\r
+    break;\r
+  case APP_CMD_GAINED_FOCUS:\r
+    LOGI("handle_cmd: APP_CMD_GAINED_FOCUS");\r
+    break;\r
+  case APP_CMD_WINDOW_RESIZED:\r
+    LOGI("handle_cmd: APP_CMD_WINDOW_RESIZED");\r
+    if (window->Window.pContext.egl.Surface != EGL_NO_SURFACE)\r
+      /* Make ProcessSingleEvent detect the new size, only available\r
+        after the next SwapBuffer */\r
+      glutPostRedisplay();\r
+    break;\r
+\r
+  case APP_CMD_SAVE_STATE: /* onSaveInstanceState */\r
+    /* The system has asked us to save our current state, when it\r
+       pauses the application without destroying it right after. */\r
+    app->savedState = strdup("Detect me as non-NULL on next android_main");\r
+    app->savedStateSize = strlen(app->savedState) + 1;\r
+    LOGI("handle_cmd: APP_CMD_SAVE_STATE");\r
+    break;\r
+  case APP_CMD_PAUSE:\r
+    LOGI("handle_cmd: APP_CMD_PAUSE");\r
+    /* Cf. fgPlatformProcessSingleEvent */\r
+    break;\r
+  case APP_CMD_LOST_FOCUS:\r
+    LOGI("handle_cmd: APP_CMD_LOST_FOCUS");\r
+    break;\r
+  case APP_CMD_TERM_WINDOW: /* surfaceDestroyed */\r
+    /* The application is being hidden, but may be restored */\r
+    LOGI("handle_cmd: APP_CMD_TERM_WINDOW");\r
+    fghPlatformCloseWindowEGL(window);\r
+    fgDisplay.pDisplay.single_native_window = NULL;\r
+    break;\r
+  case APP_CMD_STOP:\r
+    LOGI("handle_cmd: APP_CMD_STOP");\r
+    break;\r
+  case APP_CMD_DESTROY: /* Activity.onDestroy */\r
+    LOGI("handle_cmd: APP_CMD_DESTROY");\r
+    /* User closed the application for good, let's kill the window */\r
+    {\r
+      /* Can't use fgWindowByHandle as app->window is NULL */\r
+      SFG_Window* window = fgStructure.CurrentWindow;\r
+      if (window != NULL) {\r
+        fgDestroyWindow(window);\r
+      } else {\r
+        LOGI("APP_CMD_DESTROY: No current window");\r
+      }\r
+    }\r
+    /* glue has already set android_app->destroyRequested=1 */\r
+    break;\r
+\r
+  case APP_CMD_CONFIG_CHANGED:\r
+    /* Handle rotation / orientation change */\r
+    LOGI("handle_cmd: APP_CMD_CONFIG_CHANGED");\r
+    break;\r
+  case APP_CMD_LOW_MEMORY:\r
+    LOGI("handle_cmd: APP_CMD_LOW_MEMORY");\r
+    break;\r
+  default:\r
+    LOGI("handle_cmd: unhandled cmd=%d", cmd);\r
+  }\r
+}\r
+\r
+void fgPlatformOpenWindow( SFG_Window* window, const char* title,\r
+                           GLboolean positionUse, int x, int y,\r
+                           GLboolean sizeUse, int w, int h,\r
+                           GLboolean gameMode, GLboolean isSubWindow );\r
+\r
+void fgPlatformProcessSingleEvent ( void )\r
+{\r
+  /* When the screen is resized, the window handle still points to the\r
+     old window until the next SwapBuffer, while it's crucial to set\r
+     the size (onShape) correctly before the next onDisplay callback.\r
+     Plus we don't know if the next SwapBuffer already occurred at the\r
+     time we process the event (e.g. during onDisplay). */\r
+  /* So we do the check each time rather than on event. */\r
+  /* Interestingly, on a Samsung Galaxy S/PowerVR SGX540 GPU/Android\r
+     2.3, that next SwapBuffer is fake (but still necessary to get the\r
+     new size). */\r
+  SFG_Window* window = fgStructure.CurrentWindow;\r
+  if (window != NULL && window->Window.Handle != NULL) {\r
+    int32_t width = ANativeWindow_getWidth(window->Window.Handle);\r
+    int32_t height = ANativeWindow_getHeight(window->Window.Handle);\r
+    fghOnReshapeNotify(width,height);\r
+  }\r
+\r
+  /* Read pending event. */\r
+  int ident;\r
+  int events;\r
+  struct android_poll_source* source;\r
+  /* This is called "ProcessSingleEvent" but this means we'd only\r
+     process ~60 (screen Hz) mouse events per second, plus other ports\r
+     are processing all events already.  So let's process all pending\r
+     events. */\r
+  /* if ((ident=ALooper_pollOnce(0, NULL, &events, (void**)&source)) >= 0) { */\r
+  while ((ident=ALooper_pollAll(0, NULL, &events, (void**)&source)) >= 0) {\r
+    /* Process this event. */\r
+    if (source != NULL) {\r
+      source->process(source->app, source);\r
+    }\r
+  }\r
+\r
+  /* If we're not in RESUME state, Android paused us, so wait */\r
+  struct android_app* app = fgDisplay.pDisplay.app;\r
+  if (app->destroyRequested != 1 && app->activityState != APP_CMD_RESUME) {\r
+      INVOKE_WCB(*window, Pause, ());\r
+\r
+    int FOREVER = -1;\r
+    while (app->destroyRequested != 1 && (app->activityState != APP_CMD_RESUME)) {\r
+      if ((ident=ALooper_pollOnce(FOREVER, NULL, &events, (void**)&source)) >= 0) {\r
+        /* Process this event. */\r
+        if (source != NULL) {\r
+          source->process(source->app, source);\r
+        }\r
+      }\r
+    }\r
+    /* Coming back from a pause: */\r
+    /* - Recreate window context and surface */\r
+    /* - Call user-defined hook to restore resources (textures...) */\r
+    /* - Exit pause loop */\r
+    if (app->destroyRequested != 1) {\r
+      /* Android is full-screen only, simplified call.. */\r
+      /* Ideally we'd have a fgPlatformReopenWindow() */\r
+      /* If we're hidden by a non-fullscreen or translucent activity,\r
+         we'll be paused but not stopped, and keep the current\r
+         surface; in which case fgPlatformOpenWindow will no-op. */\r
+      fgPlatformOpenWindow(window, "", GL_FALSE, 0, 0, GL_FALSE, 0, 0, GL_FALSE, GL_FALSE);\r
+\r
+      /* TODO: should there be a whole GLUT_INIT_WORK forced? probably...\r
+       * Could queue that up in APP_CMD_TERM_WINDOW handler, but it'll\r
+       * be not possible to ensure InitContext CB gets called before\r
+       * Resume CB like that.. so maybe just force calling initContext CB\r
+       * here is best. Or we could force work on the window in question..\r
+       * 1) save old work mask, 2) set mask to init only, 3) call fgPlatformProcessWork directly\r
+       * 4) set work mask back to the one saved in step 1.\r
+       */\r
+      if (!FETCH_WCB(*window, InitContext))\r
+          fgWarning("Resuming application, but no callback to reload context resources (glutInitContextFunc)");\r
+    }\r
+\r
+    INVOKE_WCB(*window, Resume, ());\r
+  }\r
+}\r
+\r
+void fgPlatformMainLoopPreliminaryWork ( void )\r
+{\r
+  LOGI("fgPlatformMainLoopPreliminaryWork\n");\r
+\r
+  key_init();\r
+\r
+  /* Make sure glue isn't stripped. */\r
+  /* JNI entry points need to be bundled even when linking statically */\r
+  app_dummy();\r
+}\r
+\r
+\r
+/* Step through the work list */\r
+void fgPlatformProcessWork(SFG_Window *window)\r
+{\r
+    unsigned int workMask = window->State.WorkMask;\r
+    /* Now clear it so that any callback generated by the actions below can set work again */\r
+    window->State.WorkMask = 0;\r
+\r
+    /* This is before the first display callback: call a few callbacks to inform user of window size, position, etc\r
+     * we know this is before the first display callback of a window as for all windows GLUT_INIT_WORK is set when\r
+     * they are opened, and work is done before displaying in the mainloop.\r
+     */\r
+    if (workMask & GLUT_INIT_WORK)\r
+    {\r
+        /* notify windowStatus/visibility */\r
+        INVOKE_WCB( *window, WindowStatus, ( GLUT_FULLY_RETAINED ) );\r
+\r
+        /* Position callback, always at 0,0 */\r
+        fghOnPositionNotify(window, 0, 0, GL_TRUE);\r
+\r
+        /* Size gets notified on window creation with size detection in mainloop above\r
+         * XXX CHECK: does this messages happen too early like on windows,\r
+         * so client code cannot have registered a callback yet and the message\r
+         * is thus never received by client?\r
+         */\r
+\r
+        /* Call init context callback */\r
+        INVOKE_WCB( *window, InitContext, ());\r
+\r
+        /* Lastly, check if we have a display callback, error out if not\r
+         * This is the right place to do it, as the redisplay will be\r
+         * next right after we exit this function, so there is no more\r
+         * opportunity for the user to register a callback for this window.\r
+         */\r
+        if (!FETCH_WCB(*window, Display))\r
+            fgError ( "ERROR:  No display callback registered for window %d\n", window->ID );\r
+    }\r
+\r
+    if (workMask & GLUT_FULL_SCREEN_WORK)\r
+        fgPlatformFullScreenToggle( window );\r
+    if (workMask & GLUT_POSITION_WORK)\r
+        fgPlatformPositionWindow( window, window->State.DesiredXpos, window->State.DesiredYpos );\r
+    if (workMask & GLUT_SIZE_WORK)\r
+        fgPlatformReshapeWindow ( window, window->State.DesiredWidth, window->State.DesiredHeight );\r
+    if (workMask & GLUT_ZORDER_WORK)\r
+    {\r
+        if (window->State.DesiredZOrder < 0)\r
+            fgPlatformPushWindow( window );\r
+        else\r
+            fgPlatformPopWindow( window );\r
+    }\r
+\r
+    if (workMask & GLUT_VISIBILITY_WORK)\r
+    {\r
+        /* Visibility status of window should get updated in the window message handlers\r
+         * For now, none of these functions called below do anything, so don't worry\r
+         * about it\r
+         */\r
+        SFG_Window *win = window;\r
+        switch (window->State.DesiredVisibility)\r
+        {\r
+        case DesireHiddenState:\r
+            fgPlatformHideWindow( window );\r
+            break;\r
+        case DesireIconicState:\r
+            /* Call on top-level window */\r
+            while (win->Parent)\r
+                win = win->Parent;\r
+            fgPlatformIconifyWindow( win );\r
+            break;\r
+        case DesireNormalState:\r
+            fgPlatformShowWindow( window );\r
+            break;\r
+        }\r
+    }\r
+}\r
+\r