SDLActivity.java 64 KB

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