SDLActivity.java 34 KB

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