SDLActivity.java 55 KB

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