GameActivity.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * Copyright (c) 2006-2024 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. */
  20. package org.love2d.android;
  21. import android.Manifest;
  22. import android.content.Context;
  23. import android.content.Intent;
  24. import android.content.pm.ApplicationInfo;
  25. import android.content.pm.PackageManager;
  26. import android.content.res.AssetManager;
  27. import android.graphics.Rect;
  28. import android.media.AudioManager;
  29. import android.net.Uri;
  30. import android.os.Bundle;
  31. import android.os.ParcelFileDescriptor;
  32. import android.os.VibrationEffect;
  33. import android.os.Vibrator;
  34. import android.util.DisplayMetrics;
  35. import android.util.Log;
  36. import android.view.DisplayCutout;
  37. import android.view.WindowManager;
  38. import androidx.annotation.Keep;
  39. import androidx.core.app.ActivityCompat;
  40. import org.libsdl.app.SDLActivity;
  41. import java.io.FileNotFoundException;
  42. import java.io.IOException;
  43. import java.io.InputStream;
  44. import java.util.ArrayList;
  45. import java.util.HashMap;
  46. import java.util.Map;
  47. public class GameActivity extends SDLActivity {
  48. private static final String TAG = "GameActivity";
  49. public static final int RECORD_AUDIO_REQUEST_CODE = 3;
  50. protected Vibrator vibrator;
  51. protected boolean shortEdgesMode;
  52. protected final int[] recordAudioRequestDummy = new int[1];
  53. private Uri delayedUri = null;
  54. private String[] args;
  55. private boolean isFused;
  56. private static native void nativeSetDefaultStreamValues(int sampleRate, int framesPerBurst);
  57. @Override
  58. protected String getMainSharedObject() {
  59. String[] libs = getLibraries();
  60. // Since Lollipop, you can simply pass "libname.so" to dlopen
  61. // and it will resolve correct paths and load correct library.
  62. // This is mandatory for extractNativeLibs=false support in
  63. // Marshmallow.
  64. return "lib" + libs[libs.length - 1] + ".so";
  65. }
  66. @Override
  67. protected String[] getLibraries() {
  68. return new String[]{
  69. "c++_shared",
  70. "SDL3",
  71. "oboe",
  72. "openal",
  73. "luajit",
  74. "liblove",
  75. "love",
  76. };
  77. }
  78. @Override
  79. protected String[] getArguments() {
  80. return args;
  81. }
  82. @Override
  83. protected void onCreate(Bundle savedInstanceState) {
  84. Log.d(TAG, "started");
  85. isFused = hasEmbeddedGame();
  86. args = new String[0];
  87. if (checkCallingOrSelfPermission(Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
  88. vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
  89. }
  90. Intent intent = getIntent();
  91. handleIntent(intent, true);
  92. // Prevent SDL sending filedropped event. Let us do that instead.
  93. intent.setData(null);
  94. super.onCreate(savedInstanceState);
  95. if (mBrokenLibraries) {
  96. return;
  97. }
  98. // Set low-latency audio values
  99. nativeSetDefaultStreamValues(getAudioFreq(), getAudioSMP());
  100. if (android.os.Build.VERSION.SDK_INT >= 28) {
  101. WindowManager.LayoutParams attr = getWindow().getAttributes();
  102. attr.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
  103. shortEdgesMode = false;
  104. }
  105. if (delayedUri != null) {
  106. // This delayed fd is only sent if an embedded game is present.
  107. sendUriAsDroppedFile(delayedUri);
  108. delayedUri = null;
  109. }
  110. }
  111. @Override
  112. protected void onNewIntent(Intent intent) {
  113. super.onNewIntent(intent);
  114. handleIntent(intent, false);
  115. }
  116. @Override
  117. protected void onDestroy() {
  118. if (vibrator != null) {
  119. Log.d(TAG, "Cancelling vibration");
  120. vibrator.cancel();
  121. }
  122. super.onDestroy();
  123. }
  124. @Override
  125. protected void onPause() {
  126. if (vibrator != null) {
  127. Log.d(TAG, "Cancelling vibration");
  128. vibrator.cancel();
  129. }
  130. super.onPause();
  131. }
  132. @Override
  133. public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  134. if (grantResults.length > 0) {
  135. Log.d("GameActivity", "Received a request permission result");
  136. if (requestCode == RECORD_AUDIO_REQUEST_CODE) {
  137. if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  138. Log.d("GameActivity", "Mic permission granted");
  139. } else {
  140. Log.d("GameActivity", "Did not get mic permission.");
  141. }
  142. Log.d("GameActivity", "Unlocking LÖVE thread");
  143. synchronized (recordAudioRequestDummy) {
  144. recordAudioRequestDummy[0] = grantResults[0];
  145. recordAudioRequestDummy.notify();
  146. }
  147. } else {
  148. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  149. }
  150. }
  151. }
  152. @Keep
  153. public boolean hasEmbeddedGame() {
  154. AssetManager am = getAssets();
  155. InputStream inputStream;
  156. try {
  157. // Prioritize main.lua in assets folder
  158. inputStream = am.open("main.lua");
  159. } catch (IOException e) {
  160. // Not found, try game.love in assets folder
  161. try {
  162. inputStream = am.open("game.love");
  163. } catch (IOException e2) {
  164. // Not found
  165. return false;
  166. }
  167. }
  168. try {
  169. inputStream.close();
  170. } catch (IOException ignored) {
  171. }
  172. return true;
  173. }
  174. @Keep
  175. public void vibrate(double seconds) {
  176. if (vibrator != null) {
  177. long duration = (long) (seconds * 1000.);
  178. if (android.os.Build.VERSION.SDK_INT >= 26) {
  179. VibrationEffect ve = VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE);
  180. vibrator.vibrate(ve);
  181. } else {
  182. vibrator.vibrate(duration);
  183. }
  184. }
  185. }
  186. @Keep
  187. public boolean hasBackgroundMusic() {
  188. AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  189. return audioManager.isMusicActive();
  190. }
  191. @Keep
  192. public String[] buildFileTree() {
  193. // Map key is path, value is directory flag
  194. HashMap<String, Boolean> map = buildFileTree(getAssets(), "", new HashMap<>());
  195. ArrayList<String> result = new ArrayList<>();
  196. for (Map.Entry<String, Boolean> data : map.entrySet()) {
  197. result.add((data.getValue() ? "d" : "f") + data.getKey());
  198. }
  199. String[] r = new String[result.size()];
  200. result.toArray(r);
  201. return r;
  202. }
  203. @Keep
  204. public float getDPIScale() {
  205. DisplayMetrics metrics = getResources().getDisplayMetrics();
  206. return metrics.density;
  207. }
  208. @Keep
  209. public Rect getSafeArea() {
  210. Rect rect = null;
  211. if (android.os.Build.VERSION.SDK_INT >= 28) {
  212. DisplayCutout cutout = getWindow().getDecorView().getRootWindowInsets().getDisplayCutout();
  213. if (cutout != null) {
  214. rect = new Rect();
  215. rect.set(
  216. cutout.getSafeInsetLeft(),
  217. cutout.getSafeInsetTop(),
  218. cutout.getSafeInsetRight(),
  219. cutout.getSafeInsetBottom()
  220. );
  221. }
  222. }
  223. return rect;
  224. }
  225. @Keep
  226. public String getCRequirePath() {
  227. ApplicationInfo applicationInfo = getApplicationInfo();
  228. if (isNativeLibsExtracted()) {
  229. return applicationInfo.nativeLibraryDir + "/?.so";
  230. } else {
  231. // The native libs are inside the APK and can be loaded directly.
  232. // FIXME: What about split APKs?
  233. String abi = android.os.Build.SUPPORTED_ABIS[0];
  234. return applicationInfo.sourceDir + "!/lib/" + abi + "/?.so";
  235. }
  236. }
  237. @Keep
  238. public void setImmersiveMode(boolean enable) {
  239. if (android.os.Build.VERSION.SDK_INT >= 28) {
  240. WindowManager.LayoutParams attr = getWindow().getAttributes();
  241. if (enable) {
  242. attr.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
  243. } else {
  244. attr.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
  245. }
  246. }
  247. shortEdgesMode = enable;
  248. }
  249. @Keep
  250. public boolean getImmersiveMode() {
  251. return shortEdgesMode;
  252. }
  253. @Keep
  254. public boolean hasRecordAudioPermission() {
  255. return ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
  256. }
  257. @Keep
  258. public void requestRecordAudioPermission() {
  259. if (ActivityCompat.checkSelfPermission(this,
  260. Manifest.permission.RECORD_AUDIO)
  261. == PackageManager.PERMISSION_GRANTED) {
  262. return;
  263. }
  264. Log.d("GameActivity", "Requesting mic permission and locking LÖVE thread until we have an answer.");
  265. ActivityCompat.requestPermissions(this,
  266. new String[]{Manifest.permission.RECORD_AUDIO},
  267. RECORD_AUDIO_REQUEST_CODE);
  268. synchronized (recordAudioRequestDummy) {
  269. try {
  270. recordAudioRequestDummy.wait();
  271. } catch (InterruptedException e) {
  272. Log.d("GameActivity", "requesting mic permission", e);
  273. }
  274. }
  275. }
  276. @Keep
  277. public int convertToFileDescriptor(String uri) {
  278. return convertToFileDescriptor(Uri.parse(uri));
  279. }
  280. public int getAudioSMP() {
  281. int smp = 256;
  282. AudioManager a = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  283. if (a != null) {
  284. int b = Integer.parseInt(a.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
  285. smp = b > 0 ? b : smp;
  286. }
  287. return smp;
  288. }
  289. public int getAudioFreq() {
  290. int freq = 44100;
  291. AudioManager a = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
  292. if (a != null) {
  293. int b = Integer.parseInt(a.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
  294. freq = b > 0 ? b : freq;
  295. }
  296. return freq;
  297. }
  298. public boolean isNativeLibsExtracted() {
  299. if (android.os.Build.VERSION.SDK_INT >= 23) {
  300. ApplicationInfo appInfo = getApplicationInfo();
  301. return (appInfo.flags & ApplicationInfo.FLAG_EXTRACT_NATIVE_LIBS) != 0;
  302. }
  303. return false;
  304. }
  305. public void sendUriAsDroppedFile(Uri uri) {
  306. SDLActivity.onNativeDropFile(uri.toString());
  307. }
  308. private void handleIntent(Intent intent, boolean onCreate) {
  309. Uri game = intent.getData();
  310. if (game == null) {
  311. return;
  312. }
  313. if (onCreate) {
  314. // Game is not running
  315. if (isFused) {
  316. // Send it as dropped file later
  317. delayedUri = game;
  318. } else {
  319. // Process for arguments
  320. processOpenGame(game);
  321. }
  322. } else {
  323. // Game is already running. Send it as dropped file.
  324. sendUriAsDroppedFile(game);
  325. }
  326. }
  327. private HashMap<String, Boolean> buildFileTree(AssetManager assetManager, String dir, HashMap<String, Boolean> map) {
  328. String strippedDir = dir.endsWith("/") ? dir.substring(0, dir.length() - 1) : dir;
  329. // Try open dir
  330. try {
  331. InputStream test = assetManager.open(strippedDir);
  332. // It's a file
  333. test.close();
  334. map.put(strippedDir, false);
  335. } catch (FileNotFoundException e) {
  336. // It's a directory
  337. String[] list = null;
  338. // List files
  339. try {
  340. list = assetManager.list(strippedDir);
  341. } catch (IOException e2) {
  342. Log.e(TAG, strippedDir, e2);
  343. }
  344. // Mark as file
  345. map.put(dir, true);
  346. if (!strippedDir.equals(dir)) {
  347. map.put(strippedDir, true);
  348. }
  349. if (list != null) {
  350. for (String path : list) {
  351. buildFileTree(assetManager, dir + path + "/", map);
  352. }
  353. }
  354. } catch (IOException e) {
  355. Log.e(TAG, dir, e);
  356. }
  357. return map;
  358. }
  359. private int convertToFileDescriptor(Uri uri) {
  360. int fd = -1;
  361. try {
  362. ParcelFileDescriptor pfd = getContentResolver().openFileDescriptor(uri, "r");
  363. if (pfd == null) {
  364. throw new RuntimeException("pfd is null");
  365. }
  366. fd = pfd.dup().detachFd();
  367. pfd.close();
  368. } catch (Exception e) {
  369. Log.e(TAG, "Failed attempt to convert " + uri.toString() + " to file descriptor", e);
  370. }
  371. return fd;
  372. }
  373. private void processOpenGame(Uri game) {
  374. String scheme = game.getScheme();
  375. String path = game.getPath();
  376. if (scheme != null) {
  377. if (scheme.equals("content")) {
  378. // Convert the URI to file descriptor.
  379. args = new String[]{"love2d://fd/" + convertToFileDescriptor(game)};
  380. } else if (scheme.equals("file")) {
  381. // Regular file, pass as-is.
  382. args = new String[]{path};
  383. }
  384. }
  385. }
  386. }