Initial work to make android STK use SDL2 completely

This commit is contained in:
Benau 2020-07-12 08:25:06 +08:00
parent ddd4b8b9c9
commit 8cc4dd3383
36 changed files with 554 additions and 3669 deletions

View File

@ -175,8 +175,7 @@ include $(CLEAR_VARS)
LOCAL_MODULE := irrlicht
LOCAL_PATH := .
LOCAL_CPP_FEATURES += rtti
LOCAL_SRC_FILES := $(wildcard ../lib/irrlicht/source/Irrlicht/*.cpp) \
../lib/irrlicht/source/Irrlicht/stk_android_native_app_glue.c
LOCAL_SRC_FILES := $(wildcard ../lib/irrlicht/source/Irrlicht/*.cpp)
LOCAL_CFLAGS := -I../lib/irrlicht/source/Irrlicht/ \
-I../lib/irrlicht/include/ \
-I../src \
@ -184,6 +183,7 @@ LOCAL_CFLAGS := -I../lib/irrlicht/source/Irrlicht/ \
-Iobj/libpng/ \
-Iobj/zlib/ \
-I../lib/sdl2/include/ \
-DMOBILE_STK \
-DANDROID_PACKAGE_CALLBACK_NAME=$(PACKAGE_CALLBACK_NAME)
LOCAL_CPPFLAGS := -std=gnu++0x
LOCAL_STATIC_LIBRARIES := libjpeg png zlib

View File

@ -10,7 +10,7 @@
android:banner="@drawable/banner"
android:hasCode="true"
android:isGame="true"
android:theme="@android:style/Theme.DeviceDefault.NoActionBar.TranslucentDecor"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:hardwareAccelerated="true"
android:resizeableActivity="false">
@ -20,10 +20,6 @@
android:configChanges="fontScale|keyboard|keyboardHidden|layoutDirection|locale|mcc|mnc|navigation|orientation|screenLayout|screenSize|uiMode"
android:screenOrientation="sensorLandscape">
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="android.app.lib_name"
android:value="main" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

View File

@ -668,11 +668,15 @@ if [ $RUN_OPTIMIZE_SCRIPT -gt 0 ]; then
fi
# Generate directories list
echo "Generate directories list"
find "$OUTPUT_PATH"/* -type d | sort > "$OUTPUT_PATH/directories.txt"
sed -i s/".\/$OUTPUT_PATH\/"// "$OUTPUT_PATH/directories.txt"
sed -i s/"$OUTPUT_PATH\/"// "$OUTPUT_PATH/directories.txt"
# Generate files list
echo "Generate files list"
find "$OUTPUT_PATH"/* -type d| sort > tmp1.txt
sed -i 's/$/\//' tmp1.txt
find "$OUTPUT_PATH"/* -type f| sort > tmp2.txt
cat tmp1.txt tmp2.txt | sort > "$OUTPUT_PATH/files.txt"
rm tmp1.txt tmp2.txt
sed -i s/".\/$OUTPUT_PATH\/"// "$OUTPUT_PATH/files.txt"
sed -i s/"$OUTPUT_PATH\/"// "$OUTPUT_PATH/files.txt"
# A file that can be used to check if apk has assets
echo "has_assets" > "$OUTPUT_PATH/has_assets.txt"

View File

@ -568,11 +568,14 @@ cp -f "$DIRNAME/../lib/sdl2/android-project/app/src/main/java/org/libsdl/app/HID
"$DIRNAME/src/main/java/"
cp -f "$DIRNAME/../lib/sdl2/android-project/app/src/main/java/org/libsdl/app/HIDDeviceUSB.java" \
"$DIRNAME/src/main/java/"
cp -f "$DIRNAME/../lib/sdl2/android-project/app/src/main/java/org/libsdl/app/SDLActivity.java" \
"$DIRNAME/src/main/java/"
cp -f "$DIRNAME/../lib/sdl2/android-project/app/src/main/java/org/libsdl/app/SDLAudioManager.java" \
"$DIRNAME/src/main/java/"
cp -f "$DIRNAME/../lib/sdl2/android-project/app/src/main/java/org/libsdl/app/SDLControllerManager.java" \
"$DIRNAME/src/main/java/"
sed -i "s/import org.supertuxkart.*.SuperTuxKartActivity;/import $PACKAGE_NAME.SuperTuxKartActivity;/g" \
"$DIRNAME/src/main/java/SDLControllerManager.java"
cp -f "$DIRNAME/../lib/sdl2/android-project/app/src/main/java/org/libsdl/app/SDL.java" \
"$DIRNAME/src/main/java/"
cp "banner.png" "$DIRNAME/res/drawable/banner.png"
cp "$APP_ICON" "$DIRNAME/res/drawable/icon.png"

View File

@ -1,5 +1,6 @@
package org.supertuxkart.stk_dbg;
import org.libsdl.app.SDLActivity;
import org.supertuxkart.stk_dbg.STKInputConnection;
import android.content.Context;
@ -37,6 +38,8 @@ public class STKEditText extends EditText
// ------------------------------------------------------------------------
private native static void handleActionNext(int widget_id);
// ------------------------------------------------------------------------
private native static void handleLeftRight(boolean left, int widget_id);
// ------------------------------------------------------------------------
public STKEditText(Context context)
{
super(context);
@ -62,6 +65,61 @@ public class STKEditText extends EditText
return false;
}
});
setOnKeyListener(new EditText.OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
// Up or down pressed, leave focus
if (keyCode == KeyEvent.KEYCODE_DPAD_UP ||
keyCode == KeyEvent.KEYCODE_DPAD_DOWN)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
beforeHideKeyboard(true/*clear_text*/);
SDLActivity.onNativeKeyDown(keyCode);
SDLActivity.onNativeKeyUp(keyCode);
}
return true;
}
// For left or right let STK decides
else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT &&
getSelectionStart() == 0)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
beforeHideKeyboard(true/*clear_text*/);
handleLeftRight(true, m_stk_widget_id);
}
else
updateSTKEditBox();
return true;
}
else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT &&
getSelectionEnd() == getText().length())
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
beforeHideKeyboard(true/*clear_text*/);
handleLeftRight(false, m_stk_widget_id);
}
else
updateSTKEditBox();
return true;
}
else if (keyCode == KeyEvent.KEYCODE_ENTER)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
handleActionNext(m_stk_widget_id);
return true;
}
// Requires for hardware key like "Ctrl-a" so it will select
// all text in stk edit box
updateSTKEditBox();
return false;
}
});
}
// ------------------------------------------------------------------------
@Override
@ -88,7 +146,8 @@ public class STKEditText extends EditText
{
// Always remove the focus on STKEdit when pressing back button in
// phone, which hideSoftInputFromWindow is called by java itself
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK &&
event.getAction() == KeyEvent.ACTION_UP)
beforeHideKeyboard(false/*clear_text*/);
return false;
}
@ -134,6 +193,7 @@ public class STKEditText extends EditText
}
clearFocus();
setVisibility(View.GONE);
SDLActivity.reFocusAfterSTKEditText();
}
catch (Exception e)
{

View File

@ -1,11 +1,8 @@
package org.supertuxkart.stk_dbg;
import org.supertuxkart.stk_dbg.STKEditText;
import org.libsdl.app.SDLActivity;
import org.libsdl.app.SDLControllerManager;
import org.libsdl.app.HIDDeviceManager;
import android.app.NativeActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
@ -32,45 +29,13 @@ import org.minidns.hla.ResolverResult;
import org.minidns.record.SRV;
import org.minidns.record.TXT;
public class SuperTuxKartActivity extends NativeActivity
public class SuperTuxKartActivity extends SDLActivity
{
// Same as irrlicht
enum TouchInputEvent
{
ETIE_PRESSED_DOWN,
ETIE_LEFT_UP,
ETIE_MOVED,
ETIE_COUNT
}
class TouchEventData
{
public TouchInputEvent event_type;
public int x;
public int y;
TouchEventData()
{
event_type = TouchInputEvent.ETIE_PRESSED_DOWN;
x = 0;
y = 0;
}
};
private TouchEventData[] m_touch_event_data;
private STKEditText m_stk_edittext;
private static Context m_context;
private static HIDDeviceManager m_hid_device_manager;
private int m_bottom_y;
// ------------------------------------------------------------------------
private native void saveKeyboardHeight(int height);
// ------------------------------------------------------------------------
private native void startSTK();
// ------------------------------------------------------------------------
private native static void addKey(int key_code, int action, int meta_state,
int scan_code, int unichar);
// ------------------------------------------------------------------------
private native static void addTouch(int id, int x, int y, int event_type);
// ------------------------------------------------------------------------
private native static void addDNSSrvRecords(String name, int weight);
// ------------------------------------------------------------------------
private void hideKeyboardNative(final boolean clear_text)
@ -88,24 +53,14 @@ public class SuperTuxKartActivity extends NativeActivity
imm.hideSoftInputFromWindow(m_stk_edittext.getWindowToken(), 0);
}
// ------------------------------------------------------------------------
private void hideNavBar(View decor_view)
{
if (Build.VERSION.SDK_INT < 19)
return;
decor_view.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
// ------------------------------------------------------------------------
private void createSTKEditText()
{
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.WRAP_CONTENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
// We move the dummy edittext out of the android screen because we draw
// our own manually
params.setMargins(0, -100000, 1, -100010);
m_stk_edittext = new STKEditText(this);
// For some copy-and-paste text are not done by commitText in
// STKInputConnection, so we need an extra watcher
@ -120,7 +75,7 @@ public class SuperTuxKartActivity extends NativeActivity
@Override
public void afterTextChanged(Editable edit)
{
if (!isHardwareKeyboardConnected() && m_stk_edittext != null)
if (m_stk_edittext != null)
m_stk_edittext.updateSTKEditBox();
}
});
@ -133,15 +88,7 @@ public class SuperTuxKartActivity extends NativeActivity
public void onCreate(Bundle instance)
{
super.onCreate(instance);
// We don't use native activity input event queue
getWindow().takeInputQueue(null);
System.loadLibrary("main");
m_touch_event_data = new TouchEventData[32];
for (int i = 0; i < 32; i++)
m_touch_event_data[i] = new TouchEventData();
m_context = this;
m_stk_edittext = null;
m_bottom_y = 0;
final View root = getWindow().getDecorView().findViewById(
android.R.id.content);
root.getViewTreeObserver().addOnGlobalLayoutListener(new
@ -155,26 +102,13 @@ public class SuperTuxKartActivity extends NativeActivity
int screen_height = root.getRootView().getHeight();
int keyboard_height = screen_height - (r.bottom);
saveKeyboardHeight(keyboard_height);
int moved_height = 0;
int margin = screen_height - m_bottom_y;
if (keyboard_height > margin)
moved_height = -keyboard_height + margin;
SDLActivity.moveView(moved_height);
}
});
final View decor_view = getWindow().getDecorView();
decor_view.setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener()
{
@Override
public void onSystemUiVisibilityChange(int visibility)
{
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0)
hideNavBar(decor_view);
}
});
SDLControllerManager.nativeSetupJNI();
SDLControllerManager.initialize();
m_hid_device_manager = HIDDeviceManager.acquire(this);
// We only start stk main thread after JNI_OnLoad (for initializing the
// java environment)
startSTK();
}
// ------------------------------------------------------------------------
@Override
@ -182,194 +116,16 @@ public class SuperTuxKartActivity extends NativeActivity
{
super.onPause();
hideKeyboardNative(false/*clear_text*/);
if (m_hid_device_manager != null)
m_hid_device_manager.setFrozen(true);
}
// ------------------------------------------------------------------------
@Override
public void onResume()
/* STK statically link SDL2. */
protected String[] getLibraries()
{
super.onResume();
if (m_hid_device_manager != null)
m_hid_device_manager.setFrozen(false);
return new String[]{ "main" };
}
// ------------------------------------------------------------------------
@Override
protected void onDestroy()
{
if (m_hid_device_manager != null)
{
HIDDeviceManager.release(m_hid_device_manager);
m_hid_device_manager = null;
}
super.onDestroy();
}
// ------------------------------------------------------------------------
@Override
public void onWindowFocusChanged(boolean has_focus)
{
super.onWindowFocusChanged(has_focus);
if (has_focus)
hideNavBar(getWindow().getDecorView());
}
// ------------------------------------------------------------------------
@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
int key_code = event.getKeyCode();
int action = event.getAction();
int device_id = event.getDeviceId();
int source = event.getSource();
int meta_state = event.getMetaState();
int scan_code = event.getScanCode();
// KeyCharacterMap.COMBINING_ACCENT is not handled at the moment
int unichar = event.getUnicodeChar(meta_state);
int repeat_count = event.getRepeatCount();
// Dispatch the different events depending on where they come from
// Some SOURCE_JOYSTICK, SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD
// So, we try to process them as JOYSTICK/DPAD/GAMEPAD events first, if that fails we try them as KEYBOARD
//
// Furthermore, it's possible a game controller has SOURCE_KEYBOARD and
// SOURCE_JOYSTICK, while its key events arrive from the keyboard source
// So, retrieve the device itself and check all of its sources
if (SDLControllerManager.isDeviceSDLJoystick(device_id))
{
// Note that we process events with specific key codes here
if (action == KeyEvent.ACTION_DOWN)
{
if (SDLControllerManager.onNativePadDown(device_id, key_code, meta_state, scan_code, unichar, repeat_count) == 0)
return true;
}
else if (action == KeyEvent.ACTION_UP)
{
if (SDLControllerManager.onNativePadUp(device_id, key_code, meta_state, scan_code, unichar) == 0)
return true;
}
}
// User pressed back button
if (key_code == KeyEvent.KEYCODE_BACK &&
action == KeyEvent.ACTION_DOWN)
{
// Avoid repeating the event which leads to some strange behaviour
// For ACTION_UP it's always zero
if (repeat_count == 0)
addKey(key_code, action, meta_state, scan_code, 0);
return true;
}
boolean has_hardware_keyboard = isHardwareKeyboardConnected();
// Allow hacker keyboard (one of the native android keyboard)
// to close itself when pressing the esc button
if (key_code == KeyEvent.KEYCODE_ESCAPE &&
action == KeyEvent.ACTION_DOWN && !has_hardware_keyboard &&
m_stk_edittext != null && m_stk_edittext.isFocused())
{
hideKeyboardNative(/*clear_text*/false);
return true;
}
// Called when user change cursor / select all text in native android
// keyboard
boolean ret = super.dispatchKeyEvent(event);
if (!has_hardware_keyboard && m_stk_edittext != null)
m_stk_edittext.updateSTKEditBox();
// Allow sending navigation key event found in native android keyboard
// so user can using up or down to toggle multiple textfield
boolean send_navigation = key_code == KeyEvent.KEYCODE_DPAD_UP ||
key_code == KeyEvent.KEYCODE_DPAD_DOWN ||
key_code == KeyEvent.KEYCODE_DPAD_LEFT ||
key_code == KeyEvent.KEYCODE_DPAD_RIGHT;
// We don't send navigation event if it's consumed by input method
send_navigation = send_navigation && !ret;
if (has_hardware_keyboard || send_navigation)
{
if (has_hardware_keyboard &&
m_stk_edittext != null && m_stk_edittext.isFocused())
m_stk_edittext.beforeHideKeyboard(/*clear_text*/true);
addKey(key_code, action, meta_state, scan_code, unichar);
// We use only java to handle key for hardware keyboard
return true;
}
else
return ret;
}
// ------------------------------------------------------------------------
@Override
public boolean dispatchGenericMotionEvent(MotionEvent ev)
{
if (SDLControllerManager.useGenericMotionListener(ev))
return true;
return super.dispatchGenericMotionEvent(ev);
}
// ------------------------------------------------------------------------
@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
boolean ret = super.dispatchTouchEvent(ev);
if (!ret)
{
TouchInputEvent event_type;
int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
event_type = TouchInputEvent.ETIE_PRESSED_DOWN;
break;
case MotionEvent.ACTION_MOVE:
event_type = TouchInputEvent.ETIE_MOVED;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_CANCEL:
event_type = TouchInputEvent.ETIE_LEFT_UP;
break;
default:
return false;
}
int count = 1;
int idx = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
// Process all touches for move action.
if (event_type == TouchInputEvent.ETIE_MOVED)
{
count = ev.getPointerCount();
idx = 0;
}
for (int i = 0; i < count; i++)
{
int id = ev.getPointerId(i + idx);
int x = (int)ev.getX(i + idx);
int y = (int)ev.getY(i + idx);
if (id >= 32)
continue;
// Don't send move event when nothing changed
if (m_touch_event_data[id].event_type == event_type &&
m_touch_event_data[id].x == x &&
m_touch_event_data[id].y == y)
continue;
m_touch_event_data[id].event_type = event_type;
m_touch_event_data[id].x = x;
m_touch_event_data[id].y = y;
addTouch(id, x, y, event_type.ordinal());
}
return true;
}
return false;
}
// ------------------------------------------------------------------------
public void showKeyboard(final int type)
public void showKeyboard(final int type, final int y)
{
final Context context = this;
// Need to run in ui thread as it access the view m_stk_edittext
@ -378,6 +134,7 @@ public class SuperTuxKartActivity extends NativeActivity
@Override
public void run()
{
m_bottom_y = y;
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null)
@ -404,6 +161,7 @@ public class SuperTuxKartActivity extends NativeActivity
@Override
public void run()
{
m_bottom_y = 0;
hideKeyboardNative(clear_text);
}
});
@ -486,5 +244,9 @@ public class SuperTuxKartActivity extends NativeActivity
.keyboard == Configuration.KEYBOARD_QWERTY;
}
// ------------------------------------------------------------------------
public static Context getContext() { return m_context; }
public int getScreenSize()
{
return getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;
}
}

