SDLActivity.java 78 KB

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