SDLActivity.java 74 KB

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