View File

@ -47,7 +47,7 @@
//! Uncomment this line to compile with the SDL device
//#define _IRR_COMPILE_WITH_SDL_DEVICE_
// Always use SDL2 in STK unless server only compilation
#if defined(NO_IRR_COMPILE_WITH_SDL_DEVICE_) || defined(ANDROID)
#if defined(NO_IRR_COMPILE_WITH_SDL_DEVICE_)
#undef _IRR_COMPILE_WITH_SDL_DEVICE_
#else
#define _IRR_COMPILE_WITH_SDL_DEVICE_
@ -104,9 +104,8 @@
#endif
#if defined(_IRR_ANDROID_PLATFORM_)
#define _IRR_COMPILE_WITH_ANDROID_DEVICE_
#define _IRR_COMPILE_WITH_SDL_DEVICE_
#define _IRR_COMPILE_WITH_OGLES2_
#define _IRR_COMPILE_ANDROID_ASSET_READER_
#endif
#if !defined(_IRR_WINDOWS_API_) && !defined(_IRR_OSX_PLATFORM_) && !defined(_IRR_ANDROID_PLATFORM_) && !defined(_IRR_HAIKU_PLATFORM_)

File diff suppressed because it is too large Load Diff

View File

@ -1,135 +0,0 @@
// Copyright (C) 2002-2011 Nikolaus Gebhardt
// Copyright (C) 2016-2017 Dawid Gan
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_IRR_DEVICE_ANDROID_H_INCLUDED__
#define __C_IRR_DEVICE_ANDROID_H_INCLUDED__
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_ANDROID_DEVICE_
#include <android/window.h>
#include <android/sensor.h>
#include "stk_android_native_app_glue.h"
#include "CIrrDeviceStub.h"
#include "IrrlichtDevice.h"
#include "IImagePresenter.h"
#include <map>
#include <string>
namespace irr
{
enum DeviceOrientation
{
ORIENTATION_UNKNOWN,
ORIENTATION_PORTRAIT,
ORIENTATION_LANDSCAPE
};
struct AndroidApplicationInfo
{
std::string native_lib_dir;
std::string data_dir;
bool initialized;
AndroidApplicationInfo() : initialized(false) {};
};
class CIrrDeviceAndroid : public CIrrDeviceStub, video::IImagePresenter
{
public:
static bool IsPaused;
static bool IsFocused;
static bool IsStarted;
//! constructor
CIrrDeviceAndroid(const SIrrlichtCreationParameters& param);
//! destructor
virtual ~CIrrDeviceAndroid();
virtual bool run();
virtual void yield();
virtual void sleep(u32 timeMs, bool pauseTimer=false);
virtual void setWindowCaption(const wchar_t* text);
virtual void setWindowClass(const char* text) {}
virtual bool present(video::IImage* surface, void* windowId, core::rect<s32>* srcClip);
virtual bool isWindowActive() const;
virtual bool isWindowFocused() const;
virtual bool isWindowMinimized() const;
virtual void closeDevice();
virtual void setResizable( bool resize=false );
virtual void minimizeWindow();
virtual void maximizeWindow();
virtual void restoreWindow();
virtual bool moveWindow(int x, int y);
virtual bool getWindowPosition(int* x, int* y);
virtual E_DEVICE_TYPE getType() const;
virtual bool activateAccelerometer(float updateInterval);
virtual bool deactivateAccelerometer();
virtual bool isAccelerometerActive();
virtual bool isAccelerometerAvailable();
virtual bool activateGyroscope(float updateInterval);
virtual bool deactivateGyroscope();
virtual bool isGyroscopeActive();
virtual bool isGyroscopeAvailable();
void fromSTKEditBox(int widget_id, const core::stringw& text, int selection_start, int selection_end, int type);
virtual void toggleOnScreenKeyboard(bool show, s32 type = 0);
virtual bool supportsTouchDevice() const { return HasTouchDevice; }
virtual bool hasHardwareKeyboard() const;
// ATM if there is touch device we assume native screen keyboard is
// available which for example android tv doesn't
virtual bool hasOnScreenKeyboard() const { return HasTouchDevice; }
virtual u32 getScreenHeight() const { return m_screen_height; }
virtual u32 getOnScreenKeyboardHeight() const;
virtual s32 getMovedHeight() const { return m_moved_height; }
virtual void registerGetMovedHeightFunction(HeightFunc height_function)
{
m_moved_height_func = height_function;
}
static void onCreate();
static const AndroidApplicationInfo& getApplicationInfo(
ANativeActivity* activity);
void openURL(const std::string& url);
android_app* getAndroid() const { return Android; }
private:
static JNIEnv* m_jni_env;
s32 m_moved_height;
u32 m_screen_height;
HeightFunc m_moved_height_func;
android_app* Android;
ASensorManager* SensorManager;
ASensorEventQueue* SensorEventQueue;
const ASensor* Accelerometer;
const ASensor* Gyroscope;
bool AccelerometerActive;
bool GyroscopeActive;
static AndroidApplicationInfo ApplicationInfo;
bool HasTouchDevice;
float GamepadAxisX;
float GamepadAxisY;
DeviceOrientation DefaultOrientation;
video::SExposedVideoData ExposedVideoData;
void printConfig();
void createDriver();
void createKeyMap();
void createVideoModeList();
wchar_t getKeyChar(SEvent& event);
wchar_t getUnicodeChar(AInputEvent* event);
static void readApplicationInfo(ANativeActivity* activity);
int getRotation();
DeviceOrientation getDefaultOrientation();
video::SExposedVideoData& getExposedVideoData();
static void handleAndroidCommand(android_app* app, int32_t cmd);
};
} // end namespace irr
#endif // _IRR_COMPILE_WITH_ANDROID_DEVICE_
#endif // __C_IRR_DEVICE_ANDROID_H_INCLUDED__

View File

