SDLActivity.java 42 KB

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