SDLActivity.java 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  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 int onNativePadDown(int padId, int keycode);
  212. public static native int 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. /**
  239. * @return result of getSystemService(name) but executed on UI thread.
  240. */
  241. public Object getSystemServiceFromUiThread(final String name) {
  242. final Object lock = new Object();
  243. final Object[] results = new Object[2]; // array for writable variables
  244. synchronized (lock) {
  245. runOnUiThread(new Runnable() {
  246. @Override
  247. public void run() {
  248. synchronized (lock) {
  249. results[0] = getSystemService(name);
  250. results[1] = Boolean.TRUE;
  251. lock.notify();
  252. }
  253. }
  254. });
  255. if (results[1] == null) {
  256. try {
  257. lock.wait();
  258. } catch (InterruptedException ex) {
  259. ex.printStackTrace();
  260. }
  261. }
  262. }
  263. return results[0];
  264. }
  265. static class ShowTextInputTask implements Runnable {
  266. /*
  267. * This is used to regulate the pan&scan method to have some offset from
  268. * the bottom edge of the input region and the top edge of an input
  269. * method (soft keyboard)
  270. */
  271. static final int HEIGHT_PADDING = 15;
  272. public int x, y, w, h;
  273. public ShowTextInputTask(int x, int y, int w, int h) {
  274. this.x = x;
  275. this.y = y;
  276. this.w = w;
  277. this.h = h;
  278. }
  279. @Override
  280. public void run() {
  281. AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(
  282. w, h + HEIGHT_PADDING, x, y);
  283. if (mTextEdit == null) {
  284. mTextEdit = new DummyEdit(getContext());
  285. mLayout.addView(mTextEdit, params);
  286. } else {
  287. mTextEdit.setLayoutParams(params);
  288. }
  289. mTextEdit.setVisibility(View.VISIBLE);
  290. mTextEdit.requestFocus();
  291. InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  292. imm.showSoftInput(mTextEdit, 0);
  293. }
  294. }
  295. public static boolean showTextInput(int x, int y, int w, int h) {
  296. // Transfer the task to the main thread as a Runnable
  297. return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h));
  298. }
  299. public static Surface getNativeSurface() {
  300. return SDLActivity.mSurface.getNativeSurface();
  301. }
  302. // Audio
  303. public static int audioInit(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
  304. int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
  305. int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
  306. int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
  307. Log.v("SDL", "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + (sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  308. // Let the user pick a larger buffer if they really want -- but ye
  309. // gods they probably shouldn't, the minimums are horrifyingly high
  310. // latency already
  311. desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
  312. if (mAudioTrack == null) {
  313. mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
  314. channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
  315. // Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
  316. // Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
  317. // Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
  318. if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
  319. Log.e("SDL", "Failed during initialization of Audio Track");
  320. mAudioTrack = null;
  321. return -1;
  322. }
  323. mAudioTrack.play();
  324. }
  325. 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");
  326. return 0;
  327. }
  328. public static void audioWriteShortBuffer(short[] buffer) {
  329. for (int i = 0; i < buffer.length; ) {
  330. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  331. if (result > 0) {
  332. i += result;
  333. } else if (result == 0) {
  334. try {
  335. Thread.sleep(1);
  336. } catch(InterruptedException e) {
  337. // Nom nom
  338. }
  339. } else {
  340. Log.w("SDL", "SDL audio: error return from write(short)");
  341. return;
  342. }
  343. }
  344. }
  345. public static void audioWriteByteBuffer(byte[] buffer) {
  346. for (int i = 0; i < buffer.length; ) {
  347. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  348. if (result > 0) {
  349. i += result;
  350. } else if (result == 0) {
  351. try {
  352. Thread.sleep(1);
  353. } catch(InterruptedException e) {
  354. // Nom nom
  355. }
  356. } else {
  357. Log.w("SDL", "SDL audio: error return from write(byte)");
  358. return;
  359. }
  360. }
  361. }
  362. public static void audioQuit() {
  363. if (mAudioTrack != null) {
  364. mAudioTrack.stop();
  365. mAudioTrack = null;
  366. }
  367. }
  368. // Input
  369. /**
  370. * @return an array which may be empty but is never null.
  371. */
  372. public static int[] inputGetInputDeviceIds(int sources) {
  373. int[] ids = InputDevice.getDeviceIds();
  374. int[] filtered = new int[ids.length];
  375. int used = 0;
  376. for (int i = 0; i < ids.length; ++i) {
  377. InputDevice device = InputDevice.getDevice(ids[i]);
  378. if ((device != null) && ((device.getSources() & sources) != 0)) {
  379. filtered[used++] = device.getId();
  380. }
  381. }
  382. return Arrays.copyOf(filtered, used);
  383. }
  384. // Joystick glue code, just a series of stubs that redirect to the SDLJoystickHandler instance
  385. public static int getNumJoysticks() {
  386. return mJoystickHandler.getNumJoysticks();
  387. }
  388. public static String getJoystickName(int joy) {
  389. return mJoystickHandler.getJoystickName(joy);
  390. }
  391. public static int getJoystickAxes(int joy) {
  392. return mJoystickHandler.getJoystickAxes(joy);
  393. }
  394. public static boolean handleJoystickMotionEvent(MotionEvent event) {
  395. return mJoystickHandler.handleMotionEvent(event);
  396. }
  397. /**
  398. * @param devId the device id to get opened joystick id for.
  399. * @return joystick id for device id or -1 if there is none.
  400. */
  401. public static int getJoyId(int devId) {
  402. return mJoystickHandler.getJoyId(devId);
  403. }
  404. }
  405. /**
  406. Simple nativeInit() runnable
  407. */
  408. class SDLMain implements Runnable {
  409. @Override
  410. public void run() {
  411. // Runs SDL_main()
  412. SDLActivity.nativeInit();
  413. //Log.v("SDL", "SDL thread terminated");
  414. }
  415. }
  416. /**
  417. SDLSurface. This is what we draw on, so we need to know when it's created
  418. in order to do anything useful.
  419. Because of this, that's where we set up the SDL thread
  420. */
  421. class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
  422. View.OnKeyListener, View.OnTouchListener, SensorEventListener {
  423. // Sensors
  424. protected static SensorManager mSensorManager;
  425. protected static Display mDisplay;
  426. // Keep track of the surface size to normalize touch events
  427. protected static float mWidth, mHeight;
  428. // Startup
  429. public SDLSurface(Context context) {
  430. super(context);
  431. getHolder().addCallback(this);
  432. setFocusable(true);
  433. setFocusableInTouchMode(true);
  434. requestFocus();
  435. setOnKeyListener(this);
  436. setOnTouchListener(this);
  437. mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  438. mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  439. if(Build.VERSION.SDK_INT >= 12) {
  440. setOnGenericMotionListener(new SDLGenericMotionListener_API12());
  441. }
  442. // Some arbitrary defaults to avoid a potential division by zero
  443. mWidth = 1.0f;
  444. mHeight = 1.0f;
  445. }
  446. public Surface getNativeSurface() {
  447. return getHolder().getSurface();
  448. }
  449. // Called when we have a valid drawing surface
  450. @Override
  451. public void surfaceCreated(SurfaceHolder holder) {
  452. Log.v("SDL", "surfaceCreated()");
  453. holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  454. }
  455. // Called when we lose the surface
  456. @Override
  457. public void surfaceDestroyed(SurfaceHolder holder) {
  458. Log.v("SDL", "surfaceDestroyed()");
  459. // Call this *before* setting mIsSurfaceReady to 'false'
  460. SDLActivity.handlePause();
  461. SDLActivity.mIsSurfaceReady = false;
  462. SDLActivity.onNativeSurfaceDestroyed();
  463. }
  464. // Called when the surface is resized
  465. @Override
  466. public void surfaceChanged(SurfaceHolder holder,
  467. int format, int width, int height) {
  468. Log.v("SDL", "surfaceChanged()");
  469. int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
  470. switch (format) {
  471. case PixelFormat.A_8:
  472. Log.v("SDL", "pixel format A_8");
  473. break;
  474. case PixelFormat.LA_88:
  475. Log.v("SDL", "pixel format LA_88");
  476. break;
  477. case PixelFormat.L_8:
  478. Log.v("SDL", "pixel format L_8");
  479. break;
  480. case PixelFormat.RGBA_4444:
  481. Log.v("SDL", "pixel format RGBA_4444");
  482. sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
  483. break;
  484. case PixelFormat.RGBA_5551:
  485. Log.v("SDL", "pixel format RGBA_5551");
  486. sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
  487. break;
  488. case PixelFormat.RGBA_8888:
  489. Log.v("SDL", "pixel format RGBA_8888");
  490. sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
  491. break;
  492. case PixelFormat.RGBX_8888:
  493. Log.v("SDL", "pixel format RGBX_8888");
  494. sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
  495. break;
  496. case PixelFormat.RGB_332:
  497. Log.v("SDL", "pixel format RGB_332");
  498. sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
  499. break;
  500. case PixelFormat.RGB_565:
  501. Log.v("SDL", "pixel format RGB_565");
  502. sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
  503. break;
  504. case PixelFormat.RGB_888:
  505. Log.v("SDL", "pixel format RGB_888");
  506. // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
  507. sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
  508. break;
  509. default:
  510. Log.v("SDL", "pixel format unknown " + format);
  511. break;
  512. }
  513. mWidth = width;
  514. mHeight = height;
  515. SDLActivity.onNativeResize(width, height, sdlFormat);
  516. Log.v("SDL", "Window size:" + width + "x"+height);
  517. // Set mIsSurfaceReady to 'true' *before* making a call to handleResume
  518. SDLActivity.mIsSurfaceReady = true;
  519. SDLActivity.onNativeSurfaceChanged();
  520. if (SDLActivity.mSDLThread == null) {
  521. // This is the entry point to the C app.
  522. // Start up the C app thread and enable sensor input for the first time
  523. SDLActivity.mSDLThread = new Thread(new SDLMain(), "SDLThread");
  524. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  525. SDLActivity.mSDLThread.start();
  526. }
  527. }
  528. // unused
  529. @Override
  530. public void onDraw(Canvas canvas) {}
  531. // Key events
  532. @Override
  533. public boolean onKey(View v, int keyCode, KeyEvent event) {
  534. // Dispatch the different events depending on where they come from
  535. // Some SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD
  536. // So, we try to process them as DPAD or GAMEPAD events first, if that fails we try them as KEYBOARD
  537. if ( (event.getSource() & 0x00000401) != 0 || /* API 12: SOURCE_GAMEPAD */
  538. (event.getSource() & InputDevice.SOURCE_DPAD) != 0 ) {
  539. int id = SDLActivity.getJoyId( event.getDeviceId() );
  540. if (id != -1) {
  541. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  542. if (SDLActivity.onNativePadDown(id, keyCode) == 0) {
  543. return true;
  544. }
  545. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  546. if (SDLActivity.onNativePadUp(id, keyCode) == 0) {
  547. return true;
  548. }
  549. }
  550. }
  551. }
  552. if( (event.getSource() & InputDevice.SOURCE_KEYBOARD) != 0) {
  553. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  554. //Log.v("SDL", "key down: " + keyCode);
  555. SDLActivity.onNativeKeyDown(keyCode);
  556. return true;
  557. }
  558. else if (event.getAction() == KeyEvent.ACTION_UP) {
  559. //Log.v("SDL", "key up: " + keyCode);
  560. SDLActivity.onNativeKeyUp(keyCode);
  561. return true;
  562. }
  563. }
  564. return false;
  565. }
  566. // Touch events
  567. @Override
  568. public boolean onTouch(View v, MotionEvent event) {
  569. /* Ref: http://developer.android.com/training/gestures/multi.html */
  570. final int touchDevId = event.getDeviceId();
  571. final int pointerCount = event.getPointerCount();
  572. int action = event.getActionMasked();
  573. int pointerFingerId;
  574. int i = -1;
  575. float x,y,p;
  576. switch(action) {
  577. case MotionEvent.ACTION_MOVE:
  578. for (i = 0; i < pointerCount; i++) {
  579. pointerFingerId = event.getPointerId(i);
  580. x = event.getX(i) / mWidth;
  581. y = event.getY(i) / mHeight;
  582. p = event.getPressure(i);
  583. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  584. }
  585. break;
  586. case MotionEvent.ACTION_UP:
  587. case MotionEvent.ACTION_DOWN:
  588. // Primary pointer up/down, the index is always zero
  589. i = 0;
  590. case MotionEvent.ACTION_POINTER_UP:
  591. case MotionEvent.ACTION_POINTER_DOWN:
  592. // Non primary pointer up/down
  593. if (i == -1) {
  594. i = event.getActionIndex();
  595. }
  596. pointerFingerId = event.getPointerId(i);
  597. x = event.getX(i) / mWidth;
  598. y = event.getY(i) / mHeight;
  599. p = event.getPressure(i);
  600. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  601. break;
  602. default:
  603. break;
  604. }
  605. return true;
  606. }
  607. // Sensor events
  608. public void enableSensor(int sensortype, boolean enabled) {
  609. // TODO: This uses getDefaultSensor - what if we have >1 accels?
  610. if (enabled) {
  611. mSensorManager.registerListener(this,
  612. mSensorManager.getDefaultSensor(sensortype),
  613. SensorManager.SENSOR_DELAY_GAME, null);
  614. } else {
  615. mSensorManager.unregisterListener(this,
  616. mSensorManager.getDefaultSensor(sensortype));
  617. }
  618. }
  619. @Override
  620. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  621. // TODO
  622. }
  623. @Override
  624. public void onSensorChanged(SensorEvent event) {
  625. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  626. float x, y;
  627. switch (mDisplay.getRotation()) {
  628. case Surface.ROTATION_90:
  629. x = -event.values[1];
  630. y = event.values[0];
  631. break;
  632. case Surface.ROTATION_270:
  633. x = event.values[1];
  634. y = -event.values[0];
  635. break;
  636. case Surface.ROTATION_180:
  637. x = -event.values[1];
  638. y = -event.values[0];
  639. break;
  640. default:
  641. x = event.values[0];
  642. y = event.values[1];
  643. break;
  644. }
  645. SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
  646. y / SensorManager.GRAVITY_EARTH,
  647. event.values[2] / SensorManager.GRAVITY_EARTH - 1);
  648. }
  649. }
  650. }
  651. /* This is a fake invisible editor view that receives the input and defines the
  652. * pan&scan region
  653. */
  654. class DummyEdit extends View implements View.OnKeyListener {
  655. InputConnection ic;
  656. public DummyEdit(Context context) {
  657. super(context);
  658. setFocusableInTouchMode(true);
  659. setFocusable(true);
  660. setOnKeyListener(this);
  661. }
  662. @Override
  663. public boolean onCheckIsTextEditor() {
  664. return true;
  665. }
  666. @Override
  667. public boolean onKey(View v, int keyCode, KeyEvent event) {
  668. // This handles the hardware keyboard input
  669. if (event.isPrintingKey()) {
  670. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  671. ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  672. }
  673. return true;
  674. }
  675. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  676. SDLActivity.onNativeKeyDown(keyCode);
  677. return true;
  678. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  679. SDLActivity.onNativeKeyUp(keyCode);
  680. return true;
  681. }
  682. return false;
  683. }
  684. //
  685. @Override
  686. public boolean onKeyPreIme (int keyCode, KeyEvent event) {
  687. // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
  688. // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
  689. // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
  690. // FIXME: A more effective solution would be to change our Layout from AbsoluteLayout to Relative or Linear
  691. // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
  692. // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
  693. if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
  694. if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
  695. SDLActivity.onNativeKeyboardFocusLost();
  696. }
  697. }
  698. return super.onKeyPreIme(keyCode, event);
  699. }
  700. @Override
  701. public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
  702. ic = new SDLInputConnection(this, true);
  703. outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
  704. | 33554432 /* API 11: EditorInfo.IME_FLAG_NO_FULLSCREEN */;
  705. return ic;
  706. }
  707. }
  708. class SDLInputConnection extends BaseInputConnection {
  709. public SDLInputConnection(View targetView, boolean fullEditor) {
  710. super(targetView, fullEditor);
  711. }
  712. @Override
  713. public boolean sendKeyEvent(KeyEvent event) {
  714. /*
  715. * This handles the keycodes from soft keyboard (and IME-translated
  716. * input from hardkeyboard)
  717. */
  718. int keyCode = event.getKeyCode();
  719. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  720. if (event.isPrintingKey()) {
  721. commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  722. }
  723. SDLActivity.onNativeKeyDown(keyCode);
  724. return true;
  725. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  726. SDLActivity.onNativeKeyUp(keyCode);
  727. return true;
  728. }
  729. return super.sendKeyEvent(event);
  730. }
  731. @Override
  732. public boolean commitText(CharSequence text, int newCursorPosition) {
  733. nativeCommitText(text.toString(), newCursorPosition);
  734. return super.commitText(text, newCursorPosition);
  735. }
  736. @Override
  737. public boolean setComposingText(CharSequence text, int newCursorPosition) {
  738. nativeSetComposingText(text.toString(), newCursorPosition);
  739. return super.setComposingText(text, newCursorPosition);
  740. }
  741. public native void nativeCommitText(String text, int newCursorPosition);
  742. public native void nativeSetComposingText(String text, int newCursorPosition);
  743. @Override
  744. public boolean deleteSurroundingText(int beforeLength, int afterLength) {
  745. // Workaround to capture backspace key. Ref: http://stackoverflow.com/questions/14560344/android-backspace-in-webview-baseinputconnection
  746. if (beforeLength == 1 && afterLength == 0) {
  747. // backspace
  748. return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
  749. && super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
  750. }
  751. return super.deleteSurroundingText(beforeLength, afterLength);
  752. }
  753. }
  754. /* A null joystick handler for API level < 12 devices (the accelerometer is handled separately) */
  755. class SDLJoystickHandler {
  756. public int getNumJoysticks() {
  757. return 0;
  758. }
  759. public String getJoystickName(int joy) {
  760. return "";
  761. }
  762. public int getJoystickAxes(int joy) {
  763. return 0;
  764. }
  765. /**
  766. * @param devId the device id to get opened joystick id for.
  767. * @return joystick id for device id or -1 if there is none.
  768. */
  769. public int getJoyId(int devId) {
  770. return -1;
  771. }
  772. public boolean handleMotionEvent(MotionEvent event) {
  773. return false;
  774. }
  775. }
  776. /* Actual joystick functionality available for API >= 12 devices */
  777. class SDLJoystickHandler_API12 extends SDLJoystickHandler {
  778. class SDLJoystick {
  779. public int id;
  780. public String name;
  781. public ArrayList<InputDevice.MotionRange> axes;
  782. }
  783. private ArrayList<SDLJoystick> mJoysticks;
  784. public SDLJoystickHandler_API12() {
  785. /* FIXME: Move the joystick initialization code to its own function and support hotplugging of devices */
  786. mJoysticks = new ArrayList<SDLJoystick>();
  787. int[] deviceIds = InputDevice.getDeviceIds();
  788. for(int i=0; i<deviceIds.length; i++) {
  789. SDLJoystick joystick = new SDLJoystick();
  790. InputDevice joystickDevice = InputDevice.getDevice(deviceIds[i]);
  791. if( (joystickDevice.getSources() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
  792. joystick.id = deviceIds[i];
  793. joystick.name = joystickDevice.getName();
  794. joystick.axes = new ArrayList<InputDevice.MotionRange>();
  795. for (InputDevice.MotionRange range : joystickDevice.getMotionRanges()) {
  796. if ( (range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
  797. joystick.axes.add(range);
  798. }
  799. }
  800. mJoysticks.add(joystick);
  801. }
  802. }
  803. }
  804. @Override
  805. public int getNumJoysticks() {
  806. return mJoysticks.size();
  807. }
  808. @Override
  809. public String getJoystickName(int joy) {
  810. return mJoysticks.get(joy).name;
  811. }
  812. @Override
  813. public int getJoystickAxes(int joy) {
  814. return mJoysticks.get(joy).axes.size();
  815. }
  816. @Override
  817. public int getJoyId(int devId) {
  818. for(int i=0; i < mJoysticks.size(); i++) {
  819. if (mJoysticks.get(i).id == devId) {
  820. return i;
  821. }
  822. }
  823. return -1;
  824. }
  825. @Override
  826. public boolean handleMotionEvent(MotionEvent event) {
  827. if ( (event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
  828. int actionPointerIndex = event.getActionIndex();
  829. int action = event.getActionMasked();
  830. switch(action) {
  831. case MotionEvent.ACTION_MOVE:
  832. int id = getJoyId( event.getDeviceId() );
  833. if ( id != -1 ) {
  834. SDLJoystick joystick = mJoysticks.get(id);
  835. for (int i = 0; i < joystick.axes.size(); i++) {
  836. InputDevice.MotionRange range = joystick.axes.get(i);
  837. /* Normalize the value to -1...1 */
  838. float value = ( event.getAxisValue( range.getAxis(), actionPointerIndex) - range.getMin() ) / range.getRange() * 2.0f - 1.0f;
  839. SDLActivity.onNativeJoy(id, i, value );
  840. }
  841. }
  842. break;
  843. default:
  844. break;
  845. }
  846. }
  847. return true;
  848. }
  849. }
  850. class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener {
  851. // Generic Motion (mouse hover, joystick...) events go here
  852. // We only have joysticks yet
  853. @Override
  854. public boolean onGenericMotion(View v, MotionEvent event) {
  855. return SDLActivity.handleJoystickMotionEvent(event);
  856. }
  857. }