@ -122,7 +122,7 @@ CIrrDeviceSDL::CIrrDeviceSDL(const SIrrlichtCreationParameters& param)
if (VideoDriver)
createGUIAndScene();
#ifdef MOBILE_STK
#ifdef IOS_STK
SDL_SetEventFilter(handle_app_event, NULL);
#endif
}
@ -502,6 +502,9 @@ void CIrrDeviceSDL::createDriver()
extern "C" void handle_joystick(SDL_Event& event);
// In CGUIEditBox.cpp
extern "C" void handle_textinput(SDL_Event& event);
// In main_loop.cpp
extern "C" void pause_mainloop();
extern "C" void resume_mainloop();
//! runs the device. Returns false if device wants to be deleted
bool CIrrDeviceSDL::run()
{
@ -514,6 +517,14 @@ bool CIrrDeviceSDL::run()
{
switch ( SDL_event.type )
{
#if defined(MOBILE_STK) && !defined(IOS_STK)
case SDL_APP_WILLENTERBACKGROUND:
pause_mainloop();
break;
case SDL_APP_DIDENTERFOREGROUND:
resume_mainloop();
break;
#endif
#if SDL_VERSION_ATLEAST(2, 0, 9)
case SDL_SENSORUPDATE:
if (SDL_event.sensor.which == AccelerometerInstance)
@ -525,8 +536,13 @@ bool CIrrDeviceSDL::run()
// Mobile STK specific
if (irrevent.AccelerometerEvent.X < 0.0)
irrevent.AccelerometerEvent.X *= -1.0;
#ifdef IOS_STK
if (SDL_GetDisplayOrientation(0) == SDL_ORIENTATION_LANDSCAPE)
irrevent.AccelerometerEvent.Y *= -1.0;
#else
if (SDL_GetDisplayOrientation(0) == SDL_ORIENTATION_LANDSCAPE_FLIPPED)
irrevent.AccelerometerEvent.Y *= -1.0;
#endif
postEventFromUser(irrevent);
}
else if (SDL_event.sensor.which == GyroscopeInstance)
@ -1098,6 +1114,7 @@ void CIrrDeviceSDL::createKeyMap()
KeyMap.push_back(SKeyMap(SDLK_COMMA, IRR_KEY_COMMA));
KeyMap.push_back(SKeyMap(SDLK_MINUS, IRR_KEY_MINUS));
KeyMap.push_back(SKeyMap(SDLK_PERIOD, IRR_KEY_PERIOD));
KeyMap.push_back(SKeyMap(SDLK_AC_BACK, IRR_KEY_ESCAPE));
KeyMap.push_back(SKeyMap(SDLK_EQUALS, IRR_KEY_PLUS));
KeyMap.push_back(SKeyMap(SDLK_LEFTBRACKET, IRR_KEY_OEM_4));

View File

@ -1,496 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (C) 2018 Dawid Gan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <jni.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/resource.h>
#include "stk_android_native_app_glue.h"
#include <android/log.h>
#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "threaded_app", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "threaded_app", __VA_ARGS__))
/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
# define LOGV(...) ((void)__android_log_print(ANDROID_LOG_VERBOSE, "threaded_app", __VA_ARGS__))
#else
# define LOGV(...) ((void)0)
#endif
static void free_saved_state(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->savedState != NULL) {
free(android_app->savedState);
android_app->savedState = NULL;
android_app->savedStateSize = 0;
}
pthread_mutex_unlock(&android_app->mutex);
}
int8_t android_app_read_cmd(struct android_app* android_app) {
int8_t cmd;
if (read(android_app->msgread, &cmd, sizeof(cmd)) == sizeof(cmd)) {
switch (cmd) {
case APP_CMD_SAVE_STATE:
free_saved_state(android_app);
break;
}
return cmd;
} else {
LOGE("No data on command pipe!");
}
return -1;
}
static void print_cur_config(struct android_app* android_app) {
char lang[2], country[2];
AConfiguration_getLanguage(android_app->config, lang);
AConfiguration_getCountry(android_app->config, country);
LOGV("Config: mcc=%d mnc=%d lang=%c%c cnt=%c%c orien=%d touch=%d dens=%d "
"keys=%d nav=%d keysHid=%d navHid=%d sdk=%d size=%d long=%d "
"modetype=%d modenight=%d",
AConfiguration_getMcc(android_app->config),
AConfiguration_getMnc(android_app->config),
lang[0], lang[1], country[0], country[1],
AConfiguration_getOrientation(android_app->config),
AConfiguration_getTouchscreen(android_app->config),
AConfiguration_getDensity(android_app->config),
AConfiguration_getKeyboard(android_app->config),
AConfiguration_getNavigation(android_app->config),
AConfiguration_getKeysHidden(android_app->config),
AConfiguration_getNavHidden(android_app->config),
AConfiguration_getSdkVersion(android_app->config),
AConfiguration_getScreenSize(android_app->config),
AConfiguration_getScreenLong(android_app->config),
AConfiguration_getUiModeType(android_app->config),
AConfiguration_getUiModeNight(android_app->config));
}
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_INPUT_CHANGED:
LOGV("APP_CMD_INPUT_CHANGED\n");
pthread_mutex_lock(&android_app->mutex);
if (android_app->inputQueue != NULL) {
AInputQueue_detachLooper(android_app->inputQueue);
}
android_app->inputQueue = android_app->pendingInputQueue;
if (android_app->inputQueue != NULL) {
LOGV("Attaching input queue to looper");
AInputQueue_attachLooper(android_app->inputQueue,
android_app->looper, LOOPER_ID_INPUT, NULL,
&android_app->inputPollSource);
}
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_INIT_WINDOW:
LOGV("APP_CMD_INIT_WINDOW\n");
pthread_mutex_lock(&android_app->mutex);
android_app->window = android_app->pendingWindow;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW\n");
pthread_cond_broadcast(&android_app->cond);
break;
case APP_CMD_RESUME:
case APP_CMD_START:
case APP_CMD_PAUSE:
case APP_CMD_STOP:
LOGV("activityState=%d\n", cmd);
pthread_mutex_lock(&android_app->mutex);
android_app->activityState = cmd;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_CONFIG_CHANGED:
LOGV("APP_CMD_CONFIG_CHANGED\n");
AConfiguration_fromAssetManager(android_app->config,
android_app->activity->assetManager);
print_cur_config(android_app);
break;
case APP_CMD_DESTROY:
LOGV("APP_CMD_DESTROY\n");
android_app->destroyRequested = 1;
break;
}
}
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd) {
switch (cmd) {
case APP_CMD_TERM_WINDOW:
LOGV("APP_CMD_TERM_WINDOW\n");
pthread_mutex_lock(&android_app->mutex);
android_app->window = NULL;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_SAVE_STATE:
LOGV("APP_CMD_SAVE_STATE\n");
pthread_mutex_lock(&android_app->mutex);
android_app->stateSaved = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
break;
case APP_CMD_RESUME:
free_saved_state(android_app);
break;
}
}
void app_dummy() {
}
static void android_app_destroy(struct android_app* android_app) {
LOGV("android_app_destroy!");
free_saved_state(android_app);
pthread_mutex_lock(&android_app->mutex);
if (android_app->inputQueue != NULL) {
AInputQueue_detachLooper(android_app->inputQueue);
}
AConfiguration_delete(android_app->config);
android_app->destroyed = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
// Can't touch android_app object after this.
}
static void process_input(struct android_app* app, struct android_poll_source* source) {
AInputEvent* event = NULL;
while (AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
LOGV("New input event: type=%d\n", AInputEvent_getType(event));
if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
continue;
}
int32_t handled = 0;
if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
AInputQueue_finishEvent(app->inputQueue, event, handled);
}
}
static void process_cmd(struct android_app* app, struct android_poll_source* source) {
int8_t cmd = android_app_read_cmd(app);
android_app_pre_exec_cmd(app, cmd);
if (app->onAppCmd != NULL) app->onAppCmd(app, cmd);
android_app_post_exec_cmd(app, cmd);
}
// From CIrrDeviceAndroid.h
extern void IrrDeviceAndroid_onCreate();
static void* android_app_entry(void* param) {
struct android_app* android_app = (struct android_app*)param;
android_app->config = AConfiguration_new();
AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager);
print_cur_config(android_app);
android_app->cmdPollSource.id = LOOPER_ID_MAIN;
android_app->cmdPollSource.app = android_app;
android_app->cmdPollSource.process = process_cmd;
android_app->inputPollSource.id = LOOPER_ID_INPUT;
android_app->inputPollSource.app = android_app;
android_app->inputPollSource.process = process_input;
ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL,
&android_app->cmdPollSource);
android_app->looper = looper;
// Initialize global variables in android device before android_app->running
IrrDeviceAndroid_onCreate();
pthread_mutex_lock(&android_app->mutex);
android_app->running = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
android_main(android_app);
android_app_destroy(android_app);
return NULL;
}
// --------------------------------------------------------------------
// Native activity interaction (called from main thread)
// --------------------------------------------------------------------
struct android_app* g_android_app;
static struct android_app* android_app_create(ANativeActivity* activity,
void* savedState, size_t savedStateSize) {
struct android_app* android_app = (struct android_app*)malloc(sizeof(struct android_app));
memset(android_app, 0, sizeof(struct android_app));
android_app->activity = activity;
pthread_mutex_init(&android_app->mutex, NULL);
pthread_cond_init(&android_app->cond, NULL);
if (savedState != NULL) {
android_app->savedState = malloc(savedStateSize);
android_app->savedStateSize = savedStateSize;
memcpy(android_app->savedState, savedState, savedStateSize);
}
int msgpipe[2];
if (pipe(msgpipe)) {
LOGE("could not create pipe: %s", strerror(errno));
return NULL;
}
android_app->msgread = msgpipe[0];
android_app->msgwrite = msgpipe[1];
g_android_app = android_app;
return android_app;
}
static void android_app_write_cmd(struct android_app* android_app, int8_t cmd) {
if (write(android_app->msgwrite, &cmd, sizeof(cmd)) != sizeof(cmd)) {
LOGE("Failure writing android_app cmd: %s\n", strerror(errno));
}
}
static void android_app_set_input(struct android_app* android_app, AInputQueue* inputQueue) {
pthread_mutex_lock(&android_app->mutex);
android_app->pendingInputQueue = inputQueue;
android_app_write_cmd(android_app, APP_CMD_INPUT_CHANGED);
while (android_app->inputQueue != android_app->pendingInputQueue) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_window(struct android_app* android_app, ANativeWindow* window) {
pthread_mutex_lock(&android_app->mutex);
if (android_app->pendingWindow != NULL) {
android_app_write_cmd(android_app, APP_CMD_TERM_WINDOW);
}
android_app->pendingWindow = window;
if (window != NULL) {
android_app_write_cmd(android_app, APP_CMD_INIT_WINDOW);
}
while (android_app->window != android_app->pendingWindow) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_set_activity_state(struct android_app* android_app, int8_t cmd) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, cmd);
while (android_app->activityState != cmd) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
}
static void android_app_free(struct android_app* android_app) {
pthread_mutex_lock(&android_app->mutex);
android_app_write_cmd(android_app, APP_CMD_DESTROY);
while (!android_app->destroyed) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);
close(android_app->msgread);
close(android_app->msgwrite);
pthread_cond_destroy(&android_app->cond);
pthread_mutex_destroy(&android_app->mutex);
free(android_app);
}
static void onDestroy(ANativeActivity* activity) {
LOGV("Destroy: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_DESTROY);
android_app_free(app);
}
static void onStart(ANativeActivity* activity) {
LOGV("Start: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_START);
android_app_set_activity_state(app, APP_CMD_START);
}
// From SDL2 hid.cpp: request permission dialog in usbmanager call onPause which
// blocks the stk thread (sdl thread too), so if this return true we use
// android_app_write_cmd directly
extern int isNonBlockingEnabled();
static void onResume(ANativeActivity* activity) {
LOGV("Resume: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_RESUME);
if (isNonBlockingEnabled() == 1)
android_app_write_cmd(app, APP_CMD_RESUME);
else
android_app_set_activity_state(app, APP_CMD_RESUME);
}
static void* onSaveInstanceState(ANativeActivity* activity, size_t* outLen) {
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_SAVE_STATE);
void* savedState = NULL;
LOGV("SaveInstanceState: %p\n", activity);
pthread_mutex_lock(&app->mutex);
app->stateSaved = 0;
android_app_write_cmd(app, APP_CMD_SAVE_STATE);
while (!app->stateSaved) {
pthread_cond_wait(&app->cond, &app->mutex);
}
if (app->savedState != NULL) {
savedState = app->savedState;
*outLen = app->savedStateSize;
app->savedState = NULL;
app->savedStateSize = 0;
}
pthread_mutex_unlock(&app->mutex);
return savedState;
}
static void onPause(ANativeActivity* activity) {
LOGV("Pause: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_PAUSE);
if (isNonBlockingEnabled() == 1)
android_app_write_cmd(app, APP_CMD_PAUSE);
else
android_app_set_activity_state(app, APP_CMD_PAUSE);
}
static void onStop(ANativeActivity* activity) {
LOGV("Stop: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_STOP);
android_app_set_activity_state(app, APP_CMD_STOP);
}
static void onConfigurationChanged(ANativeActivity* activity) {
LOGV("ConfigurationChanged: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_CONFIG_CHANGED);
android_app_write_cmd(app, APP_CMD_CONFIG_CHANGED);
}
static void onLowMemory(ANativeActivity* activity) {
LOGV("LowMemory: %p\n", activity);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_LOW_MEMORY);
android_app_write_cmd(app, APP_CMD_LOW_MEMORY);
}
static void onWindowFocusChanged(ANativeActivity* activity, int focused) {
LOGV("WindowFocusChanged: %p -- %d\n", activity, focused);
struct android_app* app = (struct android_app*)activity->instance;
int cmd = focused ? APP_CMD_GAINED_FOCUS : APP_CMD_LOST_FOCUS;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, cmd);
android_app_write_cmd(app, cmd);
}
static void onNativeWindowCreated(ANativeActivity* activity, ANativeWindow* window) {
LOGV("NativeWindowCreated: %p -- %p\n", activity, window);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_INIT_WINDOW);
android_app_set_window(app, window);
}
static void onNativeWindowDestroyed(ANativeActivity* activity, ANativeWindow* window) {
LOGV("NativeWindowDestroyed: %p -- %p\n", activity, window);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_TERM_WINDOW);
android_app_set_window(app, NULL);
}
static void onInputQueueCreated(ANativeActivity* activity, AInputQueue* queue) {
LOGV("InputQueueCreated: %p -- %p\n", activity, queue);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_INPUT_CHANGED);
android_app_set_input(app, queue);
}
static void onInputQueueDestroyed(ANativeActivity* activity, AInputQueue* queue) {
LOGV("InputQueueDestroyed: %p -- %p\n", activity, queue);
struct android_app* app = (struct android_app*)activity->instance;
if (app->onAppCmdDirect != NULL) app->onAppCmdDirect(activity, APP_CMD_INPUT_CHANGED);
android_app_set_input(app, NULL);
}
// Defined in CIrrDeviceAndroid, we call it in android main thread so after activity
// starts keymap is visible to all threads
extern void createKeyMap();
void ANativeActivity_onCreate(ANativeActivity* activity,
void* savedState, size_t savedStateSize) {
LOGV("Creating: %p\n", activity);
createKeyMap();
activity->callbacks->onDestroy = onDestroy;
activity->callbacks->onStart = onStart;
activity->callbacks->onResume = onResume;
activity->callbacks->onSaveInstanceState = onSaveInstanceState;
activity->callbacks->onPause = onPause;
activity->callbacks->onStop = onStop;
activity->callbacks->onConfigurationChanged = onConfigurationChanged;
activity->callbacks->onLowMemory = onLowMemory;
activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
activity->callbacks->onInputQueueCreated = onInputQueueCreated;
activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed;
activity->instance = android_app_create(activity, savedState, savedStateSize);
}
#define MAKE_ANDROID_START_STK_CALLBACK(x) JNIEXPORT void JNICALL Java_ ## x##_SuperTuxKartActivity_startSTK(JNIEnv* env, jobject this_obj)
#define ANDROID_START_STK_CALLBACK(PKG_NAME) MAKE_ANDROID_START_STK_CALLBACK(PKG_NAME)
ANDROID_START_STK_CALLBACK(ANDROID_PACKAGE_CALLBACK_NAME)
{
// This will be called after ANativeActivity_onCreate and loadLibrary
// (so SDL java environment is ready in JNI_OnLoad)
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&g_android_app->thread, &attr, android_app_entry, g_android_app);
pthread_attr_destroy(&attr);
// Wait for thread to start.
pthread_mutex_lock(&g_android_app->mutex);
while (!g_android_app->running)
{
pthread_cond_wait(&g_android_app->cond, &g_android_app->mutex);
}
pthread_mutex_unlock(&g_android_app->mutex);
}

View File

