SDLActivity.java 51 KB

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