SDLActivity.java 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  1. package org.libsdl.app;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.Arrays;
  5. import java.util.Hashtable;
  6. import java.lang.reflect.Method;
  7. import java.lang.Math;
  8. import android.app.*;
  9. import android.content.*;
  10. import android.content.res.Configuration;
  11. import android.text.InputType;
  12. import android.view.*;
  13. import android.view.inputmethod.BaseInputConnection;
  14. import android.view.inputmethod.EditorInfo;
  15. import android.view.inputmethod.InputConnection;
  16. import android.view.inputmethod.InputMethodManager;
  17. import android.widget.RelativeLayout;
  18. import android.widget.Button;
  19. import android.widget.LinearLayout;
  20. import android.widget.TextView;
  21. import android.os.*;
  22. import android.util.DisplayMetrics;
  23. import android.util.Log;
  24. import android.util.SparseArray;
  25. import android.graphics.*;
  26. import android.graphics.drawable.Drawable;
  27. import android.hardware.*;
  28. import android.content.pm.ActivityInfo;
  29. import android.content.pm.PackageManager;
  30. import android.content.pm.ApplicationInfo;
  31. /**
  32. SDL Activity
  33. */
  34. public class SDLActivity extends Activity implements View.OnSystemUiVisibilityChangeListener {
  35. private static final String TAG = "SDL";
  36. public static boolean mIsResumedCalled, mIsSurfaceReady, mHasFocus;
  37. // Cursor types
  38. private static final int SDL_SYSTEM_CURSOR_NONE = -1;
  39. private static final int SDL_SYSTEM_CURSOR_ARROW = 0;
  40. private static final int SDL_SYSTEM_CURSOR_IBEAM = 1;
  41. private static final int SDL_SYSTEM_CURSOR_WAIT = 2;
  42. private static final int SDL_SYSTEM_CURSOR_CROSSHAIR = 3;
  43. private static final int SDL_SYSTEM_CURSOR_WAITARROW = 4;
  44. private static final int SDL_SYSTEM_CURSOR_SIZENWSE = 5;
  45. private static final int SDL_SYSTEM_CURSOR_SIZENESW = 6;
  46. private static final int SDL_SYSTEM_CURSOR_SIZEWE = 7;
  47. private static final int SDL_SYSTEM_CURSOR_SIZENS = 8;
  48. private static final int SDL_SYSTEM_CURSOR_SIZEALL = 9;
  49. private static final int SDL_SYSTEM_CURSOR_NO = 10;
  50. private static final int SDL_SYSTEM_CURSOR_HAND = 11;
  51. protected static final int SDL_ORIENTATION_UNKNOWN = 0;
  52. protected static final int SDL_ORIENTATION_LANDSCAPE = 1;
  53. protected static final int SDL_ORIENTATION_LANDSCAPE_FLIPPED = 2;
  54. protected static final int SDL_ORIENTATION_PORTRAIT = 3;
  55. protected static final int SDL_ORIENTATION_PORTRAIT_FLIPPED = 4;
  56. protected static int mCurrentOrientation;
  57. // Handle the state of the native layer
  58. public enum NativeState {
  59. INIT, RESUMED, PAUSED
  60. }
  61. public static NativeState mNextNativeState;
  62. public static NativeState mCurrentNativeState;
  63. public static boolean mExitCalledFromJava;
  64. /** If shared libraries (e.g. SDL or the native application) could not be loaded. */
  65. public static boolean mBrokenLibraries;
  66. // If we want to separate mouse and touch events.
  67. // This is only toggled in native code when a hint is set!
  68. public static boolean mSeparateMouseAndTouch;
  69. // Main components
  70. protected static SDLActivity mSingleton;
  71. protected static SDLSurface mSurface;
  72. protected static View mTextEdit;
  73. protected static boolean mScreenKeyboardShown;
  74. protected static ViewGroup mLayout;
  75. protected static SDLClipboardHandler mClipboardHandler;
  76. protected static Hashtable<Integer, Object> mCursors;
  77. protected static int mLastCursorID;
  78. protected static SDLGenericMotionListener_API12 mMotionListener;
  79. protected static HIDDeviceManager mHIDDeviceManager;
  80. // This is what SDL runs in. It invokes SDL_main(), eventually
  81. protected static Thread mSDLThread;
  82. protected static SDLGenericMotionListener_API12 getMotionListener() {
  83. if (mMotionListener == null) {
  84. if (Build.VERSION.SDK_INT >= 26) {
  85. mMotionListener = new SDLGenericMotionListener_API26();
  86. } else
  87. if (Build.VERSION.SDK_INT >= 24) {
  88. mMotionListener = new SDLGenericMotionListener_API24();
  89. } else {
  90. mMotionListener = new SDLGenericMotionListener_API12();
  91. }
  92. }
  93. return mMotionListener;
  94. }
  95. /**
  96. * This method returns the name of the shared object with the application entry point
  97. * It can be overridden by derived classes.
  98. */
  99. protected String getMainSharedObject() {
  100. String library;
  101. String[] libraries = SDLActivity.mSingleton.getLibraries();
  102. if (libraries.length > 0) {
  103. library = "lib" + libraries[libraries.length - 1] + ".so";
  104. } else {
  105. library = "libmain.so";
  106. }
  107. return getContext().getApplicationInfo().nativeLibraryDir + "/" + library;
  108. }
  109. /**
  110. * This method returns the name of the application entry point
  111. * It can be overridden by derived classes.
  112. */
  113. protected String getMainFunction() {
  114. return "SDL_main";
  115. }
  116. /**
  117. * This method is called by SDL before loading the native shared libraries.
  118. * It can be overridden to provide names of shared libraries to be loaded.
  119. * The default implementation returns the defaults. It never returns null.
  120. * An array returned by a new implementation must at least contain "SDL2".
  121. * Also keep in mind that the order the libraries are loaded may matter.
  122. * @return names of shared libraries to be loaded (e.g. "SDL2", "main").
  123. */
  124. protected String[] getLibraries() {
  125. return new String[] {
  126. "SDL2",
  127. // "SDL2_image",
  128. // "SDL2_mixer",
  129. // "SDL2_net",
  130. // "SDL2_ttf",
  131. "main"
  132. };
  133. }
  134. // Load the .so
  135. public void loadLibraries() {
  136. for (String lib : getLibraries()) {
  137. System.loadLibrary(lib);
  138. }
  139. }
  140. /**
  141. * This method is called by SDL before starting the native application thread.
  142. * It can be overridden to provide the arguments after the application name.
  143. * The default implementation returns an empty array. It never returns null.
  144. * @return arguments for the native application.
  145. */
  146. protected String[] getArguments() {
  147. return new String[0];
  148. }
  149. public static void initialize() {
  150. // The static nature of the singleton and Android quirkyness force us to initialize everything here
  151. // Otherwise, when exiting the app and returning to it, these variables *keep* their pre exit values
  152. mSingleton = null;
  153. mSurface = null;
  154. mTextEdit = null;
  155. mLayout = null;
  156. mClipboardHandler = null;
  157. mCursors = new Hashtable<Integer, Object>();
  158. mLastCursorID = 0;
  159. mSDLThread = null;
  160. mExitCalledFromJava = false;
  161. mBrokenLibraries = false;
  162. mIsResumedCalled = false;
  163. mIsSurfaceReady = false;
  164. mHasFocus = true;
  165. mNextNativeState = NativeState.INIT;
  166. mCurrentNativeState = NativeState.INIT;
  167. }
  168. // Setup
  169. @Override
  170. protected void onCreate(Bundle savedInstanceState) {
  171. Log.v(TAG, "Device: " + android.os.Build.DEVICE);
  172. Log.v(TAG, "Model: " + android.os.Build.MODEL);
  173. Log.v(TAG, "onCreate()");
  174. super.onCreate(savedInstanceState);
  175. // Load shared libraries
  176. String errorMsgBrokenLib = "";
  177. try {
  178. loadLibraries();
  179. } catch(UnsatisfiedLinkError e) {
  180. System.err.println(e.getMessage());
  181. mBrokenLibraries = true;
  182. errorMsgBrokenLib = e.getMessage();
  183. } catch(Exception e) {
  184. System.err.println(e.getMessage());
  185. mBrokenLibraries = true;
  186. errorMsgBrokenLib = e.getMessage();
  187. }
  188. if (mBrokenLibraries)
  189. {
  190. mSingleton = this;
  191. AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
  192. dlgAlert.setMessage("An error occurred while trying to start the application. Please try again and/or reinstall."
  193. + System.getProperty("line.separator")
  194. + System.getProperty("line.separator")
  195. + "Error: " + errorMsgBrokenLib);
  196. dlgAlert.setTitle("SDL Error");
  197. dlgAlert.setPositiveButton("Exit",
  198. new DialogInterface.OnClickListener() {
  199. @Override
  200. public void onClick(DialogInterface dialog,int id) {
  201. // if this button is clicked, close current activity
  202. SDLActivity.mSingleton.finish();
  203. }
  204. });
  205. dlgAlert.setCancelable(false);
  206. dlgAlert.create().show();
  207. return;
  208. }
  209. // Set up JNI
  210. SDL.setupJNI();
  211. // Initialize state
  212. SDL.initialize();
  213. // So we can call stuff from static callbacks
  214. mSingleton = this;
  215. SDL.setContext(this);
  216. if (Build.VERSION.SDK_INT >= 11) {
  217. mClipboardHandler = new SDLClipboardHandler_API11();
  218. } else {
  219. /* Before API 11, no clipboard notification (eg no SDL_CLIPBOARDUPDATE) */
  220. mClipboardHandler = new SDLClipboardHandler_Old();
  221. }
  222. mHIDDeviceManager = new HIDDeviceManager(this);
  223. // Set up the surface
  224. mSurface = new SDLSurface(getApplication());
  225. mLayout = new RelativeLayout(this);
  226. mLayout.addView(mSurface);
  227. // Get our current screen orientation and pass it down.
  228. mCurrentOrientation = SDLActivity.getCurrentOrientation();
  229. SDLActivity.onNativeOrientationChanged(mCurrentOrientation);
  230. setContentView(mLayout);
  231. setWindowStyle(false);
  232. getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(this);
  233. // Get filename from "Open with" of another application
  234. Intent intent = getIntent();
  235. if (intent != null && intent.getData() != null) {
  236. String filename = intent.getData().getPath();
  237. if (filename != null) {
  238. Log.v(TAG, "Got filename: " + filename);
  239. SDLActivity.onNativeDropFile(filename);
  240. }
  241. }
  242. }
  243. // Events
  244. @Override
  245. protected void onPause() {
  246. Log.v(TAG, "onPause()");
  247. super.onPause();
  248. mNextNativeState = NativeState.PAUSED;
  249. mIsResumedCalled = false;
  250. if (SDLActivity.mBrokenLibraries) {
  251. return;
  252. }
  253. if (mHIDDeviceManager != null) {
  254. mHIDDeviceManager.setFrozen(true);
  255. }
  256. SDLActivity.handleNativeState();
  257. }
  258. @Override
  259. protected void onResume() {
  260. Log.v(TAG, "onResume()");
  261. super.onResume();
  262. mNextNativeState = NativeState.RESUMED;
  263. mIsResumedCalled = true;
  264. if (SDLActivity.mBrokenLibraries) {
  265. return;
  266. }
  267. if (mHIDDeviceManager != null) {
  268. mHIDDeviceManager.setFrozen(false);
  269. }
  270. SDLActivity.handleNativeState();
  271. }
  272. public static int getCurrentOrientation() {
  273. final Context context = SDLActivity.getContext();
  274. final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  275. int result = SDL_ORIENTATION_UNKNOWN;
  276. switch (display.getRotation()) {
  277. case Surface.ROTATION_0:
  278. result = SDL_ORIENTATION_PORTRAIT;
  279. break;
  280. case Surface.ROTATION_90:
  281. result = SDL_ORIENTATION_LANDSCAPE;
  282. break;
  283. case Surface.ROTATION_180:
  284. result = SDL_ORIENTATION_PORTRAIT_FLIPPED;
  285. break;
  286. case Surface.ROTATION_270:
  287. result = SDL_ORIENTATION_LANDSCAPE_FLIPPED;
  288. break;
  289. }
  290. return result;
  291. }
  292. @Override
  293. public void onWindowFocusChanged(boolean hasFocus) {
  294. super.onWindowFocusChanged(hasFocus);
  295. Log.v(TAG, "onWindowFocusChanged(): " + hasFocus);
  296. if (SDLActivity.mBrokenLibraries) {
  297. return;
  298. }
  299. SDLActivity.mHasFocus = hasFocus;
  300. if (hasFocus) {
  301. mNextNativeState = NativeState.RESUMED;
  302. SDLActivity.getMotionListener().reclaimRelativeMouseModeIfNeeded();
  303. } else {
  304. mNextNativeState = NativeState.PAUSED;
  305. }
  306. SDLActivity.handleNativeState();
  307. }
  308. @Override
  309. public void onLowMemory() {
  310. Log.v(TAG, "onLowMemory()");
  311. super.onLowMemory();
  312. if (SDLActivity.mBrokenLibraries) {
  313. return;
  314. }
  315. SDLActivity.nativeLowMemory();
  316. }
  317. @Override
  318. protected void onDestroy() {
  319. Log.v(TAG, "onDestroy()");
  320. if (mHIDDeviceManager != null) {
  321. mHIDDeviceManager.close();
  322. mHIDDeviceManager = null;
  323. }
  324. if (SDLActivity.mBrokenLibraries) {
  325. super.onDestroy();
  326. // Reset everything in case the user re opens the app
  327. SDLActivity.initialize();
  328. return;
  329. }
  330. mNextNativeState = NativeState.PAUSED;
  331. SDLActivity.handleNativeState();
  332. // Send a quit message to the application
  333. SDLActivity.mExitCalledFromJava = true;
  334. SDLActivity.nativeQuit();
  335. // Now wait for the SDL thread to quit
  336. if (SDLActivity.mSDLThread != null) {
  337. try {
  338. SDLActivity.mSDLThread.join();
  339. } catch(Exception e) {
  340. Log.v(TAG, "Problem stopping thread: " + e);
  341. }
  342. SDLActivity.mSDLThread = null;
  343. //Log.v(TAG, "Finished waiting for SDL thread");
  344. }
  345. super.onDestroy();
  346. // Reset everything in case the user re opens the app
  347. SDLActivity.initialize();
  348. }
  349. @Override
  350. public void onBackPressed() {
  351. // Check if we want to block the back button in case of mouse right click.
  352. //
  353. // If we do, the normal hardware back button will no longer work and people have to use home,
  354. // but the mouse right click will work.
  355. //
  356. String trapBack = SDLActivity.nativeGetHint("SDL_ANDROID_TRAP_BACK_BUTTON");
  357. if ((trapBack != null) && trapBack.equals("1")) {
  358. // Exit and let the mouse handler handle this button (if appropriate)
  359. return;
  360. }
  361. // Default system back button behavior.
  362. super.onBackPressed();
  363. }
  364. // Called by JNI from SDL.
  365. public static void manualBackButton() {
  366. mSingleton.pressBackButton();
  367. }
  368. // Used to get us onto the activity's main thread
  369. public void pressBackButton() {
  370. runOnUiThread(new Runnable() {
  371. @Override
  372. public void run() {
  373. SDLActivity.this.superOnBackPressed();
  374. }
  375. });
  376. }
  377. // Used to access the system back behavior.
  378. public void superOnBackPressed() {
  379. super.onBackPressed();
  380. }
  381. @Override
  382. public boolean dispatchKeyEvent(KeyEvent event) {
  383. if (SDLActivity.mBrokenLibraries) {
  384. return false;
  385. }
  386. int keyCode = event.getKeyCode();
  387. // Ignore certain special keys so they're handled by Android
  388. if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
  389. keyCode == KeyEvent.KEYCODE_VOLUME_UP ||
  390. keyCode == KeyEvent.KEYCODE_CAMERA ||
  391. keyCode == KeyEvent.KEYCODE_ZOOM_IN || /* API 11 */
  392. keyCode == KeyEvent.KEYCODE_ZOOM_OUT /* API 11 */
  393. ) {
  394. return false;
  395. }
  396. return super.dispatchKeyEvent(event);
  397. }
  398. /* Transition to next state */
  399. public static void handleNativeState() {
  400. if (mNextNativeState == mCurrentNativeState) {
  401. // Already in same state, discard.
  402. return;
  403. }
  404. // Try a transition to init state
  405. if (mNextNativeState == NativeState.INIT) {
  406. mCurrentNativeState = mNextNativeState;
  407. return;
  408. }
  409. // Try a transition to paused state
  410. if (mNextNativeState == NativeState.PAUSED) {
  411. nativePause();
  412. if (mSurface != null)
  413. mSurface.handlePause();
  414. mCurrentNativeState = mNextNativeState;
  415. return;
  416. }
  417. // Try a transition to resumed state
  418. if (mNextNativeState == NativeState.RESUMED) {
  419. if (mIsSurfaceReady && mHasFocus && mIsResumedCalled) {
  420. if (mSDLThread == null) {
  421. // This is the entry point to the C app.
  422. // Start up the C app thread and enable sensor input for the first time
  423. // FIXME: Why aren't we enabling sensor input at start?
  424. mSDLThread = new Thread(new SDLMain(), "SDLThread");
  425. mSurface.enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  426. mSDLThread.start();
  427. }
  428. nativeResume();
  429. mSurface.handleResume();
  430. mCurrentNativeState = mNextNativeState;
  431. }
  432. }
  433. }
  434. /* The native thread has finished */
  435. public static void handleNativeExit() {
  436. SDLActivity.mSDLThread = null;
  437. if (mSingleton != null) {
  438. mSingleton.finish();
  439. }
  440. }
  441. // Messages from the SDLMain thread
  442. static final int COMMAND_CHANGE_TITLE = 1;
  443. static final int COMMAND_CHANGE_WINDOW_STYLE = 2;
  444. static final int COMMAND_TEXTEDIT_HIDE = 3;
  445. static final int COMMAND_SET_KEEP_SCREEN_ON = 5;
  446. protected static final int COMMAND_USER = 0x8000;
  447. protected static boolean mFullscreenModeActive;
  448. /**
  449. * This method is called by SDL if SDL did not handle a message itself.
  450. * This happens if a received message contains an unsupported command.
  451. * Method can be overwritten to handle Messages in a different class.
  452. * @param command the command of the message.
  453. * @param param the parameter of the message. May be null.
  454. * @return if the message was handled in overridden method.
  455. */
  456. protected boolean onUnhandledMessage(int command, Object param) {
  457. return false;
  458. }
  459. /**
  460. * A Handler class for Messages from native SDL applications.
  461. * It uses current Activities as target (e.g. for the title).
  462. * static to prevent implicit references to enclosing object.
  463. */
  464. protected static class SDLCommandHandler extends Handler {
  465. @Override
  466. public void handleMessage(Message msg) {
  467. Context context = SDL.getContext();
  468. if (context == null) {
  469. Log.e(TAG, "error handling message, getContext() returned null");
  470. return;
  471. }
  472. switch (msg.arg1) {
  473. case COMMAND_CHANGE_TITLE:
  474. if (context instanceof Activity) {
  475. ((Activity) context).setTitle((String)msg.obj);
  476. } else {
  477. Log.e(TAG, "error handling message, getContext() returned no Activity");
  478. }
  479. break;
  480. case COMMAND_CHANGE_WINDOW_STYLE:
  481. if (Build.VERSION.SDK_INT < 19) {
  482. // This version of Android doesn't support the immersive fullscreen mode
  483. break;
  484. }
  485. if (context instanceof Activity) {
  486. Window window = ((Activity) context).getWindow();
  487. if (window != null) {
  488. if ((msg.obj instanceof Integer) && (((Integer) msg.obj).intValue() != 0)) {
  489. int flags = View.SYSTEM_UI_FLAG_FULLSCREEN |
  490. View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
  491. View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
  492. View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
  493. View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
  494. View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.INVISIBLE;
  495. window.getDecorView().setSystemUiVisibility(flags);
  496. window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  497. window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
  498. SDLActivity.mFullscreenModeActive = true;
  499. } else {
  500. int flags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_VISIBLE;
  501. window.getDecorView().setSystemUiVisibility(flags);
  502. window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
  503. window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  504. SDLActivity.mFullscreenModeActive = false;
  505. }
  506. }
  507. } else {
  508. Log.e(TAG, "error handling message, getContext() returned no Activity");
  509. }
  510. break;
  511. case COMMAND_TEXTEDIT_HIDE:
  512. if (mTextEdit != null) {
  513. // Note: On some devices setting view to GONE creates a flicker in landscape.
  514. // Setting the View's sizes to 0 is similar to GONE but without the flicker.
  515. // The sizes will be set to useful values when the keyboard is shown again.
  516. mTextEdit.setLayoutParams(new RelativeLayout.LayoutParams(0, 0));
  517. InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
  518. imm.hideSoftInputFromWindow(mTextEdit.getWindowToken(), 0);
  519. mScreenKeyboardShown = false;
  520. }
  521. break;
  522. case COMMAND_SET_KEEP_SCREEN_ON:
  523. {
  524. if (context instanceof Activity) {
  525. Window window = ((Activity) context).getWindow();
  526. if (window != null) {
  527. if ((msg.obj instanceof Integer) && (((Integer) msg.obj).intValue() != 0)) {
  528. window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  529. } else {
  530. window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  531. }
  532. }
  533. }
  534. break;
  535. }
  536. default:
  537. if ((context instanceof SDLActivity) && !((SDLActivity) context).onUnhandledMessage(msg.arg1, msg.obj)) {
  538. Log.e(TAG, "error handling message, command is " + msg.arg1);
  539. }
  540. }
  541. }
  542. }
  543. // Handler for the messages
  544. Handler commandHandler = new SDLCommandHandler();
  545. // Send a message from the SDLMain thread
  546. boolean sendCommand(int command, Object data) {
  547. Message msg = commandHandler.obtainMessage();
  548. msg.arg1 = command;
  549. msg.obj = data;
  550. return commandHandler.sendMessage(msg);
  551. }
  552. // C functions we call
  553. public static native int nativeSetupJNI();
  554. public static native int nativeRunMain(String library, String function, Object arguments);
  555. public static native void nativeLowMemory();
  556. public static native void nativeQuit();
  557. public static native void nativePause();
  558. public static native void nativeResume();
  559. public static native void onNativeDropFile(String filename);
  560. public static native void onNativeResize(int surfaceWidth, int surfaceHeight, int deviceWidth, int deviceHeight, int format, float rate);
  561. public static native void onNativeKeyDown(int keycode);
  562. public static native void onNativeKeyUp(int keycode);
  563. public static native void onNativeKeyboardFocusLost();
  564. public static native void onNativeMouse(int button, int action, float x, float y, boolean relative);
  565. public static native void onNativeTouch(int touchDevId, int pointerFingerId,
  566. int action, float x,
  567. float y, float p);
  568. public static native void onNativeAccel(float x, float y, float z);
  569. public static native void onNativeClipboardChanged();
  570. public static native void onNativeSurfaceChanged();
  571. public static native void onNativeSurfaceDestroyed();
  572. public static native String nativeGetHint(String name);
  573. public static native void nativeSetenv(String name, String value);
  574. public static native void onNativeOrientationChanged(int orientation);
  575. /**
  576. * This method is called by SDL using JNI.
  577. */
  578. public static boolean setActivityTitle(String title) {
  579. // Called from SDLMain() thread and can't directly affect the view
  580. return mSingleton.sendCommand(COMMAND_CHANGE_TITLE, title);
  581. }
  582. /**
  583. * This method is called by SDL using JNI.
  584. */
  585. public static void setWindowStyle(boolean fullscreen) {
  586. // Called from SDLMain() thread and can't directly affect the view
  587. mSingleton.sendCommand(COMMAND_CHANGE_WINDOW_STYLE, fullscreen ? 1 : 0);
  588. }
  589. /**
  590. * This method is called by SDL using JNI.
  591. * This is a static method for JNI convenience, it calls a non-static method
  592. * so that is can be overridden
  593. */
  594. public static void setOrientation(int w, int h, boolean resizable, String hint)
  595. {
  596. if (mSingleton != null) {
  597. mSingleton.setOrientationBis(w, h, resizable, hint);
  598. }
  599. }
  600. /**
  601. * This can be overridden
  602. */
  603. public void setOrientationBis(int w, int h, boolean resizable, String hint)
  604. {
  605. int orientation = -1;
  606. if (hint.contains("LandscapeRight") && hint.contains("LandscapeLeft")) {
  607. orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
  608. } else if (hint.contains("LandscapeRight")) {
  609. orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
  610. } else if (hint.contains("LandscapeLeft")) {
  611. orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
  612. } else if (hint.contains("Portrait") && hint.contains("PortraitUpsideDown")) {
  613. orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
  614. } else if (hint.contains("Portrait")) {
  615. orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
  616. } else if (hint.contains("PortraitUpsideDown")) {
  617. orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
  618. }
  619. /* no valid hint */
  620. if (orientation == -1) {
  621. if (resizable) {
  622. /* no fixed orientation */
  623. } else {
  624. if (w > h) {
  625. orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
  626. } else {
  627. orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
  628. }
  629. }
  630. }
  631. Log.v("SDL", "setOrientation() orientation=" + orientation + " width=" + w +" height="+ h +" resizable=" + resizable + " hint=" + hint);
  632. if (orientation != -1) {
  633. mSingleton.setRequestedOrientation(orientation);
  634. }
  635. }
  636. /**
  637. * This method is called by SDL using JNI.
  638. */
  639. public static boolean isScreenKeyboardShown()
  640. {
  641. if (mTextEdit == null) {
  642. return false;
  643. }
  644. if (!mScreenKeyboardShown) {
  645. return false;
  646. }
  647. InputMethodManager imm = (InputMethodManager) SDL.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  648. return imm.isAcceptingText();
  649. }
  650. /**
  651. * This method is called by SDL using JNI.
  652. */
  653. public static boolean supportsRelativeMouse()
  654. {
  655. // ChromeOS doesn't provide relative mouse motion via the Android 7 APIs
  656. if (isChromebook()) {
  657. return false;
  658. }
  659. // Samsung DeX mode doesn't support relative mice properly under Android 7 APIs,
  660. // and simply returns no data under Android 8 APIs.
  661. if (isDeXMode()) {
  662. return false;
  663. }
  664. return SDLActivity.getMotionListener().supportsRelativeMouse();
  665. }
  666. /**
  667. * This method is called by SDL using JNI.
  668. */
  669. public static boolean setRelativeMouseEnabled(boolean enabled)
  670. {
  671. if (enabled && !supportsRelativeMouse()) {
  672. return false;
  673. }
  674. return SDLActivity.getMotionListener().setRelativeMouseEnabled(enabled);
  675. }
  676. /**
  677. * This method is called by SDL using JNI.
  678. */
  679. public static boolean sendMessage(int command, int param) {
  680. if (mSingleton == null) {
  681. return false;
  682. }
  683. return mSingleton.sendCommand(command, Integer.valueOf(param));
  684. }
  685. /**
  686. * This method is called by SDL using JNI.
  687. */
  688. public static Context getContext() {
  689. return SDL.getContext();
  690. }
  691. /**
  692. * This method is called by SDL using JNI.
  693. */
  694. public static boolean isAndroidTV() {
  695. UiModeManager uiModeManager = (UiModeManager) getContext().getSystemService(UI_MODE_SERVICE);
  696. if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION) {
  697. return true;
  698. }
  699. if (Build.MANUFACTURER.equals("MINIX") && Build.MODEL.equals("NEO-U1")) {
  700. return true;
  701. }
  702. return false;
  703. }
  704. /**
  705. * This method is called by SDL using JNI.
  706. */
  707. public static boolean isTablet() {
  708. DisplayMetrics metrics = new DisplayMetrics();
  709. Activity sdlActivity = (Activity)getContext();
  710. sdlActivity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
  711. double dWidthInches = metrics.widthPixels / (double)metrics.densityDpi;
  712. double dHeightInches = metrics.heightPixels / (double)metrics.densityDpi;
  713. double dDiagonal = Math.sqrt((dWidthInches * dWidthInches) + (dHeightInches * dHeightInches));
  714. // If our diagonal size is seven inches or greater, we consider ourselves a tablet.
  715. return (dDiagonal > 7.0);
  716. }
  717. /**
  718. * This method is called by SDL using JNI.
  719. */
  720. public static boolean isChromebook() {
  721. return getContext().getPackageManager().hasSystemFeature("org.chromium.arc.device_management");
  722. }
  723. /**
  724. * This method is called by SDL using JNI.
  725. */
  726. public static boolean isDeXMode() {
  727. if (Build.VERSION.SDK_INT < 24) {
  728. return false;
  729. }
  730. try {
  731. final Configuration config = getContext().getResources().getConfiguration();
  732. final Class configClass = config.getClass();
  733. return configClass.getField("SEM_DESKTOP_MODE_ENABLED").getInt(configClass)
  734. == configClass.getField("semDesktopModeEnabled").getInt(config);
  735. } catch(Exception ignored) {
  736. return false;
  737. }
  738. }
  739. /**
  740. * This method is called by SDL using JNI.
  741. */
  742. public static DisplayMetrics getDisplayDPI() {
  743. return getContext().getResources().getDisplayMetrics();
  744. }
  745. /**
  746. * This method is called by SDL using JNI.
  747. */
  748. public static boolean getManifestEnvironmentVariables() {
  749. try {
  750. ApplicationInfo applicationInfo = getContext().getPackageManager().getApplicationInfo(getContext().getPackageName(), PackageManager.GET_META_DATA);
  751. Bundle bundle = applicationInfo.metaData;
  752. if (bundle == null) {
  753. return false;
  754. }
  755. String prefix = "SDL_ENV.";
  756. final int trimLength = prefix.length();
  757. for (String key : bundle.keySet()) {
  758. if (key.startsWith(prefix)) {
  759. String name = key.substring(trimLength);
  760. String value = bundle.get(key).toString();
  761. nativeSetenv(name, value);
  762. }
  763. }
  764. /* environment variables set! */
  765. return true;
  766. } catch (Exception e) {
  767. Log.v("SDL", "exception " + e.toString());
  768. }
  769. return false;
  770. }
  771. // This method is called by SDLControllerManager's API 26 Generic Motion Handler.
  772. public static View getContentView()
  773. {
  774. return mSingleton.mLayout;
  775. }
  776. static class ShowTextInputTask implements Runnable {
  777. /*
  778. * This is used to regulate the pan&scan method to have some offset from
  779. * the bottom edge of the input region and the top edge of an input
  780. * method (soft keyboard)
  781. */
  782. static final int HEIGHT_PADDING = 15;
  783. public int x, y, w, h;
  784. public ShowTextInputTask(int x, int y, int w, int h) {
  785. this.x = x;
  786. this.y = y;
  787. this.w = w;
  788. this.h = h;
  789. }
  790. @Override
  791. public void run() {
  792. RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(w, h + HEIGHT_PADDING);
  793. params.leftMargin = x;
  794. params.topMargin = y;
  795. if (mTextEdit == null) {
  796. mTextEdit = new DummyEdit(SDL.getContext());
  797. mLayout.addView(mTextEdit, params);
  798. } else {
  799. mTextEdit.setLayoutParams(params);
  800. }
  801. mTextEdit.setVisibility(View.VISIBLE);
  802. mTextEdit.requestFocus();
  803. InputMethodManager imm = (InputMethodManager) SDL.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
  804. imm.showSoftInput(mTextEdit, 0);
  805. mScreenKeyboardShown = true;
  806. }
  807. }
  808. /**
  809. * This method is called by SDL using JNI.
  810. */
  811. public static boolean showTextInput(int x, int y, int w, int h) {
  812. // Transfer the task to the main thread as a Runnable
  813. return mSingleton.commandHandler.post(new ShowTextInputTask(x, y, w, h));
  814. }
  815. public static boolean isTextInputEvent(KeyEvent event) {
  816. // Key pressed with Ctrl should be sent as SDL_KEYDOWN/SDL_KEYUP and not SDL_TEXTINPUT
  817. if (Build.VERSION.SDK_INT >= 11) {
  818. if (event.isCtrlPressed()) {
  819. return false;
  820. }
  821. }
  822. return event.isPrintingKey() || event.getKeyCode() == KeyEvent.KEYCODE_SPACE;
  823. }
  824. /**
  825. * This method is called by SDL using JNI.
  826. */
  827. public static Surface getNativeSurface() {
  828. if (SDLActivity.mSurface == null) {
  829. return null;
  830. }
  831. return SDLActivity.mSurface.getNativeSurface();
  832. }
  833. // Input
  834. /**
  835. * This method is called by SDL using JNI.
  836. * @return an array which may be empty but is never null.
  837. */
  838. public static int[] inputGetInputDeviceIds(int sources) {
  839. int[] ids = InputDevice.getDeviceIds();
  840. int[] filtered = new int[ids.length];
  841. int used = 0;
  842. for (int i = 0; i < ids.length; ++i) {
  843. InputDevice device = InputDevice.getDevice(ids[i]);
  844. if ((device != null) && ((device.getSources() & sources) != 0)) {
  845. filtered[used++] = device.getId();
  846. }
  847. }
  848. return Arrays.copyOf(filtered, used);
  849. }
  850. // APK expansion files support
  851. /** com.android.vending.expansion.zipfile.ZipResourceFile object or null. */
  852. private static Object expansionFile;
  853. /** com.android.vending.expansion.zipfile.ZipResourceFile's getInputStream() or null. */
  854. private static Method expansionFileMethod;
  855. /**
  856. * This method is called by SDL using JNI.
  857. * @return an InputStream on success or null if no expansion file was used.
  858. * @throws IOException on errors. Message is set for the SDL error message.
  859. */
  860. public static InputStream openAPKExpansionInputStream(String fileName) throws IOException {
  861. // Get a ZipResourceFile representing a merger of both the main and patch files
  862. if (expansionFile == null) {
  863. String mainHint = nativeGetHint("SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION");
  864. if (mainHint == null) {
  865. return null; // no expansion use if no main version was set
  866. }
  867. String patchHint = nativeGetHint("SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION");
  868. if (patchHint == null) {
  869. return null; // no expansion use if no patch version was set
  870. }
  871. Integer mainVersion;
  872. Integer patchVersion;
  873. try {
  874. mainVersion = Integer.valueOf(mainHint);
  875. patchVersion = Integer.valueOf(patchHint);
  876. } catch (NumberFormatException ex) {
  877. ex.printStackTrace();
  878. throw new IOException("No valid file versions set for APK expansion files", ex);
  879. }
  880. try {
  881. // To avoid direct dependency on Google APK expansion library that is
  882. // not a part of Android SDK we access it using reflection
  883. expansionFile = Class.forName("com.android.vending.expansion.zipfile.APKExpansionSupport")
  884. .getMethod("getAPKExpansionZipFile", Context.class, int.class, int.class)
  885. .invoke(null, SDL.getContext(), mainVersion, patchVersion);
  886. expansionFileMethod = expansionFile.getClass()
  887. .getMethod("getInputStream", String.class);
  888. } catch (Exception ex) {
  889. ex.printStackTrace();
  890. expansionFile = null;
  891. expansionFileMethod = null;
  892. throw new IOException("Could not access APK expansion support library", ex);
  893. }
  894. }
  895. // Get an input stream for a known file inside the expansion file ZIPs
  896. InputStream fileStream;
  897. try {
  898. fileStream = (InputStream)expansionFileMethod.invoke(expansionFile, fileName);
  899. } catch (Exception ex) {
  900. // calling "getInputStream" failed
  901. ex.printStackTrace();
  902. throw new IOException("Could not open stream from APK expansion file", ex);
  903. }
  904. if (fileStream == null) {
  905. // calling "getInputStream" was successful but null was returned
  906. throw new IOException("Could not find path in APK expansion file");
  907. }
  908. return fileStream;
  909. }
  910. // Messagebox
  911. /** Result of current messagebox. Also used for blocking the calling thread. */
  912. protected final int[] messageboxSelection = new int[1];
  913. /** Id of current dialog. */
  914. protected int dialogs = 0;
  915. /**
  916. * This method is called by SDL using JNI.
  917. * Shows the messagebox from UI thread and block calling thread.
  918. * buttonFlags, buttonIds and buttonTexts must have same length.
  919. * @param buttonFlags array containing flags for every button.
  920. * @param buttonIds array containing id for every button.
  921. * @param buttonTexts array containing text for every button.
  922. * @param colors null for default or array of length 5 containing colors.
  923. * @return button id or -1.
  924. */
  925. public int messageboxShowMessageBox(
  926. final int flags,
  927. final String title,
  928. final String message,
  929. final int[] buttonFlags,
  930. final int[] buttonIds,
  931. final String[] buttonTexts,
  932. final int[] colors) {
  933. messageboxSelection[0] = -1;
  934. // sanity checks
  935. if ((buttonFlags.length != buttonIds.length) && (buttonIds.length != buttonTexts.length)) {
  936. return -1; // implementation broken
  937. }
  938. // collect arguments for Dialog
  939. final Bundle args = new Bundle();
  940. args.putInt("flags", flags);
  941. args.putString("title", title);
  942. args.putString("message", message);
  943. args.putIntArray("buttonFlags", buttonFlags);
  944. args.putIntArray("buttonIds", buttonIds);
  945. args.putStringArray("buttonTexts", buttonTexts);
  946. args.putIntArray("colors", colors);
  947. // trigger Dialog creation on UI thread
  948. runOnUiThread(new Runnable() {
  949. @Override
  950. public void run() {
  951. showDialog(dialogs++, args);
  952. }
  953. });
  954. // block the calling thread
  955. synchronized (messageboxSelection) {
  956. try {
  957. messageboxSelection.wait();
  958. } catch (InterruptedException ex) {
  959. ex.printStackTrace();
  960. return -1;
  961. }
  962. }
  963. // return selected value
  964. return messageboxSelection[0];
  965. }
  966. @Override
  967. protected Dialog onCreateDialog(int ignore, Bundle args) {
  968. // TODO set values from "flags" to messagebox dialog
  969. // get colors
  970. int[] colors = args.getIntArray("colors");
  971. int backgroundColor;
  972. int textColor;
  973. int buttonBorderColor;
  974. int buttonBackgroundColor;
  975. int buttonSelectedColor;
  976. if (colors != null) {
  977. int i = -1;
  978. backgroundColor = colors[++i];
  979. textColor = colors[++i];
  980. buttonBorderColor = colors[++i];
  981. buttonBackgroundColor = colors[++i];
  982. buttonSelectedColor = colors[++i];
  983. } else {
  984. backgroundColor = Color.TRANSPARENT;
  985. textColor = Color.TRANSPARENT;
  986. buttonBorderColor = Color.TRANSPARENT;
  987. buttonBackgroundColor = Color.TRANSPARENT;
  988. buttonSelectedColor = Color.TRANSPARENT;
  989. }
  990. // create dialog with title and a listener to wake up calling thread
  991. final Dialog dialog = new Dialog(this);
  992. dialog.setTitle(args.getString("title"));
  993. dialog.setCancelable(false);
  994. dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
  995. @Override
  996. public void onDismiss(DialogInterface unused) {
  997. synchronized (messageboxSelection) {
  998. messageboxSelection.notify();
  999. }
  1000. }
  1001. });
  1002. // create text
  1003. TextView message = new TextView(this);
  1004. message.setGravity(Gravity.CENTER);
  1005. message.setText(args.getString("message"));
  1006. if (textColor != Color.TRANSPARENT) {
  1007. message.setTextColor(textColor);
  1008. }
  1009. // create buttons
  1010. int[] buttonFlags = args.getIntArray("buttonFlags");
  1011. int[] buttonIds = args.getIntArray("buttonIds");
  1012. String[] buttonTexts = args.getStringArray("buttonTexts");
  1013. final SparseArray<Button> mapping = new SparseArray<Button>();
  1014. LinearLayout buttons = new LinearLayout(this);
  1015. buttons.setOrientation(LinearLayout.HORIZONTAL);
  1016. buttons.setGravity(Gravity.CENTER);
  1017. for (int i = 0; i < buttonTexts.length; ++i) {
  1018. Button button = new Button(this);
  1019. final int id = buttonIds[i];
  1020. button.setOnClickListener(new View.OnClickListener() {
  1021. @Override
  1022. public void onClick(View v) {
  1023. messageboxSelection[0] = id;
  1024. dialog.dismiss();
  1025. }
  1026. });
  1027. if (buttonFlags[i] != 0) {
  1028. // see SDL_messagebox.h
  1029. if ((buttonFlags[i] & 0x00000001) != 0) {
  1030. mapping.put(KeyEvent.KEYCODE_ENTER, button);
  1031. }
  1032. if ((buttonFlags[i] & 0x00000002) != 0) {
  1033. mapping.put(KeyEvent.KEYCODE_ESCAPE, button); /* API 11 */
  1034. }
  1035. }
  1036. button.setText(buttonTexts[i]);
  1037. if (textColor != Color.TRANSPARENT) {
  1038. button.setTextColor(textColor);
  1039. }
  1040. if (buttonBorderColor != Color.TRANSPARENT) {
  1041. // TODO set color for border of messagebox button
  1042. }
  1043. if (buttonBackgroundColor != Color.TRANSPARENT) {
  1044. Drawable drawable = button.getBackground();
  1045. if (drawable == null) {
  1046. // setting the color this way removes the style
  1047. button.setBackgroundColor(buttonBackgroundColor);
  1048. } else {
  1049. // setting the color this way keeps the style (gradient, padding, etc.)
  1050. drawable.setColorFilter(buttonBackgroundColor, PorterDuff.Mode.MULTIPLY);
  1051. }
  1052. }
  1053. if (buttonSelectedColor != Color.TRANSPARENT) {
  1054. // TODO set color for selected messagebox button
  1055. }
  1056. buttons.addView(button);
  1057. }
  1058. // create content
  1059. LinearLayout content = new LinearLayout(this);
  1060. content.setOrientation(LinearLayout.VERTICAL);
  1061. content.addView(message);
  1062. content.addView(buttons);
  1063. if (backgroundColor != Color.TRANSPARENT) {
  1064. content.setBackgroundColor(backgroundColor);
  1065. }
  1066. // add content to dialog and return
  1067. dialog.setContentView(content);
  1068. dialog.setOnKeyListener(new Dialog.OnKeyListener() {
  1069. @Override
  1070. public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
  1071. Button button = mapping.get(keyCode);
  1072. if (button != null) {
  1073. if (event.getAction() == KeyEvent.ACTION_UP) {
  1074. button.performClick();
  1075. }
  1076. return true; // also for ignored actions
  1077. }
  1078. return false;
  1079. }
  1080. });
  1081. return dialog;
  1082. }
  1083. private final Runnable rehideSystemUi = new Runnable() {
  1084. @Override
  1085. public void run() {
  1086. int flags = View.SYSTEM_UI_FLAG_FULLSCREEN |
  1087. View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
  1088. View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
  1089. View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
  1090. View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
  1091. View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.INVISIBLE;
  1092. SDLActivity.this.getWindow().getDecorView().setSystemUiVisibility(flags);
  1093. }
  1094. };
  1095. public void onSystemUiVisibilityChange(int visibility) {
  1096. if (SDLActivity.mFullscreenModeActive && (visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0 || (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
  1097. Handler handler = getWindow().getDecorView().getHandler();
  1098. if (handler != null) {
  1099. handler.removeCallbacks(rehideSystemUi); // Prevent a hide loop.
  1100. handler.postDelayed(rehideSystemUi, 2000);
  1101. }
  1102. }
  1103. }
  1104. /**
  1105. * This method is called by SDL using JNI.
  1106. */
  1107. public static boolean clipboardHasText() {
  1108. return mClipboardHandler.clipboardHasText();
  1109. }
  1110. /**
  1111. * This method is called by SDL using JNI.
  1112. */
  1113. public static String clipboardGetText() {
  1114. return mClipboardHandler.clipboardGetText();
  1115. }
  1116. /**
  1117. * This method is called by SDL using JNI.
  1118. */
  1119. public static void clipboardSetText(String string) {
  1120. mClipboardHandler.clipboardSetText(string);
  1121. }
  1122. /**
  1123. * This method is called by SDL using JNI.
  1124. */
  1125. public static int createCustomCursor(int[] colors, int width, int height, int hotSpotX, int hotSpotY) {
  1126. Bitmap bitmap = Bitmap.createBitmap(colors, width, height, Bitmap.Config.ARGB_8888);
  1127. ++mLastCursorID;
  1128. // This requires API 24, so use reflection to implement this
  1129. try {
  1130. Class PointerIconClass = Class.forName("android.view.PointerIcon");
  1131. Class[] arg_types = new Class[] { Bitmap.class, float.class, float.class };
  1132. Method create = PointerIconClass.getMethod("create", arg_types);
  1133. mCursors.put(mLastCursorID, create.invoke(null, bitmap, hotSpotX, hotSpotY));
  1134. } catch (Exception e) {
  1135. return 0;
  1136. }
  1137. return mLastCursorID;
  1138. }
  1139. /**
  1140. * This method is called by SDL using JNI.
  1141. */
  1142. public static boolean setCustomCursor(int cursorID) {
  1143. // This requires API 24, so use reflection to implement this
  1144. try {
  1145. Class PointerIconClass = Class.forName("android.view.PointerIcon");
  1146. Method setPointerIcon = SDLSurface.class.getMethod("setPointerIcon", PointerIconClass);
  1147. setPointerIcon.invoke(mSurface, mCursors.get(cursorID));
  1148. } catch (Exception e) {
  1149. return false;
  1150. }
  1151. return true;
  1152. }
  1153. /**
  1154. * This method is called by SDL using JNI.
  1155. */
  1156. public static boolean setSystemCursor(int cursorID) {
  1157. int cursor_type = 0; //PointerIcon.TYPE_NULL;
  1158. switch (cursorID) {
  1159. case SDL_SYSTEM_CURSOR_ARROW:
  1160. cursor_type = 1000; //PointerIcon.TYPE_ARROW;
  1161. break;
  1162. case SDL_SYSTEM_CURSOR_IBEAM:
  1163. cursor_type = 1008; //PointerIcon.TYPE_TEXT;
  1164. break;
  1165. case SDL_SYSTEM_CURSOR_WAIT:
  1166. cursor_type = 1004; //PointerIcon.TYPE_WAIT;
  1167. break;
  1168. case SDL_SYSTEM_CURSOR_CROSSHAIR:
  1169. cursor_type = 1007; //PointerIcon.TYPE_CROSSHAIR;
  1170. break;
  1171. case SDL_SYSTEM_CURSOR_WAITARROW:
  1172. cursor_type = 1004; //PointerIcon.TYPE_WAIT;
  1173. break;
  1174. case SDL_SYSTEM_CURSOR_SIZENWSE:
  1175. cursor_type = 1017; //PointerIcon.TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW;
  1176. break;
  1177. case SDL_SYSTEM_CURSOR_SIZENESW:
  1178. cursor_type = 1016; //PointerIcon.TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW;
  1179. break;
  1180. case SDL_SYSTEM_CURSOR_SIZEWE:
  1181. cursor_type = 1014; //PointerIcon.TYPE_HORIZONTAL_DOUBLE_ARROW;
  1182. break;
  1183. case SDL_SYSTEM_CURSOR_SIZENS:
  1184. cursor_type = 1015; //PointerIcon.TYPE_VERTICAL_DOUBLE_ARROW;
  1185. break;
  1186. case SDL_SYSTEM_CURSOR_SIZEALL:
  1187. cursor_type = 1020; //PointerIcon.TYPE_GRAB;
  1188. break;
  1189. case SDL_SYSTEM_CURSOR_NO:
  1190. cursor_type = 1012; //PointerIcon.TYPE_NO_DROP;
  1191. break;
  1192. case SDL_SYSTEM_CURSOR_HAND:
  1193. cursor_type = 1002; //PointerIcon.TYPE_HAND;
  1194. break;
  1195. }
  1196. // This requires API 24, so use reflection to implement this
  1197. try {
  1198. Class PointerIconClass = Class.forName("android.view.PointerIcon");
  1199. Class[] arg_types = new Class[] { Context.class, int.class };
  1200. Method getSystemIcon = PointerIconClass.getMethod("getSystemIcon", arg_types);
  1201. Method setPointerIcon = SDLSurface.class.getMethod("setPointerIcon", PointerIconClass);
  1202. setPointerIcon.invoke(mSurface, getSystemIcon.invoke(null, SDL.getContext(), cursor_type));
  1203. } catch (Exception e) {
  1204. return false;
  1205. }
  1206. return true;
  1207. }
  1208. }
  1209. /**
  1210. Simple runnable to start the SDL application
  1211. */
  1212. class SDLMain implements Runnable {
  1213. @Override
  1214. public void run() {
  1215. // Runs SDL_main()
  1216. String library = SDLActivity.mSingleton.getMainSharedObject();
  1217. String function = SDLActivity.mSingleton.getMainFunction();
  1218. String[] arguments = SDLActivity.mSingleton.getArguments();
  1219. Log.v("SDL", "Running main function " + function + " from library " + library);
  1220. SDLActivity.nativeRunMain(library, function, arguments);
  1221. Log.v("SDL", "Finished main function");
  1222. // Native thread has finished, let's finish the Activity
  1223. if (!SDLActivity.mExitCalledFromJava) {
  1224. SDLActivity.handleNativeExit();
  1225. }
  1226. }
  1227. }
  1228. /**
  1229. SDLSurface. This is what we draw on, so we need to know when it's created
  1230. in order to do anything useful.
  1231. Because of this, that's where we set up the SDL thread
  1232. */
  1233. class SDLSurface extends SurfaceView implements SurfaceHolder.Callback,
  1234. View.OnKeyListener, View.OnTouchListener, SensorEventListener {
  1235. // Sensors
  1236. protected static SensorManager mSensorManager;
  1237. protected static Display mDisplay;
  1238. // Keep track of the surface size to normalize touch events
  1239. protected static float mWidth, mHeight;
  1240. // Startup
  1241. public SDLSurface(Context context) {
  1242. super(context);
  1243. getHolder().addCallback(this);
  1244. setFocusable(true);
  1245. setFocusableInTouchMode(true);
  1246. requestFocus();
  1247. setOnKeyListener(this);
  1248. setOnTouchListener(this);
  1249. mDisplay = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  1250. mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
  1251. if (Build.VERSION.SDK_INT >= 12) {
  1252. setOnGenericMotionListener(SDLActivity.getMotionListener());
  1253. }
  1254. // Some arbitrary defaults to avoid a potential division by zero
  1255. mWidth = 1.0f;
  1256. mHeight = 1.0f;
  1257. }
  1258. public void handlePause() {
  1259. enableSensor(Sensor.TYPE_ACCELEROMETER, false);
  1260. }
  1261. public void handleResume() {
  1262. setFocusable(true);
  1263. setFocusableInTouchMode(true);
  1264. requestFocus();
  1265. setOnKeyListener(this);
  1266. setOnTouchListener(this);
  1267. enableSensor(Sensor.TYPE_ACCELEROMETER, true);
  1268. }
  1269. public Surface getNativeSurface() {
  1270. return getHolder().getSurface();
  1271. }
  1272. // Called when we have a valid drawing surface
  1273. @Override
  1274. public void surfaceCreated(SurfaceHolder holder) {
  1275. Log.v("SDL", "surfaceCreated()");
  1276. holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
  1277. }
  1278. // Called when we lose the surface
  1279. @Override
  1280. public void surfaceDestroyed(SurfaceHolder holder) {
  1281. Log.v("SDL", "surfaceDestroyed()");
  1282. // Transition to pause, if needed
  1283. SDLActivity.mNextNativeState = SDLActivity.NativeState.PAUSED;
  1284. SDLActivity.handleNativeState();
  1285. SDLActivity.mIsSurfaceReady = false;
  1286. SDLActivity.onNativeSurfaceDestroyed();
  1287. }
  1288. // Called when the surface is resized
  1289. @Override
  1290. public void surfaceChanged(SurfaceHolder holder,
  1291. int format, int width, int height) {
  1292. Log.v("SDL", "surfaceChanged()");
  1293. int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default
  1294. switch (format) {
  1295. case PixelFormat.A_8:
  1296. Log.v("SDL", "pixel format A_8");
  1297. break;
  1298. case PixelFormat.LA_88:
  1299. Log.v("SDL", "pixel format LA_88");
  1300. break;
  1301. case PixelFormat.L_8:
  1302. Log.v("SDL", "pixel format L_8");
  1303. break;
  1304. case PixelFormat.RGBA_4444:
  1305. Log.v("SDL", "pixel format RGBA_4444");
  1306. sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444
  1307. break;
  1308. case PixelFormat.RGBA_5551:
  1309. Log.v("SDL", "pixel format RGBA_5551");
  1310. sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551
  1311. break;
  1312. case PixelFormat.RGBA_8888:
  1313. Log.v("SDL", "pixel format RGBA_8888");
  1314. sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888
  1315. break;
  1316. case PixelFormat.RGBX_8888:
  1317. Log.v("SDL", "pixel format RGBX_8888");
  1318. sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888
  1319. break;
  1320. case PixelFormat.RGB_332:
  1321. Log.v("SDL", "pixel format RGB_332");
  1322. sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332
  1323. break;
  1324. case PixelFormat.RGB_565:
  1325. Log.v("SDL", "pixel format RGB_565");
  1326. sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565
  1327. break;
  1328. case PixelFormat.RGB_888:
  1329. Log.v("SDL", "pixel format RGB_888");
  1330. // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead?
  1331. sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888
  1332. break;
  1333. default:
  1334. Log.v("SDL", "pixel format unknown " + format);
  1335. break;
  1336. }
  1337. mWidth = width;
  1338. mHeight = height;
  1339. int nDeviceWidth = width;
  1340. int nDeviceHeight = height;
  1341. try
  1342. {
  1343. if ( android.os.Build.VERSION.SDK_INT >= 17 )
  1344. {
  1345. android.util.DisplayMetrics realMetrics = new android.util.DisplayMetrics();
  1346. mDisplay.getRealMetrics( realMetrics );
  1347. nDeviceWidth = realMetrics.widthPixels;
  1348. nDeviceHeight = realMetrics.heightPixels;
  1349. }
  1350. }
  1351. catch ( java.lang.Throwable throwable ) {}
  1352. Log.v("SDL", "Window size: " + width + "x" + height);
  1353. Log.v("SDL", "Device size: " + nDeviceWidth + "x" + nDeviceHeight);
  1354. SDLActivity.onNativeResize(width, height, nDeviceWidth, nDeviceHeight, sdlFormat, mDisplay.getRefreshRate());
  1355. boolean skip = false;
  1356. int requestedOrientation = SDLActivity.mSingleton.getRequestedOrientation();
  1357. if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
  1358. {
  1359. // Accept any
  1360. }
  1361. else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT)
  1362. {
  1363. if (mWidth > mHeight) {
  1364. skip = true;
  1365. }
  1366. } else if (requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || requestedOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
  1367. if (mWidth < mHeight) {
  1368. skip = true;
  1369. }
  1370. }
  1371. // Special Patch for Square Resolution: Black Berry Passport
  1372. if (skip) {
  1373. double min = Math.min(mWidth, mHeight);
  1374. double max = Math.max(mWidth, mHeight);
  1375. if (max / min < 1.20) {
  1376. Log.v("SDL", "Don't skip on such aspect-ratio. Could be a square resolution.");
  1377. skip = false;
  1378. }
  1379. }
  1380. if (skip) {
  1381. Log.v("SDL", "Skip .. Surface is not ready.");
  1382. SDLActivity.mIsSurfaceReady = false;
  1383. return;
  1384. }
  1385. /* Surface is ready */
  1386. SDLActivity.mIsSurfaceReady = true;
  1387. /* If the surface has been previously destroyed by onNativeSurfaceDestroyed, recreate it here */
  1388. SDLActivity.onNativeSurfaceChanged();
  1389. SDLActivity.handleNativeState();
  1390. }
  1391. // Key events
  1392. @Override
  1393. public boolean onKey(View v, int keyCode, KeyEvent event) {
  1394. // Dispatch the different events depending on where they come from
  1395. // Some SOURCE_JOYSTICK, SOURCE_DPAD or SOURCE_GAMEPAD are also SOURCE_KEYBOARD
  1396. // So, we try to process them as JOYSTICK/DPAD/GAMEPAD events first, if that fails we try them as KEYBOARD
  1397. //
  1398. // Furthermore, it's possible a game controller has SOURCE_KEYBOARD and
  1399. // SOURCE_JOYSTICK, while its key events arrive from the keyboard source
  1400. // So, retrieve the device itself and check all of its sources
  1401. if (SDLControllerManager.isDeviceSDLJoystick(event.getDeviceId())) {
  1402. // Note that we process events with specific key codes here
  1403. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1404. if (SDLControllerManager.onNativePadDown(event.getDeviceId(), keyCode) == 0) {
  1405. return true;
  1406. }
  1407. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  1408. if (SDLControllerManager.onNativePadUp(event.getDeviceId(), keyCode) == 0) {
  1409. return true;
  1410. }
  1411. }
  1412. }
  1413. if ((event.getSource() & InputDevice.SOURCE_KEYBOARD) != 0) {
  1414. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1415. //Log.v("SDL", "key down: " + keyCode);
  1416. if (SDLActivity.isTextInputEvent(event)) {
  1417. SDLInputConnection.nativeCommitText(String.valueOf((char) event.getUnicodeChar()), 1);
  1418. }
  1419. SDLActivity.onNativeKeyDown(keyCode);
  1420. return true;
  1421. }
  1422. else if (event.getAction() == KeyEvent.ACTION_UP) {
  1423. //Log.v("SDL", "key up: " + keyCode);
  1424. SDLActivity.onNativeKeyUp(keyCode);
  1425. return true;
  1426. }
  1427. }
  1428. if ((event.getSource() & InputDevice.SOURCE_MOUSE) != 0) {
  1429. // on some devices key events are sent for mouse BUTTON_BACK/FORWARD presses
  1430. // they are ignored here because sending them as mouse input to SDL is messy
  1431. if ((keyCode == KeyEvent.KEYCODE_BACK) || (keyCode == KeyEvent.KEYCODE_FORWARD)) {
  1432. switch (event.getAction()) {
  1433. case KeyEvent.ACTION_DOWN:
  1434. case KeyEvent.ACTION_UP:
  1435. // mark the event as handled or it will be handled by system
  1436. // handling KEYCODE_BACK by system will call onBackPressed()
  1437. return true;
  1438. }
  1439. }
  1440. }
  1441. return false;
  1442. }
  1443. // Touch events
  1444. @Override
  1445. public boolean onTouch(View v, MotionEvent event) {
  1446. /* Ref: http://developer.android.com/training/gestures/multi.html */
  1447. final int touchDevId = event.getDeviceId();
  1448. final int pointerCount = event.getPointerCount();
  1449. int action = event.getActionMasked();
  1450. int pointerFingerId;
  1451. int mouseButton;
  1452. int i = -1;
  1453. float x,y,p;
  1454. // !!! FIXME: dump this SDK check after 2.0.4 ships and require API14.
  1455. // 12290 = Samsung DeX mode desktop mouse
  1456. if ((event.getSource() == InputDevice.SOURCE_MOUSE || event.getSource() == 12290) && SDLActivity.mSeparateMouseAndTouch) {
  1457. if (Build.VERSION.SDK_INT < 14) {
  1458. mouseButton = 1; // all mouse buttons are the left button
  1459. } else {
  1460. try {
  1461. mouseButton = (Integer) event.getClass().getMethod("getButtonState").invoke(event);
  1462. } catch(Exception e) {
  1463. mouseButton = 1; // oh well.
  1464. }
  1465. }
  1466. // We need to check if we're in relative mouse mode and get the axis offset rather than the x/y values
  1467. // if we are. We'll leverage our existing mouse motion listener
  1468. SDLGenericMotionListener_API12 motionListener = SDLActivity.getMotionListener();
  1469. x = motionListener.getEventX(event);
  1470. y = motionListener.getEventY(event);
  1471. SDLActivity.onNativeMouse(mouseButton, action, x, y, motionListener.inRelativeMode());
  1472. } else {
  1473. switch(action) {
  1474. case MotionEvent.ACTION_MOVE:
  1475. for (i = 0; i < pointerCount; i++) {
  1476. pointerFingerId = event.getPointerId(i);
  1477. x = event.getX(i) / mWidth;
  1478. y = event.getY(i) / mHeight;
  1479. p = event.getPressure(i);
  1480. if (p > 1.0f) {
  1481. // may be larger than 1.0f on some devices
  1482. // see the documentation of getPressure(i)
  1483. p = 1.0f;
  1484. }
  1485. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  1486. }
  1487. break;
  1488. case MotionEvent.ACTION_UP:
  1489. case MotionEvent.ACTION_DOWN:
  1490. // Primary pointer up/down, the index is always zero
  1491. i = 0;
  1492. case MotionEvent.ACTION_POINTER_UP:
  1493. case MotionEvent.ACTION_POINTER_DOWN:
  1494. // Non primary pointer up/down
  1495. if (i == -1) {
  1496. i = event.getActionIndex();
  1497. }
  1498. pointerFingerId = event.getPointerId(i);
  1499. x = event.getX(i) / mWidth;
  1500. y = event.getY(i) / mHeight;
  1501. p = event.getPressure(i);
  1502. if (p > 1.0f) {
  1503. // may be larger than 1.0f on some devices
  1504. // see the documentation of getPressure(i)
  1505. p = 1.0f;
  1506. }
  1507. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, action, x, y, p);
  1508. break;
  1509. case MotionEvent.ACTION_CANCEL:
  1510. for (i = 0; i < pointerCount; i++) {
  1511. pointerFingerId = event.getPointerId(i);
  1512. x = event.getX(i) / mWidth;
  1513. y = event.getY(i) / mHeight;
  1514. p = event.getPressure(i);
  1515. if (p > 1.0f) {
  1516. // may be larger than 1.0f on some devices
  1517. // see the documentation of getPressure(i)
  1518. p = 1.0f;
  1519. }
  1520. SDLActivity.onNativeTouch(touchDevId, pointerFingerId, MotionEvent.ACTION_UP, x, y, p);
  1521. }
  1522. break;
  1523. default:
  1524. break;
  1525. }
  1526. }
  1527. return true;
  1528. }
  1529. // Sensor events
  1530. public void enableSensor(int sensortype, boolean enabled) {
  1531. // TODO: This uses getDefaultSensor - what if we have >1 accels?
  1532. if (enabled) {
  1533. mSensorManager.registerListener(this,
  1534. mSensorManager.getDefaultSensor(sensortype),
  1535. SensorManager.SENSOR_DELAY_GAME, null);
  1536. } else {
  1537. mSensorManager.unregisterListener(this,
  1538. mSensorManager.getDefaultSensor(sensortype));
  1539. }
  1540. }
  1541. @Override
  1542. public void onAccuracyChanged(Sensor sensor, int accuracy) {
  1543. // TODO
  1544. }
  1545. @Override
  1546. public void onSensorChanged(SensorEvent event) {
  1547. if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
  1548. // Since we may have an orientation set, we won't receive onConfigurationChanged events.
  1549. // We thus should check here.
  1550. int newOrientation = SDLActivity.SDL_ORIENTATION_UNKNOWN;
  1551. float x, y;
  1552. switch (mDisplay.getRotation()) {
  1553. case Surface.ROTATION_90:
  1554. x = -event.values[1];
  1555. y = event.values[0];
  1556. newOrientation = SDLActivity.SDL_ORIENTATION_LANDSCAPE;
  1557. break;
  1558. case Surface.ROTATION_270:
  1559. x = event.values[1];
  1560. y = -event.values[0];
  1561. newOrientation = SDLActivity.SDL_ORIENTATION_LANDSCAPE_FLIPPED;
  1562. break;
  1563. case Surface.ROTATION_180:
  1564. x = -event.values[1];
  1565. y = -event.values[0];
  1566. newOrientation = SDLActivity.SDL_ORIENTATION_PORTRAIT_FLIPPED;
  1567. break;
  1568. default:
  1569. x = event.values[0];
  1570. y = event.values[1];
  1571. newOrientation = SDLActivity.SDL_ORIENTATION_PORTRAIT;
  1572. break;
  1573. }
  1574. if (newOrientation != SDLActivity.mCurrentOrientation) {
  1575. SDLActivity.mCurrentOrientation = newOrientation;
  1576. SDLActivity.onNativeOrientationChanged(newOrientation);
  1577. }
  1578. SDLActivity.onNativeAccel(-x / SensorManager.GRAVITY_EARTH,
  1579. y / SensorManager.GRAVITY_EARTH,
  1580. event.values[2] / SensorManager.GRAVITY_EARTH);
  1581. }
  1582. }
  1583. // Captured pointer events for API 26.
  1584. public boolean onCapturedPointerEvent(MotionEvent event)
  1585. {
  1586. int action = event.getActionMasked();
  1587. float x, y;
  1588. switch (action) {
  1589. case MotionEvent.ACTION_SCROLL:
  1590. x = event.getAxisValue(MotionEvent.AXIS_HSCROLL, 0);
  1591. y = event.getAxisValue(MotionEvent.AXIS_VSCROLL, 0);
  1592. SDLActivity.onNativeMouse(0, action, x, y, false);
  1593. return true;
  1594. case MotionEvent.ACTION_HOVER_MOVE:
  1595. case MotionEvent.ACTION_MOVE:
  1596. x = event.getX(0);
  1597. y = event.getY(0);
  1598. SDLActivity.onNativeMouse(0, action, x, y, true);
  1599. return true;
  1600. case MotionEvent.ACTION_BUTTON_PRESS:
  1601. case MotionEvent.ACTION_BUTTON_RELEASE:
  1602. // Change our action value to what SDL's code expects.
  1603. if (action == MotionEvent.ACTION_BUTTON_PRESS) {
  1604. action = MotionEvent.ACTION_DOWN;
  1605. }
  1606. else if (action == MotionEvent.ACTION_BUTTON_RELEASE) {
  1607. action = MotionEvent.ACTION_UP;
  1608. }
  1609. x = event.getX(0);
  1610. y = event.getY(0);
  1611. int button = event.getButtonState();
  1612. SDLActivity.onNativeMouse(button, action, x, y, true);
  1613. return true;
  1614. }
  1615. return false;
  1616. }
  1617. }
  1618. /* This is a fake invisible editor view that receives the input and defines the
  1619. * pan&scan region
  1620. */
  1621. class DummyEdit extends View implements View.OnKeyListener {
  1622. InputConnection ic;
  1623. public DummyEdit(Context context) {
  1624. super(context);
  1625. setFocusableInTouchMode(true);
  1626. setFocusable(true);
  1627. setOnKeyListener(this);
  1628. }
  1629. @Override
  1630. public boolean onCheckIsTextEditor() {
  1631. return true;
  1632. }
  1633. @Override
  1634. public boolean onKey(View v, int keyCode, KeyEvent event) {
  1635. /*
  1636. * This handles the hardware keyboard input
  1637. */
  1638. if (event.getAction() == KeyEvent.ACTION_DOWN) {
  1639. if (SDLActivity.isTextInputEvent(event)) {
  1640. ic.commitText(String.valueOf((char) event.getUnicodeChar()), 1);
  1641. return true;
  1642. }
  1643. SDLActivity.onNativeKeyDown(keyCode);
  1644. return true;
  1645. } else if (event.getAction() == KeyEvent.ACTION_UP) {
  1646. SDLActivity.onNativeKeyUp(keyCode);
  1647. return true;
  1648. }
  1649. return false;
  1650. }
  1651. //
  1652. @Override
  1653. public boolean onKeyPreIme (int keyCode, KeyEvent event) {
  1654. // As seen on StackOverflow: http://stackoverflow.com/questions/7634346/keyboard-hide-event
  1655. // FIXME: Discussion at http://bugzilla.libsdl.org/show_bug.cgi?id=1639
  1656. // FIXME: This is not a 100% effective solution to the problem of detecting if the keyboard is showing or not
  1657. // FIXME: A more effective solution would be to assume our Layout to be RelativeLayout or LinearLayout
  1658. // FIXME: And determine the keyboard presence doing this: http://stackoverflow.com/questions/2150078/how-to-check-visibility-of-software-keyboard-in-android
  1659. // FIXME: An even more effective way would be if Android provided this out of the box, but where would the fun be in that :)
  1660. if (event.getAction()==KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
  1661. if (SDLActivity.mTextEdit != null && SDLActivity.mTextEdit.getVisibility() == View.VISIBLE) {
  1662. SDLActivity.onNativeKeyboardFocusLost();
  1663. }
  1664. }
  1665. return super.onKeyPreIme(keyCode, event);
  1666. }
  1667. @Override
  1668. public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
  1669. ic = new SDLInputConnection(this, true);
  1670. outAttrs.inputType = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
  1671. outAttrs.imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
  1672. | EditorInfo.IME_FLAG_NO_FULLSCREEN /* API 11 */;
  1673. return ic;
  1674. }
  1675. }
  1676. class SDLInputConnection extends BaseInputConnection {
  1677. public SDLInputConnection(View targetView, boolean fullEditor) {
  1678. super(targetView, fullEditor);
  1679. }
  1680. @Override
  1681. public boolean sendKeyEvent(KeyEvent event) {
  1682. /*
  1683. * This used to handle the keycodes from soft keyboard (and IME-translated input from hardkeyboard)
  1684. * However, as of Ice Cream Sandwich and later, almost all soft keyboard doesn't generate key presses
  1685. * and so we need to generate them ourselves in commitText. To avoid duplicates on the handful of keys
  1686. * that still do, we empty this out.
  1687. */
  1688. /*
  1689. * Return DOES still generate a key event, however. So rather than using it as the 'click a button' key
  1690. * as we do with physical keyboards, let's just use it to hide the keyboard.
  1691. */
  1692. if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
  1693. String imeHide = SDLActivity.nativeGetHint("SDL_RETURN_KEY_HIDES_IME");
  1694. if ((imeHide != null) && imeHide.equals("1")) {
  1695. Context c = SDL.getContext();
  1696. if (c instanceof SDLActivity) {
  1697. SDLActivity activity = (SDLActivity)c;
  1698. activity.sendCommand(SDLActivity.COMMAND_TEXTEDIT_HIDE, null);
  1699. return true;
  1700. }
  1701. }
  1702. }
  1703. return super.sendKeyEvent(event);
  1704. }
  1705. @Override
  1706. public boolean commitText(CharSequence text, int newCursorPosition) {
  1707. for (int i = 0; i < text.length(); i++) {
  1708. char c = text.charAt(i);
  1709. nativeGenerateScancodeForUnichar(c);
  1710. }
  1711. SDLInputConnection.nativeCommitText(text.toString(), newCursorPosition);
  1712. return super.commitText(text, newCursorPosition);
  1713. }
  1714. @Override
  1715. public boolean setComposingText(CharSequence text, int newCursorPosition) {
  1716. nativeSetComposingText(text.toString(), newCursorPosition);
  1717. return super.setComposingText(text, newCursorPosition);
  1718. }
  1719. public static native void nativeCommitText(String text, int newCursorPosition);
  1720. public native void nativeGenerateScancodeForUnichar(char c);
  1721. public native void nativeSetComposingText(String text, int newCursorPosition);
  1722. @Override
  1723. public boolean deleteSurroundingText(int beforeLength, int afterLength) {
  1724. // Workaround to capture backspace key. Ref: http://stackoverflow.com/questions/14560344/android-backspace-in-webview-baseinputconnection
  1725. // and https://bugzilla.libsdl.org/show_bug.cgi?id=2265
  1726. if (beforeLength > 0 && afterLength == 0) {
  1727. boolean ret = true;
  1728. // backspace(s)
  1729. while (beforeLength-- > 0) {
  1730. boolean ret_key = sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
  1731. && sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
  1732. ret = ret && ret_key;
  1733. }
  1734. return ret;
  1735. }
  1736. return super.deleteSurroundingText(beforeLength, afterLength);
  1737. }
  1738. }
  1739. interface SDLClipboardHandler {
  1740. public boolean clipboardHasText();
  1741. public String clipboardGetText();
  1742. public void clipboardSetText(String string);
  1743. }
  1744. class SDLClipboardHandler_API11 implements
  1745. SDLClipboardHandler,
  1746. android.content.ClipboardManager.OnPrimaryClipChangedListener {
  1747. protected android.content.ClipboardManager mClipMgr;
  1748. SDLClipboardHandler_API11() {
  1749. mClipMgr = (android.content.ClipboardManager) SDL.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
  1750. mClipMgr.addPrimaryClipChangedListener(this);
  1751. }
  1752. @Override
  1753. public boolean clipboardHasText() {
  1754. return mClipMgr.hasText();
  1755. }
  1756. @Override
  1757. public String clipboardGetText() {
  1758. CharSequence text;
  1759. text = mClipMgr.getText();
  1760. if (text != null) {
  1761. return text.toString();
  1762. }
  1763. return null;
  1764. }
  1765. @Override
  1766. public void clipboardSetText(String string) {
  1767. mClipMgr.removePrimaryClipChangedListener(this);
  1768. mClipMgr.setText(string);
  1769. mClipMgr.addPrimaryClipChangedListener(this);
  1770. }
  1771. @Override
  1772. public void onPrimaryClipChanged() {
  1773. SDLActivity.onNativeClipboardChanged();
  1774. }
  1775. }
  1776. class SDLClipboardHandler_Old implements
  1777. SDLClipboardHandler {
  1778. protected android.text.ClipboardManager mClipMgrOld;
  1779. SDLClipboardHandler_Old() {
  1780. mClipMgrOld = (android.text.ClipboardManager) SDL.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
  1781. }
  1782. @Override
  1783. public boolean clipboardHasText() {
  1784. return mClipMgrOld.hasText();
  1785. }
  1786. @Override
  1787. public String clipboardGetText() {
  1788. CharSequence text;
  1789. text = mClipMgrOld.getText();
  1790. if (text != null) {
  1791. return text.toString();
  1792. }
  1793. return null;
  1794. }
  1795. @Override
  1796. public void clipboardSetText(String string) {
  1797. mClipMgrOld.setText(string);
  1798. }
  1799. }