SDLActivity.java 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. package org.libsdl.app;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.ArrayList;
  5. import java.util.Arrays;
  6. import java.util.Collections;
  7. import java.util.Comparator;
  8. import java.util.List;
  9. import java.lang.reflect.Method;
  10. import android.app.*;
  11. import android.content.*;
  12. import android.view.*;
  13. import android.view.inputmethod.BaseInputConnection;
  14. import android.view.inputmethod.EditorInfo;
  15. import android.view.inputmethod.InputConnection;
  16. import android.view.inputmethod.InputMethodManager;
  17. import android.widget.AbsoluteLayout;
  18. import android.widget.Button;
  19. import android.widget.LinearLayout;
  20. import android.widget.TextView;
  21. import android.os.*;
  22. import android.util.Log;
  23. import android.util.SparseArray;
  24. import android.graphics.*;
  25. import android.media.*;
  26. import android.hardware.*;
  27. /**
  28. SDL Activity
  29. */
  30. public class SDLActivity extends Activity {
  31. private static final String TAG = "SDL";
  32. // Keep track of the paused state
  33. public static boolean mIsPaused, mIsSurfaceReady, mHasFocus;
  34. public static boolean mExitCalledFromJava;
  35. // Main components
  36. protected static SDLActivity mSingleton;
  37. protected static SDLSurface mSurface;
  38. protected static View mTextEdit;
  39. protected static ViewGroup mLayout;
  40. protected static SDLJoystickHandler mJoystickHandler;
  41. // This is what SDL runs in. It invokes SDL_main(), eventually
  42. protected static Thread mSDLThread;
  43. // Audio
  44. protected static AudioTrack mAudioTrack;
  45. // Load the .so
  46. static {
  47. System.loadLibrary("SDL2");
  48. //System.loadLibrary("SDL2_image");
  49. //System.loadLibrary("SDL2_mixer");
  50. //System.loadLibrary("SDL2_net");
  51. //System.loadLibrary("SDL2_ttf");
  52. System.loadLibrary("main");
  53. }
  54. public static void initialize() {
  55. // The static nature of the singleton and Android quirkyness force us to initialize everything here
  56. // Otherwise, when exiting the app and returning to it, these variables *keep* their pre exit values
  57. mSingleton = null;
  58. mSurface = null;
  59. mTextEdit = null;
  60. mLayout = null;
  61. mJoystickHandler = null;
  62. mSDLThread = null;
  63. mAudioTrack = null;
  64. mExitCalledFromJava = false;
  65. mIsPaused = false;
  66. mIsSurfaceReady = false;
  67. mHasFocus = true;
  68. }
  69. // Setup
  70. @Override
  71. protected void onCreate(Bundle savedInstanceState) {
  72. Log.v("SDL", "onCreate():" + mSingleton);
  73. super.onCreate(savedInstanceState);
  74. SDLActivity.initialize();
  75. // So we can call stuff from static callbacks
  76. mSingleton = this;
  77. // Set up the surface
  78. mSurface = new SDLSurface(getApplication());
  79. if(Build.VERSION.SDK_INT >= 12) {
  80. mJoystickHandler = new SDLJoystickHandler_API12();
  81. }
  82. else {
  83. mJoystickHandler = new SDLJoystickHandler();
  84. }
  85. mLayout = new AbsoluteLayout(this);
  86. mLayout.addView(mSurface);
  87. setContentView(mLayout);
  88. }
  89. // Events
  90. @Override
  91. protected void onPause() {
  92. Log.v("SDL", "onPause()");
  93. super.onPause();
  94. SDLActivity.handlePause();
  95. }
  96. @Override
  97. protected void onResume() {
  98. Log.v("SDL", "onResume()");
  99. super.onResume();
  100. SDLActivity.handleResume();
  101. }
  102. @Override
  103. public void onWindowFocusChanged(boolean hasFocus) {
  104. super.onWindowFocusChanged(hasFocus);
  105. Log.v("SDL", "onWindowFocusChanged(): " + hasFocus);
  106. SDLActivity.mHasFocus = hasFocus;
  107. if (hasFocus) {
  108. SDLActivity.handleResume();
  109. }
  110. }
  111. @Override
  112. public void onLowMemory() {
  113. Log.v("SDL", "onLowMemory()");
  114. super.onLowMemory();
  115. SDLActivity.nativeLowMemory();
  116. }
  117. @Override
  118. protected void onDestroy() {
  119. Log.v("SDL", "onDestroy()");
  120. // Send a quit message to the application
  121. SDLActivity.mExitCalledFromJava = true;
  122. SDLActivity.nativeQuit();
  123. // Now wait for the SDL thread to quit
  124. if (SDLActivity.mSDLThread != null) {
  125. try {
  126. SDLActivity.mSDLThread.join();
  127. } catch(Exception e) {
  128. Log.v("SDL", "Problem stopping thread: " + e);
  129. }
  130. SDLActivity.mSDLThread = null;
  131. //Log.v("SDL", "Finished waiting for SDL thread");
  132. }
  133. super.onDestroy();
  134. // Reset everything in case the user re opens the app
  135. SDLActivity.initialize();
  136. }
  137. @Override
  138. public boolean dispatchKeyEvent(KeyEvent event) {
  139. int keyCode = event.getKeyCode();
  140. // Ignore certain special keys so they're handled by Android
  141. if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
  142. keyCode == KeyEvent.KEYCODE_VOLUME_UP ||
  143. keyCode == KeyEvent.KEYCODE_CAMERA ||
  144. keyCode == 168 || /* API 11: KeyEvent.KEYCODE_ZOOM_IN */
  145. keyCode == 169 /* API 11: KeyEvent.KEYCODE_ZOOM_OUT */
  146. ) {
  147. return false;
  148. }
  149. return super.dispatchKeyEvent(event);
  150. }
  151. /** Called by onPause or surfaceDestroyed. Even if surfaceDestroyed
  152. * is the first to be called, mIsSurfaceReady should still be set
  153. * to 'true' during the call to onPause (in a usual scenario).
  154. */
  155. public static void handlePause() {
  156. if (!SDLActivity.mIsPaused && SDLActivity.mIsSurfaceReady) {
  157. SDLActivity.mIsPaused = true;
  158. SDLActivity.nativePause();
  159. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, false);
  160. }
  161. }
  162. /** Called by onResume or surfaceCreated. An actual resume should be done only when the surface is ready.
  163. * Note: Some Android variants may send multiple surfaceChanged events, so we don't need to resume
  164. * every time we get one of those events, only if it comes after surfaceDestroyed
  165. */
  166. public static void handleResume() {
  167. if (SDLActivity.mIsPaused && SDLActivity.mIsSurfaceReady && SDLActivity.mHasFocus) {
  168. SDLActivity.mIsPaused = false;
  169. SDLActivity.nativeResume();
  170. mSurface.handleResume();
  171. }
  172. }
  173. /* The native thread has finished */
  174. public static void handleNativeExit() {
  175. SDLActivity.mSDLThread = null;
  176. mSingleton.finish();
  177. }
  178. // Messages from the SDLMain thread
  179. static final int COMMAND_CHANGE_TITLE = 1;
  180. static final int COMMAND_UNUSED = 2;
  181. static final int COMMAND_TEXTEDIT_HIDE = 3;
  182. protected static final int COMMAND_USER = 0x8000;
  183. /**
  184. * This method is called by SDL if SDL did not handle a message itself.
  185. * This happens if a received message contains an unsupported command.
  186. * Method can be overwritten to handle Messages in a different class.
  187. * @param command the command of the message.
  188. * @param param the parameter of the message. May be null.
  189. * @return if the message was handled in overridden method.
  190. */
  191. protected boolean onUnhandledMessage(int command, Object param) {
  192. return false;
  193. }
  194. /**
  195. * A Handler class for Messages from native SDL applications.
  196. * It uses current Activities as target (e.g. for the title).
  197. * static to prevent implicit references to enclosing object.
  198. */
  199. protected static class SDLCommandHandler extends Handler {
  200. @Override
  201. public void handleMessage(Message msg) {
  202. Context context = getContext();
  203. if (context == null) {
  204. Log.e(TAG, "error handling message, getContext() returned null");
  205. return;
  206. }
  207. switch (msg.arg1) {
  208. case COMMAND_CHANGE_TITLE:
  209. if (context instanceof Activity) {
  210. ((Activity) context).setTitle((String)msg.obj);
  211. } else {
  212. Log.e(TAG, "error handling message, getContext() returned no Activity");
  213. }
  214. break;
  215. case COMMAND_TEXTEDIT_HIDE:
  216. if (mTextEdit != null) {
  217. mTextEdit.setVisibility(View.GONE);
  218. InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  219. imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0);
  220. }
  221. break;
  222. default:
  223. if ((context instanceof SDLActivity) && !((SDLActivity) context).onUnhandledMessage(msg.arg1, msg.obj)) {
  224. Log.e(TAG, "error handling message, command is " + msg.arg1);
  225. }
  226. }
  227. }
  228. }
  229. // Handler for the messages
  230. Handler commandHandler = new SDLCommandHandler();
  231. // Send a message from the SDLMain thread
  232. boolean sendCommand(int command, Object data) {
  233. Message msg = commandHandler.obtainMessage();
  234. msg.arg1 = command;
  235. msg.obj = data;
  236. return commandHandler.sendMessage(msg);
  237. }
  238. // C functions we call
  239. public static native int nativeInit();
  240. public static native void nativeLowMemory();
  241. public static native void nativeQuit();
  242. public static native void nativePause();
  243. public static native void nativeResume();
  244. public static native void onNativeResize(int x, int y, int format);
  245. public static native int onNativePadDown(int device_id, int keycode);
  246. public static native int onNativePadUp(int device_id, int keycode);
  247. public static native void onNativeJoy(int device_id, int axis,
  248. float value);
  249. public static native void onNativeHat(int device_id, int hat_id,
  250. int x, int y);
  251. public static native void onNativeKeyDown(int keycode);
  252. public static native void onNativeKeyUp(int keycode);
  253. public static native void onNativeKeyboardFocusLost();
  254. public static native void onNativeTouch(int touchDevId, int pointerFingerId,
  255. int action, float x,
  256. float y, float p);
  257. public static native void onNativeAccel(float x, float y, float z);
  258. public static native void onNativeSurfaceChanged();
  259. public static native void onNativeSurfaceDestroyed();
  260. public static native void nativeFlipBuffers();
  261. public static native int nativeAddJoystick(int device_id, String name,
  262. int is_accelerometer, int nbuttons,
  263. int naxes, int nhats, int nballs);
  264. public static native int nativeRemoveJoystick(int device_id);
  265. public static native String nativeGetHint(String name);
  266. /**
  267. * This method is called by SDL using JNI.
  268. */
  269. public static void flipBuffers() {
  270. SDLActivity.nativeFlipBuffers();
  271. }
  272. /**
  273. * This method is called by SDL using JNI.
  274. */
  275. public static boolean setActivityTitle(String title) {
  276. // Called from SDLMain() thread and can't directly affect the view
  277. return mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
  278. }
  279. /**
  280. * This method is called by SDL using JNI.
  281. */
  282. public static boolean sendMessage(int command, int param) {
  283. return mSingleton.sendCommand(command, Integer.valueOf(param));
  284. }
  285. /**
  286. * This method is called by SDL using JNI.
  287. */
  288. public static Context getContext() {
  289. return mSingleton;
  290. }
  291. /**
  292. * This method is called by SDL using JNI.
  293. * @return result of getSystemService(name) but executed on UI thread.
  294. */
  295. public Object getSystemServiceFromUiThread(final String name) {
  296. final Object lock = new Object();
  297. final Object[] results = new Object[2]; // array for writable variables
  298. synchronized (lock) {
  299. runOnUiThread(new Runnable() {
  300. @Override
  301. public void run() {
  302. synchronized (lock) {
  303. results[0] = getSystemService(name);
  304. results[1] = Boolean.TRUE;
  305. lock.notify();
  306. }
  307. }
  308. });
  309. if (results[1] == null) {
  310. try {
  311. lock.wait();
  312. } catch (InterruptedException ex) {
  313. ex.printStackTrace();
  314. }
  315. }
  316. }
  317. return results[0];
  318. }
  319. static class ShowTextInputTask implements Runnable {
  320. /*
  321. * This is used to regulate the pan&scan method to have some offset from
  322. * the bottom edge of the input region and the top edge of an input
  323. * method (soft keyboard)
  324. */
  325. static final int HEIGHT_PADDING = 15;
  326. public int x, y, w, h;
  327. public ShowTextInputTask(int x, int y, int w, int h) {
  328. this.x = x;
  329. this.y = y;
  330. this.w = w;
  331. this.h = h;
  332. }
  333. @Override
  334. public void run() {
  335. AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
  336. w, h + HEIGHT_PADDING, x, y);
  337. if (mTextEdit == null) {
  338. mTextEdit = new DummyEdit(getContext());
  339. mLayout.addView(mTextEdit, params);
  340. } else {
  341. mTextEdit.setLayoutParams(params);
  342. }
  343. mTextEdit.setVisibility(View.VISIBLE);
  344. mTextEdit.requestFocus();
  345. InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  346. imm.showSoftInput(mTextEdit, 0);
  347. }
  348. }
  349. /**
  350. * This method is called by SDL using JNI.
  351. */
  352. public static boolean showTextInput(int x, int y, int w, int h) {
  353. // Transfer the task to the main thread as a Runnable
  354. return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h));
  355. }
  356. /**
  357. * This method is called by SDL using JNI.
  358. */
  359. public static Surface getNativeSurface() {
  360. return SDLActivity.mSurface.getNativeSurface();
  361. }
  362. // Audio
  363. /**
  364. * This method is called by SDL using JNI.
  365. */
  366. public static int audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
  367. int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
  368. int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
  369. int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
  370. Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + (sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  371. // Let the user pick a larger buffer if they really want -- but ye
  372. // gods they probably shouldn't, the minimums are horrifyingly high
  373. // latency already
  374. desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
  375. if (mAudioTrack == null) {
  376. mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
  377. channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
  378. // Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
  379. // Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
  380. // Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
  381. if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
  382. Log.e("SDL", "Failed during initialization of Audio Track");
  383. mAudioTrack = null;
  384. return -1;
  385. }
  386. mAudioTrack.play();
  387. }
  388. Log.v("SDL", "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + (mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  389. return 0;
  390. }
  391. /**
  392. * This method is called by SDL using JNI.
  393. */
  394. public static void audioWriteShortBuffer(short[] buffer) {
  395. for (int i = 0; i < buffer.length; ) {
  396. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  397. if (result > 0) {
  398. i += result;
  399. } else if (result == 0) {
  400. try {
  401. Thread.sleep(1);
  402. } catch(InterruptedException e) {
  403. // Nom nom
  404. }
  405. } else {
  406. Log.w("SDL", "SDL audio: error return from write(short)");
  407. return;
  408. }
  409. }
  410. }
  411. /**
  412. * This method is called by SDL using JNI.
  413. */
  414. public static void audioWriteByteBuffer(byte[] buffer) {
  415. for (int i = 0; i < buffer.length; ) {
  416. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  417. if (result > 0) {
  418. i += result;
  419. } else if (result == 0) {
  420. try {
  421. Thread.sleep(1);
  422. } catch(InterruptedException e) {
  423. // Nom nom
  424. }
  425. } else {
  426. Log.w("SDL", "SDL audio: error return from write(byte)");
  427. return;
  428. }
  429. }
  430. }
  431. /**
  432. * This method is called by SDL using JNI.
  433. */
  434. public static void audioQuit() {
  435. if (mAudioTrack != null) {
  436. mAudioTrack.stop();
  437. mAudioTrack = null;
  438. }
  439. }
  440. // Input
  441. /**
  442. * This method is called by SDL using JNI.
  443. * @return an array which may be empty but is never null.
  444. */
  445. public static int[] inputGetInputDeviceIds(int sources) {
  446. int[] ids = InputDevice.getDeviceIds();
  447. int[] filtered = new int[ids.length];
  448. int used = 0;
  449. for (int i = 0; i < ids.length; ++i) {
  450. InputDevice device = InputDevice.getDevice(ids[i]);
  451. if ((device != null) && ((device.getSources() & sources) != 0)) {
  452. filtered[used++] = device.getId();
  453. }
  454. }
  455. return Arrays.copyOf(filtered, used);
  456. }
  457. // Joystick glue code, just a series of stubs that redirect to the SDLJoystickHandler instance
  458. public static boolean handleJoystickMotionEvent(MotionEvent event) {
  459. return mJoystickHandler.handleMotionEvent(event);
  460. }
  461. /**
  462. * This method is called by SDL using JNI.
  463. */
  464. public static void pollInputDevices() {
  465. if (SDLActivity.mSDLThread != null) {
  466. mJoystickHandler.pollInputDevices();
  467. }
  468. }
  469. // APK extension files support
  470. /** com.android.vending.expansion.zipfile.ZipResourceFile object or null. */
  471. private Object expansionFile;
  472. /** com.android.vending.expansion.zipfile.ZipResourceFile's getInputStream() or null. */
  473. private Method expansionFileMethod;
  474. /**
  475. * This method is called by SDL using JNI.
  476. */
  477. public InputStream openAPKExtensionInputStream(String fileName) throws IOException {
  478. // Get a ZipResourceFile representing a merger of both the main and patch files
  479. if (expansionFile == null) {
  480. Integer mainVersion = Integer.valueOf(nativeGetHint("SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"));
  481. Integer patchVersion = Integer.valueOf(nativeGetHint("SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"));
  482. try {
  483. // To avoid direct dependency on Google APK extension library that is
  484. // not a part of Android SDK we access it using reflection
  485. expansionFile = Class.forName("com.android.vending.expansion.zipfile.APKExpansionSupport")
  486. .getMethod("getAPKExpansionZipFile", Context.class, int.class, int.class)
  487. .invoke(null, this, mainVersion, patchVersion);
  488. expansionFileMethod = expansionFile.getClass()
  489. .getMethod("getInputStream", String.class);
  490. } catch (Exception ex) {
  491. ex.printStackTrace();
  492. expansionFile = null;
  493. expansionFileMethod = null;
  494. }
  495. }
  496. // Get an input stream for a known file inside the expansion file ZIPs
  497. InputStream fileStream;
  498. try {
  499. fileStream = (InputStream)expansionFileMethod.invoke(expansionFile, fileName);
  500. } catch (Exception ex) {
  501. ex.printStackTrace();
  502. fileStream = null;
  503. }
  504. if (fileStream == null) {
  505. throw new IOException();
  506. }
  507. return fileStream;
  508. }
  509. // Messagebox
  510. /** Result of current messagebox. Also used for blocking the calling thread. */
  511. protected final int[] messageboxSelection = new int[1];
  512. /** Id of current dialog. */
  513. protected int dialogs = 0;
  514. /**
  515. * This method is called by SDL using JNI.
  516. * Shows the messagebox from UI thread and block calling thread.
  517. * buttonFlags, buttonIds and buttonTexts must have same length.
  518. * @param buttonFlags array containing flags for every button.
  519. * @param buttonIds array containing id for every button.
  520. * @param buttonTexts array containing text for every button.
  521. * @param colors null for default or array of length 5 containing colors.
  522. * @return button id or -1.
  523. */
  524. public int messageboxShowMessageBox(
  525. final int flags,
  526. final String title,
  527. final String message,
  528. final int[] buttonFlags,
  529. final int[] buttonIds,
  530. final String[] buttonTexts,
  531. final int[] colors) {
  532. messageboxSelection[0] = -1;
  533. // sanity checks
  534. if ((buttonFlags.length != buttonIds.length) && (buttonIds.length != buttonTexts.length)) {
  535. return -1; // implementation broken
  536. }
  537. // collect arguments for Dialog
  538. final Bundle args = new Bundle();
  539. args.putInt("flags", flags);
  540. args.putString("title", title);
  541. args.putString("message", message);
  542. args.putIntArray("buttonFlags", buttonFlags);
  543. args.putIntArray("buttonIds", buttonIds);
  544. args.putStringArray("buttonTexts", buttonTexts);
  545. args.putIntArray("colors", colors);
  546. // trigger Dialog creation on UI thread
  547. runOnUiThread(new Runnable() {
  548. @Override
  549. public void run() {
  550. showDialog(dialogs++, args);
  551. }
  552. });
  553. // block the calling thread
  554. synchronized (messageboxSelection) {
  555. try {
  556. messageboxSelection.wait();
  557. } catch (InterruptedException ex) {
  558. ex.printStackTrace();
  559. return -1;
  560. }
  561. }
  562. // return selected value
  563. return messageboxSelection[0];
  564. }
  565. @Override
  566. protected Dialog onCreateDialog(int ignore, Bundle args) {
  567. // TODO set values from "flags" to messagebox dialog
  568. // get colors
  569. int[] colors = args.getIntArray("colors");
  570. int backgroundColor;
  571. int textColor;
  572. int buttonBorderColor;
  573. int buttonBackgroundColor;
  574. int buttonSelectedColor;
  575. if (colors != null) {
  576. int i = -1;
  577. backgroundColor = colors[++i];
  578. textColor = colors[++i];
  579. buttonBorderColor = colors[++i];
  580. buttonBackgroundColor = colors[++i];
  581. buttonSelectedColor = colors[++i];
  582. } else {
  583. backgroundColor = Color.TRANSPARENT;
  584. textColor = Color.TRANSPARENT;
  585. buttonBorderColor = Color.TRANSPARENT;
  586. buttonBackgroundColor = Color.TRANSPARENT;
  587. buttonSelectedColor = Color.TRANSPARENT;
  588. }
  589. // create dialog with title and a listener to wake up calling thread
  590. final Dialog dialog = new Dialog(this);
  591. dialog.setTitle(args.getString("title"));
  592. dialog.setCancelable(false);
  593. dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
  594. @Override
  595. public void onDismiss(DialogInterface unused) {
  596. synchronized (messageboxSelection) {
  597. messageboxSelection.notify();
  598. }
  599. }
  600. });
  601. // create text
  602. TextView message = new TextView(this);
  603. message.setGravity(Gravity.CENTER);
  604. message.setText(args.getString("message"));
  605. if (textColor != Color.TRANSPARENT) {
  606. message.setTextColor(textColor);
  607. }
  608. // create buttons
  609. int[] buttonFlags = args.getIntArray("buttonFlags");
  610. int[] buttonIds = args.getIntArray("buttonIds");
  611. String[] buttonTexts = args.getStringArray("buttonTexts");
  612. final SparseArray<Button> mapping = new SparseArray<Button>();
  613. LinearLayout buttons = new LinearLayout(this);
  614. buttons.setOrientation(LinearLayout.HORIZONTAL);
  615. buttons.setGravity(Gravity.CENTER);
  616. for (int i = 0; i < buttonTexts.length; ++i) {
  617. Button button = new Button(this);
  618. final int id = buttonIds[i];
  619. button.setOnClickListener(new View.OnClickListener() {
  620. @Override
  621. public void onClick(View v) {
  622. messageboxSelection[0] = id;
  623. dialog.dismiss();
  624. }
  625. });
  626. if (buttonFlags[i] != 0) {
  627. // see SDL_messagebox.h
  628. if ((buttonFlags[i] & 0x00000001) != 0) {
  629. mapping.put(KeyEvent.KEYCODE_ENTER, button);
  630. }
  631. if ((buttonFlags[i] & 0x00000002) != 0) {
  632. mapping.put(111, button); /* API 11: KeyEvent.KEYCODE_ESCAPE */
  633. }
  634. }
  635. button.setText(buttonTexts[i]);
  636. if (buttonBorderColor != Color.TRANSPARENT) {
  637. // TODO set color for border of messagebox button
  638. }
  639. if (buttonBackgroundColor != Color.TRANSPARENT) {
  640. button.setBackgroundColor(buttonBackgroundColor);
  641. }
  642. if (buttonSelectedColor != Color.TRANSPARENT) {
  643. // TODO set color for selected messagebox button
  644. }
  645. buttons.addView(button);
  646. }
  647. // create content
  648. LinearLayout content = new LinearLayout(this);
  649. content.setOrientation(LinearLayout.VERTICAL);
  650. content.addView(message);
  651. content.addView(buttons);
  652. if (backgroundColor != Color.TRANSPARENT) {
  653. content.setBackgroundColor(backgroundColor);
  654. }
  655. // add content to dialog and return
  656. dialog.setContentView(content);
  657. dialog.setOnKeyListener(new Dialog.OnKeyListener() {
  658. @Override
  659. public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
  660. Button button = mapping.get(keyCode);
  661. if (button != null) {
  662. if (event.getAction() == KeyEvent.ACTION_UP) {
  663. button.performClick();
  664. }
  665. return true; // also for ignored actions
  666. }
  667. return false;
  668. }
  669. });
  670. return dialog;
  671. }
  672. }
  673. /**
  674. Simple nativeInit() runnable
  675. */
  676. class SDLMain implements Runnable {
  677. @Override
  678. public void run() {
  679. // Runs SDL_main()
  680. SDLActivity.nativeInit();
  681. //Log.v("SDL", "SDL thread terminated");
  682. }
  683. }
  684. /**
  685. SDLSurface. This is what we draw on, so we need to know when it's created
  686. in order to do anything useful.
  687. Because of this, that's where we set up the SDL thread
  688. */
  689. class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
  690. View.OnKeyListener, View.OnTouchListener, SensorEventListener {
  691. // Sensors
  692. protected static SensorManager mSensorManager;
  693. protected static Display mDisplay;
  694. // Keep track of the surface size to normalize touch events
  695. protected static float mWidth, mHeight;
  696. // Startup
  697. public SDLSurface(Context context) {
  698. super(context);
  699. getHolder().addCallback(this);
  700. setFocusable(true);
  701. setFocusableInTouchMode(true);
  702. requestFocus();
  703. setOnKeyListener(this);
  704. setOnTouchListener(this);
  705. mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  706. mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  707. if(Build.VERSION.SDK_INT >= 12) {
  708. setOnGenericMotionListener(new SDLGenericMotionListener_API12());
  709. }
  710. // Some arbitrary defaults to avoid a potential division by zero
  711. mWidth = 1.0f;
  712. mHeight = 1.0f;
  713. }
  714. public void handleResume() {
  715. setFocusable(true);
  716. setFocusableInTouchMode(true);
  717. requestFocus();
  718. setOnKeyListener(this);
  719. setOnTouchListener(this);
  720. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  721. }
  722. public Surface getNativeSurface() {
  723. return getHolder().getSurface();
  724. }
  725. // Called when we have a valid drawing surface
  726. @Override
  727. public void surfaceCreated(SurfaceHolder holder) {
  728. Log.v("SDL", "surfaceCreated()");
  729. holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  730. }
  731. // Called when we lose the surface
  732. @Override
  733. public void surfaceDestroyed(SurfaceHolder holder) {
  734. Log.v("SDL", "surfaceDestroyed()");
  735. // Call this *before* setting mIsSurfaceReady to 'false'
  736. SDLActivity.handlePause();
  737. SDLActivity.mIsSurfaceReady = false;
  738. SDLActivity.onNativeSurfaceDestroyed();
  739. }
  740. // Called when the surface is resized
  741. @Override
  742. public void surfaceChanged(SurfaceHolder holder,
  743. int format, int width, int height) {
  744. Log.v("SDL", "surfaceChanged()");
  745. int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
  746. switch (format) {
  747. case PixelFormat.A_8:
  748. Log.v("SDL", "pixel format A_8");
  749. break;
  750. case PixelFormat.LA_88:
  751. Log.v("SDL", "pixel format LA_88");
  752. break;
  753. case PixelFormat.L_8:
  754. Log.v("SDL", "pixel format L_8");
  755. break;
  756. case PixelFormat.RGBA_4444:
  757. Log.v("SDL", "pixel format RGBA_4444");
  758. sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
  759. break;
  760. case PixelFormat.RGBA_5551:
  761. Log.v("SDL", "pixel format RGBA_5551");
  762. sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
  763. break;
  764. case PixelFormat.RGBA_8888:
  765. Log.v("SDL", "pixel format RGBA_8888");
  766. sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
  767. break;
  768. case PixelFormat.RGBX_8888:
  769. Log.v("SDL", "pixel format RGBX_8888");
  770. sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
  771. break;
  772. case PixelFormat.RGB_332:
  773. Log.v("SDL", "pixel format RGB_332");
  774. sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
  775. break;
  776. case PixelFormat.RGB_565:
  777. Log.v("SDL", "pixel format RGB_565");
  778. sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
  779. break;
  780. case PixelFormat.RGB_888:
  781. Log.v("SDL", "pixel format RGB_888");
  782. // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
  783. sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
  784. break;
  785. default:
  786. Log.v("SDL", "pixel format unknown " + format);
  787. break;
  788. }
  789. mWidth = width;
  790. mHeight = height;
  791. SDLActivity.onNativeResize(width, height, sdlFormat);
  792. Log.v("SDL", "Window size:" + width + "x"+height);
  793. // Set mIsSurfaceReady to 'true' *before* making a call to handleResume
  794. SDLActivity.mIsSurfaceReady = true;
  795. SDLActivity.onNativeSurfaceChanged();
  796. if (SDLActivity.mSDLThread == null) {
  797. // This is the entry point to the C app.
  798. // Start up the C app thread and enable sensor input for the first time
  799. SDLActivity.mSDLThread = new Thread(new SDLMain(), "SDLThread");
  800. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  801. SDLActivity.mSDLThread.start();
  802. // Set up a listener thread to catch when the native thread ends
  803. new Thread(new Runnable(){
  804. @Override
  805. public void run(){
  806. try {
  807. SDLActivity.mSDLThread.join();
  808. }
  809. catch(Exception e){}
  810. finally{
  811. // Native thread has finished
  812. if (! SDLActivity.mExitCalledFromJava) {
  813. SDLActivity.handleNativeExit();
  814. }
  815. }
  816. }
  817. }).start();
  818. }
  819. }
  820. // unused
  821. @Override
  822. public void onDraw(Canvas canvas) {}
  823. // Key events
  824. @Override
  825. public boolean onKey(View v, int keyCode, KeyEvent event) {
  826. // Dispatch the different events depending on where they come from
  827. // Some SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD
  828. // So, we try to process them as DPAD or GAMEPAD events first, if that fails we try them as KEYBOARD
  829. if ( (event.getSource() & 0x00000401) != 0 || /* API 12: SOURCE_GAMEPAD */
  830. (event.getSource() & InputDevice.SOURCE_DPAD) != 0 ) {
  831. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  832. if (SDLActivity.onNativePadDown(event.getDeviceId(), keyCode) == 0) {
  833. return true;
  834. }
  835. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  836. if (SDLActivity.onNativePadUp(event.getDeviceId(), keyCode) == 0) {
  837. return true;
  838. }
  839. }
  840. }
  841. if( (event.getSource() & InputDevice.SOURCE_KEYBOARD) != 0) {
  842. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  843. //Log.v("SDL", "key down: " + keyCode);
  844. SDLActivity.onNativeKeyDown(keyCode);
  845. return true;
  846. }
  847. else if (event.getAction() == KeyEvent.ACTION_UP) {
  848. //Log.v("SDL", "key up: " + keyCode);
  849. SDLActivity.onNativeKeyUp(keyCode);
  850. return true;
  851. }
  852. }
  853. return false;
  854. }
  855. // Touch events
  856. @Override
  857. public boolean onTouch(View v, MotionEvent event) {
  858. /* Ref: http://developer.android.com/training/gestures/multi.html */
  859. final int touchDevId = event.getDeviceId();
  860. final int pointerCount = event.getPointerCount();
  861. int action = event.getActionMasked();
  862. int pointerFingerId;
  863. int i = -1;
  864. float x,y,p;
  865. switch(action) {
  866. case MotionEvent.ACTION_MOVE:
  867. for (i = 0; i < pointerCount; i++) {
  868. pointerFingerId = event.getPointerId(i);
  869. x = event.getX(i) / mWidth;
  870. y = event.getY(i) / mHeight;
  871. p = event.getPressure(i);
  872. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  873. }
  874. break;
  875. case MotionEvent.ACTION_UP:
  876. case MotionEvent.ACTION_DOWN:
  877. // Primary pointer up/down, the index is always zero
  878. i = 0;
  879. case MotionEvent.ACTION_POINTER_UP:
  880. case MotionEvent.ACTION_POINTER_DOWN:
  881. // Non primary pointer up/down
  882. if (i == -1) {
  883. i = event.getActionIndex();
  884. }
  885. pointerFingerId = event.getPointerId(i);
  886. x = event.getX(i) / mWidth;
  887. y = event.getY(i) / mHeight;
  888. p = event.getPressure(i);
  889. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  890. break;
  891. case MotionEvent.ACTION_CANCEL:
  892. for (i = 0; i < pointerCount; i++) {
  893. pointerFingerId = event.getPointerId(i);
  894. x = event.getX(i) / mWidth;
  895. y = event.getY(i) / mHeight;
  896. p = event.getPressure(i);
  897. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, MotionEvent.ACTION_UP, x, y, p);
  898. }
  899. break;
  900. default:
  901. break;
  902. }
  903. return true;
  904. }
  905. // Sensor events
  906. public void enableSensor(int sensortype, boolean enabled) {
  907. // TODO: This uses getDefaultSensor - what if we have >1 accels?
  908. if (enabled) {
  909. mSensorManager.registerListener(this,
  910. mSensorManager.getDefaultSensor(sensortype),
  911. SensorManager.SENSOR_DELAY_GAME, null);
  912. } else {
  913. mSensorManager.unregisterListener(this,
  914. mSensorManager.getDefaultSensor(sensortype));
  915. }
  916. }
  917. @Override
  918. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  919. // TODO
  920. }
  921. @Override
  922. public void onSensorChanged(SensorEvent event) {
  923. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  924. float x, y;
  925. switch (mDisplay.getRotation()) {
  926. case Surface.ROTATION_90:
  927. x = -event.values[1];
  928. y = event.values[0];
  929. break;
  930. case Surface.ROTATION_270:
  931. x = event.values[1];
  932. y = -event.values[0];
  933. break;
  934. case Surface.ROTATION_180:
  935. x = -event.values[1];
  936. y = -event.values[0];
  937. break;
  938. default:
  939. x = event.values[0];
  940. y = event.values[1];
  941. break;
  942. }
  943. SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
  944. y / SensorManager.GRAVITY_EARTH,
  945. event.values[2] / SensorManager.GRAVITY_EARTH - 1);
  946. }
  947. }
  948. }
  949. /* This is a fake invisible editor view that receives the input and defines the
  950. * pan&scan region
  951. */
  952. class DummyEdit extends View implements View.OnKeyListener {
  953. InputConnection ic;
  954. public DummyEdit(Context context) {
  955. super(context);
  956. setFocusableInTouchMode(true);
  957. setFocusable(true);
  958. setOnKeyListener(this);
  959. }
  960. @Override
  961. public boolean onCheckIsTextEditor() {
  962. return true;
  963. }
  964. @Override
  965. public boolean onKey(View v, int keyCode, KeyEvent event) {
  966. // This handles the hardware keyboard input
  967. if (event.isPrintingKey()) {
  968. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  969. ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  970. }
  971. return true;
  972. }
  973. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  974. SDLActivity.onNativeKeyDown(keyCode);
  975. return true;
  976. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  977. SDLActivity.onNativeKeyUp(keyCode);
  978. return true;
  979. }
  980. return false;
  981. }
  982. //
  983. @Override
  984. public boolean onKeyPreIme (int keyCode, KeyEvent event) {
  985. // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
  986. // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
  987. // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
  988. // FIXME: A more effective solution would be to change our Layout from AbsoluteLayout to Relative or Linear
  989. // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
  990. // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
  991. if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
  992. if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
  993. SDLActivity.onNativeKeyboardFocusLost();
  994. }
  995. }
  996. return super.onKeyPreIme(keyCode, event);
  997. }
  998. @Override
  999. public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
  1000. ic = new SDLInputConnection(this, true);
  1001. outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
  1002. | 33554432 /* API 11: EditorInfo.IME_FLAG_NO_FULLSCREEN */;
  1003. return ic;
  1004. }
  1005. }
  1006. class SDLInputConnection extends BaseInputConnection {
  1007. public SDLInputConnection(View targetView, boolean fullEditor) {
  1008. super(targetView, fullEditor);
  1009. }
  1010. @Override
  1011. public boolean sendKeyEvent(KeyEvent event) {
  1012. /*
  1013. * This handles the keycodes from soft keyboard (and IME-translated
  1014. * input from hardkeyboard)
  1015. */
  1016. int keyCode = event.getKeyCode();
  1017. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1018. if (event.isPrintingKey()) {
  1019. commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  1020. }
  1021. SDLActivity.onNativeKeyDown(keyCode);
  1022. return true;
  1023. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  1024. SDLActivity.onNativeKeyUp(keyCode);
  1025. return true;
  1026. }
  1027. return super.sendKeyEvent(event);
  1028. }
  1029. @Override
  1030. public boolean commitText(CharSequence text, int newCursorPosition) {
  1031. nativeCommitText(text.toString(), newCursorPosition);
  1032. return super.commitText(text, newCursorPosition);
  1033. }
  1034. @Override
  1035. public boolean setComposingText(CharSequence text, int newCursorPosition) {
  1036. nativeSetComposingText(text.toString(), newCursorPosition);
  1037. return super.setComposingText(text, newCursorPosition);
  1038. }
  1039. public native void nativeCommitText(String text, int newCursorPosition);
  1040. public native void nativeSetComposingText(String text, int newCursorPosition);
  1041. @Override
  1042. public boolean deleteSurroundingText(int beforeLength, int afterLength) {
  1043. // Workaround to capture backspace key. Ref: http://stackoverflow.com/questions/14560344/android-backspace-in-webview-baseinputconnection
  1044. if (beforeLength == 1 && afterLength == 0) {
  1045. // backspace
  1046. return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
  1047. && super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
  1048. }
  1049. return super.deleteSurroundingText(beforeLength, afterLength);
  1050. }
  1051. }
  1052. /* A null joystick handler for API level < 12 devices (the accelerometer is handled separately) */
  1053. class SDLJoystickHandler {
  1054. /**
  1055. * Handles given MotionEvent.
  1056. * @param event the event to be handled.
  1057. * @return if given event was processed.
  1058. */
  1059. public boolean handleMotionEvent(MotionEvent event) {
  1060. return false;
  1061. }
  1062. /**
  1063. * Handles adding and removing of input devices.
  1064. */
  1065. public void pollInputDevices() {
  1066. }
  1067. }
  1068. /* Actual joystick functionality available for API >= 12 devices */
  1069. class SDLJoystickHandler_API12 extends SDLJoystickHandler {
  1070. static class SDLJoystick {
  1071. public int device_id;
  1072. public String name;
  1073. public ArrayList<InputDevice.MotionRange> axes;
  1074. public ArrayList<InputDevice.MotionRange> hats;
  1075. }
  1076. static class RangeComparator implements Comparator<InputDevice.MotionRange> {
  1077. @Override
  1078. public int compare(InputDevice.MotionRange arg0, InputDevice.MotionRange arg1) {
  1079. return arg0.getAxis() - arg1.getAxis();
  1080. }
  1081. }
  1082. private ArrayList<SDLJoystick> mJoysticks;
  1083. public SDLJoystickHandler_API12() {
  1084. mJoysticks = new ArrayList<SDLJoystick>();
  1085. }
  1086. @Override
  1087. public void pollInputDevices() {
  1088. int[] deviceIds = InputDevice.getDeviceIds();
  1089. // It helps processing the device ids in reverse order
  1090. // For example, in the case of the XBox 360 wireless dongle,
  1091. // so the first controller seen by SDL matches what the receiver
  1092. // considers to be the first controller
  1093. for(int i=deviceIds.length-1; i>-1; i--) {
  1094. SDLJoystick joystick = getJoystick(deviceIds[i]);
  1095. if (joystick == null) {
  1096. joystick = new SDLJoystick();
  1097. InputDevice joystickDevice = InputDevice.getDevice(deviceIds[i]);
  1098. if( (joystickDevice.getSources() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
  1099. joystick.device_id = deviceIds[i];
  1100. joystick.name = joystickDevice.getName();
  1101. joystick.axes = new ArrayList<InputDevice.MotionRange>();
  1102. joystick.hats = new ArrayList<InputDevice.MotionRange>();
  1103. List<InputDevice.MotionRange> ranges = joystickDevice.getMotionRanges();
  1104. Collections.sort(ranges, new RangeComparator());
  1105. for (InputDevice.MotionRange range : ranges ) {
  1106. if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0 ) {
  1107. if (range.getAxis() == MotionEvent.AXIS_HAT_X ||
  1108. range.getAxis() == MotionEvent.AXIS_HAT_Y) {
  1109. joystick.hats.add(range);
  1110. }
  1111. else {
  1112. joystick.axes.add(range);
  1113. }
  1114. }
  1115. }
  1116. mJoysticks.add(joystick);
  1117. SDLActivity.nativeAddJoystick(joystick.device_id, joystick.name, 0, -1,
  1118. joystick.axes.size(), joystick.hats.size()/2, 0);
  1119. }
  1120. }
  1121. }
  1122. /* Check removed devices */
  1123. ArrayList<Integer> removedDevices = new ArrayList<Integer>();
  1124. for(int i=0; i < mJoysticks.size(); i++) {
  1125. int device_id = mJoysticks.get(i).device_id;
  1126. int j;
  1127. for (j=0; j < deviceIds.length; j++) {
  1128. if (device_id == deviceIds[j]) break;
  1129. }
  1130. if (j == deviceIds.length) {
  1131. removedDevices.add(Integer.valueOf(device_id));
  1132. }
  1133. }
  1134. for(int i=0; i < removedDevices.size(); i++) {
  1135. int device_id = removedDevices.get(i).intValue();
  1136. SDLActivity.nativeRemoveJoystick(device_id);
  1137. for (int j=0; j < mJoysticks.size(); j++) {
  1138. if (mJoysticks.get(j).device_id == device_id) {
  1139. mJoysticks.remove(j);
  1140. break;
  1141. }
  1142. }
  1143. }
  1144. }
  1145. protected SDLJoystick getJoystick(int device_id) {
  1146. for(int i=0; i < mJoysticks.size(); i++) {
  1147. if (mJoysticks.get(i).device_id == device_id) {
  1148. return mJoysticks.get(i);
  1149. }
  1150. }
  1151. return null;
  1152. }
  1153. @Override
  1154. public boolean handleMotionEvent(MotionEvent event) {
  1155. if ( (event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
  1156. int actionPointerIndex = event.getActionIndex();
  1157. int action = event.getActionMasked();
  1158. switch(action) {
  1159. case MotionEvent.ACTION_MOVE:
  1160. SDLJoystick joystick = getJoystick(event.getDeviceId());
  1161. if ( joystick != null ) {
  1162. for (int i = 0; i < joystick.axes.size(); i++) {
  1163. InputDevice.MotionRange range = joystick.axes.get(i);
  1164. /* Normalize the value to -1...1 */
  1165. float value = ( event.getAxisValue( range.getAxis(), actionPointerIndex) - range.getMin() ) / range.getRange() * 2.0f - 1.0f;
  1166. SDLActivity.onNativeJoy(joystick.device_id, i, value );
  1167. }
  1168. for (int i = 0; i < joystick.hats.size(); i+=2) {
  1169. int hatX = Math.round(event.getAxisValue( joystick.hats.get(i).getAxis(), actionPointerIndex ) );
  1170. int hatY = Math.round(event.getAxisValue( joystick.hats.get(i+1).getAxis(), actionPointerIndex ) );
  1171. SDLActivity.onNativeHat(joystick.device_id, i/2, hatX, hatY );
  1172. }
  1173. }
  1174. break;
  1175. default:
  1176. break;
  1177. }
  1178. }
  1179. return true;
  1180. }
  1181. }
  1182. class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener {
  1183. // Generic Motion (mouse hover, joystick...) events go here
  1184. // We only have joysticks yet
  1185. @Override
  1186. public boolean onGenericMotion(View v, MotionEvent event) {
  1187. return SDLActivity.handleJoystickMotionEvent(event);
  1188. }
  1189. }