@ -1,353 +0,0 @@
/*
* Copyright (C) 2010 The Android Open Source Project
* Copyright (C) 2018 Dawid Gan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _ANDROID_NATIVE_APP_GLUE_H
#define _ANDROID_NATIVE_APP_GLUE_H
#include <poll.h>
#include <pthread.h>
#include <sched.h>
#include <android/configuration.h>
#include <android/looper.h>
#include <android/native_activity.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* The native activity interface provided by <android/native_activity.h>
* is based on a set of application-provided callbacks that will be called
* by the Activity's main thread when certain events occur.
*
* This means that each one of this callbacks _should_ _not_ block, or they
* risk having the system force-close the application. This programming
* model is direct, lightweight, but constraining.
*
* The 'android_native_app_glue' static library is used to provide a different
* execution model where the application can implement its own main event
* loop in a different thread instead. Here's how it works:
*
* 1/ The application must provide a function named "android_main()" that
* will be called when the activity is created, in a new thread that is
* distinct from the activity's main thread.
*
* 2/ android_main() receives a pointer to a valid "android_app" structure
* that contains references to other important objects, e.g. the
* ANativeActivity obejct instance the application is running in.
*
* 3/ the "android_app" object holds an ALooper instance that already
* listens to two important things:
*
* - activity lifecycle events (e.g. "pause", "resume"). See APP_CMD_XXX
* declarations below.
*
* - input events coming from the AInputQueue attached to the activity.
*
* Each of these correspond to an ALooper identifier returned by
* ALooper_pollOnce with values of LOOPER_ID_MAIN and LOOPER_ID_INPUT,
* respectively.
*
* Your application can use the same ALooper to listen to additional
* file-descriptors. They can either be callback based, or with return
* identifiers starting with LOOPER_ID_USER.
*
* 4/ Whenever you receive a LOOPER_ID_MAIN or LOOPER_ID_INPUT event,
* the returned data will point to an android_poll_source structure. You
* can call the process() function on it, and fill in android_app->onAppCmd
* and android_app->onInputEvent to be called for your own processing
* of the event.
*
* Alternatively, you can call the low-level functions to read and process
* the data directly... look at the process_cmd() and process_input()
* implementations in the glue to see how to do this.
*
* See the sample named "native-activity" that comes with the NDK with a
* full usage example. Also look at the JavaDoc of NativeActivity.
*/
struct android_app;
/**
* Data associated with an ALooper fd that will be returned as the "outData"
* when that source has data ready.
*/
struct android_poll_source {
// The identifier of this source. May be LOOPER_ID_MAIN or
// LOOPER_ID_INPUT.
int32_t id;
// The android_app this ident is associated with.
struct android_app* app;
// Function to call to perform the standard processing of data from
// this source.
void (*process)(struct android_app* app, struct android_poll_source* source);
};
/**
* This is the interface for the standard glue code of a threaded
* application. In this model, the application's code is running
* in its own thread separate from the main thread of the process.
* It is not required that this thread be associated with the Java
* VM, although it will need to be in order to make JNI calls any
* Java objects.
*/
struct android_app {
// The application can place a pointer to its own state object
// here if it likes.
void* userData;
// Fill this in with the function to process main app commands (APP_CMD_*)
void (*onAppCmd)(struct android_app* app, int32_t cmd);
// Fill this in with the function to process input events. At this point
// the event has already been pre-dispatched, and it will be finished upon
// return. Return 1 if you have handled the event, 0 for any default
// dispatching.
int32_t (*onInputEvent)(struct android_app* app, AInputEvent* event);
// Function that allows to process (APP_CMD_*) directly in main thread
void (*onAppCmdDirect)(ANativeActivity* activity, int32_t cmd);
// The ANativeActivity object instance that this app is running in.
ANativeActivity* activity;
// The current configuration the app is running in.
AConfiguration* config;
// This is the last instance's saved state, as provided at creation time.
// It is NULL if there was no state. You can use this as you need; the
// memory will remain around until you call android_app_exec_cmd() for
// APP_CMD_RESUME, at which point it will be freed and savedState set to NULL.
// These variables should only be changed when processing a APP_CMD_SAVE_STATE,
// at which point they will be initialized to NULL and you can malloc your
// state and place the information here. In that case the memory will be
// freed for you later.
void* savedState;
size_t savedStateSize;
// The ALooper associated with the app's thread.
ALooper* looper;
// When non-NULL, this is the input queue from which the app will
// receive user input events.
AInputQueue* inputQueue;
// When non-NULL, this is the window surface that the app can draw in.
ANativeWindow* window;
// Current content rectangle of the window; this is the area where the
// window's content should be placed to be seen by the user.
ARect contentRect;
// Current state of the app's activity. May be either APP_CMD_START,
// APP_CMD_RESUME, APP_CMD_PAUSE, or APP_CMD_STOP; see below.
int activityState;
// This is non-zero when the application's NativeActivity is being
// destroyed and waiting for the app thread to complete.
int destroyRequested;
// -------------------------------------------------
// Below are "private" implementation of the glue code.
pthread_mutex_t mutex;
pthread_cond_t cond;
int msgread;
int msgwrite;
pthread_t thread;
struct android_poll_source cmdPollSource;
struct android_poll_source inputPollSource;
int running;
int stateSaved;
int destroyed;
int redrawNeeded;
AInputQueue* pendingInputQueue;
ANativeWindow* pendingWindow;
ARect pendingContentRect;
};
enum {
/**
* Looper data ID of commands coming from the app's main thread, which
* is returned as an identifier from ALooper_pollOnce(). The data for this
* identifier is a pointer to an android_poll_source structure.
* These can be retrieved and processed with android_app_read_cmd()
* and android_app_exec_cmd().
*/
LOOPER_ID_MAIN = 1,
/**
* Looper data ID of events coming from the AInputQueue of the
* application's window, which is returned as an identifier from
* ALooper_pollOnce(). The data for this identifier is a pointer to an
* android_poll_source structure. These can be read via the inputQueue
* object of android_app.
*/
LOOPER_ID_INPUT = 2,
/**
* Start of user-defined ALooper identifiers.
*/
LOOPER_ID_USER = 3,
};
enum {
/**
* Command from main thread: the AInputQueue has changed. Upon processing
* this command, android_app->inputQueue will be updated to the new queue
* (or NULL).
*/
APP_CMD_INPUT_CHANGED,
/**
* Command from main thread: a new ANativeWindow is ready for use. Upon
* receiving this command, android_app->window will contain the new window
* surface.
*/
APP_CMD_INIT_WINDOW,
/**
* Command from main thread: the existing ANativeWindow needs to be
* terminated. Upon receiving this command, android_app->window still
* contains the existing window; after calling android_app_exec_cmd
* it will be set to NULL.
*/
APP_CMD_TERM_WINDOW,
/**
* Command from main thread: the current ANativeWindow has been resized.
* Please redraw with its new size.
*/
APP_CMD_WINDOW_RESIZED,
/**
* Command from main thread: the system needs that the current ANativeWindow
* be redrawn. You should redraw the window before handing this to
* android_app_exec_cmd() in order to avoid transient drawing glitches.
*/
APP_CMD_WINDOW_REDRAW_NEEDED,
/**
* Command from main thread: the content area of the window has changed,
* such as from the soft input window being shown or hidden. You can
* find the new content rect in android_app::contentRect.
*/
APP_CMD_CONTENT_RECT_CHANGED,
/**
* Command from main thread: the app's activity window has gained
* input focus.
*/
APP_CMD_GAINED_FOCUS,
/**
* Command from main thread: the app's activity window has lost
* input focus.
*/
APP_CMD_LOST_FOCUS,
/**
* Command from main thread: the current device configuration has changed.
*/
APP_CMD_CONFIG_CHANGED,
/**
* Command from main thread: the system is running low on memory.
* Try to reduce your memory use.
*/
APP_CMD_LOW_MEMORY,
/**
* Command from main thread: the app's activity has been started.
*/
APP_CMD_START,
/**
* Command from main thread: the app's activity has been resumed.
*/
APP_CMD_RESUME,
/**
* Command from main thread: the app should generate a new saved state
* for itself, to restore from later if needed. If you have saved state,
* allocate it with malloc and place it in android_app.savedState with
* the size in android_app.savedStateSize. The will be freed for you
* later.
*/
APP_CMD_SAVE_STATE,
/**
* Command from main thread: the app's activity has been paused.
*/
APP_CMD_PAUSE,
/**
* Command from main thread: the app's activity has been stopped.
*/
APP_CMD_STOP,
/**
* Command from main thread: the app's activity is being destroyed,
* and waiting for the app thread to clean up and exit before proceeding.
*/
APP_CMD_DESTROY,
};
/**
* Call when ALooper_pollAll() returns LOOPER_ID_MAIN, reading the next
* app command message.
*/
int8_t android_app_read_cmd(struct android_app* android_app);
/**
* Call with the command returned by android_app_read_cmd() to do the
* initial pre-processing of the given command. You can perform your own
* actions for the command after calling this function.
*/
void android_app_pre_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Call with the command returned by android_app_read_cmd() to do the
* final post-processing of the given command. You must have done your own
* actions for the command before calling this function.
*/
void android_app_post_exec_cmd(struct android_app* android_app, int8_t cmd);
/**
* Dummy function you can call to ensure glue code isn't stripped.
*/
void app_dummy();
/**
* This is the function that application code must implement, representing
* the main entry to the app.
*/
extern void android_main(struct android_app* app);
#ifdef __cplusplus
}
#endif
#endif /* _ANDROID_NATIVE_APP_GLUE_H */

View File

@ -26,7 +26,7 @@
#include "utils/types.hpp"
#ifdef ANDROID
#include "main_android.hpp"
#include "SDL_system.h"
#endif
#include <algorithm>
@ -145,7 +145,7 @@ public:
#ifdef ANDROID
// Android version should be enough to disable certain features on this
// platform
int version = AConfiguration_getSdkVersion(global_android_app->config);
int version = SDL_GetAndroidSDKVersion();
if (version > 0)
{

View File

@ -168,9 +168,7 @@ IrrDriver::IrrDriver()
p.SwapInterval = 0;
p.EventReceiver = NULL;
p.FileSystem = file_manager->getFileSystem();
#ifdef ANDROID
p.PrivateData = (void*)global_android_app;
#endif
p.PrivateData = NULL;
m_device = createDeviceEx(p);
@ -465,9 +463,7 @@ void IrrDriver::initDevice()
#else
params.DriverType = video::EDT_OPENGL;
#endif
#if defined(ANDROID)
params.PrivateData = (void*)global_android_app;
#endif
params.PrivateData = NULL;
params.Stencilbuffer = false;
params.Bits = bits;
params.EventReceiver = this;
@ -776,38 +772,6 @@ void IrrDriver::initDevice()
if (GUIEngine::isNoGraphics())
return;
m_device->registerGetMovedHeightFunction([]
(const IrrlichtDevice* device)->int
{
#ifdef ANDROID
int screen_keyboard_height =
device->getOnScreenKeyboardHeight();
int screen_height = device->getScreenHeight();
if (screen_keyboard_height == 0 || screen_height == 0)
return 0;
GUIEngine::Widget* w = GUIEngine::getFocusForPlayer(0);
if (!w)
return 0;
core::rect<s32> pos =
w->getIrrlichtElement()->getAbsolutePosition();
// Add 10% margin
int element_height = (int)device->getScreenHeight() -
pos.LowerRightCorner.Y - int(screen_height * 0.01f);
if (element_height > screen_keyboard_height)
return 0;
else if (element_height < 0)
{
// For buttons near the edge of the bottom of screen
return screen_keyboard_height;
}
return screen_keyboard_height - element_height;
#else
return 0;
#endif
});
} // initDevice
// ----------------------------------------------------------------------------

View File

@ -45,10 +45,6 @@
#include <string>
#include <vector>
#ifdef ANDROID
#include "main_android.hpp"
#endif
namespace SP
{

View File

@ -17,9 +17,6 @@
#include "guiengine/event_handler.hpp"
#ifdef ANDROID
#include "addons/addons_manager.hpp"
#endif
#include "audio/music_manager.hpp"
#include "audio/sfx_manager.hpp"
#include "config/player_manager.hpp"
@ -49,10 +46,6 @@
#include <iostream>
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/stk_android_native_app_glue.h"
#endif
using GUIEngine::EventHandler;
using GUIEngine::EventPropagation;
using GUIEngine::NavigationDirection;
@ -169,51 +162,6 @@ bool EventHandler::OnEvent (const SEvent &event)
{
return onGUIEvent(event) == EVENT_BLOCK;
}
#ifdef ANDROID
else if (event.EventType == EET_SYSTEM_EVENT &&
event.SystemEvent.EventType == ESET_ANDROID_CMD)
{
int cmd = event.SystemEvent.AndroidCmd.Cmd;
IrrlichtDevice* device = irr_driver->getDevice();
assert(device != NULL);
if (cmd == APP_CMD_PAUSE || cmd == APP_CMD_LOST_FOCUS)
{
// Make sure that pause/unpause is executed only once
if (device->isWindowMinimized() == device->isWindowFocused())
{
if (music_manager)
music_manager->pauseMusic();
if (SFXManager::get())
SFXManager::get()->pauseAll();
PlayerManager::get()->save();
if (addons_manager->hasDownloadedIcons())
addons_manager->saveInstalled();
}
}
else if (cmd == APP_CMD_RESUME || cmd == APP_CMD_GAINED_FOCUS)
{
if (device->isWindowActive())
{
if (music_manager)
music_manager->resumeMusic();
if (SFXManager::get())
SFXManager::get()->resumeAll();
// Improve rubber banding effects of rewinders when going
// back to phone, because the smooth timer is paused
if (World::getWorld() && RewindManager::isEnabled())
RewindManager::get()->resetSmoothNetworkBody();
}
}
else if (cmd == APP_CMD_LOW_MEMORY)
{
Log::warn("EventHandler", "Low memory event received");
}
return false;
}
#endif
else if (GUIEngine::getStateManager()->getGameState() != GUIEngine::GAME &&
event.EventType != EET_KEY_INPUT_EVENT && event.EventType != EET_JOYSTICK_INPUT_EVENT &&
event.EventType != EET_LOG_TEXT_EVENT)

View File

@ -529,13 +529,8 @@ bool ScreenKeyboard::shouldUseScreenKeyboard()
bool always_use_screen_keyboard =
UserConfigParams::m_screen_keyboard == 2;
// Enable if no hardware keyboard
if (UserConfigParams::m_screen_keyboard == 1)
{
if (irr_driver->getDevice()->hasHardwareKeyboard())
return false;
return true;
}
return always_use_screen_keyboard;
}

View File

