SDLActivity.java 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. package org.libsdl.app;
  2. import java.util.ArrayList;
  3. import java.util.Arrays;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. import android.app.*;
  8. import android.content.*;
  9. import android.view.*;
  10. import android.view.inputmethod.BaseInputConnection;
  11. import android.view.inputmethod.EditorInfo;
  12. import android.view.inputmethod.InputConnection;
  13. import android.view.inputmethod.InputMethodManager;
  14. import android.widget.AbsoluteLayout;
  15. import android.os.*;
  16. import android.util.Log;
  17. import android.graphics.*;
  18. import android.media.*;
  19. import android.hardware.*;
  20. /**
  21. SDL Activity
  22. */
  23. public class SDLActivity extends Activity {
  24. private static final String TAG = "SDL";
  25. // Keep track of the paused state
  26. public static boolean mIsPaused, mIsSurfaceReady, mHasFocus;
  27. public static boolean mExitCalledFromJava;
  28. // Main components
  29. protected static SDLActivity mSingleton;
  30. protected static SDLSurface mSurface;
  31. protected static View mTextEdit;
  32. protected static ViewGroup mLayout;
  33. protected static SDLJoystickHandler mJoystickHandler;
  34. // This is what SDL runs in. It invokes SDL_main(), eventually
  35. protected static Thread mSDLThread;
  36. // Audio
  37. protected static AudioTrack mAudioTrack;
  38. // Load the .so
  39. static {
  40. System.loadLibrary("SDL2");
  41. //System.loadLibrary("SDL2_image");
  42. //System.loadLibrary("SDL2_mixer");
  43. //System.loadLibrary("SDL2_net");
  44. //System.loadLibrary("SDL2_ttf");
  45. System.loadLibrary("main");
  46. }
  47. public static void initialize() {
  48. // The static nature of the singleton and Android quirkyness force us to initialize everything here
  49. // Otherwise, when exiting the app and returning to it, these variables *keep* their pre exit values
  50. mSingleton = null;
  51. mSurface = null;
  52. mTextEdit = null;
  53. mLayout = null;
  54. mJoystickHandler = null;
  55. mSDLThread = null;
  56. mAudioTrack = null;
  57. mExitCalledFromJava = false;
  58. mIsPaused = false;
  59. mIsSurfaceReady = false;
  60. mHasFocus = true;
  61. }
  62. // Setup
  63. @Override
  64. protected void onCreate(Bundle savedInstanceState) {
  65. Log.v("SDL", "onCreate():" + mSingleton);
  66. super.onCreate(savedInstanceState);
  67. SDLActivity.initialize();
  68. // So we can call stuff from static callbacks
  69. mSingleton = this;
  70. // Set up the surface
  71. mSurface = new SDLSurface(getApplication());
  72. if(Build.VERSION.SDK_INT >= 12) {
  73. mJoystickHandler = new SDLJoystickHandler_API12();
  74. }
  75. else {
  76. mJoystickHandler = new SDLJoystickHandler();
  77. }
  78. mLayout = new AbsoluteLayout(this);
  79. mLayout.addView(mSurface);
  80. setContentView(mLayout);
  81. }
  82. // Events
  83. @Override
  84. protected void onPause() {
  85. Log.v("SDL", "onPause()");
  86. super.onPause();
  87. SDLActivity.handlePause();
  88. }
  89. @Override
  90. protected void onResume() {
  91. Log.v("SDL", "onResume()");
  92. super.onResume();
  93. SDLActivity.handleResume();
  94. }
  95. @Override
  96. public void onWindowFocusChanged(boolean hasFocus) {
  97. super.onWindowFocusChanged(hasFocus);
  98. Log.v("SDL", "onWindowFocusChanged(): " + hasFocus);
  99. SDLActivity.mHasFocus = hasFocus;
  100. if (hasFocus) {
  101. SDLActivity.handleResume();
  102. }
  103. }
  104. @Override
  105. public void onLowMemory() {
  106. Log.v("SDL", "onLowMemory()");
  107. super.onLowMemory();
  108. SDLActivity.nativeLowMemory();
  109. }
  110. @Override
  111. protected void onDestroy() {
  112. Log.v("SDL", "onDestroy()");
  113. // Send a quit message to the application
  114. SDLActivity.mExitCalledFromJava = true;
  115. SDLActivity.nativeQuit();
  116. // Now wait for the SDL thread to quit
  117. if (SDLActivity.mSDLThread != null) {
  118. try {
  119. SDLActivity.mSDLThread.join();
  120. } catch(Exception e) {
  121. Log.v("SDL", "Problem stopping thread: " + e);
  122. }
  123. SDLActivity.mSDLThread = null;
  124. //Log.v("SDL", "Finished waiting for SDL thread");
  125. }
  126. super.onDestroy();
  127. // Reset everything in case the user re opens the app
  128. SDLActivity.initialize();
  129. }
  130. @Override
  131. public boolean dispatchKeyEvent(KeyEvent event) {
  132. int keyCode = event.getKeyCode();
  133. // Ignore certain special keys so they're handled by Android
  134. if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
  135. keyCode == KeyEvent.KEYCODE_VOLUME_UP ||
  136. keyCode == KeyEvent.KEYCODE_CAMERA ||
  137. keyCode == 168 || /* API 11: KeyEvent.KEYCODE_ZOOM_IN */
  138. keyCode == 169 /* API 11: KeyEvent.KEYCODE_ZOOM_OUT */
  139. ) {
  140. return false;
  141. }
  142. return super.dispatchKeyEvent(event);
  143. }
  144. /** Called by onPause or surfaceDestroyed. Even if surfaceDestroyed
  145. * is the first to be called, mIsSurfaceReady should still be set
  146. * to 'true' during the call to onPause (in a usual scenario).
  147. */
  148. public static void handlePause() {
  149. if (!SDLActivity.mIsPaused && SDLActivity.mIsSurfaceReady) {
  150. SDLActivity.mIsPaused = true;
  151. SDLActivity.nativePause();
  152. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, false);
  153. }
  154. }
  155. /** Called by onResume or surfaceCreated. An actual resume should be done only when the surface is ready.
  156. * Note: Some Android variants may send multiple surfaceChanged events, so we don't need to resume
  157. * every time we get one of those events, only if it comes after surfaceDestroyed
  158. */
  159. public static void handleResume() {
  160. if (SDLActivity.mIsPaused && SDLActivity.mIsSurfaceReady && SDLActivity.mHasFocus) {
  161. SDLActivity.mIsPaused = false;
  162. SDLActivity.nativeResume();
  163. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  164. }
  165. }
  166. /* The native thread has finished */
  167. public static void handleNativeExit() {
  168. SDLActivity.mSDLThread = null;
  169. mSingleton.finish();
  170. }
  171. // Messages from the SDLMain thread
  172. static final int COMMAND_CHANGE_TITLE = 1;
  173. static final int COMMAND_UNUSED = 2;
  174. static final int COMMAND_TEXTEDIT_HIDE = 3;
  175. protected static final int COMMAND_USER = 0x8000;
  176. /**
  177. * This method is called by SDL if SDL did not handle a message itself.
  178. * This happens if a received message contains an unsupported command.
  179. * Method can be overwritten to handle Messages in a different class.
  180. * @param command the command of the message.
  181. * @param param the parameter of the message. May be null.
  182. * @return if the message was handled in overridden method.
  183. */
  184. protected boolean onUnhandledMessage(int command, Object param) {
  185. return false;
  186. }
  187. /**
  188. * A Handler class for Messages from native SDL applications.
  189. * It uses current Activities as target (e.g. for the title).
  190. * static to prevent implicit references to enclosing object.
  191. */
  192. protected static class SDLCommandHandler extends Handler {
  193. @Override
  194. public void handleMessage(Message msg) {
  195. Context context = getContext();
  196. if (context == null) {
  197. Log.e(TAG, "error handling message, getContext() returned null");
  198. return;
  199. }
  200. switch (msg.arg1) {
  201. case COMMAND_CHANGE_TITLE:
  202. if (context instanceof Activity) {
  203. ((Activity) context).setTitle((String)msg.obj);
  204. } else {
  205. Log.e(TAG, "error handling message, getContext() returned no Activity");
  206. }
  207. break;
  208. case COMMAND_TEXTEDIT_HIDE:
  209. if (mTextEdit != null) {
  210. mTextEdit.setVisibility(View.GONE);
  211. InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  212. imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0);
  213. }
  214. break;
  215. default:
  216. if ((context instanceof SDLActivity) && !((SDLActivity) context).onUnhandledMessage(msg.arg1, msg.obj)) {
  217. Log.e(TAG, "error handling message, command is " + msg.arg1);
  218. }
  219. }
  220. }
  221. }
  222. // Handler for the messages
  223. Handler commandHandler = new SDLCommandHandler();
  224. // Send a message from the SDLMain thread
  225. boolean sendCommand(int command, Object data) {
  226. Message msg = commandHandler.obtainMessage();
  227. msg.arg1 = command;
  228. msg.obj = data;
  229. return commandHandler.sendMessage(msg);
  230. }
  231. // C functions we call
  232. public static native void nativeInit();
  233. public static native void nativeLowMemory();
  234. public static native void nativeQuit();
  235. public static native void nativePause();
  236. public static native void nativeResume();
  237. public static native void onNativeResize(int x, int y, int format);
  238. public static native int onNativePadDown(int device_id, int keycode);
  239. public static native int onNativePadUp(int device_id, int keycode);
  240. public static native void onNativeJoy(int device_id, int axis,
  241. float value);
  242. public static native void onNativeHat(int device_id, int hat_id,
  243. int x, int y);
  244. public static native void onNativeKeyDown(int keycode);
  245. public static native void onNativeKeyUp(int keycode);
  246. public static native void onNativeKeyboardFocusLost();
  247. public static native void onNativeTouch(int touchDevId, int pointerFingerId,
  248. int action, float x,
  249. float y, float p);
  250. public static native void onNativeAccel(float x, float y, float z);
  251. public static native void onNativeSurfaceChanged();
  252. public static native void onNativeSurfaceDestroyed();
  253. public static native void nativeFlipBuffers();
  254. public static native int nativeAddJoystick(int device_id, String name,
  255. int is_accelerometer, int nbuttons,
  256. int naxes, int nhats, int nballs);
  257. public static native int nativeRemoveJoystick(int device_id);
  258. public static void flipBuffers() {
  259. SDLActivity.nativeFlipBuffers();
  260. }
  261. public static boolean setActivityTitle(String title) {
  262. // Called from SDLMain() thread and can't directly affect the view
  263. return mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
  264. }
  265. public static boolean sendMessage(int command, int param) {
  266. return mSingleton.sendCommand(command, Integer.valueOf(param));
  267. }
  268. public static Context getContext() {
  269. return mSingleton;
  270. }
  271. /**
  272. * @return result of getSystemService(name) but executed on UI thread.
  273. */
  274. public Object getSystemServiceFromUiThread(final String name) {
  275. final Object lock = new Object();
  276. final Object[] results = new Object[2]; // array for writable variables
  277. synchronized (lock) {
  278. runOnUiThread(new Runnable() {
  279. @Override
  280. public void run() {
  281. synchronized (lock) {
  282. results[0] = getSystemService(name);
  283. results[1] = Boolean.TRUE;
  284. lock.notify();
  285. }
  286. }
  287. });
  288. if (results[1] == null) {
  289. try {
  290. lock.wait();
  291. } catch (InterruptedException ex) {
  292. ex.printStackTrace();
  293. }
  294. }
  295. }
  296. return results[0];
  297. }
  298. static class ShowTextInputTask implements Runnable {
  299. /*
  300. * This is used to regulate the pan&scan method to have some offset from
  301. * the bottom edge of the input region and the top edge of an input
  302. * method (soft keyboard)
  303. */
  304. static final int HEIGHT_PADDING = 15;
  305. public int x, y, w, h;
  306. public ShowTextInputTask(int x, int y, int w, int h) {
  307. this.x = x;
  308. this.y = y;
  309. this.w = w;
  310. this.h = h;
  311. }
  312. @Override
  313. public void run() {
  314. AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
  315. w, h + HEIGHT_PADDING, x, y);
  316. if (mTextEdit == null) {
  317. mTextEdit = new DummyEdit(getContext());
  318. mLayout.addView(mTextEdit, params);
  319. } else {
  320. mTextEdit.setLayoutParams(params);
  321. }
  322. mTextEdit.setVisibility(View.VISIBLE);
  323. mTextEdit.requestFocus();
  324. InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  325. imm.showSoftInput(mTextEdit, 0);
  326. }
  327. }
  328. public static boolean showTextInput(int x, int y, int w, int h) {
  329. // Transfer the task to the main thread as a Runnable
  330. return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h));
  331. }
  332. public static Surface getNativeSurface() {
  333. return SDLActivity.mSurface.getNativeSurface();
  334. }
  335. // Audio
  336. public static int audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
  337. int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
  338. int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
  339. int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
  340. Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + (sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  341. // Let the user pick a larger buffer if they really want -- but ye
  342. // gods they probably shouldn't, the minimums are horrifyingly high
  343. // latency already
  344. desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
  345. if (mAudioTrack == null) {
  346. mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
  347. channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
  348. // Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
  349. // Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
  350. // Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
  351. if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
  352. Log.e("SDL", "Failed during initialization of Audio Track");
  353. mAudioTrack = null;
  354. return -1;
  355. }
  356. mAudioTrack.play();
  357. }
  358. Log.v("SDL", "SDL audio: got " + ((mAudioTrack.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioTrack.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + (mAudioTrack.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  359. return 0;
  360. }
  361. public static void audioWriteShortBuffer(short[] buffer) {
  362. for (int i = 0; i < buffer.length; ) {
  363. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  364. if (result > 0) {
  365. i += result;
  366. } else if (result == 0) {
  367. try {
  368. Thread.sleep(1);
  369. } catch(InterruptedException e) {
  370. // Nom nom
  371. }
  372. } else {
  373. Log.w("SDL", "SDL audio: error return from write(short)");
  374. return;
  375. }
  376. }
  377. }
  378. public static void audioWriteByteBuffer(byte[] buffer) {
  379. for (int i = 0; i < buffer.length; ) {
  380. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  381. if (result > 0) {
  382. i += result;
  383. } else if (result == 0) {
  384. try {
  385. Thread.sleep(1);
  386. } catch(InterruptedException e) {
  387. // Nom nom
  388. }
  389. } else {
  390. Log.w("SDL", "SDL audio: error return from write(byte)");
  391. return;
  392. }
  393. }
  394. }
  395. public static void audioQuit() {
  396. if (mAudioTrack != null) {
  397. mAudioTrack.stop();
  398. mAudioTrack = null;
  399. }
  400. }
  401. // Input
  402. /**
  403. * @return an array which may be empty but is never null.
  404. */
  405. public static int[] inputGetInputDeviceIds(int sources) {
  406. int[] ids = InputDevice.getDeviceIds();
  407. int[] filtered = new int[ids.length];
  408. int used = 0;
  409. for (int i = 0; i < ids.length; ++i) {
  410. InputDevice device = InputDevice.getDevice(ids[i]);
  411. if ((device != null) && ((device.getSources() & sources) != 0)) {
  412. filtered[used++] = device.getId();
  413. }
  414. }
  415. return Arrays.copyOf(filtered, used);
  416. }
  417. // Joystick glue code, just a series of stubs that redirect to the SDLJoystickHandler instance
  418. public static boolean handleJoystickMotionEvent(MotionEvent event) {
  419. return mJoystickHandler.handleMotionEvent(event);
  420. }
  421. public static void pollInputDevices() {
  422. if (SDLActivity.mSDLThread != null) {
  423. mJoystickHandler.pollInputDevices();
  424. }
  425. }
  426. }
  427. /**
  428. Simple nativeInit() runnable
  429. */
  430. class SDLMain implements Runnable {
  431. @Override
  432. public void run() {
  433. // Runs SDL_main()
  434. SDLActivity.nativeInit();
  435. //Log.v("SDL", "SDL thread terminated");
  436. }
  437. }
  438. /**
  439. SDLSurface. This is what we draw on, so we need to know when it's created
  440. in order to do anything useful.
  441. Because of this, that's where we set up the SDL thread
  442. */
  443. class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
  444. View.OnKeyListener, View.OnTouchListener, SensorEventListener {
  445. // Sensors
  446. protected static SensorManager mSensorManager;
  447. protected static Display mDisplay;
  448. // Keep track of the surface size to normalize touch events
  449. protected static float mWidth, mHeight;
  450. // Startup
  451. public SDLSurface(Context context) {
  452. super(context);
  453. getHolder().addCallback(this);
  454. setFocusable(true);
  455. setFocusableInTouchMode(true);
  456. requestFocus();
  457. setOnKeyListener(this);
  458. setOnTouchListener(this);
  459. mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  460. mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  461. if(Build.VERSION.SDK_INT >= 12) {
  462. setOnGenericMotionListener(new SDLGenericMotionListener_API12());
  463. }
  464. // Some arbitrary defaults to avoid a potential division by zero
  465. mWidth = 1.0f;
  466. mHeight = 1.0f;
  467. }
  468. public Surface getNativeSurface() {
  469. return getHolder().getSurface();
  470. }
  471. // Called when we have a valid drawing surface
  472. @Override
  473. public void surfaceCreated(SurfaceHolder holder) {
  474. Log.v("SDL", "surfaceCreated()");
  475. holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  476. }
  477. // Called when we lose the surface
  478. @Override
  479. public void surfaceDestroyed(SurfaceHolder holder) {
  480. Log.v("SDL", "surfaceDestroyed()");
  481. // Call this *before* setting mIsSurfaceReady to 'false'
  482. SDLActivity.handlePause();
  483. SDLActivity.mIsSurfaceReady = false;
  484. SDLActivity.onNativeSurfaceDestroyed();
  485. }
  486. // Called when the surface is resized
  487. @Override
  488. public void surfaceChanged(SurfaceHolder holder,
  489. int format, int width, int height) {
  490. Log.v("SDL", "surfaceChanged()");
  491. int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
  492. switch (format) {
  493. case PixelFormat.A_8:
  494. Log.v("SDL", "pixel format A_8");
  495. break;
  496. case PixelFormat.LA_88:
  497. Log.v("SDL", "pixel format LA_88");
  498. break;
  499. case PixelFormat.L_8:
  500. Log.v("SDL", "pixel format L_8");
  501. break;
  502. case PixelFormat.RGBA_4444:
  503. Log.v("SDL", "pixel format RGBA_4444");
  504. sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
  505. break;
  506. case PixelFormat.RGBA_5551:
  507. Log.v("SDL", "pixel format RGBA_5551");
  508. sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
  509. break;
  510. case PixelFormat.RGBA_8888:
  511. Log.v("SDL", "pixel format RGBA_8888");
  512. sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
  513. break;
  514. case PixelFormat.RGBX_8888:
  515. Log.v("SDL", "pixel format RGBX_8888");
  516. sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
  517. break;
  518. case PixelFormat.RGB_332:
  519. Log.v("SDL", "pixel format RGB_332");
  520. sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
  521. break;
  522. case PixelFormat.RGB_565:
  523. Log.v("SDL", "pixel format RGB_565");
  524. sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
  525. break;
  526. case PixelFormat.RGB_888:
  527. Log.v("SDL", "pixel format RGB_888");
  528. // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
  529. sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
  530. break;
  531. default:
  532. Log.v("SDL", "pixel format unknown " + format);
  533. break;
  534. }
  535. mWidth = width;
  536. mHeight = height;
  537. SDLActivity.onNativeResize(width, height, sdlFormat);
  538. Log.v("SDL", "Window size:" + width + "x"+height);
  539. // Set mIsSurfaceReady to 'true' *before* making a call to handleResume
  540. SDLActivity.mIsSurfaceReady = true;
  541. SDLActivity.onNativeSurfaceChanged();
  542. if (SDLActivity.mSDLThread == null) {
  543. // This is the entry point to the C app.
  544. // Start up the C app thread and enable sensor input for the first time
  545. SDLActivity.mSDLThread = new Thread(new SDLMain(), "SDLThread");
  546. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  547. SDLActivity.mSDLThread.start();
  548. // Set up a listener thread to catch when the native thread ends
  549. new Thread(new Runnable(){
  550. @Override
  551. public void run(){
  552. try {
  553. SDLActivity.mSDLThread.join();
  554. }
  555. catch(Exception e){}
  556. finally{
  557. // Native thread has finished
  558. if (! SDLActivity.mExitCalledFromJava) {
  559. SDLActivity.handleNativeExit();
  560. }
  561. }
  562. }
  563. }).start();
  564. }
  565. }
  566. // unused
  567. @Override
  568. public void onDraw(Canvas canvas) {}
  569. // Key events
  570. @Override
  571. public boolean onKey(View v, int keyCode, KeyEvent event) {
  572. // Dispatch the different events depending on where they come from
  573. // Some SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD
  574. // So, we try to process them as DPAD or GAMEPAD events first, if that fails we try them as KEYBOARD
  575. if ( (event.getSource() & 0x00000401) != 0 || /* API 12: SOURCE_GAMEPAD */
  576. (event.getSource() & InputDevice.SOURCE_DPAD) != 0 ) {
  577. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  578. if (SDLActivity.onNativePadDown(event.getDeviceId(), keyCode) == 0) {
  579. return true;
  580. }
  581. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  582. if (SDLActivity.onNativePadUp(event.getDeviceId(), keyCode) == 0) {
  583. return true;
  584. }
  585. }
  586. }
  587. if( (event.getSource() & InputDevice.SOURCE_KEYBOARD) != 0) {
  588. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  589. //Log.v("SDL", "key down: " + keyCode);
  590. SDLActivity.onNativeKeyDown(keyCode);
  591. return true;
  592. }
  593. else if (event.getAction() == KeyEvent.ACTION_UP) {
  594. //Log.v("SDL", "key up: " + keyCode);
  595. SDLActivity.onNativeKeyUp(keyCode);
  596. return true;
  597. }
  598. }
  599. return false;
  600. }
  601. // Touch events
  602. @Override
  603. public boolean onTouch(View v, MotionEvent event) {
  604. /* Ref: http://developer.android.com/training/gestures/multi.html */
  605. final int touchDevId = event.getDeviceId();
  606. final int pointerCount = event.getPointerCount();
  607. int action = event.getActionMasked();
  608. int pointerFingerId;
  609. int i = -1;
  610. float x,y,p;
  611. switch(action) {
  612. case MotionEvent.ACTION_MOVE:
  613. for (i = 0; i < pointerCount; i++) {
  614. pointerFingerId = event.getPointerId(i);
  615. x = event.getX(i) / mWidth;
  616. y = event.getY(i) / mHeight;
  617. p = event.getPressure(i);
  618. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  619. }
  620. break;
  621. case MotionEvent.ACTION_UP:
  622. case MotionEvent.ACTION_DOWN:
  623. // Primary pointer up/down, the index is always zero
  624. i = 0;
  625. case MotionEvent.ACTION_POINTER_UP:
  626. case MotionEvent.ACTION_POINTER_DOWN:
  627. // Non primary pointer up/down
  628. if (i == -1) {
  629. i = event.getActionIndex();
  630. }
  631. pointerFingerId = event.getPointerId(i);
  632. x = event.getX(i) / mWidth;
  633. y = event.getY(i) / mHeight;
  634. p = event.getPressure(i);
  635. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  636. break;
  637. default:
  638. break;
  639. }
  640. return true;
  641. }
  642. // Sensor events
  643. public void enableSensor(int sensortype, boolean enabled) {
  644. // TODO: This uses getDefaultSensor - what if we have >1 accels?
  645. if (enabled) {
  646. mSensorManager.registerListener(this,
  647. mSensorManager.getDefaultSensor(sensortype),
  648. SensorManager.SENSOR_DELAY_GAME, null);
  649. } else {
  650. mSensorManager.unregisterListener(this,
  651. mSensorManager.getDefaultSensor(sensortype));
  652. }
  653. }
  654. @Override
  655. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  656. // TODO
  657. }
  658. @Override
  659. public void onSensorChanged(SensorEvent event) {
  660. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  661. float x, y;
  662. switch (mDisplay.getRotation()) {
  663. case Surface.ROTATION_90:
  664. x = -event.values[1];
  665. y = event.values[0];
  666. break;
  667. case Surface.ROTATION_270:
  668. x = event.values[1];
  669. y = -event.values[0];
  670. break;
  671. case Surface.ROTATION_180:
  672. x = -event.values[1];
  673. y = -event.values[0];
  674. break;
  675. default:
  676. x = event.values[0];
  677. y = event.values[1];
  678. break;
  679. }
  680. SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
  681. y / SensorManager.GRAVITY_EARTH,
  682. event.values[2] / SensorManager.GRAVITY_EARTH - 1);
  683. }
  684. }
  685. }
  686. /* This is a fake invisible editor view that receives the input and defines the
  687. * pan&scan region
  688. */
  689. class DummyEdit extends View implements View.OnKeyListener {
  690. InputConnection ic;
  691. public DummyEdit(Context context) {
  692. super(context);
  693. setFocusableInTouchMode(true);
  694. setFocusable(true);
  695. setOnKeyListener(this);
  696. }
  697. @Override
  698. public boolean onCheckIsTextEditor() {
  699. return true;
  700. }
  701. @Override
  702. public boolean onKey(View v, int keyCode, KeyEvent event) {
  703. // This handles the hardware keyboard input
  704. if (event.isPrintingKey()) {
  705. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  706. ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  707. }
  708. return true;
  709. }
  710. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  711. SDLActivity.onNativeKeyDown(keyCode);
  712. return true;
  713. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  714. SDLActivity.onNativeKeyUp(keyCode);
  715. return true;
  716. }
  717. return false;
  718. }
  719. //
  720. @Override
  721. public boolean onKeyPreIme (int keyCode, KeyEvent event) {
  722. // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
  723. // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
  724. // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
  725. // FIXME: A more effective solution would be to change our Layout from AbsoluteLayout to Relative or Linear
  726. // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
  727. // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
  728. if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
  729. if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
  730. SDLActivity.onNativeKeyboardFocusLost();
  731. }
  732. }
  733. return super.onKeyPreIme(keyCode, event);
  734. }
  735. @Override
  736. public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
  737. ic = new SDLInputConnection(this, true);
  738. outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
  739. | 33554432 /* API 11: EditorInfo.IME_FLAG_NO_FULLSCREEN */;
  740. return ic;
  741. }
  742. }
  743. class SDLInputConnection extends BaseInputConnection {
  744. public SDLInputConnection(View targetView, boolean fullEditor) {
  745. super(targetView, fullEditor);
  746. }
  747. @Override
  748. public boolean sendKeyEvent(KeyEvent event) {
  749. /*
  750. * This handles the keycodes from soft keyboard (and IME-translated
  751. * input from hardkeyboard)
  752. */
  753. int keyCode = event.getKeyCode();
  754. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  755. if (event.isPrintingKey()) {
  756. commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  757. }
  758. SDLActivity.onNativeKeyDown(keyCode);
  759. return true;
  760. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  761. SDLActivity.onNativeKeyUp(keyCode);
  762. return true;
  763. }
  764. return super.sendKeyEvent(event);
  765. }
  766. @Override
  767. public boolean commitText(CharSequence text, int newCursorPosition) {
  768. nativeCommitText(text.toString(), newCursorPosition);
  769. return super.commitText(text, newCursorPosition);
  770. }
  771. @Override
  772. public boolean setComposingText(CharSequence text, int newCursorPosition) {
  773. nativeSetComposingText(text.toString(), newCursorPosition);
  774. return super.setComposingText(text, newCursorPosition);
  775. }
  776. public native void nativeCommitText(String text, int newCursorPosition);
  777. public native void nativeSetComposingText(String text, int newCursorPosition);
  778. @Override
  779. public boolean deleteSurroundingText(int beforeLength, int afterLength) {
  780. // Workaround to capture backspace key. Ref: http://stackoverflow.com/questions/14560344/android-backspace-in-webview-baseinputconnection
  781. if (beforeLength == 1 && afterLength == 0) {
  782. // backspace
  783. return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
  784. && super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
  785. }
  786. return super.deleteSurroundingText(beforeLength, afterLength);
  787. }
  788. }
  789. /* A null joystick handler for API level < 12 devices (the accelerometer is handled separately) */
  790. class SDLJoystickHandler {
  791. public boolean handleMotionEvent(MotionEvent event) {
  792. return false;
  793. }
  794. public void pollInputDevices() {
  795. }
  796. }
  797. /* Actual joystick functionality available for API >= 12 devices */
  798. class SDLJoystickHandler_API12 extends SDLJoystickHandler {
  799. class SDLJoystick {
  800. public int device_id;
  801. public String name;
  802. public ArrayList<InputDevice.MotionRange> axes;
  803. public ArrayList<InputDevice.MotionRange> hats;
  804. }
  805. class RangeComparator implements Comparator<InputDevice.MotionRange>
  806. {
  807. @Override
  808. public int compare(InputDevice.MotionRange arg0, InputDevice.MotionRange arg1) {
  809. return arg0.getAxis() - arg1.getAxis();
  810. }
  811. }
  812. private ArrayList<SDLJoystick> mJoysticks;
  813. public SDLJoystickHandler_API12() {
  814. mJoysticks = new ArrayList<SDLJoystick>();
  815. }
  816. @Override
  817. public void pollInputDevices() {
  818. int[] deviceIds = InputDevice.getDeviceIds();
  819. // It helps processing the device ids in reverse order
  820. // For example, in the case of the XBox 360 wireless dongle,
  821. // so the first controller seen by SDL matches what the receiver
  822. // considers to be the first controller
  823. for(int i=deviceIds.length-1; i>-1; i--) {
  824. SDLJoystick joystick = getJoystick(deviceIds[i]);
  825. if (joystick == null) {
  826. joystick = new SDLJoystick();
  827. InputDevice joystickDevice = InputDevice.getDevice(deviceIds[i]);
  828. if( (joystickDevice.getSources() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
  829. joystick.device_id = deviceIds[i];
  830. joystick.name = joystickDevice.getName();
  831. joystick.axes = new ArrayList<InputDevice.MotionRange>();
  832. joystick.hats = new ArrayList<InputDevice.MotionRange>();
  833. List<InputDevice.MotionRange> ranges = joystickDevice.getMotionRanges();
  834. Collections.sort(ranges, new RangeComparator());
  835. for (InputDevice.MotionRange range : ranges ) {
  836. if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0 ) {
  837. if (range.getAxis() == MotionEvent.AXIS_HAT_X ||
  838. range.getAxis() == MotionEvent.AXIS_HAT_Y) {
  839. joystick.hats.add(range);
  840. }
  841. else {
  842. joystick.axes.add(range);
  843. }
  844. }
  845. }
  846. mJoysticks.add(joystick);
  847. SDLActivity.nativeAddJoystick(joystick.device_id, joystick.name, 0, -1,
  848. joystick.axes.size(), joystick.hats.size()/2, 0);
  849. }
  850. }
  851. }
  852. /* Check removed devices */
  853. ArrayList<Integer> removedDevices = new ArrayList<Integer>();
  854. for(int i=0; i < mJoysticks.size(); i++) {
  855. int device_id = mJoysticks.get(i).device_id;
  856. int j;
  857. for (j=0; j < deviceIds.length; j++) {
  858. if (device_id == deviceIds[j]) break;
  859. }
  860. if (j == deviceIds.length) {
  861. removedDevices.add(device_id);
  862. }
  863. }
  864. for(int i=0; i < removedDevices.size(); i++) {
  865. int device_id = removedDevices.get(i);
  866. SDLActivity.nativeRemoveJoystick(device_id);
  867. for (int j=0; j < mJoysticks.size(); j++) {
  868. if (mJoysticks.get(j).device_id == device_id) {
  869. mJoysticks.remove(j);
  870. break;
  871. }
  872. }
  873. }
  874. }
  875. protected SDLJoystick getJoystick(int device_id) {
  876. for(int i=0; i < mJoysticks.size(); i++) {
  877. if (mJoysticks.get(i).device_id == device_id) {
  878. return mJoysticks.get(i);
  879. }
  880. }
  881. return null;
  882. }
  883. @Override
  884. public boolean handleMotionEvent(MotionEvent event) {
  885. if ( (event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
  886. int actionPointerIndex = event.getActionIndex();
  887. int action = event.getActionMasked();
  888. switch(action) {
  889. case MotionEvent.ACTION_MOVE:
  890. SDLJoystick joystick = getJoystick(event.getDeviceId());
  891. if ( joystick != null ) {
  892. for (int i = 0; i < joystick.axes.size(); i++) {
  893. InputDevice.MotionRange range = joystick.axes.get(i);
  894. /* Normalize the value to -1...1 */
  895. float value = ( event.getAxisValue( range.getAxis(), actionPointerIndex) - range.getMin() ) / range.getRange() * 2.0f - 1.0f;
  896. SDLActivity.onNativeJoy(joystick.device_id, i, value );
  897. }
  898. for (int i = 0; i < joystick.hats.size(); i+=2) {
  899. int hatX = Math.round(event.getAxisValue( joystick.hats.get(i).getAxis(), actionPointerIndex ) );
  900. int hatY = Math.round(event.getAxisValue( joystick.hats.get(i+1).getAxis(), actionPointerIndex ) );
  901. SDLActivity.onNativeHat(joystick.device_id, i/2, hatX, hatY );
  902. }
  903. }
  904. break;
  905. default:
  906. break;
  907. }
  908. }
  909. return true;
  910. }
  911. }
  912. class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener {
  913. // Generic Motion (mouse hover, joystick...) events go here
  914. // We only have joysticks yet
  915. @Override
  916. public boolean onGenericMotion(View v, MotionEvent event) {
  917. return SDLActivity.handleJoystickMotionEvent(event);
  918. }
  919. }