SDLActivity.java 59 KB

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