forked from libretro/RetroArch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRetroActivityCommon.java
More file actions
805 lines (673 loc) · 26.5 KB
/
RetroActivityCommon.java
File metadata and controls
805 lines (673 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
/* RetroArch - A frontend for libretro.
* Copyright (C) 2026 - Adam "TideGear" Milecki
*
* RetroArch is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.retroarch.browser.retroactivity;
import com.retroarch.BuildConfig;
import com.retroarch.browser.preferences.util.UserPreferences;
import com.retroarch.playcore.PlayCoreManager;
import android.annotation.TargetApi;
import android.app.NativeActivity;
import android.content.res.Configuration;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.system.Os;
import android.view.accessibility.AccessibilityManager;
import android.view.HapticFeedbackConstants;
import android.view.InputDevice;
import android.view.Surface;
import android.view.WindowManager;
import android.app.UiModeManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.PowerManager;
import android.os.CombinedVibration;
import android.os.Vibrator;
import android.os.VibrationEffect;
import android.os.VibratorManager;
import android.util.Log;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.Locale;
/**
* Class which provides common methods for RetroActivity related classes.
*/
public class RetroActivityCommon extends NativeActivity
{
static {
System.loadLibrary("retroarch-activity");
}
public static final int FRONTEND_POWERSTATE_NONE = 0;
public static final int FRONTEND_POWERSTATE_NO_SOURCE = 1;
public static final int FRONTEND_POWERSTATE_CHARGING = 2;
public static final int FRONTEND_POWERSTATE_CHARGED = 3;
public static final int FRONTEND_POWERSTATE_ON_POWER_SOURCE = 4;
public static final int FRONTEND_ORIENTATION_0 = 0;
public static final int FRONTEND_ORIENTATION_90 = 1;
public static final int FRONTEND_ORIENTATION_180 = 2;
public static final int FRONTEND_ORIENTATION_270 = 3;
public static final int RETRO_RUMBLE_STRONG = 0;
public static final int RETRO_RUMBLE_WEAK = 1;
public static final int REQUEST_CODE_OPEN_DOCUMENT_TREE = 0;
public boolean sustainedPerformanceMode = true;
public int screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
@Override
protected void onCreate(Bundle savedInstanceState) {
cleanupSymlinks();
updateSymlinks();
PlayCoreManager.getInstance().onCreate(this);
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
PlayCoreManager.getInstance().onDestroy();
super.onDestroy();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (intent == null)
return;
switch (requestCode)
{
case REQUEST_CODE_OPEN_DOCUMENT_TREE:
{
Uri uri = intent.getData();
if (uri == null)
break;
if (Build.VERSION.SDK_INT >= 19)
getContentResolver().takePersistableUriPermission(uri, intent.getFlags() & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
safTreeAdded(uri.toString());
}
break;
default:
break;
}
}
public void requestOpenDocumentTree()
{
startActivityForResult(new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE), REQUEST_CODE_OPEN_DOCUMENT_TREE);
}
public void doVibrate(int id, int effect, int strength, int oneShot)
{
Vibrator vibrator = null;
int repeat = 0;
long[] pattern = {0, 16};
int[] strengths = {0, strength};
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
if (id == -1)
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
else
{
InputDevice dev = InputDevice.getDevice(id);
if (dev != null)
vibrator = dev.getVibrator();
}
}
if (vibrator == null)
return;
if (strength == 0) {
vibrator.cancel();
return;
}
if (oneShot > 0)
repeat = -1;
else
pattern[1] = 1000;
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if (id >= 0)
Log.i("RetroActivity", "Vibrate id " + id + ": strength " + strength);
vibrator.vibrate(VibrationEffect.createWaveform(pattern, strengths, repeat), new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_GAME).setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION).build());
}else{
vibrator.vibrate(pattern, repeat);
}
}
/**
* Vibrates a controller's motors independently for dual-rumble gamepads.
*
* On Android 12+ (API 31) this uses VibratorManager to address each
* controller motor separately, preserving the RETRO_RUMBLE_STRONG /
* RETRO_RUMBLE_WEAK distinction that the legacy single-vibrator path lost
* by OR-merging both channels into one amplitude value.
*
* Falls back to doVibrate (single-vibrator) on Android < 12 or when the
* controller does not expose multiple vibrators.
*
* @param id InputDevice ID of the controller
* @param strongStrength Large / low-frequency motor amplitude (0–255)
* @param weakStrength Small / high-frequency motor amplitude (0–255)
* @param unused Reserved; always pass 0
*/
public void doVibrateJoypad(int id, int strongStrength, int weakStrength, int unused)
{
/* Android 12+ (API 31): attempt the multi-vibrator path. */
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
{
if (doVibrateJoypadApi31(id, strongStrength, weakStrength))
return;
}
/* Fallback for Android < 12 or when VibratorManager cannot be used:
* drive the single vibrator with the stronger channel value so the
* controller still rumbles rather than staying silent. */
int fallbackStrength = Math.max(strongStrength, weakStrength);
doVibrate(id, RETRO_RUMBLE_STRONG, fallbackStrength, 0);
}
/**
* Inner implementation of doVibrateJoypad for Android 12+ (API 31).
*
* Uses InputDevice.getVibratorManager() to enumerate the controller's
* vibrator IDs and drive them independently via CombinedVibration so each
* motor receives its own amplitude.
*
* The mapping assumes vibratorIds[0] is the large / low-frequency
* (strong) motor and vibratorIds[1] is the small / high-frequency (weak)
* motor. This ordering has been observed consistently for DualShock 4,
* DualSense, and Xbox controllers on Android 12+, but is NOT guaranteed
* by the Android API — treat this as a best-effort heuristic and code
* defensively.
*
* @return true if vibration was handled, false to trigger fallback
*/
@TargetApi(Build.VERSION_CODES.S)
private boolean doVibrateJoypadApi31(int id, int strongStrength, int weakStrength)
{
InputDevice dev = InputDevice.getDevice(id);
if (dev == null)
return false;
VibratorManager vm = dev.getVibratorManager();
int[] vibratorIds = vm.getVibratorIds();
if (vibratorIds.length == 0)
return false;
if (vibratorIds.length == 1)
{
/* Single-motor controller: use the stronger channel value so the
* controller still rumbles rather than going silent. */
int singleStrength = Math.max(strongStrength, weakStrength);
Vibrator singleVibrator = vm.getVibrator(vibratorIds[0]);
if (singleStrength == 0)
{
singleVibrator.cancel();
return true;
}
long[] timings = {0, 1000};
int[] amps = {0, singleStrength};
singleVibrator.vibrate(
VibrationEffect.createWaveform(timings, amps, 0),
new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build());
return true;
}
/* Dual-motor (or more) path: cancel cleanly when both are zero. */
if (strongStrength == 0 && weakStrength == 0)
{
vm.cancel();
return true;
}
/* Drive both motors with independent looping waveforms. */
long[] timings = {0, 1000};
VibrationEffect strongEffect = VibrationEffect.createWaveform(
timings, new int[]{0, strongStrength}, 0);
VibrationEffect weakEffect = VibrationEffect.createWaveform(
timings, new int[]{0, weakStrength}, 0);
CombinedVibration combined = CombinedVibration.startParallel()
.addVibrator(vibratorIds[0], strongEffect)
.addVibrator(vibratorIds[1], weakEffect)
.combine();
vm.vibrate(combined);
Log.i("RetroActivity", "doVibrateJoypad id=" + id
+ " strong=" + strongStrength + " weak=" + weakStrength
+ " vibrators=" + vibratorIds.length);
return true;
}
public void doHapticFeedback(int effect)
{
getWindow().getDecorView().performHapticFeedback(effect,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING | HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING);
Log.i("RetroActivity", "Haptic Feedback effect " + effect);
}
// Exiting cleanly from NDK seems to be nearly impossible.
// Have to use exit(0) to avoid weird things happening, even with runOnUiThread() approaches.
// Use a separate JNI function to explicitly trigger the readback.
public void onRetroArchExit()
{
finish();
}
public int getVolumeCount()
{
int ret = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
StorageManager storageManager = (StorageManager) getApplicationContext().getSystemService(Context.STORAGE_SERVICE);
List<StorageVolume> storageVolumeList = storageManager.getStorageVolumes();
for (int i = 0; i < storageVolumeList.size(); i++) {
ret++;
}
Log.i("RetroActivity", "volume count: " + ret);
}
return (int)ret;
}
public String getVolumePath(String input)
{
String ret = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
int index = Integer.valueOf(input);
int j = 0;
StorageManager storageManager = (StorageManager) getApplicationContext().getSystemService(Context.STORAGE_SERVICE);
List<StorageVolume> storageVolumeList = storageManager.getStorageVolumes();
for (int i = 0; i < storageVolumeList.size(); i++) {
if (i == j) {
ret = String.valueOf(storageVolumeList.get(index).getDirectory());
}
}
Log.i("RetroActivity", "volume path: " + ret);
}
return ret;
}
public String[] getPersistedSafTrees()
{
if (Build.VERSION.SDK_INT >= 19)
{
List<android.content.UriPermission> uriPermissions = getContentResolver().getPersistedUriPermissions();
List<String> trees = new ArrayList<>();
for (android.content.UriPermission uriPermission : uriPermissions)
{
Uri uri = uriPermission.getUri();
if (uri != null)
trees.add(uri.toString());
}
return trees.toArray(new String[0]);
}
else
return new String[0];
}
// https://stackoverflow.com/questions/4553650/how-to-check-device-natural-default-orientation-on-android-i-e-get-landscape/4555528#4555528
public int getDeviceDefaultOrientation() {
WindowManager windowManager = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
Configuration config = getResources().getConfiguration();
int rotation = windowManager.getDefaultDisplay().getRotation();
if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&
config.orientation == Configuration.ORIENTATION_LANDSCAPE)
|| ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&
config.orientation == Configuration.ORIENTATION_PORTRAIT))
{
return Configuration.ORIENTATION_LANDSCAPE;
}else{
return Configuration.ORIENTATION_PORTRAIT;
}
}
public void setScreenOrientation(int orientation)
{
int naturalOrientation = getDeviceDefaultOrientation();
int newOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
// We assume no device has a natural orientation that is reversed
switch (naturalOrientation) {
case Configuration.ORIENTATION_PORTRAIT:
{
if (orientation == FRONTEND_ORIENTATION_0) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}else if (orientation == FRONTEND_ORIENTATION_90) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
}else if (orientation == FRONTEND_ORIENTATION_180) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}else if (orientation == FRONTEND_ORIENTATION_270) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
break;
}
case Configuration.ORIENTATION_LANDSCAPE:
{
if (orientation == FRONTEND_ORIENTATION_0) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
}else if (orientation == FRONTEND_ORIENTATION_90) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}else if (orientation == FRONTEND_ORIENTATION_180) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}else if (orientation == FRONTEND_ORIENTATION_270) {
newOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}
break;
}
}
screenOrientation = newOrientation;
Log.i("RetroActivity", "setting new orientation to " + screenOrientation);
runOnUiThread(new Runnable() {
@Override
public void run() {
setRequestedOrientation(screenOrientation);
}
});
}
public String getUserLanguageString()
{
String lang = Locale.getDefault().getLanguage();
String country = Locale.getDefault().getCountry();
if (lang.length() == 0)
return "en";
if (country.length() == 0)
return lang;
return lang + '_' + country;
}
@TargetApi(24)
public void setSustainedPerformanceMode(boolean on)
{
sustainedPerformanceMode = on;
if (Build.VERSION.SDK_INT >= 24) {
if (isSustainedPerformanceModeSupported()) {
final CountDownLatch latch = new CountDownLatch(1);
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("RetroActivity", "setting sustained performance mode to " + sustainedPerformanceMode);
getWindow().setSustainedPerformanceMode(sustainedPerformanceMode);
latch.countDown();
}
});
try {
latch.await();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
@TargetApi(24)
public boolean isSustainedPerformanceModeSupported()
{
boolean supported = false;
if (Build.VERSION.SDK_INT >= 24)
{
PowerManager powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
if (powerManager.isSustainedPerformanceModeSupported())
supported = true;
}
Log.i("RetroActivity", "isSustainedPerformanceModeSupported? " + supported);
return supported;
}
public int getBatteryLevel()
{
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
// This doesn't actually register anything (or need to) because we know this particular intent is sticky and we do not specify a BroadcastReceiver anyway
Intent batteryStatus = registerReceiver(null, ifilter);
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
float percent = ((float)level / (float)scale) * 100.0f;
Log.i("RetroActivity", "battery: level = " + level + ", scale = " + scale + ", percent = " + percent);
return (int)percent;
}
public int getPowerstate()
{
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
// This doesn't actually register anything (or need to) because we know this particular intent is sticky and we do not specify a BroadcastReceiver anyway
Intent batteryStatus = registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean hasBattery = batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false);
boolean isCharging = (status == BatteryManager.BATTERY_STATUS_CHARGING);
boolean isCharged = (status == BatteryManager.BATTERY_STATUS_FULL);
int powerstate = FRONTEND_POWERSTATE_NONE;
if (isCharged)
powerstate = FRONTEND_POWERSTATE_CHARGED;
else if (isCharging)
powerstate = FRONTEND_POWERSTATE_CHARGING;
else if (!hasBattery)
powerstate = FRONTEND_POWERSTATE_NO_SOURCE;
else
powerstate = FRONTEND_POWERSTATE_ON_POWER_SOURCE;
Log.i("RetroActivity", "power state = " + powerstate);
return powerstate;
}
public boolean isAndroidTV()
{
Configuration config = getResources().getConfiguration();
UiModeManager uiModeManager = (UiModeManager)getSystemService(UI_MODE_SERVICE);
if (uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION)
{
Log.i("RetroActivity", "isAndroidTV == true");
return true;
}
else
{
Log.i("RetroActivity", "isAndroidTV == false");
return false;
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
int oldOrientation = 0;
boolean hasOldOrientation = false;
super.onConfigurationChanged(newConfig);
Log.i("RetroActivity", "onConfigurationChanged: orientation is now " + newConfig.orientation);
SharedPreferences prefs = UserPreferences.getPreferences(this);
SharedPreferences.Editor edit = prefs.edit();
hasOldOrientation = prefs.contains("ORIENTATION");
if (hasOldOrientation)
oldOrientation = prefs.getInt("ORIENTATION", 0);
edit.putInt("ORIENTATION", newConfig.orientation);
edit.apply();
Log.i("RetroActivity", "hasOldOrientation? " + hasOldOrientation + " newOrientation: " + newConfig.orientation + " oldOrientation: " + oldOrientation);
}
/**
* Checks if this version of RetroArch is a Play Store build.
*
* @return true if this is a Play Store build, false otherwise
*/
public boolean isPlayStoreBuild() {
Log.i("RetroActivity", "isPlayStoreBuild: " + BuildConfig.PLAY_STORE_BUILD);
return BuildConfig.PLAY_STORE_BUILD;
}
/**
* Gets the list of available cores that can be downloaded as Dynamic Feature Modules.
*
* @return the list of available cores
*/
public String[] getAvailableCores() {
int id = getResources().getIdentifier("module_names_" + Build.CPU_ABI.replace('-', '_'), "array", getPackageName());
String[] returnVal = getResources().getStringArray(id);
Log.i("RetroActivity", "getAvailableCores: " + Arrays.toString(returnVal));
return returnVal;
}
/**
* Gets the list of cores that are currently installed as Dynamic Feature Modules.
*
* @return the list of installed cores
*/
public String[] getInstalledCores() {
String[] modules = PlayCoreManager.getInstance().getInstalledModules();
List<String> cores = new ArrayList<>();
List<String> availableCores = Arrays.asList(getAvailableCores());
SharedPreferences prefs = UserPreferences.getPreferences(this);
for(int i = 0; i < modules.length; i++) {
String coreName = unsanitizeCoreName(modules[i]);
if(!prefs.getBoolean("core_deleted_" + coreName, false)
&& availableCores.contains(coreName)) {
cores.add(coreName);
}
}
String[] returnVal = cores.toArray(new String[0]);
Log.i("RetroActivity", "getInstalledCores: " + Arrays.toString(returnVal));
return returnVal;
}
/**
* Asks the system to download a core.
*
* @param coreName Name of the core to install
*/
public void downloadCore(final String coreName) {
Log.i("RetroActivity", "downloadCore: " + coreName);
SharedPreferences prefs = UserPreferences.getPreferences(this);
prefs.edit().remove("core_deleted_" + coreName).apply();
PlayCoreManager.getInstance().downloadCore(coreName);
}
/**
* Asks the system to delete a core.
*
* Note that the actual module deletion will not happen immediately (the OS will delete
* it whenever it feels like it), but the symlink will still be immediately removed.
*
* @param coreName Name of the core to delete
*/
public void deleteCore(String coreName) {
Log.i("RetroActivity", "deleteCore: " + coreName);
String newFilename = getCorePath() + coreName + "_libretro_android.so";
new File(newFilename).delete();
SharedPreferences prefs = UserPreferences.getPreferences(this);
prefs.edit().putBoolean("core_deleted_" + coreName, true).apply();
PlayCoreManager.getInstance().deleteCore(coreName);
}
/////////////// JNI methods ///////////////
/**
* Called when a core install is initiated.
*
* @param coreName Name of the core that the install is initiated for.
* @param successful true if success, false if failure
*/
public native void coreInstallInitiated(String coreName, boolean successful);
/**
* Called when the status of a core install has changed.
*
* @param coreNames Names of all cores that are currently being downloaded.
* @param status One of INSTALL_STATUS_DOWNLOADING, INSTALL_STATUS_INSTALLING,
* INSTALL_STATUS_INSTALLED, or INSTALL_STATUS_FAILED
* @param bytesDownloaded Number of bytes downloaded.
* @param totalBytesToDownload Total number of bytes to download.
*/
public native void coreInstallStatusChanged(String[] coreNames, int status, long bytesDownloaded, long totalBytesToDownload);
/**
* Called when the user grants access to a Storage Access Framework tree.
*/
public native void safTreeAdded(String tree);
/////////////// Private methods ///////////////
/**
* Sanitizes a core name so that it can be used when dealing with
* Dynamic Feature Modules. Needed because Gradle modules cannot use
* dashes, but we have at least one core name ("mesen-s") that uses them.
*
* @param coreName Name of the core to sanitize.
* @return The sanitized core name.
*/
public String sanitizeCoreName(String coreName) {
return "core_" + coreName.replace('-', '_');
}
/**
* Unsanitizes a core name from its module name.
*
* @param coreName Name of the core to unsanitize.
* @return The unsanitized core name.
*/
public String unsanitizeCoreName(String coreName) {
if(coreName.equals("core_mesen_s")) {
return "mesen-s";
}
return coreName.substring(5);
}
/**
* Gets the path to the RetroArch cores directory.
*
* @return The path to the RetroArch cores directory
*/
private String getCorePath() {
String path = getApplicationInfo().dataDir + "/cores/";
new File(path).mkdirs();
return path;
}
/**
* Cleans up existing symlinks before new ones are created.
*/
private void cleanupSymlinks() {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return;
File[] files = new File(getCorePath()).listFiles();
for(int i = 0; i < files.length; i++) {
try {
Os.readlink(files[i].getAbsolutePath());
files[i].delete();
} catch (Exception e) {
// File is not a symlink, so don't delete.
}
}
}
/**
* Triggers a symlink update in the known places that Dynamic Feature Modules
* are installed to.
*/
public void updateSymlinks() {
if(!isPlayStoreBuild()) return;
traverseFilesystem(getFilesDir());
traverseFilesystem(new File(getApplicationInfo().nativeLibraryDir));
}
/**
* Traverse the filesystem, looking for native libraries.
* Symlinks any libraries it finds to the main RetroArch "cores" folder,
* updating any existing symlinks with the correct path to the native libraries.
*
* This is necessary because Dynamic Feature Modules are first downloaded
* and installed to a temporary location on disk, before being moved
* to a more permanent location by the system at a later point.
*
* This could probably be done in native code instead, if that's preferred.
*
* @param file The parent directory of the tree to traverse.
* @param cores List of cores to update.
* @param filenames List of filenames to update.
*/
private void traverseFilesystem(File file) {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return;
File[] list = file.listFiles();
if(list == null) return;
List<String> availableCores = Arrays.asList(getAvailableCores());
// Check each file in a directory to see if it's a native library.
for(int i = 0; i < list.length; i++) {
File child = list[i];
String name = child.getName();
if(name.startsWith("lib") && name.endsWith(".so") && !name.contains("retroarch-activity")) {
// Found a native library!
String core = name.subSequence(3, name.length() - 3).toString();
String filename = child.getAbsolutePath();
SharedPreferences prefs = UserPreferences.getPreferences(this);
if(!prefs.getBoolean("core_deleted_" + core, false)
&& availableCores.contains(core)) {
// Generate the destination filename and delete any existing symlinks / cores
String newFilename = getCorePath() + core + "_libretro_android.so";
new File(newFilename).delete();
try {
Os.symlink(filename, newFilename);
} catch (Exception e) {
// Symlink failed to be created. Should never happen.
}
}
} else if(file.isDirectory()) {
// Found another directory, so traverse it
traverseFilesystem(child);
}
}
}
public boolean isScreenReaderEnabled() {
AccessibilityManager accessibilityManager = (AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE);
boolean isAccessibilityEnabled = accessibilityManager.isEnabled();
boolean isExploreByTouchEnabled = accessibilityManager.isTouchExplorationEnabled();
return isAccessibilityEnabled && isExploreByTouchEnabled;
}
public void accessibilitySpeak(String message) {
getWindow().getDecorView().announceForAccessibility(message);
}
}