@ -29,7 +29,8 @@
#include <cstdlib>
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
extern void Android_toggleOnScreenKeyboard(bool show, int type, int y);
extern void Android_fromSTKEditBox(int widget_id, const core::stringw& text, int selection_start, int selection_end, int type);
#endif
#if !defined(SERVER_ONLY) && defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
@ -269,15 +270,13 @@ CGUIEditBox::~CGUIEditBox()
#ifndef SERVER_ONLY
if (Operator)
Operator->drop();
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
SDL_StopTextInput();
g_editbox = NULL;
#endif
#ifdef ANDROID
if (GUIEngine::ScreenKeyboard::shouldUseScreenKeyboard() &&
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard())
irr_driver->getDevice()->toggleOnScreenKeyboard(false);
Android_toggleOnScreenKeyboard(false, 0, 0);
#elif defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
SDL_StopTextInput();
g_editbox = NULL;
#endif
#endif
@ -380,7 +379,7 @@ bool CGUIEditBox::OnEvent(const SEvent& event)
MouseMarking = false;
setTextMarkers(0,0);
}
#if defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
#if !defined(ANDROID) && defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
SDL_StopTextInput();
g_editbox = NULL;
#endif
@ -391,7 +390,18 @@ bool CGUIEditBox::OnEvent(const SEvent& event)
else if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED)
{
m_mark_begin = m_mark_end = m_cursor_pos = getTextCount();
#ifdef _IRR_COMPILE_WITH_SDL_DEVICE_
#ifdef ANDROID
calculateScrollPos();
if (GUIEngine::ScreenKeyboard::shouldUseScreenKeyboard() &&
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard())
{
// If user toggle with hacker keyboard with arrows, keep
// using only text from STKEditText
Android_fromSTKEditBox(getID(), Text, m_mark_begin, m_mark_end, m_type);
// Enable auto focus which allows hardware keyboard unicode characters
Android_toggleOnScreenKeyboard(true, m_type, CurrentTextRect.LowerRightCorner.Y + 5);
}
#elif defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
#ifdef WIN32
// In windows we use caret to determine candidate box, which
// needs to calculate it first
@ -400,21 +410,10 @@ bool CGUIEditBox::OnEvent(const SEvent& event)
SDL_StartTextInput();
g_editbox = this;
#endif
#ifndef WIN32
#if !defined(ANDROID) && !defined(WIN32)
calculateScrollPos();
#endif
#ifdef ANDROID
if (GUIEngine::ScreenKeyboard::shouldUseScreenKeyboard() &&
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard() &&
irr_driver->getDevice()->getType() == irr::EIDT_ANDROID)
{
// If user toggle with hacker keyboard with arrows, keep
// using only text from STKEditTex
CIrrDeviceAndroid* dl = dynamic_cast<CIrrDeviceAndroid*>(
irr_driver->getDevice());
dl->fromSTKEditBox(getID(), Text, m_mark_begin, m_mark_end, m_type);
}
#endif
m_composing_text.clear();
}
break;
@ -692,7 +691,7 @@ bool CGUIEditBox::processKey(const SEvent& event)
#ifdef ANDROID
if (GUIEngine::ScreenKeyboard::shouldUseScreenKeyboard() &&
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard())
irr_driver->getDevice()->toggleOnScreenKeyboard(false);
Android_toggleOnScreenKeyboard(false, 0, 0);
#endif
sendGuiEvent( EGET_EDITBOX_ENTER );
}
@ -1038,12 +1037,9 @@ void CGUIEditBox::setText(const core::stringw& text)
calculateScrollPos();
#ifdef ANDROID
if (GUIEngine::ScreenKeyboard::shouldUseScreenKeyboard() &&
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard() &&
irr_driver->getDevice()->getType() == irr::EIDT_ANDROID)
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard())
{
CIrrDeviceAndroid* dl = dynamic_cast<CIrrDeviceAndroid*>(
irr_driver->getDevice());
dl->fromSTKEditBox(getID(), Text, m_mark_begin, m_mark_end, m_type);
Android_fromSTKEditBox(getID(), Text, m_mark_begin, m_mark_end, m_type);
}
#endif
}
@ -1163,7 +1159,7 @@ bool CGUIEditBox::processMouse(const SEvent& event)
{
#ifdef ANDROID
if (GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard())
irr_driver->getDevice()->toggleOnScreenKeyboard(true, m_type);
Android_toggleOnScreenKeyboard(true, m_type, CurrentTextRect.LowerRightCorner.Y + 5);
else
#endif
openScreenKeyboard();
@ -1382,7 +1378,7 @@ void CGUIEditBox::calculateScrollPos()
// todo: adjust scrollbar
// calculate the position of input composition window
#if defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
#if !defined(ANDROID) && defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
SDL_Rect rect;
rect.x = CurrentTextRect.UpperLeftCorner.X + m_cursor_distance - 1;
rect.y = CurrentTextRect.UpperLeftCorner.Y;
@ -1418,12 +1414,9 @@ void CGUIEditBox::setTextMarkers(s32 begin, s32 end)
sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED);
#ifdef ANDROID
if (GUIEngine::ScreenKeyboard::shouldUseScreenKeyboard() &&
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard() &&
irr_driver->getDevice()->getType() == irr::EIDT_ANDROID)
GUIEngine::ScreenKeyboard::hasSystemScreenKeyboard())
{
CIrrDeviceAndroid* dl = dynamic_cast<CIrrDeviceAndroid*>(
irr_driver->getDevice());
dl->fromSTKEditBox(getID(), Text, m_mark_begin, m_mark_end, m_type);
Android_fromSTKEditBox(getID(), Text, m_mark_begin, m_mark_end, m_type);
}
#endif
}

View File

@ -336,6 +336,9 @@ ANDROID_EDITTEXT_CALLBACK(ANDROID_PACKAGE_CALLBACK_NAME)
});
}
extern void Android_toggleOnScreenKeyboard(bool show, int type, int y);
extern bool Android_isHardwareKeyboardConnected();
#define MAKE_HANDLE_ACTION_NEXT_CALLBACK(x) JNIEXPORT void JNICALL Java_ ## x##_STKEditText_handleActionNext(JNIEnv* env, jobject this_obj, jint widget_id)
#define ANDROID_HANDLE_ACTION_NEXT_CALLBACK(PKG_NAME) MAKE_HANDLE_ACTION_NEXT_CALLBACK(PKG_NAME)
@ -352,12 +355,18 @@ ANDROID_HANDLE_ACTION_NEXT_CALLBACK(ANDROID_PACKAGE_CALLBACK_NAME)
if (!eb)
return;
bool has_hardware_keyboard = Android_isHardwareKeyboardConnected();
// First test for onEnterPressed, if true then close keyboard
if (eb->handleEnterPressed())
{
// Clear text like onEnterPressed callback
GUIEngine::getDevice()->toggleOnScreenKeyboard(false,
1/*clear_text*/);
// If hardware keyboard connected don't out focus stk edittext
if (has_hardware_keyboard)
tb->setText(L"");
else
{
// Clear text like onEnterPressed callback
Android_toggleOnScreenKeyboard(false, 1/*clear_text*/, 0/*y*/);
}
return;
}
@ -377,7 +386,7 @@ ANDROID_HANDLE_ACTION_NEXT_CALLBACK(ANDROID_PACKAGE_CALLBACK_NAME)
{
closest_tb->setFocusForPlayer(0);
}
else
else if (!has_hardware_keyboard)
{
// Post an enter event and close the keyboard
SEvent enter_event;
@ -388,8 +397,34 @@ ANDROID_HANDLE_ACTION_NEXT_CALLBACK(ANDROID_PACKAGE_CALLBACK_NAME)
GUIEngine::getDevice()->postEventFromUser(enter_event);
enter_event.KeyInput.PressedDown = false;
GUIEngine::getDevice()->postEventFromUser(enter_event);
GUIEngine::getDevice()->toggleOnScreenKeyboard(false);
Android_toggleOnScreenKeyboard(false, 1/*clear_text*/, 0/*y*/);
}
});
}
#define MAKE_HANDLE_LEFT_RIGHT_CALLBACK(x) JNIEXPORT void JNICALL Java_ ## x##_STKEditText_handleLeftRight(JNIEnv* env, jobject this_obj, jboolean left, jint widget_id)
#define ANDROID_HANDLE_LEFT_RIGHT_CALLBACK(PKG_NAME) MAKE_HANDLE_LEFT_RIGHT_CALLBACK(PKG_NAME)
extern "C"
ANDROID_HANDLE_LEFT_RIGHT_CALLBACK(ANDROID_PACKAGE_CALLBACK_NAME)
{
GUIEngine::addGUIFunctionBeforeRendering([left, widget_id]()
{
// Handle left, right pressed in android edit box, out focus it if
// no widget found
TextBoxWidget* tb =
dynamic_cast<TextBoxWidget*>(getFocusForPlayer(0));
if (!tb || (int)widget_id != tb->getID())
return;
int id = GUIEngine::EventHandler::get()->findIDClosestWidget(
left ? NAV_LEFT: NAV_RIGHT, 0, tb, true/*ignore_disabled*/);
Widget* next_widget = GUIEngine::getWidget(id);
if (next_widget)
next_widget->setFocusForPlayer(0);
else
tb->unsetFocusForPlayer(0);
});
}
#endif

View File

