SDLActivity.java 39 KB

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