SDLActivity.java 80 KB

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