@ -26,10 +26,9 @@
#include <fstream>
#ifdef ANDROID
#include <android/asset_manager.h>
#include <SDL_system.h>
#include <sys/statfs.h>
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
#endif
//-----------------------------------------------------------------------------
@ -52,9 +51,6 @@ void AssetsAndroid::init()
if (m_file_manager == NULL)
return;
if (!global_android_app)
return;
bool needs_extract_data = false;
const std::string version = std::string("supertuxkart.") + STK_VERSION;
@ -64,18 +60,18 @@ void AssetsAndroid::init()
if (getenv("SUPERTUXKART_DATADIR"))
paths.push_back(getenv("SUPERTUXKART_DATADIR"));
if (global_android_app->activity->externalDataPath)
if (SDL_AndroidGetExternalStoragePath() != NULL)
{
m_file_manager->checkAndCreateDirectoryP(
global_android_app->activity->externalDataPath);
paths.push_back(global_android_app->activity->externalDataPath);
std::string external_storage_path = SDL_AndroidGetExternalStoragePath();
m_file_manager->checkAndCreateDirectoryP(external_storage_path);
paths.push_back(external_storage_path);
}
if (global_android_app->activity->internalDataPath)
if (SDL_AndroidGetInternalStoragePath() != NULL)
{
m_file_manager->checkAndCreateDirectoryP(
global_android_app->activity->internalDataPath);
paths.push_back(global_android_app->activity->internalDataPath);
std::string internal_storage_path = SDL_AndroidGetInternalStoragePath();
m_file_manager->checkAndCreateDirectoryP(internal_storage_path);
paths.push_back(internal_storage_path);
}
if (getenv("EXTERNAL_STORAGE"))
@ -229,11 +225,10 @@ void AssetsAndroid::init()
// Extract data directory from apk if it's needed
if (needs_extract_data)
{
m_progress_bar = new ProgressBarAndroid();
m_progress_bar->draw(0.01f);
if (hasAssets())
{
m_progress_bar = new ProgressBarAndroid();
m_progress_bar->draw(0.01f);
removeData();
extractData();
@ -242,10 +237,8 @@ void AssetsAndroid::init()
Log::fatal("AssetsAndroid", "Fatal error: Assets were not "
"extracted properly");
}
delete m_progress_bar;
}
delete m_progress_bar;
}
#endif
@ -258,7 +251,7 @@ void AssetsAndroid::init()
void AssetsAndroid::extractData()
{
#ifdef ANDROID
const std::string dirs_list = "directories.txt";
const std::string dirs_list = "files.txt";
bool success = true;
@ -267,7 +260,7 @@ void AssetsAndroid::extractData()
// Extract base directory first, so that we will be able to open the file
// with dir names
success = extractDir("");
success = extractFile("files.txt");
if (!success)
{
@ -301,13 +294,13 @@ void AssetsAndroid::extractData()
while (!file.eof())
{
std::string dir_name;
getline(file, dir_name);
std::string file_name;
getline(file, file_name);
if (dir_name.length() == 0 || dir_name.at(0) == '#')
if (file_name.length() == 0 || file_name.at(0) == '#')
continue;
success = extractDir(dir_name);
success = extractFile(file_name);
assert(lines_count > 0);
float pos = 0.01f + (float)(current_line) / lines_count * 0.99f;
@ -341,122 +334,83 @@ void AssetsAndroid::extractData()
}
//-----------------------------------------------------------------------------
/** A function that extracts selected directory from apk file
/** A function that extracts selected file or directory from apk file
* \param dir_name Directory to extract from assets
* \return True if successfully extracted
*/
bool AssetsAndroid::extractDir(std::string dir_name)
bool AssetsAndroid::extractFile(std::string filename)
{
#ifdef ANDROID
if (!global_android_app)
return false;
bool creating_dir = !filename.empty() && filename.back() == '/';
if (creating_dir)
Log::info("AssetsAndroid", "Creating %s directory", filename.c_str());
else
Log::info("AssetsAndroid", "Extracting %s file", filename.c_str());
AAssetManager* amgr = global_android_app->activity->assetManager;
Log::info("AssetsAndroid", "Extracting %s directory",
dir_name.length() > 0 ? dir_name.c_str() : "main");
std::string output_dir = dir_name;
std::string output_file = filename;
if (m_stk_dir.length() > 0)
{
output_dir = m_stk_dir + "/" + dir_name;
output_file = m_stk_dir + "/" + filename;
}
AAssetDir* asset_dir = AAssetManager_openDir(amgr, dir_name.c_str());
if (asset_dir == NULL)
if (creating_dir)
{
Log::warn("AssetsAndroid", "Couldn't get asset dir: %s",
dir_name.c_str());
bool dir_created = m_file_manager->checkAndCreateDirectoryP(output_file);
if (!dir_created)
{
Log::warn("AssetsAndroid", "Couldn't create %s directory",
output_file.c_str());
return false;
}
return true;
}
bool dir_created = m_file_manager->checkAndCreateDirectory(output_dir);
if (!dir_created)
SDL_RWops* asset = SDL_RWFromFile(filename.c_str(), "rb");
if (asset == NULL)
{
dir_created = m_file_manager->checkAndCreateDirectoryP(output_dir);
}
if (!dir_created)
{
Log::warn("AssetsAndroid", "Couldn't create %s directory",
output_dir.c_str());
return false;
Log::warn("AssetsAndroid", "Couldn't get asset: %s",
filename.c_str());
return true;
}
const int buf_size = 65536;
char* buf = new char[buf_size]();
bool extraction_failed = false;
while (!extraction_failed)
std::fstream out_file(output_file.c_str(), std::ios::out | std::ios::binary);
if (!out_file.good())
{
const char* filename = AAssetDir_getNextFileName(asset_dir);
// Check if finished
if (filename == NULL)
break;
if (strlen(filename) == 0)
continue;
std::string file_path = std::string(filename);
if (dir_name.length() > 0)
{
file_path = dir_name + "/" + std::string(filename);
}
AAsset* asset = AAssetManager_open(amgr, file_path.c_str(),
AASSET_MODE_STREAMING);
if (asset == NULL)
{
Log::warn("AssetsAndroid", "Asset is null: %s", filename);
continue;
}
std::string output_path = output_dir + "/" + std::string(filename);
std::fstream out_file(output_path, std::ios::out | std::ios::binary);
if (!out_file.good())
{
extraction_failed = true;
Log::error("AssetsAndroid", "Couldn't create a file: %s", filename);
AAsset_close(asset);
break;
}
int nb_read = 0;
while ((nb_read = AAsset_read(asset, buf, buf_size)) > 0)
{
out_file.write(buf, nb_read);
if (out_file.fail())
{
extraction_failed = true;
break;
}
}
out_file.close();
if (out_file.fail() || extraction_failed)
{
extraction_failed = true;
Log::error("AssetsAndroid", "Extraction failed for file: %s",
filename);
}
AAsset_close(asset);
Log::error("AssetsAndroid", "Couldn't create a file: %s",
output_file.c_str());
SDL_RWclose(asset);
return false;
}
size_t nb_read = 0;
while ((nb_read = SDL_RWread(asset, buf, 1, buf_size)) > 0)
{
out_file.write(buf, nb_read);
if (out_file.fail())
{
delete[] buf;
SDL_RWclose(asset);
return false;
}
}
out_file.close();
delete[] buf;
SDL_RWclose(asset);
AAssetDir_close(asset_dir);
if (out_file.fail())
{
Log::error("AssetsAndroid", "Extraction failed for file: %s",
filename.c_str());
return false;
}
return !extraction_failed;
return true;
#endif
return false;
@ -543,10 +497,7 @@ void AssetsAndroid::removeData()
bool AssetsAndroid::hasAssets()
{
#ifdef ANDROID
AAssetManager* amgr = global_android_app->activity->assetManager;
AAsset* asset = AAssetManager_open(amgr, "has_assets.txt",
AASSET_MODE_STREAMING);
SDL_RWops* asset = SDL_RWFromFile("has_assets.txt", "r");
if (asset == NULL)
{
@ -555,7 +506,7 @@ bool AssetsAndroid::hasAssets()
}
Log::info("AssetsAndroid", "Package has assets");
AAsset_close(asset);
SDL_RWclose(asset);
return true;
#endif
@ -659,13 +610,8 @@ std::string AssetsAndroid::getDataPath()
{
Log::warn("AssetsAndroid", "Cannot use standard data dir");
if (global_android_activity)
{
AndroidApplicationInfo application_info =
CIrrDeviceAndroid::getApplicationInfo(global_android_activity);
data_path = application_info.data_dir;
}
if (SDL_AndroidGetInternalStoragePath() != NULL)
data_path = SDL_AndroidGetInternalStoragePath();
if (access(data_path.c_str(), R_OK) != 0)
{
@ -678,31 +624,3 @@ std::string AssetsAndroid::getDataPath()
return "";
}
//-----------------------------------------------------------------------------
/** Get a path for internal lib directory
* \return Path for internal lib directory or empty string when failed
*/
std::string AssetsAndroid::getLibPath()
{
#ifdef ANDROID
std::string lib_path;
if (global_android_activity)
{
AndroidApplicationInfo application_info =
CIrrDeviceAndroid::getApplicationInfo(global_android_activity);
lib_path = application_info.native_lib_dir;
}
if (access(lib_path.c_str(), R_OK) != 0)
{
lib_path = "";
}
return lib_path;
#endif
return "";
}

View File

@ -31,7 +31,7 @@ private:
std::string m_stk_dir;
void extractData();
bool extractDir(std::string dir_name);
bool extractFile(std::string file_name);
void removeData();
bool hasAssets();
void touchFile(std::string path);
@ -44,7 +44,6 @@ public:
void init();
static std::string getDataPath();
static std::string getLibPath();
};

View File

@ -1924,7 +1924,9 @@ void main_abort()
#endif
// ----------------------------------------------------------------------------
#ifdef IOS_STK
#if defined(ANDROID)
int android_main(int argc, char *argv[])
#elif defined(IOS_STK)
int ios_main(int argc, char *argv[])
#else
int main(int argc, char *argv[])
@ -2175,18 +2177,12 @@ int main(int argc, char *argv[])
#ifdef MOBILE_STK
if (UserConfigParams::m_multitouch_controls == MULTITOUCH_CONTROLS_UNDEFINED)
{
#ifdef ANDROID
int32_t touch = AConfiguration_getTouchscreen(
global_android_app->config);
if (touch != ACONFIGURATION_TOUCHSCREEN_NOTOUCH)
if (irr_driver->getDevice()->supportsTouchDevice())
{
#endif
InitAndroidDialog* init_android = new InitAndroidDialog(
0.6f, 0.6f);
GUIEngine::DialogQueue::get()->pushDialog(init_android);
#ifdef ANDROID
}
#endif
}
#endif

View File

@ -23,21 +23,24 @@
#include "utils/string_utils.hpp"
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
#endif
#include "SDL_system.h"
#include <jni.h>
extern int main(int argc, char *argv[]);
extern int android_main(int argc, char *argv[]);
#ifdef ANDROID
struct android_app* global_android_app = NULL;
ANativeActivity* global_android_activity = NULL;
extern "C"
void override_default_params_for_mobile();
extern "C" int SDL_main(int argc, char *argv[])
{
void set_global_android_activity(ANativeActivity* activity)
{
global_android_activity = activity;
}
override_default_params_for_mobile();
int result = android_main(argc, argv);
// TODO: Irrlicht device is properly waiting for destroy event, but
// some global variables are not initialized/cleared in functions and thus
// its state is remembered when the window is restored. We will use exit
// call to make sure that all variables are cleared until a proper fix will
// be done.
fflush(NULL);
_exit(0);
return 0;
}
#endif
@ -64,22 +67,42 @@ void override_default_params_for_mobile()
#ifdef ANDROID
// Set multitouch device scale depending on actual screen size
int32_t screen_size = AConfiguration_getScreenSize(global_android_app->config);
const int SCREENLAYOUT_SIZE_SMALL = 1;
const int SCREENLAYOUT_SIZE_NORMAL = 2;
const int SCREENLAYOUT_SIZE_LARGE = 3;
const int SCREENLAYOUT_SIZE_XLARGE = 4;
int32_t screen_size = 0;
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
assert(env);
jobject activity = (jobject)SDL_AndroidGetActivity();
if (activity != NULL)
{
jclass clazz = env->GetObjectClass(activity);
if (clazz != NULL)
{
jmethodID method_id = env->GetMethodID(clazz, "getScreenSize",
"()I");
if (method_id != NULL)
screen_size = env->CallIntMethod(activity, method_id);
env->DeleteLocalRef(clazz);
}
env->DeleteLocalRef(activity);
}
switch (screen_size)
{
case ACONFIGURATION_SCREENSIZE_SMALL:
case ACONFIGURATION_SCREENSIZE_NORMAL:
case SCREENLAYOUT_SIZE_SMALL:
case SCREENLAYOUT_SIZE_NORMAL:
UserConfigParams::m_multitouch_scale.setDefaultValue(1.3f);
UserConfigParams::m_multitouch_sensitivity_x.setDefaultValue(0.1f);
UserConfigParams::m_font_size = 5.0f;
break;
case ACONFIGURATION_SCREENSIZE_LARGE:
case SCREENLAYOUT_SIZE_LARGE:
UserConfigParams::m_multitouch_scale.setDefaultValue(1.2f);
UserConfigParams::m_multitouch_sensitivity_x.setDefaultValue(0.15f);
UserConfigParams::m_font_size = 5.0f;
break;
case ACONFIGURATION_SCREENSIZE_XLARGE:
case SCREENLAYOUT_SIZE_XLARGE:
UserConfigParams::m_multitouch_scale.setDefaultValue(1.1f);
UserConfigParams::m_multitouch_sensitivity_x.setDefaultValue(0.2f);
UserConfigParams::m_font_size = 4.0f;
@ -179,29 +202,4 @@ void getConfigForDevice(const char* dev)
#endif
#ifdef ANDROID
void android_main(struct android_app* app)
{
Log::info("AndroidMain", "Loading application...");
global_android_app = app;
global_android_activity = app->activity;
app_dummy();
override_default_params_for_mobile();
main(0, {});
Log::info("AndroidMain", "Closing STK...");
// TODO: Irrlicht device is properly waiting for destroy event, but
// some global variables are not initialized/cleared in functions and thus
// its state is remembered when the window is restored. We will use exit
// call to make sure that all variables are cleared until a proper fix will
// be done.
fflush(NULL);
_exit(0);
}
#endif
#endif

View File

@ -1,29 +0,0 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2016-2017 SuperTuxKart-Team
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_MAIN_ANDROID_HPP
#define HEADER_MAIN_ANDROID_HPP
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/stk_android_native_app_glue.h"
extern struct android_app* global_android_app;
extern ANativeActivity* global_android_activity;
#endif
#endif

View File

@ -19,7 +19,7 @@
#include "main_loop.hpp"
#ifdef IOS_STK
#ifdef MOBILE_STK
#include "addons/addons_manager.hpp"
#endif
#include "audio/music_manager.hpp"
@ -111,6 +111,45 @@ MainLoop::~MainLoop()
{
} // ~MainLoop
#ifdef MOBILE_STK
//-----------------------------------------------------------------------------
extern "C" void pause_mainloop()
{
if (!main_loop)
return;
if (music_manager)
music_manager->pauseMusic();
if (SFXManager::get())
SFXManager::get()->pauseAll();
PlayerManager::get()->save();
if (addons_manager->hasDownloadedIcons())
addons_manager->saveInstalled();
Online::RequestManager::get()->setPaused(true);
IrrlichtDevice* dev = irr_driver->getDevice();
if (dev)
dev->resetPaused();
} // pause_mainloop
//-----------------------------------------------------------------------------
extern "C" void resume_mainloop()
{
if (!main_loop)
return;
IrrlichtDevice* dev = irr_driver->getDevice();
if (dev)
dev->resetUnpaused();
if (music_manager)
music_manager->resumeMusic();
if (SFXManager::get())
SFXManager::get()->resumeAll();
// Improve rubber banding effects of rewinders when going
// back to phone, because the smooth timer is paused
if (World::getWorld() && RewindManager::isEnabled())
RewindManager::get()->resetSmoothNetworkBody();
Online::RequestManager::get()->setPaused(false);
} // resume_mainloop
#endif
//-----------------------------------------------------------------------------
/** Returns the current dt, which guarantees a limited frame rate. If dt is
* too low (the frame rate too high), the process will sleep to reach the
@ -125,18 +164,7 @@ float MainLoop::getLimitedDt()
{
// When iOS apps entering background it should not run any
// opengl command from apple document, so we stop here
if (music_manager)
music_manager->pauseMusic();
if (SFXManager::get())
SFXManager::get()->pauseAll();
PlayerManager::get()->save();
if (addons_manager->hasDownloadedIcons())
addons_manager->saveInstalled();
Online::RequestManager::get()->setPaused(true);
IrrlichtDevice* dev = irr_driver->getDevice();
if (dev)
dev->resetPaused();
pause_mainloop();
while (true)
{
// iOS will pause this thread completely when fully in background
@ -148,21 +176,11 @@ float MainLoop::getLimitedDt()
{
if (quit)
return 1.0f/60.0f;
dev->resetUnpaused();
break;
}
}
if (music_manager)
music_manager->resumeMusic();
if (SFXManager::get())
SFXManager::get()->resumeAll();
// Improve rubber banding effects of rewinders when going
// back to phone, because the smooth timer is paused
if (World::getWorld() && RewindManager::isEnabled())
RewindManager::get()->resetSmoothNetworkBody();
Online::RequestManager::get()->setPaused(false);
resume_mainloop();
}
#endif
float dt = 0;
@ -729,7 +747,9 @@ void MainLoop::renderGUI(int phase, int loop_index, int loop_size)
} // renderGUI
/* EOF */
#if !defined(SERVER_ONLY) && defined(_IRR_COMPILE_WITH_SDL_DEVICE_)
#ifdef IOS_STK
// For iOS STK we need to make sure no rendering command is executed after pause
// so we need a handle_app_event callback
#include "SDL_events.h"
extern "C" int handle_app_event(void* userdata, SDL_Event* event)
{

View File

@ -54,8 +54,8 @@
#endif
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
#include "graphics/irr_driver.hpp"
#include <jni.h>
#include "SDL_system.h"
std::vector<std::pair<std::string, int> >* g_list = NULL;
@ -482,46 +482,28 @@ void NetworkConfig::fillStunList(std::vector<std::pair<std::string, int> >* l,
}
#elif defined(ANDROID)
CIrrDeviceAndroid* dev =
dynamic_cast<CIrrDeviceAndroid*>(irr_driver->getDevice());
if (!dev)
return;
android_app* android = dev->getAndroid();
if (!android)
return;
bool was_detached = false;
JNIEnv* env = NULL;
jint status = android->activity->vm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (status == JNI_EDETACHED)
{
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6;
args.name = "NativeThread";
args.group = NULL;
status = android->activity->vm->AttachCurrentThread(&env, &args);
was_detached = true;
}
if (status != JNI_OK)
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
if (env == NULL)
{
Log::error("NetworkConfig",
"Cannot attach current thread in getDNSSrvRecords.");
"getDNSSrvRecords unable to SDL_AndroidGetJNIEnv.");
return;
}
jobject native_activity = android->activity->clazz;
jclass class_native_activity = env->GetObjectClass(native_activity);
jobject native_activity = (jobject)SDL_AndroidGetActivity();
if (native_activity == NULL)
{
Log::error("NetworkConfig",
"getDNSSrvRecords unable to SDL_AndroidGetActivity.");
return;
}
jclass class_native_activity = env->GetObjectClass(native_activity);
if (class_native_activity == NULL)
{
Log::error("NetworkConfig",
"getDNSSrvRecords unable to find object class.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(native_activity);
return;
}
@ -532,10 +514,8 @@ void NetworkConfig::fillStunList(std::vector<std::pair<std::string, int> >* l,
{
Log::error("NetworkConfig",
"getDNSSrvRecords unable to find method id.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return;
}
@ -548,19 +528,16 @@ void NetworkConfig::fillStunList(std::vector<std::pair<std::string, int> >* l,
{
Log::error("NetworkConfig",
"Failed to create text for domain name.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return;
}
g_list = l;
env->CallVoidMethod(native_activity, method_id, text);
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(text);
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
g_list = NULL;
#elif !defined(__CYGWIN__)

View File

@ -43,8 +43,8 @@
#include "utils/translation.hpp"
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
#include "graphics/irr_driver.hpp"
#include <jni.h>
#include "SDL_system.h"
#include "utils/utf8/unchecked.h"
#endif
@ -526,46 +526,30 @@ bool ConnectToServer::registerWithSTKServer()
auto get_txt_record = [](const core::stringw& name)->std::vector<std::string>
{
std::vector<std::string> result;
CIrrDeviceAndroid* dev =
dynamic_cast<CIrrDeviceAndroid*>(irr_driver->getDevice());
if (!dev)
return result;
android_app* android = dev->getAndroid();
if (!android)
return result;
bool was_detached = false;
JNIEnv* env = NULL;
jint status = android->activity->vm->GetEnv((void**)&env, JNI_VERSION_1_6);
if (status == JNI_EDETACHED)
{
JavaVMAttachArgs args;
args.version = JNI_VERSION_1_6;
args.name = "NativeThread";
args.group = NULL;
status = android->activity->vm->AttachCurrentThread(&env, &args);
was_detached = true;
}
if (status != JNI_OK)
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
if (env == NULL)
{
Log::error("ConnectToServer",
"Cannot attach current thread in getDNSTxtRecords.");
"getDNSSrvRecords unable to SDL_AndroidGetJNIEnv.");
return result;
}
jobject native_activity = (jobject)SDL_AndroidGetActivity();
if (native_activity == NULL)
{
Log::error("ConnectToServer",
"getDNSSrvRecords unable to SDL_AndroidGetActivity.");
return result;
}
jobject native_activity = android->activity->clazz;
jclass class_native_activity = env->GetObjectClass(native_activity);
if (class_native_activity == NULL)
{
Log::error("ConnectToServer",
"getDNSTxtRecords unable to find object class.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(native_activity);
return result;
}
@ -576,10 +560,8 @@ auto get_txt_record = [](const core::stringw& name)->std::vector<std::string>
{
Log::error("ConnectToServer",
"getDNSTxtRecords unable to find method id.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return result;
}
@ -592,10 +574,8 @@ auto get_txt_record = [](const core::stringw& name)->std::vector<std::string>
{
Log::error("ConnectToServer",
"Failed to create text for domain name.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return result;
}
@ -604,10 +584,9 @@ auto get_txt_record = [](const core::stringw& name)->std::vector<std::string>
if (arr == NULL)
{
Log::error("ConnectToServer", "No array is created.");
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(text);
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return result;
}
int len = env->GetArrayLength(arr);
@ -619,18 +598,22 @@ auto get_txt_record = [](const core::stringw& name)->std::vector<std::string>
const uint16_t* utf16_text =
(const uint16_t*)env->GetStringChars(jstr, NULL);
if (utf16_text == NULL)
{
env->DeleteLocalRef(jstr);
continue;
}
const size_t str_len = env->GetStringLength(jstr);
std::string tmp;
utf8::unchecked::utf16to8(
utf16_text, utf16_text + str_len, std::back_inserter(tmp));
result.push_back(tmp);
env->ReleaseStringChars(jstr, utf16_text);
env->DeleteLocalRef(jstr);
}
if (was_detached)
{
android->activity->vm->DetachCurrentThread();
}
env->DeleteLocalRef(arr);
env->DeleteLocalRef(text);
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return result;
};
#endif

View File

@ -37,7 +37,6 @@
#include "network/stk_ipv6.hpp"
#include "network/stk_peer.hpp"
#include "utils/log.hpp"
#include "utils/separate_process.hpp"
#include "utils/string_utils.hpp"
#include "utils/time.hpp"
#include "utils/vs.hpp"

View File

@ -24,7 +24,8 @@
#endif
#ifdef ANDROID
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
#include <jni.h>
#include "SDL_system.h"
#endif
#ifdef IOS_STK
@ -47,9 +48,45 @@ namespace Online
void LinkHelper::openURL (std::string url)
{
#if defined(ANDROID)
CIrrDeviceAndroid* android = dynamic_cast<CIrrDeviceAndroid*>(irr_driver->getDevice());
if (android)
android->openURL(url);
JNIEnv* env = (JNIEnv*)SDL_AndroidGetJNIEnv();
if (env == NULL)
{
Log::error("LinkHelper",
"openURL unable to SDL_AndroidGetJNIEnv.");
return;
}
jobject native_activity = (jobject)SDL_AndroidGetActivity();
if (native_activity == NULL)
{
Log::error("LinkHelper",
"openURL unable to SDL_AndroidGetActivity.");
return;
}
jclass class_native_activity = env->GetObjectClass(native_activity);
if (class_native_activity == NULL)
{
Log::error("LinkHelper", "openURL unable to find object class.");
env->DeleteLocalRef(native_activity);
return;
}
jmethodID method_id = env->GetMethodID(class_native_activity, "openURL", "(Ljava/lang/String;)V");
if (method_id == NULL)
{
Log::error("LinkHelper", "openURL unable to find method id.");
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
return;
}
jstring url_jstring = env->NewStringUTF(url.c_str());
env->CallVoidMethod(native_activity, method_id, url_jstring);
env->DeleteLocalRef(url_jstring);
env->DeleteLocalRef(class_native_activity);
env->DeleteLocalRef(native_activity);
#elif defined(_WIN32)
ShellExecuteA(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL);
#elif defined(IOS_STK)

View File

@ -489,12 +489,7 @@ void MainMenuScreen::eventCallback(Widget* widget, const std::string& name,
}
else if (selection == "quit")
{
#ifdef ANDROID
GUIEngine::EventHandler::get()->setAcceptEvents(false);
ANativeActivity_finish(global_android_app->activity);
#else
StateManager::get()->popMenu();
#endif
return;
}
else if (selection == "about")
@ -638,11 +633,5 @@ void MainMenuScreen::onDisabledItemClicked(const std::string& item)
bool MainMenuScreen::onEscapePressed()
{
#ifdef ANDROID
GUIEngine::EventHandler::get()->setAcceptEvents(false);
ANativeActivity_finish(global_android_app->activity);
return false;
#endif
return true;
} // onEscapePressed

View File

@ -27,12 +27,6 @@
#include "utils/constants.hpp"
#include "utils/log.hpp"
#ifdef ANDROID
#include <android/asset_manager.h>
#include "../../../lib/irrlicht/source/Irrlicht/CIrrDeviceAndroid.h"
extern struct android_app* global_android_app;
#endif
// ----------------------------------------------------------------------------
bool ExtractMobileAssets::hasFullAssets()
{

View File

@ -147,9 +147,8 @@ void ProgressBarAndroid::init()
params.Bits = 32;
params.Fullscreen = UserConfigParams::m_fullscreen;
params.WindowSize = core::dimension2du(640, 480);
#if defined(ANDROID)
params.PrivateData = (void*)global_android_app;
#endif
params.PrivateData = NULL;
m_device = createDeviceEx(params);

View File

@ -1,650 +0,0 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2018 Joerg Henrichs
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "utils/separate_process.hpp"
#include "io/file_manager.hpp"
#include "utils/command_line.hpp"
#include "utils/log.hpp"
#include "utils/string_utils.hpp"
#ifdef __APPLE__
# include <mach-o/dyld.h>
#endif
#ifdef WIN32
# include <windows.h>
#else
# include <iostream>
# include <unistd.h>
# include <signal.h>
# include <sys/wait.h>
# include <errno.h>
#endif
#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/sysctl.h>
#endif
#ifdef ANDROID
#include <dlfcn.h>
#include <fstream>
#include "main_android.hpp"
#include "io/assets_android.hpp"
#endif
#ifdef __HAIKU__
#include <kernel/image.h>
#endif
// ----------------------------------------------------------------------------
std::string SeparateProcess::getCurrentExecutableLocation()
{
#ifdef WIN32
// We already set the full path of exe name in windows
return CommandLine::getExecName();
#elif defined (__APPLE__)
char path[1024];
unsigned buf_size = 1024;
if (_NSGetExecutablePath(path, &buf_size) == 0)
{
return file_manager->getFileSystem()->getAbsolutePath(path).c_str();
}
return "";
#elif defined (__FreeBSD__)
char path[PATH_MAX];
size_t len = PATH_MAX;
const int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
if (sysctl(&mib[0], 4, &path, &len, NULL, 0) == 0)
{
return file_manager->getFileSystem()->getAbsolutePath(path).c_str();
}
return "";
#elif defined(__NetBSD__)
return file_manager->getFileSystem()->getAbsolutePath("/proc/curproc/exe")
.c_str();
#elif defined(__HAIKU__)
image_info ii;
int32_t g = 0;
while (get_next_image_info(0, &g, &ii) == B_OK)
{
if (ii.type == B_APP_IMAGE)
break;
}
if (ii.type != B_APP_IMAGE)
{
return "";
}
return file_manager->getFileSystem()->getAbsolutePath(ii.name).c_str();
#else
// Assume Linux
return file_manager->getFileSystem()->getAbsolutePath("/proc/self/exe")
.c_str();
#endif
} // getCurrentExecutableLocation
// ----------------------------------------------------------------------------
SeparateProcess::SeparateProcess(const std::string& exe,
const std::string& argument, bool create_pipe,
const std::string& childprocess_name)
{
#ifdef ANDROID
m_child_handle = NULL;
m_child_abort_proc = NULL;
#endif
if (!createChildProcess(exe, argument, create_pipe, childprocess_name))
{
Log::error("SeparateProcess", "Failed to run %s %s",
exe.c_str(), argument.c_str());
return;
}
} // SeparateProcess
// ----------------------------------------------------------------------------
SeparateProcess::~SeparateProcess()
{
bool dead = false;
#if defined(WIN32)
core::stringw class_name = "separate_process";
class_name += StringUtils::toWString(m_child_pid);
HWND hwnd = FindWindowEx(HWND_MESSAGE, NULL, class_name.c_str(), NULL);
if (hwnd != NULL)
{
PostMessage(hwnd, WM_DESTROY, 0, 0);
if (WaitForSingleObject(m_child_handle, 5000) != WAIT_TIMEOUT)
{
dead = true;
}
}
if (!dead)
{
Log::info("SeparateProcess", "Timeout waiting for child process to "
"self-destroying, killing it anyway");
if (TerminateProcess(m_child_handle, 0) == 0)
Log::warn("SeparateProcess", "Failed to kill child process.");
}
if (CloseHandle(m_child_handle) == 0)
Log::warn("SeparateProcess", "Failed to close child process handle.");
#elif defined(ANDROID)
if (m_child_handle != NULL)
{
Log::info("SeparateProcess", "Closing child process");
m_child_abort_proc();
StkTime::sleep(1000);
if (m_child_thread.joinable())
{
Log::info("SeparateProcess", "Wait for closing");
m_child_thread.join();
}
dlclose(m_child_handle);
m_child_handle = NULL;
m_child_abort_proc = NULL;
for (char* arg : m_child_args)
{
delete[] arg;
}
}
#else
if (m_child_stdin_write != -1 && m_child_stdout_read != -1)
{
close(m_child_stdin_write);
close(m_child_stdout_read);
}
if (m_child_pid != -1)
{
kill(m_child_pid, SIGTERM);
for (int i = 0; i < 5; i++)
{
int status;
if (waitpid(m_child_pid, &status, WNOHANG) == m_child_pid)
{
dead = true;
break;
}
StkTime::sleep(1000);
}
if (!dead)
{
Log::info("SeparateProcess", "Timeout waiting for child process to "
"self-destroying, killing it anyway");
kill(m_child_pid, SIGKILL);
}
}
#endif
Log::info("SeparateProcess", "Destroyed");
} // ~SeparateProcess
// ----------------------------------------------------------------------------
/** Starts separate as a child process
* and sets up communication via pipes.
* \return True if the child process creation was successful.
*/
#if defined(WIN32)
bool SeparateProcess::createChildProcess(const std::string& exe,
const std::string& argument,
bool create_pipe,
const std::string& childprocess_name)
{
int error = 0;
// Based on: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
SECURITY_ATTRIBUTES sec_attr;
// Set the bInheritHandle flag so pipe handles are inherited.
sec_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sec_attr.bInheritHandle = TRUE;
sec_attr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT if needed.
if (create_pipe)
{
if (!CreatePipe(&m_child_stdout_read, &m_child_stdout_write, &sec_attr, 0))
{
error = GetLastError();
Log::error("SeparateProcess", "StdoutRd CreatePipe error code: %d",
error);
return false;
}
// Ensure the read handle to the pipe for STDOUT is not inherited.
if (!SetHandleInformation(m_child_stdout_read, HANDLE_FLAG_INHERIT, 0))
{
error = GetLastError();
Log::error("SeparateProcess",
"Stdout SetHandleInformation error code: %d", error);
return false;
}
// Create a pipe for the child process's STDIN.
if (!CreatePipe(&m_child_stdin_read, &m_child_stdin_write, &sec_attr, 0))
{
error = GetLastError();
Log::error("SeparateProcess", "Stdin CreatePipe error code: %d",
error);
return false;
}
// Ensure the write handle to the pipe for STDIN is not inherited.
if (!SetHandleInformation(m_child_stdin_write, HANDLE_FLAG_INHERIT, 0))
{
error = GetLastError();
Log::error("SeparateProcess",
"Stdin SetHandleInformation error code: %d", error);
return false;
}
}
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
if (create_pipe)
{
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdError = m_child_stdout_write;
siStartInfo.hStdOutput = m_child_stdout_write;
siStartInfo.hStdInput = m_child_stdin_read;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
}
// Create the child process.
std::string cmd = " "; // Required for 1st argument
cmd += argument + " --parent-process=" +
StringUtils::toString(GetCurrentProcessId());
core::stringw exe_w = StringUtils::utf8ToWide(exe);
core::stringw cmd_w = StringUtils::utf8ToWide(cmd);
bool success = CreateProcess(exe_w.data(), // application name
cmd_w.data(), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
CREATE_NO_WINDOW, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo) != 0; // receives PROCESS_INFORMATION
if (!success)
{
error = GetLastError();
Log::error("SeparateProcess", "CreateProcess error code: %d", error);
return false;
}
m_child_handle = piProcInfo.hProcess;
m_child_pid = piProcInfo.dwProcessId;
if (m_child_pid == 0)
{
Log::warn("SeparateProcess", "Invalid child pid.");
return false;
}
if (CloseHandle(piProcInfo.hThread) == 0)
Log::warn("SeparateProcess", "Failed to close child thread handle.");
return true;
} // createChildProcess - windows version
#elif defined(ANDROID)
bool SeparateProcess::createChildProcess(const std::string& exe,
const std::string& argument,
bool create_pipe,
const std::string& childprocess_name)
{
if (create_pipe)
{
Log::error("SeparateProcess", "Error: create_pipe is not supported.");
return false;
}
if (m_child_handle != NULL)
{
Log::error("SeparateProcess", "Error: Child process is already started");
return false;
}
std::string data_path = AssetsAndroid::getDataPath();
std::string main_path;
if (!data_path.empty())
{
main_path = data_path + "/lib/libmain.so";
}
if (main_path.empty() || access(main_path.c_str(), R_OK) != 0)
{
std::string lib_path = AssetsAndroid::getLibPath();
if (!lib_path.empty())
{
main_path = lib_path + "/libmain.so";
}
Log::info("SeparateProcess", "Trying to use fallback lib path: %s",
main_path.c_str());
}
if (main_path.empty() || access(main_path.c_str(), R_OK) != 0)
{
Log::error("SeparateProcess", "Error: Cannot read libmain.so");
return false;
}
Log::info("SeparateProcess", "Data dir found in: %s", data_path.c_str());
std::string child_path = data_path + "/files/lib" +
childprocess_name + ".so";
if (access(child_path.c_str(), R_OK) != 0)
{
Log::info("SeparateProcess", "Creating libchildprocess.so");
std::ifstream src(main_path, std::ios::binary);
if (!src.good())
{
Log::error("SeparateProcess", "Error: Cannot open libmain.so");
return false;
}
std::ofstream dst(child_path, std::ios::binary);
if (!dst.good())
{
Log::error("SeparateProcess", "Error: Cannot copy libmain.so");
return false;
}
dst << src.rdbuf();
}
if (access(child_path.c_str(), R_OK) != 0)
{
Log::error("SeparateProcess", "Error: Cannot read libchildprocess.so");
return false;
}
m_child_handle = dlopen(child_path.c_str(), RTLD_NOW);
if (m_child_handle == NULL)
{
Log::error("SeparateProcess", "Error: Cannot dlopen libchildprocess.so");
return false;
}
typedef void (*main_proc_t)(int, char**);
main_proc_t main_proc = (main_proc_t)dlsym(m_child_handle, "main");
if (main_proc == NULL)
{
Log::error("SeparateProcess", "Error: Cannot get handle to main()");
dlclose(m_child_handle);
m_child_handle = NULL;
return false;
}
m_child_abort_proc = (void(*)())dlsym(m_child_handle, "main_abort");
if (m_child_abort_proc == NULL)
{
Log::error("SeparateProcess", "Error: Cannot get handle to main_abort()");
dlclose(m_child_handle);
m_child_handle = NULL;
return false;
}
typedef void (*set_activity_proc_t)(ANativeActivity*);
set_activity_proc_t set_activity_proc =
(set_activity_proc_t)dlsym(m_child_handle, "set_global_android_activity");
if (set_activity_proc == NULL)
{
Log::error("SeparateProcess", "Error: Cannot get handle to "
"set_global_android_activity()");
dlclose(m_child_handle);
m_child_handle = NULL;
return false;
}
set_activity_proc(global_android_activity);
const std::string exe_file = StringUtils::getBasename(exe);
auto rest_argv = StringUtils::split(argument, ' ');
char* arg = new char[exe_file.size() + 1]();
memcpy(arg, exe_file.c_str(), exe_file.size());
m_child_args.push_back(arg);
for (unsigned i = 0; i < rest_argv.size(); i++)
{
char* arg = new char[rest_argv[i].size() + 1]();
memcpy(arg, rest_argv[i].c_str(), rest_argv[i].size());
m_child_args.push_back(arg);
}
Log::info("SeparateProcess", "Starting main()");
m_child_thread = std::thread(main_proc, m_child_args.size(), &m_child_args[0]);
return true;
}
#else // linux and osx
bool SeparateProcess::createChildProcess(const std::string& exe,
const std::string& argument,
bool create_pipe,
const std::string& childprocess_name)
{
const int PIPE_READ=0;
const int PIPE_WRITE=1;
int stdin_pipe[2];
int stdout_pipe[2];
int child;
if (create_pipe)
{
if (pipe(stdin_pipe) < 0)
{
Log::error("SeparateProcess", "Can't allocate pipe for input "
"redirection.");
return -1;
}
if (pipe(stdout_pipe) < 0)
{
close(stdin_pipe[PIPE_READ]);
close(stdin_pipe[PIPE_WRITE]);
Log::error("SeparateProcess", "allocating pipe for child output "
"redirect");
return false;
}
}
std::string parent_pid = "--parent-process=";
int current_pid = getpid();
parent_pid += StringUtils::toString(current_pid);
child = fork();
if (child == 0)
{
// Child process:
Log::info("SeparateProcess", "Child process started.");
if (create_pipe)
{
// redirect stdin
if (dup2(stdin_pipe[PIPE_READ], STDIN_FILENO) == -1)
{
Log::error("SeparateProcess", "Redirecting stdin");
return false;
}
// redirect stdout
if (dup2(stdout_pipe[PIPE_WRITE], STDOUT_FILENO) == -1)
{
Log::error("SeparateProcess", "Redirecting stdout");
return false;
}
// all these are for use by parent only
close(stdin_pipe[PIPE_READ]);
close(stdin_pipe[PIPE_WRITE]);
close(stdout_pipe[PIPE_READ]);
close(stdout_pipe[PIPE_WRITE]);
}
// run child process image
std::vector<char*> argv;
const std::string exe_file = StringUtils::getBasename(exe);
auto rest_argv = StringUtils::split(argument, ' ');
argv.push_back(const_cast<char*>(exe_file.c_str()));
for (unsigned i = 0; i < rest_argv.size(); i++)
argv.push_back(const_cast<char*>(rest_argv[i].c_str()));
argv.push_back(const_cast<char*>(parent_pid.c_str()));
argv.push_back(NULL);
execvp(exe.c_str(), argv.data());
Log::error("SeparateProcess", "Error in execl: errnp %d", errno);
// if we get here at all, an error occurred, but we are in the child
// process, so just exit
perror("SeparateProcess: execl error");
exit(-1);
}
else if (child > 0)
{
m_child_pid = child;
if (create_pipe)
{
// parent continues here
// close unused file descriptors, these are for child only
close(stdin_pipe[PIPE_READ]);
close(stdout_pipe[PIPE_WRITE]);
m_child_stdin_write = stdin_pipe[PIPE_WRITE];
m_child_stdout_read = stdout_pipe[PIPE_READ];
}
}
else // child < 0
{
if (create_pipe)
{
// failed to create child
close(stdin_pipe[PIPE_READ]);
close(stdin_pipe[PIPE_WRITE]);
close(stdout_pipe[PIPE_READ]);
close(stdout_pipe[PIPE_WRITE]);
}
return false;
}
return true;
} // createChildProcess
#endif
// ----------------------------------------------------------------------------
/** Reads a command from the input pipe.
*/
std::string SeparateProcess::getLine()
{
#define BUFSIZE 1024
char buffer[BUFSIZE];
#if defined(WIN32)
DWORD bytes_read;
// Read from pipe that is the standard output for child process.
bool success = ReadFile(m_child_stdout_read, buffer, BUFSIZE-1,
&bytes_read, NULL)!=0;
if (success && bytes_read < BUFSIZE)
{
buffer[bytes_read] = 0;
std::string s = buffer;
return s;
}
#elif defined(ANDROID)
return "";
#else
//std::string s;
//std::getline(std::cin, s);
//return s;
int bytes_read = read(m_child_stdout_read, buffer, BUFSIZE-1);
if(bytes_read>0)
{
buffer[bytes_read] = 0;
std::string s = buffer;
return s;
}
#endif
return std::string("");
} // getLine
// ----------------------------------------------------------------------------
/** Sends a command to the SeparateProcess via a pipe, and reads the answer.
* \return Answer from SeparateProcess.
*/
std::string SeparateProcess::sendCommand(const std::string &command)
{
#if defined(WIN32)
// Write to the pipe that is the standard input for a child process.
// Data is written to the pipe's buffers, so it is not necessary to wait
// until the child process is running before writing data.
DWORD bytes_written;
bool success = WriteFile(m_child_stdin_write, command.c_str(),
unsigned(command.size()) + 1, &bytes_written, NULL) != 0;
#elif defined(ANDROID)
#else
write(m_child_stdin_write, (command+"\n").c_str(), command.size()+1);
#endif
return getLine();
return std::string("");
} // sendCommand
// ----------------------------------------------------------------------------
/** All answer strings from SeparateProcess are in the form: "length string",
* i.e. the length of the string, followed by a space and then the actual
* strings. This allows for checking on some potential problems (e.g. if a
* pipe should only send part of the answer string - todo: handle this problem
* instead of ignoring it.
*/
std::string SeparateProcess::decodeString(const std::string &s)
{
std::vector<std::string> l = StringUtils::split(s, ' ');
if (l.size() != 2) return "INVALID ANSWER - wrong number of fields";
int n;
StringUtils::fromString(l[0], n);
if (n != (int)l[1].size()) return "INVALID ANSWER - incorrect length";
return l[1];
} // decodeString

View File

@ -1,75 +0,0 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2018 Joerg Henrichs
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_SEPERATE_PROCESS_HPP
#define HEADER_SEPERATE_PROCESS_HPP
#ifdef WIN32
# include <windows.h>
#endif
#include <assert.h>
#include <string>
#include <thread>
#include <vector>
class SeparateProcess
{
private:
#if defined(WIN32)
// Various handles for the window pipes
HANDLE m_child_stdin_read;
HANDLE m_child_stdin_write;
HANDLE m_child_stdout_read;
HANDLE m_child_stdout_write;
HANDLE m_child_handle;
DWORD m_child_pid;
#elif defined(ANDROID)
void* m_child_handle;
void (*m_child_abort_proc)();
std::thread m_child_thread;
std::vector<char*> m_child_args;
#else
int m_child_stdin_write = -1;
int m_child_stdout_read = -1;
int m_child_pid = -1;
#endif
// ------------------------------------------------------------------------
bool createChildProcess(const std::string& exe,
const std::string& argument, bool create_pipe,
const std::string& childprocess_name);
// ------------------------------------------------------------------------
std::string getLine();
public:
// ------------------------------------------------------------------------
static std::string getCurrentExecutableLocation();
// ------------------------------------------------------------------------
SeparateProcess(const std::string& exe, const std::string& argument,
bool create_pipe = false,
const std::string& childprocess_name = "childprocess");
// ------------------------------------------------------------------------
~SeparateProcess();
// ------------------------------------------------------------------------
std::string sendCommand(const std::string &command);
// ------------------------------------------------------------------------
std::string decodeString(const std::string &s);
}; // class SeparateProcess
#endif // HEADER_SEPERATE_PROCESS_HPP

View File

@ -45,12 +45,8 @@
#include "utils/log.hpp"
#include "utils/string_utils.hpp"
#ifdef ANDROID
#include "main_android.hpp"
#endif
#ifdef IOS_STK
#include "../../lib/irrlicht/source/Irrlicht/CIrrDeviceiOS.h"
#ifdef MOBILE_STK
#include "SDL_locale.h"
#endif
// set to 1 to debug i18n
@ -325,13 +321,29 @@ Translations::Translations() //: m_dictionary_manager("UTF-16")
language = p_lang;
else
{
#ifdef IOS_STK
language = irr::CIrrDeviceiOS::getSystemLanguageCode();
if (language.find("zh-Hans") != std::string::npos)
language = "zh_CN";
else if (language.find("zh-Hant") != std::string::npos)
language = "zh_TW";
language = StringUtils::findAndReplace(language, "-", "_");
#ifdef MOBILE_STK
SDL_Locale* locale = SDL_GetPreferredLocales();
if (locale)
{
// First locale only
for (int l = 0; locale[l].language != NULL; l++)
{
language = locale[l].language;
if (locale[l].country != NULL)
{
language += "-";
language += locale[l].country;
}
// iOS specific
if (language.find("zh-Hans") != std::string::npos)
language = "zh_CN";
else if (language.find("zh-Hant") != std::string::npos)
language = "zh_TW";
language = StringUtils::findAndReplace(language, "-", "_");
break;
}
SDL_free(locale);
}
#elif defined(WIN32)
// Thanks to the frogatto developer for this code snippet:
char c[1024];
@ -348,29 +360,6 @@ Translations::Translations() //: m_dictionary_manager("UTF-16")
"GetLocaleInfo tryname returns '%s'.", c);
if(c[0]) language += std::string("_")+c;
} // if c[0]
#elif defined(ANDROID)
if (global_android_app)
{
char p_language[3] = {};
AConfiguration_getLanguage(global_android_app->config,
p_language);
std::string s_language(p_language);
if (!s_language.empty())
{
language += s_language;
char p_country[3] = {};
AConfiguration_getCountry(global_android_app->config,
p_country);
std::string s_country(p_country);
if (!s_country.empty())
{
language += "_";
language += s_country;
}
}
}
#endif
} // neither LANGUAGE nor LANG defined