SDLActivity.java 76 KB

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