SDLActivity.java 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778
  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.text.InputType;
  13. import android.view.*;
  14. import android.view.inputmethod.BaseInputConnection;
  15. import android.view.inputmethod.EditorInfo;
  16. import android.view.inputmethod.InputConnection;
  17. import android.view.inputmethod.InputMethodManager;
  18. import android.widget.RelativeLayout;
  19. import android.widget.Button;
  20. import android.widget.LinearLayout;
  21. import android.widget.TextView;
  22. import android.os.*;
  23. import android.util.Log;
  24. import android.util.SparseArray;
  25. import android.graphics.*;
  26. import android.graphics.drawable.Drawable;
  27. import android.media.*;
  28. import android.hardware.*;
  29. import android.content.pm.ActivityInfo;
  30. /**
  31. SDL Activity
  32. */
  33. public class SDLActivity extends Activity {
  34. private static final String TAG = "SDL";
  35. public static boolean mIsResumedCalled, mIsSurfaceReady, mHasFocus;
  36. // Handle the state of the native layer
  37. public enum NativeState {
  38. INIT, RESUMED, PAUSED
  39. }
  40. public static NativeState mNextNativeState;
  41. public static NativeState mCurrentNativeState;
  42. public static boolean mExitCalledFromJava;
  43. /** If shared libraries (e.g. SDL or the native application) could not be loaded. */
  44. public static boolean mBrokenLibraries;
  45. // If we want to separate mouse and touch events.
  46. // This is only toggled in native code when a hint is set!
  47. public static boolean mSeparateMouseAndTouch;
  48. // Main components
  49. protected static SDLActivity mSingleton;
  50. protected static SDLSurface mSurface;
  51. protected static View mTextEdit;
  52. protected static ViewGroup mLayout;
  53. protected static SDLJoystickHandler mJoystickHandler;
  54. // This is what SDL runs in. It invokes SDL_main(), eventually
  55. protected static Thread mSDLThread;
  56. // Audio
  57. protected static AudioTrack mAudioTrack;
  58. protected static AudioRecord mAudioRecord;
  59. /**
  60. * This method is called by SDL before loading the native shared libraries.
  61. * It can be overridden to provide names of shared libraries to be loaded.
  62. * The default implementation returns the defaults. It never returns null.
  63. * An array returned by a new implementation must at least contain "SDL2".
  64. * Also keep in mind that the order the libraries are loaded may matter.
  65. * @return names of shared libraries to be loaded (e.g. "SDL2", "main").
  66. */
  67. protected String[] getLibraries() {
  68. return new String[] {
  69. "SDL2",
  70. // "SDL2_image",
  71. // "SDL2_mixer",
  72. // "SDL2_net",
  73. // "SDL2_ttf",
  74. "main"
  75. };
  76. }
  77. // Load the .so
  78. public void loadLibraries() {
  79. for (String lib : getLibraries()) {
  80. System.loadLibrary(lib);
  81. }
  82. }
  83. /**
  84. * This method is called by SDL before starting the native application thread.
  85. * It can be overridden to provide the arguments after the application name.
  86. * The default implementation returns an empty array. It never returns null.
  87. * @return arguments for the native application.
  88. */
  89. protected String[] getArguments() {
  90. return new String[0];
  91. }
  92. public static void initialize() {
  93. // The static nature of the singleton and Android quirkyness force us to initialize everything here
  94. // Otherwise, when exiting the app and returning to it, these variables *keep* their pre exit values
  95. mSingleton = null;
  96. mSurface = null;
  97. mTextEdit = null;
  98. mLayout = null;
  99. mJoystickHandler = null;
  100. mSDLThread = null;
  101. mAudioTrack = null;
  102. mAudioRecord = null;
  103. mExitCalledFromJava = false;
  104. mBrokenLibraries = false;
  105. mIsResumedCalled = false;
  106. mIsSurfaceReady = false;
  107. mHasFocus = true;
  108. mNextNativeState = NativeState.INIT;
  109. mCurrentNativeState = NativeState.INIT;
  110. }
  111. // Setup
  112. @Override
  113. protected void onCreate(Bundle savedInstanceState) {
  114. Log.v(TAG, "Device: " + android.os.Build.DEVICE);
  115. Log.v(TAG, "Model: " + android.os.Build.MODEL);
  116. Log.v(TAG, "onCreate(): " + mSingleton);
  117. super.onCreate(savedInstanceState);
  118. SDLActivity.initialize();
  119. // So we can call stuff from static callbacks
  120. mSingleton = this;
  121. // Load shared libraries
  122. String errorMsgBrokenLib = "";
  123. try {
  124. loadLibraries();
  125. } catch(UnsatisfiedLinkError e) {
  126. System.err.println(e.getMessage());
  127. mBrokenLibraries = true;
  128. errorMsgBrokenLib = e.getMessage();
  129. } catch(Exception e) {
  130. System.err.println(e.getMessage());
  131. mBrokenLibraries = true;
  132. errorMsgBrokenLib = e.getMessage();
  133. }
  134. if (mBrokenLibraries)
  135. {
  136. AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
  137. dlgAlert.setMessage("An error occurred while trying to start the application. Please try again and/or reinstall."
  138. + System.getProperty("line.separator")
  139. + System.getProperty("line.separator")
  140. + "Error: " + errorMsgBrokenLib);
  141. dlgAlert.setTitle("SDL Error");
  142. dlgAlert.setPositiveButton("Exit",
  143. new DialogInterface.OnClickListener() {
  144. @Override
  145. public void onClick(DialogInterface dialog,int id) {
  146. // if this button is clicked, close current activity
  147. SDLActivity.mSingleton.finish();
  148. }
  149. });
  150. dlgAlert.setCancelable(false);
  151. dlgAlert.create().show();
  152. return;
  153. }
  154. // Set up the surface
  155. mSurface = new SDLSurface(getApplication());
  156. if(Build.VERSION.SDK_INT >= 12) {
  157. mJoystickHandler = new SDLJoystickHandler_API12();
  158. }
  159. else {
  160. mJoystickHandler = new SDLJoystickHandler();
  161. }
  162. mLayout = new RelativeLayout(this);
  163. mLayout.addView(mSurface);
  164. setContentView(mLayout);
  165. // Get filename from "Open with" of another application
  166. Intent intent = getIntent();
  167. if (intent != null && intent.getData() != null) {
  168. String filename = intent.getData().getPath();
  169. if (filename != null) {
  170. Log.v(TAG, "Got filename: " + filename);
  171. SDLActivity.onNativeDropFile(filename);
  172. }
  173. }
  174. }
  175. // Events
  176. @Override
  177. protected void onPause() {
  178. Log.v(TAG, "onPause()");
  179. super.onPause();
  180. mNextNativeState = NativeState.PAUSED;
  181. mIsResumedCalled = false;
  182. if (SDLActivity.mBrokenLibraries) {
  183. return;
  184. }
  185. SDLActivity.handleNativeState();
  186. }
  187. @Override
  188. protected void onResume() {
  189. Log.v(TAG, "onResume()");
  190. super.onResume();
  191. mNextNativeState = NativeState.RESUMED;
  192. mIsResumedCalled = true;
  193. if (SDLActivity.mBrokenLibraries) {
  194. return;
  195. }
  196. SDLActivity.handleNativeState();
  197. }
  198. @Override
  199. public void onWindowFocusChanged(boolean hasFocus) {
  200. super.onWindowFocusChanged(hasFocus);
  201. Log.v(TAG, "onWindowFocusChanged(): " + hasFocus);
  202. if (SDLActivity.mBrokenLibraries) {
  203. return;
  204. }
  205. SDLActivity.mHasFocus = hasFocus;
  206. if (hasFocus) {
  207. mNextNativeState = NativeState.RESUMED;
  208. } else {
  209. mNextNativeState = NativeState.PAUSED;
  210. }
  211. SDLActivity.handleNativeState();
  212. }
  213. @Override
  214. public void onLowMemory() {
  215. Log.v(TAG, "onLowMemory()");
  216. super.onLowMemory();
  217. if (SDLActivity.mBrokenLibraries) {
  218. return;
  219. }
  220. SDLActivity.nativeLowMemory();
  221. }
  222. @Override
  223. protected void onDestroy() {
  224. Log.v(TAG, "onDestroy()");
  225. mNextNativeState = NativeState.PAUSED;
  226. SDLActivity.handleNativeState();
  227. if (SDLActivity.mBrokenLibraries) {
  228. super.onDestroy();
  229. // Reset everything in case the user re opens the app
  230. SDLActivity.initialize();
  231. return;
  232. }
  233. // Send a quit message to the application
  234. SDLActivity.mExitCalledFromJava = true;
  235. SDLActivity.nativeQuit();
  236. // Now wait for the SDL thread to quit
  237. if (SDLActivity.mSDLThread != null) {
  238. try {
  239. SDLActivity.mSDLThread.join();
  240. } catch(Exception e) {
  241. Log.v(TAG, "Problem stopping thread: " + e);
  242. }
  243. SDLActivity.mSDLThread = null;
  244. //Log.v(TAG, "Finished waiting for SDL thread");
  245. }
  246. super.onDestroy();
  247. // Reset everything in case the user re opens the app
  248. SDLActivity.initialize();
  249. }
  250. @Override
  251. public boolean dispatchKeyEvent(KeyEvent event) {
  252. if (SDLActivity.mBrokenLibraries) {
  253. return false;
  254. }
  255. int keyCode = event.getKeyCode();
  256. // Ignore certain special keys so they're handled by Android
  257. if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
  258. keyCode == KeyEvent.KEYCODE_VOLUME_UP ||
  259. keyCode == KeyEvent.KEYCODE_CAMERA ||
  260. keyCode == 168 || /* API 11: KeyEvent.KEYCODE_ZOOM_IN */
  261. keyCode == 169 /* API 11: KeyEvent.KEYCODE_ZOOM_OUT */
  262. ) {
  263. return false;
  264. }
  265. return super.dispatchKeyEvent(event);
  266. }
  267. /* Transition to next state */
  268. public static void handleNativeState() {
  269. if (mNextNativeState == mCurrentNativeState) {
  270. // Already in same state, discard.
  271. return;
  272. }
  273. // Try a transition to init state
  274. if (mNextNativeState == NativeState.INIT) {
  275. mCurrentNativeState = mNextNativeState;
  276. return;
  277. }
  278. // Try a transition to paused state
  279. if (mNextNativeState == NativeState.PAUSED) {
  280. nativePause();
  281. mSurface.handlePause();
  282. mCurrentNativeState = mNextNativeState;
  283. return;
  284. }
  285. // Try a transition to resumed state
  286. if (mNextNativeState == NativeState.RESUMED) {
  287. if (mIsSurfaceReady && mHasFocus && mIsResumedCalled) {
  288. if (mSDLThread == null) {
  289. // This is the entry point to the C app.
  290. // Start up the C app thread and enable sensor input for the first time
  291. final Thread sdlThread = new Thread(new SDLMain(), "SDLThread");
  292. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  293. sdlThread.start();
  294. // Set up a listener thread to catch when the native thread ends
  295. mSDLThread = new Thread(new Runnable(){
  296. @Override
  297. public void run(){
  298. try {
  299. sdlThread.join();
  300. }
  301. catch(Exception e){}
  302. finally{
  303. // Native thread has finished
  304. if (! mExitCalledFromJava) {
  305. handleNativeExit();
  306. }
  307. }
  308. }
  309. }, "SDLThreadListener");
  310. mSDLThread.start();
  311. }
  312. nativeResume();
  313. mSurface.handleResume();
  314. mCurrentNativeState = mNextNativeState;
  315. }
  316. return;
  317. }
  318. }
  319. /* The native thread has finished */
  320. public static void handleNativeExit() {
  321. SDLActivity.mSDLThread = null;
  322. mSingleton.finish();
  323. }
  324. // Messages from the SDLMain thread
  325. static final int COMMAND_CHANGE_TITLE = 1;
  326. static final int COMMAND_UNUSED = 2;
  327. static final int COMMAND_TEXTEDIT_HIDE = 3;
  328. static final int COMMAND_SET_KEEP_SCREEN_ON = 5;
  329. protected static final int COMMAND_USER = 0x8000;
  330. /**
  331. * This method is called by SDL if SDL did not handle a message itself.
  332. * This happens if a received message contains an unsupported command.
  333. * Method can be overwritten to handle Messages in a different class.
  334. * @param command the command of the message.
  335. * @param param the parameter of the message. May be null.
  336. * @return if the message was handled in overridden method.
  337. */
  338. protected boolean onUnhandledMessage(int command, Object param) {
  339. return false;
  340. }
  341. /**
  342. * A Handler class for Messages from native SDL applications.
  343. * It uses current Activities as target (e.g. for the title).
  344. * static to prevent implicit references to enclosing object.
  345. */
  346. protected static class SDLCommandHandler extends Handler {
  347. @Override
  348. public void handleMessage(Message msg) {
  349. Context context = getContext();
  350. if (context == null) {
  351. Log.e(TAG, "error handling message, getContext() returned null");
  352. return;
  353. }
  354. switch (msg.arg1) {
  355. case COMMAND_CHANGE_TITLE:
  356. if (context instanceof Activity) {
  357. ((Activity) context).setTitle((String)msg.obj);
  358. } else {
  359. Log.e(TAG, "error handling message, getContext() returned no Activity");
  360. }
  361. break;
  362. case COMMAND_TEXTEDIT_HIDE:
  363. if (mTextEdit != null) {
  364. // Note: On some devices setting view to GONE creates a flicker in landscape.
  365. // Setting the View's sizes to 0 is similar to GONE but without the flicker.
  366. // The sizes will be set to useful values when the keyboard is shown again.
  367. mTextEdit.setLayoutParams(new RelativeLayout.LayoutParams(0, 0));
  368. InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  369. imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0);
  370. }
  371. break;
  372. case COMMAND_SET_KEEP_SCREEN_ON:
  373. {
  374. Window window = ((Activity) context).getWindow();
  375. if (window != null) {
  376. if ((msg.obj instanceof Integer) && (((Integer) msg.obj).intValue() != 0)) {
  377. window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  378. } else {
  379. window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  380. }
  381. }
  382. break;
  383. }
  384. default:
  385. if ((context instanceof SDLActivity) && !((SDLActivity) context).onUnhandledMessage(msg.arg1, msg.obj)) {
  386. Log.e(TAG, "error handling message, command is " + msg.arg1);
  387. }
  388. }
  389. }
  390. }
  391. // Handler for the messages
  392. Handler commandHandler = new SDLCommandHandler();
  393. // Send a message from the SDLMain thread
  394. boolean sendCommand(int command, Object data) {
  395. Message msg = commandHandler.obtainMessage();
  396. msg.arg1 = command;
  397. msg.obj = data;
  398. return commandHandler.sendMessage(msg);
  399. }
  400. // C functions we call
  401. public static native int nativeInit(Object arguments);
  402. public static native void nativeLowMemory();
  403. public static native void nativeQuit();
  404. public static native void nativePause();
  405. public static native void nativeResume();
  406. public static native void onNativeDropFile(String filename);
  407. public static native void onNativeResize(int x, int y, int format, float rate);
  408. public static native int onNativePadDown(int device_id, int keycode);
  409. public static native int onNativePadUp(int device_id, int keycode);
  410. public static native void onNativeJoy(int device_id, int axis,
  411. float value);
  412. public static native void onNativeHat(int device_id, int hat_id,
  413. int x, int y);
  414. public static native void onNativeKeyDown(int keycode);
  415. public static native void onNativeKeyUp(int keycode);
  416. public static native void onNativeKeyboardFocusLost();
  417. public static native void onNativeMouse(int button, int action, float x, float y);
  418. public static native void onNativeTouch(int touchDevId, int pointerFingerId,
  419. int action, float x,
  420. float y, float p);
  421. public static native void onNativeAccel(float x, float y, float z);
  422. public static native void onNativeSurfaceChanged();
  423. public static native void onNativeSurfaceDestroyed();
  424. public static native int nativeAddJoystick(int device_id, String name,
  425. int is_accelerometer, int nbuttons,
  426. int naxes, int nhats, int nballs);
  427. public static native int nativeRemoveJoystick(int device_id);
  428. public static native String nativeGetHint(String name);
  429. /**
  430. * This method is called by SDL using JNI.
  431. */
  432. public static boolean setActivityTitle(String title) {
  433. // Called from SDLMain() thread and can't directly affect the view
  434. return mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
  435. }
  436. /**
  437. * This method is called by SDL using JNI.
  438. */
  439. public static boolean sendMessage(int command, int param) {
  440. return mSingleton.sendCommand(command, Integer.valueOf(param));
  441. }
  442. /**
  443. * This method is called by SDL using JNI.
  444. */
  445. public static Context getContext() {
  446. return mSingleton;
  447. }
  448. /**
  449. * This method is called by SDL using JNI.
  450. * @return result of getSystemService(name) but executed on UI thread.
  451. */
  452. public Object getSystemServiceFromUiThread(final String name) {
  453. final Object lock = new Object();
  454. final Object[] results = new Object[2]; // array for writable variables
  455. synchronized (lock) {
  456. runOnUiThread(new Runnable() {
  457. @Override
  458. public void run() {
  459. synchronized (lock) {
  460. results[0] = getSystemService(name);
  461. results[1] = Boolean.TRUE;
  462. lock.notify();
  463. }
  464. }
  465. });
  466. if (results[1] == null) {
  467. try {
  468. lock.wait();
  469. } catch (InterruptedException ex) {
  470. ex.printStackTrace();
  471. }
  472. }
  473. }
  474. return results[0];
  475. }
  476. static class ShowTextInputTask implements Runnable {
  477. /*
  478. * This is used to regulate the pan&scan method to have some offset from
  479. * the bottom edge of the input region and the top edge of an input
  480. * method (soft keyboard)
  481. */
  482. static final int HEIGHT_PADDING = 15;
  483. public int x, y, w, h;
  484. public ShowTextInputTask(int x, int y, int w, int h) {
  485. this.x = x;
  486. this.y = y;
  487. this.w = w;
  488. this.h = h;
  489. }
  490. @Override
  491. public void run() {
  492. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h + HEIGHT_PADDING);
  493. params.leftMargin = x;
  494. params.topMargin = y;
  495. if (mTextEdit == null) {
  496. mTextEdit = new DummyEdit(getContext());
  497. mLayout.addView(mTextEdit, params);
  498. } else {
  499. mTextEdit.setLayoutParams(params);
  500. }
  501. mTextEdit.setVisibility(View.VISIBLE);
  502. mTextEdit.requestFocus();
  503. InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  504. imm.showSoftInput(mTextEdit, 0);
  505. }
  506. }
  507. /**
  508. * This method is called by SDL using JNI.
  509. */
  510. public static boolean showTextInput(int x, int y, int w, int h) {
  511. // Transfer the task to the main thread as a Runnable
  512. return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h));
  513. }
  514. /**
  515. * This method is called by SDL using JNI.
  516. */
  517. public static Surface getNativeSurface() {
  518. return SDLActivity.mSurface.getNativeSurface();
  519. }
  520. // Audio
  521. /**
  522. * This method is called by SDL using JNI.
  523. */
  524. public static int audioOpen(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
  525. int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
  526. int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
  527. int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
  528. Log.v(TAG, "SDL audio: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + (sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  529. // Let the user pick a larger buffer if they really want -- but ye
  530. // gods they probably shouldn't, the minimums are horrifyingly high
  531. // latency already
  532. desiredFrames = Math.max(desiredFrames, (AudioTrack.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
  533. if (mAudioTrack == null) {
  534. mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
  535. channelConfig, audioFormat, desiredFrames * frameSize, AudioTrack.MODE_STREAM);
  536. // Instantiating AudioTrack can "succeed" without an exception and the track may still be invalid
  537. // Ref: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/media/java/android/media/AudioTrack.java
  538. // Ref: http://developer.android.com/reference/android/media/AudioTrack.html#getState()
  539. if (mAudioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
  540. Log.e(TAG, "Failed during initialization of Audio Track");
  541. mAudioTrack = null;
  542. return -1;
  543. }
  544. mAudioTrack.play();
  545. }
  546. Log.v(TAG, "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");
  547. return 0;
  548. }
  549. /**
  550. * This method is called by SDL using JNI.
  551. */
  552. public static void audioWriteShortBuffer(short[] buffer) {
  553. for (int i = 0; i < buffer.length; ) {
  554. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  555. if (result > 0) {
  556. i += result;
  557. } else if (result == 0) {
  558. try {
  559. Thread.sleep(1);
  560. } catch(InterruptedException e) {
  561. // Nom nom
  562. }
  563. } else {
  564. Log.w(TAG, "SDL audio: error return from write(short)");
  565. return;
  566. }
  567. }
  568. }
  569. /**
  570. * This method is called by SDL using JNI.
  571. */
  572. public static void audioWriteByteBuffer(byte[] buffer) {
  573. for (int i = 0; i < buffer.length; ) {
  574. int result = mAudioTrack.write(buffer, i, buffer.length - i);
  575. if (result > 0) {
  576. i += result;
  577. } else if (result == 0) {
  578. try {
  579. Thread.sleep(1);
  580. } catch(InterruptedException e) {
  581. // Nom nom
  582. }
  583. } else {
  584. Log.w(TAG, "SDL audio: error return from write(byte)");
  585. return;
  586. }
  587. }
  588. }
  589. /**
  590. * This method is called by SDL using JNI.
  591. */
  592. public static int captureOpen(int sampleRate, boolean is16Bit, boolean isStereo, int desiredFrames) {
  593. int channelConfig = isStereo ? AudioFormat.CHANNEL_CONFIGURATION_STEREO : AudioFormat.CHANNEL_CONFIGURATION_MONO;
  594. int audioFormat = is16Bit ? AudioFormat.ENCODING_PCM_16BIT : AudioFormat.ENCODING_PCM_8BIT;
  595. int frameSize = (isStereo ? 2 : 1) * (is16Bit ? 2 : 1);
  596. Log.v(TAG, "SDL capture: wanted " + (isStereo ? "stereo" : "mono") + " " + (is16Bit ? "16-bit" : "8-bit") + " " + (sampleRate / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  597. // Let the user pick a larger buffer if they really want -- but ye
  598. // gods they probably shouldn't, the minimums are horrifyingly high
  599. // latency already
  600. desiredFrames = Math.max(desiredFrames, (AudioRecord.getMinBufferSize(sampleRate, channelConfig, audioFormat) + frameSize - 1) / frameSize);
  601. if (mAudioRecord == null) {
  602. mAudioRecord = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, sampleRate,
  603. channelConfig, audioFormat, desiredFrames * frameSize);
  604. // see notes about AudioTrack state in audioOpen(), above. Probably also applies here.
  605. if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
  606. Log.e(TAG, "Failed during initialization of AudioRecord");
  607. mAudioRecord.release();
  608. mAudioRecord = null;
  609. return -1;
  610. }
  611. mAudioRecord.startRecording();
  612. }
  613. Log.v(TAG, "SDL capture: got " + ((mAudioRecord.getChannelCount() >= 2) ? "stereo" : "mono") + " " + ((mAudioRecord.getAudioFormat() == AudioFormat.ENCODING_PCM_16BIT) ? "16-bit" : "8-bit") + " " + (mAudioRecord.getSampleRate() / 1000f) + "kHz, " + desiredFrames + " frames buffer");
  614. return 0;
  615. }
  616. /** This method is called by SDL using JNI. */
  617. public static int captureReadShortBuffer(short[] buffer, boolean blocking) {
  618. // !!! FIXME: this is available in API Level 23. Until then, we always block. :(
  619. //return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
  620. return mAudioRecord.read(buffer, 0, buffer.length);
  621. }
  622. /** This method is called by SDL using JNI. */
  623. public static int captureReadByteBuffer(byte[] buffer, boolean blocking) {
  624. // !!! FIXME: this is available in API Level 23. Until then, we always block. :(
  625. //return mAudioRecord.read(buffer, 0, buffer.length, blocking ? AudioRecord.READ_BLOCKING : AudioRecord.READ_NON_BLOCKING);
  626. return mAudioRecord.read(buffer, 0, buffer.length);
  627. }
  628. /** This method is called by SDL using JNI. */
  629. public static void audioClose() {
  630. if (mAudioTrack != null) {
  631. mAudioTrack.stop();
  632. mAudioTrack.release();
  633. mAudioTrack = null;
  634. }
  635. }
  636. /** This method is called by SDL using JNI. */
  637. public static void captureClose() {
  638. if (mAudioRecord != null) {
  639. mAudioRecord.stop();
  640. mAudioRecord.release();
  641. mAudioRecord = null;
  642. }
  643. }
  644. // Input
  645. /**
  646. * This method is called by SDL using JNI.
  647. * @return an array which may be empty but is never null.
  648. */
  649. public static int[] inputGetInputDeviceIds(int sources) {
  650. int[] ids = InputDevice.getDeviceIds();
  651. int[] filtered = new int[ids.length];
  652. int used = 0;
  653. for (int i = 0; i < ids.length; ++i) {
  654. InputDevice device = InputDevice.getDevice(ids[i]);
  655. if ((device != null) && ((device.getSources() & sources) != 0)) {
  656. filtered[used++] = device.getId();
  657. }
  658. }
  659. return Arrays.copyOf(filtered, used);
  660. }
  661. // Joystick glue code, just a series of stubs that redirect to the SDLJoystickHandler instance
  662. public static boolean handleJoystickMotionEvent(MotionEvent event) {
  663. return mJoystickHandler.handleMotionEvent(event);
  664. }
  665. /**
  666. * This method is called by SDL using JNI.
  667. */
  668. public static void pollInputDevices() {
  669. if (SDLActivity.mSDLThread != null) {
  670. mJoystickHandler.pollInputDevices();
  671. }
  672. }
  673. // Check if a given device is considered a possible SDL joystick
  674. public static boolean isDeviceSDLJoystick(int deviceId) {
  675. InputDevice device = InputDevice.getDevice(deviceId);
  676. // We cannot use InputDevice.isVirtual before API 16, so let's accept
  677. // only nonnegative device ids (VIRTUAL_KEYBOARD equals -1)
  678. if ((device == null) || (deviceId < 0)) {
  679. return false;
  680. }
  681. int sources = device.getSources();
  682. return (((sources & InputDevice.SOURCE_CLASS_JOYSTICK) == InputDevice.SOURCE_CLASS_JOYSTICK) ||
  683. ((sources & InputDevice.SOURCE_DPAD) == InputDevice.SOURCE_DPAD) ||
  684. ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD)
  685. );
  686. }
  687. // APK expansion files support
  688. /** com.android.vending.expansion.zipfile.ZipResourceFile object or null. */
  689. private Object expansionFile;
  690. /** com.android.vending.expansion.zipfile.ZipResourceFile's getInputStream() or null. */
  691. private Method expansionFileMethod;
  692. /**
  693. * This method is called by SDL using JNI.
  694. * @return an InputStream on success or null if no expansion file was used.
  695. * @throws IOException on errors. Message is set for the SDL error message.
  696. */
  697. public InputStream openAPKExpansionInputStream(String fileName) throws IOException {
  698. // Get a ZipResourceFile representing a merger of both the main and patch files
  699. if (expansionFile == null) {
  700. String mainHint = nativeGetHint("SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION");
  701. if (mainHint == null) {
  702. return null; // no expansion use if no main version was set
  703. }
  704. String patchHint = nativeGetHint("SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION");
  705. if (patchHint == null) {
  706. return null; // no expansion use if no patch version was set
  707. }
  708. Integer mainVersion;
  709. Integer patchVersion;
  710. try {
  711. mainVersion = Integer.valueOf(mainHint);
  712. patchVersion = Integer.valueOf(patchHint);
  713. } catch (NumberFormatException ex) {
  714. ex.printStackTrace();
  715. throw new IOException("No valid file versions set for APK expansion files", ex);
  716. }
  717. try {
  718. // To avoid direct dependency on Google APK expansion library that is
  719. // not a part of Android SDK we access it using reflection
  720. expansionFile = Class.forName("com.android.vending.expansion.zipfile.APKExpansionSupport")
  721. .getMethod("getAPKExpansionZipFile", Context.class, int.class, int.class)
  722. .invoke(null, this, mainVersion, patchVersion);
  723. expansionFileMethod = expansionFile.getClass()
  724. .getMethod("getInputStream", String.class);
  725. } catch (Exception ex) {
  726. ex.printStackTrace();
  727. expansionFile = null;
  728. expansionFileMethod = null;
  729. throw new IOException("Could not access APK expansion support library", ex);
  730. }
  731. }
  732. // Get an input stream for a known file inside the expansion file ZIPs
  733. InputStream fileStream;
  734. try {
  735. fileStream = (InputStream)expansionFileMethod.invoke(expansionFile, fileName);
  736. } catch (Exception ex) {
  737. // calling "getInputStream" failed
  738. ex.printStackTrace();
  739. throw new IOException("Could not open stream from APK expansion file", ex);
  740. }
  741. if (fileStream == null) {
  742. // calling "getInputStream" was successful but null was returned
  743. throw new IOException("Could not find path in APK expansion file");
  744. }
  745. return fileStream;
  746. }
  747. // Messagebox
  748. /** Result of current messagebox. Also used for blocking the calling thread. */
  749. protected final int[] messageboxSelection = new int[1];
  750. /** Id of current dialog. */
  751. protected int dialogs = 0;
  752. /**
  753. * This method is called by SDL using JNI.
  754. * Shows the messagebox from UI thread and block calling thread.
  755. * buttonFlags, buttonIds and buttonTexts must have same length.
  756. * @param buttonFlags array containing flags for every button.
  757. * @param buttonIds array containing id for every button.
  758. * @param buttonTexts array containing text for every button.
  759. * @param colors null for default or array of length 5 containing colors.
  760. * @return button id or -1.
  761. */
  762. public int messageboxShowMessageBox(
  763. final int flags,
  764. final String title,
  765. final String message,
  766. final int[] buttonFlags,
  767. final int[] buttonIds,
  768. final String[] buttonTexts,
  769. final int[] colors) {
  770. messageboxSelection[0] = -1;
  771. // sanity checks
  772. if ((buttonFlags.length != buttonIds.length) && (buttonIds.length != buttonTexts.length)) {
  773. return -1; // implementation broken
  774. }
  775. // collect arguments for Dialog
  776. final Bundle args = new Bundle();
  777. args.putInt("flags", flags);
  778. args.putString("title", title);
  779. args.putString("message", message);
  780. args.putIntArray("buttonFlags", buttonFlags);
  781. args.putIntArray("buttonIds", buttonIds);
  782. args.putStringArray("buttonTexts", buttonTexts);
  783. args.putIntArray("colors", colors);
  784. // trigger Dialog creation on UI thread
  785. runOnUiThread(new Runnable() {
  786. @Override
  787. public void run() {
  788. showDialog(dialogs++, args);
  789. }
  790. });
  791. // block the calling thread
  792. synchronized (messageboxSelection) {
  793. try {
  794. messageboxSelection.wait();
  795. } catch (InterruptedException ex) {
  796. ex.printStackTrace();
  797. return -1;
  798. }
  799. }
  800. // return selected value
  801. return messageboxSelection[0];
  802. }
  803. @Override
  804. protected Dialog onCreateDialog(int ignore, Bundle args) {
  805. // TODO set values from "flags" to messagebox dialog
  806. // get colors
  807. int[] colors = args.getIntArray("colors");
  808. int backgroundColor;
  809. int textColor;
  810. int buttonBorderColor;
  811. int buttonBackgroundColor;
  812. int buttonSelectedColor;
  813. if (colors != null) {
  814. int i = -1;
  815. backgroundColor = colors[++i];
  816. textColor = colors[++i];
  817. buttonBorderColor = colors[++i];
  818. buttonBackgroundColor = colors[++i];
  819. buttonSelectedColor = colors[++i];
  820. } else {
  821. backgroundColor = Color.TRANSPARENT;
  822. textColor = Color.TRANSPARENT;
  823. buttonBorderColor = Color.TRANSPARENT;
  824. buttonBackgroundColor = Color.TRANSPARENT;
  825. buttonSelectedColor = Color.TRANSPARENT;
  826. }
  827. // create dialog with title and a listener to wake up calling thread
  828. final Dialog dialog = new Dialog(this);
  829. dialog.setTitle(args.getString("title"));
  830. dialog.setCancelable(false);
  831. dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
  832. @Override
  833. public void onDismiss(DialogInterface unused) {
  834. synchronized (messageboxSelection) {
  835. messageboxSelection.notify();
  836. }
  837. }
  838. });
  839. // create text
  840. TextView message = new TextView(this);
  841. message.setGravity(Gravity.CENTER);
  842. message.setText(args.getString("message"));
  843. if (textColor != Color.TRANSPARENT) {
  844. message.setTextColor(textColor);
  845. }
  846. // create buttons
  847. int[] buttonFlags = args.getIntArray("buttonFlags");
  848. int[] buttonIds = args.getIntArray("buttonIds");
  849. String[] buttonTexts = args.getStringArray("buttonTexts");
  850. final SparseArray<Button> mapping = new SparseArray<Button>();
  851. LinearLayout buttons = new LinearLayout(this);
  852. buttons.setOrientation(LinearLayout.HORIZONTAL);
  853. buttons.setGravity(Gravity.CENTER);
  854. for (int i = 0; i < buttonTexts.length; ++i) {
  855. Button button = new Button(this);
  856. final int id = buttonIds[i];
  857. button.setOnClickListener(new View.OnClickListener() {
  858. @Override
  859. public void onClick(View v) {
  860. messageboxSelection[0] = id;
  861. dialog.dismiss();
  862. }
  863. });
  864. if (buttonFlags[i] != 0) {
  865. // see SDL_messagebox.h
  866. if ((buttonFlags[i] & 0x00000001) != 0) {
  867. mapping.put(KeyEvent.KEYCODE_ENTER, button);
  868. }
  869. if ((buttonFlags[i] & 0x00000002) != 0) {
  870. mapping.put(111, button); /* API 11: KeyEvent.KEYCODE_ESCAPE */
  871. }
  872. }
  873. button.setText(buttonTexts[i]);
  874. if (textColor != Color.TRANSPARENT) {
  875. button.setTextColor(textColor);
  876. }
  877. if (buttonBorderColor != Color.TRANSPARENT) {
  878. // TODO set color for border of messagebox button
  879. }
  880. if (buttonBackgroundColor != Color.TRANSPARENT) {
  881. Drawable drawable = button.getBackground();
  882. if (drawable == null) {
  883. // setting the color this way removes the style
  884. button.setBackgroundColor(buttonBackgroundColor);
  885. } else {
  886. // setting the color this way keeps the style (gradient, padding, etc.)
  887. drawable.setColorFilter(buttonBackgroundColor, PorterDuff.Mode.MULTIPLY);
  888. }
  889. }
  890. if (buttonSelectedColor != Color.TRANSPARENT) {
  891. // TODO set color for selected messagebox button
  892. }
  893. buttons.addView(button);
  894. }
  895. // create content
  896. LinearLayout content = new LinearLayout(this);
  897. content.setOrientation(LinearLayout.VERTICAL);
  898. content.addView(message);
  899. content.addView(buttons);
  900. if (backgroundColor != Color.TRANSPARENT) {
  901. content.setBackgroundColor(backgroundColor);
  902. }
  903. // add content to dialog and return
  904. dialog.setContentView(content);
  905. dialog.setOnKeyListener(new Dialog.OnKeyListener() {
  906. @Override
  907. public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
  908. Button button = mapping.get(keyCode);
  909. if (button != null) {
  910. if (event.getAction() == KeyEvent.ACTION_UP) {
  911. button.performClick();
  912. }
  913. return true; // also for ignored actions
  914. }
  915. return false;
  916. }
  917. });
  918. return dialog;
  919. }
  920. }
  921. /**
  922. Simple nativeInit() runnable
  923. */
  924. class SDLMain implements Runnable {
  925. @Override
  926. public void run() {
  927. // Runs SDL_main()
  928. SDLActivity.nativeInit(SDLActivity.mSingleton.getArguments());
  929. //Log.v("SDL", "SDL thread terminated");
  930. }
  931. }
  932. /**
  933. SDLSurface. This is what we draw on, so we need to know when it's created
  934. in order to do anything useful.
  935. Because of this, that's where we set up the SDL thread
  936. */
  937. class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
  938. View.OnKeyListener, View.OnTouchListener, SensorEventListener {
  939. // Sensors
  940. protected static SensorManager mSensorManager;
  941. protected static Display mDisplay;
  942. // Keep track of the surface size to normalize touch events
  943. protected static float mWidth, mHeight;
  944. // Startup
  945. public SDLSurface(Context context) {
  946. super(context);
  947. getHolder().addCallback(this);
  948. setFocusable(true);
  949. setFocusableInTouchMode(true);
  950. requestFocus();
  951. setOnKeyListener(this);
  952. setOnTouchListener(this);
  953. mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  954. mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  955. if(Build.VERSION.SDK_INT >= 12) {
  956. setOnGenericMotionListener(new SDLGenericMotionListener_API12());
  957. }
  958. // Some arbitrary defaults to avoid a potential division by zero
  959. mWidth = 1.0f;
  960. mHeight = 1.0f;
  961. }
  962. public void handlePause() {
  963. enableSensor(Sensor.TYPE_ACCELEROMETER, false);
  964. }
  965. public void handleResume() {
  966. setFocusable(true);
  967. setFocusableInTouchMode(true);
  968. requestFocus();
  969. setOnKeyListener(this);
  970. setOnTouchListener(this);
  971. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  972. }
  973. public Surface getNativeSurface() {
  974. return getHolder().getSurface();
  975. }
  976. // Called when we have a valid drawing surface
  977. @Override
  978. public void surfaceCreated(SurfaceHolder holder) {
  979. Log.v("SDL", "surfaceCreated()");
  980. holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  981. }
  982. // Called when we lose the surface
  983. @Override
  984. public void surfaceDestroyed(SurfaceHolder holder) {
  985. Log.v("SDL", "surfaceDestroyed()");
  986. // Transition to pause, if needed
  987. SDLActivity.mNextNativeState = SDLActivity.NativeState.PAUSED;
  988. SDLActivity.handleNativeState();
  989. SDLActivity.mIsSurfaceReady = false;
  990. SDLActivity.onNativeSurfaceDestroyed();
  991. }
  992. // Called when the surface is resized
  993. @Override
  994. public void surfaceChanged(SurfaceHolder holder,
  995. int format, int width, int height) {
  996. Log.v("SDL", "surfaceChanged()");
  997. int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
  998. switch (format) {
  999. case PixelFormat.A_8:
  1000. Log.v("SDL", "pixel format A_8");
  1001. break;
  1002. case PixelFormat.LA_88:
  1003. Log.v("SDL", "pixel format LA_88");
  1004. break;
  1005. case PixelFormat.L_8:
  1006. Log.v("SDL", "pixel format L_8");
  1007. break;
  1008. case PixelFormat.RGBA_4444:
  1009. Log.v("SDL", "pixel format RGBA_4444");
  1010. sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
  1011. break;
  1012. case PixelFormat.RGBA_5551:
  1013. Log.v("SDL", "pixel format RGBA_5551");
  1014. sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
  1015. break;
  1016. case PixelFormat.RGBA_8888:
  1017. Log.v("SDL", "pixel format RGBA_8888");
  1018. sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
  1019. break;
  1020. case PixelFormat.RGBX_8888:
  1021. Log.v("SDL", "pixel format RGBX_8888");
  1022. sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
  1023. break;
  1024. case PixelFormat.RGB_332:
  1025. Log.v("SDL", "pixel format RGB_332");
  1026. sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
  1027. break;
  1028. case PixelFormat.RGB_565:
  1029. Log.v("SDL", "pixel format RGB_565");
  1030. sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
  1031. break;
  1032. case PixelFormat.RGB_888:
  1033. Log.v("SDL", "pixel format RGB_888");
  1034. // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
  1035. sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
  1036. break;
  1037. default:
  1038. Log.v("SDL", "pixel format unknown " + format);
  1039. break;
  1040. }
  1041. mWidth = width;
  1042. mHeight = height;
  1043. SDLActivity.onNativeResize(width, height, sdlFormat, mDisplay.getRefreshRate());
  1044. Log.v("SDL", "Window size: " + width + "x" + height);
  1045. boolean skip = false;
  1046. int requestedOrientation = SDLActivity.mSingleton.getRequestedOrientation();
  1047. if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
  1048. {
  1049. // Accept any
  1050. }
  1051. else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT)
  1052. {
  1053. if (mWidth > mHeight) {
  1054. skip = true;
  1055. }
  1056. } else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
  1057. if (mWidth < mHeight) {
  1058. skip = true;
  1059. }
  1060. }
  1061. // Special Patch for Square Resolution: Black Berry Passport
  1062. if (skip) {
  1063. double min = Math.min(mWidth, mHeight);
  1064. double max = Math.max(mWidth, mHeight);
  1065. if (max / min < 1.20) {
  1066. Log.v("SDL", "Don't skip on such aspect-ratio. Could be a square resolution.");
  1067. skip = false;
  1068. }
  1069. }
  1070. if (skip) {
  1071. Log.v("SDL", "Skip .. Surface is not ready.");
  1072. SDLActivity.mIsSurfaceReady = false;
  1073. return;
  1074. }
  1075. /* Surface is ready */
  1076. SDLActivity.mIsSurfaceReady = true;
  1077. /* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
  1078. SDLActivity.onNativeSurfaceChanged();
  1079. SDLActivity.handleNativeState();
  1080. }
  1081. // Key events
  1082. @Override
  1083. public boolean onKey(View v, int keyCode, KeyEvent event) {
  1084. // Dispatch the different events depending on where they come from
  1085. // Some SOURCE_JOYSTICK, SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD
  1086. // So, we try to process them as JOYSTICK/DPAD/GAMEPAD events first, if that fails we try them as KEYBOARD
  1087. //
  1088. // Furthermore, it's possible a game controller has SOURCE_KEYBOARD and
  1089. // SOURCE_JOYSTICK, while its key events arrive from the keyboard source
  1090. // So, retrieve the device itself and check all of its sources
  1091. if (SDLActivity.isDeviceSDLJoystick(event.getDeviceId())) {
  1092. // Note that we process events with specific key codes here
  1093. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1094. if (SDLActivity.onNativePadDown(event.getDeviceId(), keyCode) == 0) {
  1095. return true;
  1096. }
  1097. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  1098. if (SDLActivity.onNativePadUp(event.getDeviceId(), keyCode) == 0) {
  1099. return true;
  1100. }
  1101. }
  1102. }
  1103. if ((event.getSource() & InputDevice.SOURCE_KEYBOARD) != 0) {
  1104. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1105. //Log.v("SDL", "key down: " + keyCode);
  1106. SDLActivity.onNativeKeyDown(keyCode);
  1107. return true;
  1108. }
  1109. else if (event.getAction() == KeyEvent.ACTION_UP) {
  1110. //Log.v("SDL", "key up: " + keyCode);
  1111. SDLActivity.onNativeKeyUp(keyCode);
  1112. return true;
  1113. }
  1114. }
  1115. if ((event.getSource() & InputDevice.SOURCE_MOUSE) != 0) {
  1116. // on some devices key events are sent for mouse BUTTON_BACK/FORWARD presses
  1117. // they are ignored here because sending them as mouse input to SDL is messy
  1118. if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_FORWARD)) {
  1119. switch (event.getAction()) {
  1120. case KeyEvent.ACTION_DOWN:
  1121. case KeyEvent.ACTION_UP:
  1122. // mark the event as handled or it will be handled by system
  1123. // handling KEYCODE_BACK by system will call onBackPressed()
  1124. return true;
  1125. }
  1126. }
  1127. }
  1128. return false;
  1129. }
  1130. // Touch events
  1131. @Override
  1132. public boolean onTouch(View v, MotionEvent event) {
  1133. /* Ref: http://developer.android.com/training/gestures/multi.html */
  1134. final int touchDevId = event.getDeviceId();
  1135. final int pointerCount = event.getPointerCount();
  1136. int action = event.getActionMasked();
  1137. int pointerFingerId;
  1138. int mouseButton;
  1139. int i = -1;
  1140. float x,y,p;
  1141. // !!! FIXME: dump this SDK check after 2.0.4 ships and require API14.
  1142. if (event.getSource() == InputDevice.SOURCE_MOUSE && SDLActivity.mSeparateMouseAndTouch) {
  1143. if (Build.VERSION.SDK_INT < 14) {
  1144. mouseButton = 1; // all mouse buttons are the left button
  1145. } else {
  1146. try {
  1147. mouseButton = (Integer) event.getClass().getMethod("getButtonState").invoke(event);
  1148. } catch(Exception e) {
  1149. mouseButton = 1; // oh well.
  1150. }
  1151. }
  1152. SDLActivity.onNativeMouse(mouseButton, action, event.getX(0), event.getY(0));
  1153. } else {
  1154. switch(action) {
  1155. case MotionEvent.ACTION_MOVE:
  1156. for (i = 0; i < pointerCount; i++) {
  1157. pointerFingerId = event.getPointerId(i);
  1158. x = event.getX(i) / mWidth;
  1159. y = event.getY(i) / mHeight;
  1160. p = event.getPressure(i);
  1161. if (p > 1.0f) {
  1162. // may be larger than 1.0f on some devices
  1163. // see the documentation of getPressure(i)
  1164. p = 1.0f;
  1165. }
  1166. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  1167. }
  1168. break;
  1169. case MotionEvent.ACTION_UP:
  1170. case MotionEvent.ACTION_DOWN:
  1171. // Primary pointer up/down, the index is always zero
  1172. i = 0;
  1173. case MotionEvent.ACTION_POINTER_UP:
  1174. case MotionEvent.ACTION_POINTER_DOWN:
  1175. // Non primary pointer up/down
  1176. if (i == -1) {
  1177. i = event.getActionIndex();
  1178. }
  1179. pointerFingerId = event.getPointerId(i);
  1180. x = event.getX(i) / mWidth;
  1181. y = event.getY(i) / mHeight;
  1182. p = event.getPressure(i);
  1183. if (p > 1.0f) {
  1184. // may be larger than 1.0f on some devices
  1185. // see the documentation of getPressure(i)
  1186. p = 1.0f;
  1187. }
  1188. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  1189. break;
  1190. case MotionEvent.ACTION_CANCEL:
  1191. for (i = 0; i < pointerCount; i++) {
  1192. pointerFingerId = event.getPointerId(i);
  1193. x = event.getX(i) / mWidth;
  1194. y = event.getY(i) / mHeight;
  1195. p = event.getPressure(i);
  1196. if (p > 1.0f) {
  1197. // may be larger than 1.0f on some devices
  1198. // see the documentation of getPressure(i)
  1199. p = 1.0f;
  1200. }
  1201. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, MotionEvent.ACTION_UP, x, y, p);
  1202. }
  1203. break;
  1204. default:
  1205. break;
  1206. }
  1207. }
  1208. return true;
  1209. }
  1210. // Sensor events
  1211. public void enableSensor(int sensortype, boolean enabled) {
  1212. // TODO: This uses getDefaultSensor - what if we have >1 accels?
  1213. if (enabled) {
  1214. mSensorManager.registerListener(this,
  1215. mSensorManager.getDefaultSensor(sensortype),
  1216. SensorManager.SENSOR_DELAY_GAME, null);
  1217. } else {
  1218. mSensorManager.unregisterListener(this,
  1219. mSensorManager.getDefaultSensor(sensortype));
  1220. }
  1221. }
  1222. @Override
  1223. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  1224. // TODO
  1225. }
  1226. @Override
  1227. public void onSensorChanged(SensorEvent event) {
  1228. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  1229. float x, y;
  1230. switch (mDisplay.getRotation()) {
  1231. case Surface.ROTATION_90:
  1232. x = -event.values[1];
  1233. y = event.values[0];
  1234. break;
  1235. case Surface.ROTATION_270:
  1236. x = event.values[1];
  1237. y = -event.values[0];
  1238. break;
  1239. case Surface.ROTATION_180:
  1240. x = -event.values[1];
  1241. y = -event.values[0];
  1242. break;
  1243. default:
  1244. x = event.values[0];
  1245. y = event.values[1];
  1246. break;
  1247. }
  1248. SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
  1249. y / SensorManager.GRAVITY_EARTH,
  1250. event.values[2] / SensorManager.GRAVITY_EARTH);
  1251. }
  1252. }
  1253. }
  1254. /* This is a fake invisible editor view that receives the input and defines the
  1255. * pan&scan region
  1256. */
  1257. class DummyEdit extends View implements View.OnKeyListener {
  1258. InputConnection ic;
  1259. public DummyEdit(Context context) {
  1260. super(context);
  1261. setFocusableInTouchMode(true);
  1262. setFocusable(true);
  1263. setOnKeyListener(this);
  1264. }
  1265. @Override
  1266. public boolean onCheckIsTextEditor() {
  1267. return true;
  1268. }
  1269. @Override
  1270. public boolean onKey(View v, int keyCode, KeyEvent event) {
  1271. // This handles the hardware keyboard input
  1272. if (event.isPrintingKey() || keyCode == KeyEvent.KEYCODE_SPACE) {
  1273. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1274. ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  1275. }
  1276. return true;
  1277. }
  1278. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1279. SDLActivity.onNativeKeyDown(keyCode);
  1280. return true;
  1281. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  1282. SDLActivity.onNativeKeyUp(keyCode);
  1283. return true;
  1284. }
  1285. return false;
  1286. }
  1287. //
  1288. @Override
  1289. public boolean onKeyPreIme (int keyCode, KeyEvent event) {
  1290. // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
  1291. // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
  1292. // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
  1293. // FIXME: A more effective solution would be to assume our Layout to be RelativeLayout or LinearLayout
  1294. // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
  1295. // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
  1296. if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
  1297. if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
  1298. SDLActivity.onNativeKeyboardFocusLost();
  1299. }
  1300. }
  1301. return super.onKeyPreIme(keyCode, event);
  1302. }
  1303. @Override
  1304. public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
  1305. ic = new SDLInputConnection(this, true);
  1306. outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
  1307. outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
  1308. | 33554432 /* API 11: EditorInfo.IME_FLAG_NO_FULLSCREEN */;
  1309. return ic;
  1310. }
  1311. }
  1312. class SDLInputConnection extends BaseInputConnection {
  1313. public SDLInputConnection(View targetView, boolean fullEditor) {
  1314. super(targetView, fullEditor);
  1315. }
  1316. @Override
  1317. public boolean sendKeyEvent(KeyEvent event) {
  1318. /*
  1319. * This handles the keycodes from soft keyboard (and IME-translated
  1320. * input from hardkeyboard)
  1321. */
  1322. int keyCode = event.getKeyCode();
  1323. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1324. if (event.isPrintingKey() || keyCode == KeyEvent.KEYCODE_SPACE) {
  1325. commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  1326. }
  1327. SDLActivity.onNativeKeyDown(keyCode);
  1328. return true;
  1329. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  1330. SDLActivity.onNativeKeyUp(keyCode);
  1331. return true;
  1332. }
  1333. return super.sendKeyEvent(event);
  1334. }
  1335. @Override
  1336. public boolean commitText(CharSequence text, int newCursorPosition) {
  1337. nativeCommitText(text.toString(), newCursorPosition);
  1338. return super.commitText(text, newCursorPosition);
  1339. }
  1340. @Override
  1341. public boolean setComposingText(CharSequence text, int newCursorPosition) {
  1342. nativeSetComposingText(text.toString(), newCursorPosition);
  1343. return super.setComposingText(text, newCursorPosition);
  1344. }
  1345. public native void nativeCommitText(String text, int newCursorPosition);
  1346. public native void nativeSetComposingText(String text, int newCursorPosition);
  1347. @Override
  1348. public boolean deleteSurroundingText(int beforeLength, int afterLength) {
  1349. // Workaround to capture backspace key. Ref: http://stackoverflow.com/questions/14560344/android-backspace-in-webview-baseinputconnection
  1350. if (beforeLength == 1 && afterLength == 0) {
  1351. // backspace
  1352. return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
  1353. && super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
  1354. }
  1355. return super.deleteSurroundingText(beforeLength, afterLength);
  1356. }
  1357. }
  1358. /* A null joystick handler for API level < 12 devices (the accelerometer is handled separately) */
  1359. class SDLJoystickHandler {
  1360. /**
  1361. * Handles given MotionEvent.
  1362. * @param event the event to be handled.
  1363. * @return if given event was processed.
  1364. */
  1365. public boolean handleMotionEvent(MotionEvent event) {
  1366. return false;
  1367. }
  1368. /**
  1369. * Handles adding and removing of input devices.
  1370. */
  1371. public void pollInputDevices() {
  1372. }
  1373. }
  1374. /* Actual joystick functionality available for API >= 12 devices */
  1375. class SDLJoystickHandler_API12 extends SDLJoystickHandler {
  1376. static class SDLJoystick {
  1377. public int device_id;
  1378. public String name;
  1379. public ArrayList<InputDevice.MotionRange> axes;
  1380. public ArrayList<InputDevice.MotionRange> hats;
  1381. }
  1382. static class RangeComparator implements Comparator<InputDevice.MotionRange> {
  1383. @Override
  1384. public int compare(InputDevice.MotionRange arg0, InputDevice.MotionRange arg1) {
  1385. return arg0.getAxis() - arg1.getAxis();
  1386. }
  1387. }
  1388. private ArrayList<SDLJoystick> mJoysticks;
  1389. public SDLJoystickHandler_API12() {
  1390. mJoysticks = new ArrayList<SDLJoystick>();
  1391. }
  1392. @Override
  1393. public void pollInputDevices() {
  1394. int[] deviceIds = InputDevice.getDeviceIds();
  1395. // It helps processing the device ids in reverse order
  1396. // For example, in the case of the XBox 360 wireless dongle,
  1397. // so the first controller seen by SDL matches what the receiver
  1398. // considers to be the first controller
  1399. for(int i=deviceIds.length-1; i>-1; i--) {
  1400. SDLJoystick joystick = getJoystick(deviceIds[i]);
  1401. if (joystick == null) {
  1402. joystick = new SDLJoystick();
  1403. InputDevice joystickDevice = InputDevice.getDevice(deviceIds[i]);
  1404. if (SDLActivity.isDeviceSDLJoystick(deviceIds[i])) {
  1405. joystick.device_id = deviceIds[i];
  1406. joystick.name = joystickDevice.getName();
  1407. joystick.axes = new ArrayList<InputDevice.MotionRange>();
  1408. joystick.hats = new ArrayList<InputDevice.MotionRange>();
  1409. List<InputDevice.MotionRange> ranges = joystickDevice.getMotionRanges();
  1410. Collections.sort(ranges, new RangeComparator());
  1411. for (InputDevice.MotionRange range : ranges ) {
  1412. if ((range.getSource() & InputDevice.SOURCE_CLASS_JOYSTICK) != 0) {
  1413. if (range.getAxis() == MotionEvent.AXIS_HAT_X ||
  1414. range.getAxis() == MotionEvent.AXIS_HAT_Y) {
  1415. joystick.hats.add(range);
  1416. }
  1417. else {
  1418. joystick.axes.add(range);
  1419. }
  1420. }
  1421. }
  1422. mJoysticks.add(joystick);
  1423. SDLActivity.nativeAddJoystick(joystick.device_id, joystick.name, 0, -1,
  1424. joystick.axes.size(), joystick.hats.size()/2, 0);
  1425. }
  1426. }
  1427. }
  1428. /* Check removed devices */
  1429. ArrayList<Integer> removedDevices = new ArrayList<Integer>();
  1430. for(int i=0; i < mJoysticks.size(); i++) {
  1431. int device_id = mJoysticks.get(i).device_id;
  1432. int j;
  1433. for (j=0; j < deviceIds.length; j++) {
  1434. if (device_id == deviceIds[j]) break;
  1435. }
  1436. if (j == deviceIds.length) {
  1437. removedDevices.add(Integer.valueOf(device_id));
  1438. }
  1439. }
  1440. for(int i=0; i < removedDevices.size(); i++) {
  1441. int device_id = removedDevices.get(i).intValue();
  1442. SDLActivity.nativeRemoveJoystick(device_id);
  1443. for (int j=0; j < mJoysticks.size(); j++) {
  1444. if (mJoysticks.get(j).device_id == device_id) {
  1445. mJoysticks.remove(j);
  1446. break;
  1447. }
  1448. }
  1449. }
  1450. }
  1451. protected SDLJoystick getJoystick(int device_id) {
  1452. for(int i=0; i < mJoysticks.size(); i++) {
  1453. if (mJoysticks.get(i).device_id == device_id) {
  1454. return mJoysticks.get(i);
  1455. }
  1456. }
  1457. return null;
  1458. }
  1459. @Override
  1460. public boolean handleMotionEvent(MotionEvent event) {
  1461. if ((event.getSource() & InputDevice.SOURCE_JOYSTICK) != 0) {
  1462. int actionPointerIndex = event.getActionIndex();
  1463. int action = event.getActionMasked();
  1464. switch(action) {
  1465. case MotionEvent.ACTION_MOVE:
  1466. SDLJoystick joystick = getJoystick(event.getDeviceId());
  1467. if ( joystick != null ) {
  1468. for (int i = 0; i < joystick.axes.size(); i++) {
  1469. InputDevice.MotionRange range = joystick.axes.get(i);
  1470. /* Normalize the value to -1...1 */
  1471. float value = ( event.getAxisValue( range.getAxis(), actionPointerIndex) - range.getMin() ) / range.getRange() * 2.0f - 1.0f;
  1472. SDLActivity.onNativeJoy(joystick.device_id, i, value );
  1473. }
  1474. for (int i = 0; i < joystick.hats.size(); i+=2) {
  1475. int hatX = Math.round(event.getAxisValue( joystick.hats.get(i).getAxis(), actionPointerIndex ) );
  1476. int hatY = Math.round(event.getAxisValue( joystick.hats.get(i+1).getAxis(), actionPointerIndex ) );
  1477. SDLActivity.onNativeHat(joystick.device_id, i/2, hatX, hatY );
  1478. }
  1479. }
  1480. break;
  1481. default:
  1482. break;
  1483. }
  1484. }
  1485. return true;
  1486. }
  1487. }
  1488. class SDLGenericMotionListener_API12 implements View.OnGenericMotionListener {
  1489. // Generic Motion (mouse hover, joystick...) events go here
  1490. @Override
  1491. public boolean onGenericMotion(View v, MotionEvent event) {
  1492. float x, y;
  1493. int action;
  1494. switch ( event.getSource() ) {
  1495. case InputDevice.SOURCE_JOYSTICK:
  1496. case InputDevice.SOURCE_GAMEPAD:
  1497. case InputDevice.SOURCE_DPAD:
  1498. return SDLActivity.handleJoystickMotionEvent(event);
  1499. case InputDevice.SOURCE_MOUSE:
  1500. action = event.getActionMasked();
  1501. switch (action) {
  1502. case MotionEvent.ACTION_SCROLL:
  1503. x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
  1504. y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
  1505. SDLActivity.onNativeMouse(0, action, x, y);
  1506. return true;
  1507. case MotionEvent.ACTION_HOVER_MOVE:
  1508. x = event.getX(0);
  1509. y = event.getY(0);
  1510. SDLActivity.onNativeMouse(0, action, x, y);
  1511. return true;
  1512. default:
  1513. break;
  1514. }
  1515. break;
  1516. default:
  1517. break;
  1518. }
  1519. // Event was not managed
  1520. return false;
  1521. }
  1522. }