SDLActivity.java 55 KB

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