SDLActivity.java 28 KB

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