SDLActivity.java 27 KB

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