SDLActivity.java 71 KB

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