SDLActivity.java 74 KB

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