SDLActivity.java 52 KB

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