forked from PojavLauncherTeam/PojavLauncher
-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathTools.java
More file actions
1922 lines (1723 loc) · 91.1 KB
/
Copy pathTools.java
File metadata and controls
1922 lines (1723 loc) · 91.1 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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package net.kdt.pojavlaunch;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.P;
import static net.kdt.pojavlaunch.Architecture.archAsStringAndroid;
import static net.kdt.pojavlaunch.Architecture.getDeviceArchitecture;
import static net.kdt.pojavlaunch.PojavApplication.sExecutorService;
import static net.kdt.pojavlaunch.PojavProfile.getAllProfiles;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_IGNORE_NOTCH;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_NOTCH_SIZE;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.InputDevice;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask;
import net.kdt.pojavlaunch.lifecycle.LifecycleAwareAlertDialog;
import net.kdt.pojavlaunch.memory.MemoryHoleFinder;
import net.kdt.pojavlaunch.memory.SelfMapsParser;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.multirt.Runtime;
import net.kdt.pojavlaunch.plugins.FFmpegPlugin;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
import net.kdt.pojavlaunch.utils.DateUtils;
import net.kdt.pojavlaunch.utils.DownloadUtils;
import net.kdt.pojavlaunch.utils.FileUtils;
import net.kdt.pojavlaunch.utils.GLInfoUtils;
import net.kdt.pojavlaunch.utils.JREUtils;
import net.kdt.pojavlaunch.utils.JSONUtils;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import net.kdt.pojavlaunch.utils.OldVersionsUtils;
import net.kdt.pojavlaunch.value.DependentLibrary;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import net.kdt.pojavlaunch.value.MinecraftLibraryArtifact;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.IOUtils;
import org.libsdl.app.SDLControllerManager;
import org.lwjgl.glfw.CallbackBridge;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@SuppressWarnings("IOStreamConstructor")
public final class Tools {
public static final float BYTE_TO_MB = 1024 * 1024;
public static final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());
public static String APP_NAME = "Amethyst";
public static final Gson GLOBAL_GSON = new GsonBuilder().setPrettyPrinting().create();
public static final String URL_HOME = "https://wiki.angelauramc.dev";
public static String NATIVE_LIB_DIR;
public static String DIR_DATA; //Initialized later to get context
public static File DIR_CACHE;
public static String MULTIRT_HOME;
public static String LOCAL_RENDERER = null;
public static int DEVICE_ARCHITECTURE;
public static final String LAUNCHERPROFILES_RTPREFIX = "amethyst://";
// New since 3.3.1
public static String DIR_ACCOUNT_NEW;
public static String DIR_GAME_HOME = Environment.getExternalStorageDirectory().getAbsolutePath() + "/games/Amethyst";
public static String DIR_GAME_NEW;
public static String GAME_PROFILES_FILE;
// New since 3.0.0
public static String DIRNAME_HOME_JRE = "lib";
// New since 2.4.2
public static String DIR_HOME_VERSION;
public static String DIR_HOME_LIBRARY;
public static String DIR_HOME_CRASH;
public static String ASSETS_PATH;
public static String OBSOLETE_RESOURCES_PATH;
public static String CTRLMAP_PATH;
public static String CTRLDEF_FILE;
private static RenderersList sCompatibleRenderers;
public static int iLwjglVersion = 0;
public static String sLwjglVersion = null;
public static String lwjglNativesDir = null;
private static File getPojavStorageRoot(Context ctx) {
if(SDK_INT >= 29) {
return ctx.getExternalFilesDir(null);
}else{
return new File(Environment.getExternalStorageDirectory(),"games/Amethyst");
}
}
/**
* Checks if the Pojav's storage root is accessible and read-writable
* @param context context to get the storage root if it's not set yet
* @return true if storage is fine, false if storage is not accessible
*/
public static boolean checkStorageRoot(Context context) {
File externalFilesDir = DIR_GAME_HOME == null ? Tools.getPojavStorageRoot(context) : new File(DIR_GAME_HOME);
//externalFilesDir == null when the storage is not mounted if it was obtained with the context call
return externalFilesDir != null && Environment.getExternalStorageState(externalFilesDir).equals(Environment.MEDIA_MOUNTED);
}
/**
* Checks if the Pojav's storage root is accessible and read-writable. If it's not, starts
* the MissingStorageActivity and finishes the supplied activity.
* @param context the Activity that checks for storage availability
* @return whether the storage is available or not.
*/
public static boolean checkStorageInteractive(Activity context) {
if(!Tools.checkStorageRoot(context)) {
context.startActivity(new Intent(context, MissingStorageActivity.class));
context.finish();
return false;
}
return true;
}
/**
* Initialize context constants most necessary for launcher's early startup phase
* that are not dependent on user storage.
* All values that depend on DIR_DATA and are not dependent on DIR_GAME_HOME must
* be initialized here.
* @param ctx the context for initialization.
*/
public static void initEarlyConstants(Context ctx) {
DIR_CACHE = ctx.getCacheDir();
DIR_DATA = ctx.getFilesDir().getParent();
MULTIRT_HOME = DIR_DATA + "/runtimes";
DIR_ACCOUNT_NEW = DIR_DATA + "/accounts";
NATIVE_LIB_DIR = ctx.getApplicationInfo().nativeLibraryDir;
}
/**
* Initialize context constants that depend on user storage.
* Any value (in)directly dependent on DIR_GAME_HOME should be set only here.
* You ABSOLUTELY MUST check for storage presence using checkStorageRoot() before calling this.
*/
public static void initStorageConstants(Context ctx){
initEarlyConstants(ctx);
DIR_GAME_HOME = getPojavStorageRoot(ctx).getAbsolutePath();
DIR_GAME_NEW = DIR_GAME_HOME + "/.minecraft";
DIR_HOME_VERSION = DIR_GAME_NEW + "/versions";
DIR_HOME_LIBRARY = DIR_GAME_NEW + "/libraries";
DIR_HOME_CRASH = DIR_GAME_NEW + "/crash-reports";
ASSETS_PATH = DIR_GAME_NEW + "/assets";
OBSOLETE_RESOURCES_PATH = DIR_GAME_NEW + "/resources";
CTRLMAP_PATH = DIR_GAME_HOME + "/controlmap";
CTRLDEF_FILE = DIR_GAME_HOME + "/controlmap/default.json";
GAME_PROFILES_FILE = Tools.DIR_GAME_NEW + "/launcher_profiles.json";
switchDemo(isDemoProfile(ctx));
}
@SuppressLint("PrivateApi")
private static String systemPropertiesGet(String systemProperty) throws NoSuchMethodException, ClassNotFoundException, InvocationTargetException, IllegalAccessException {
Class<?> cSystemProperties = Class.forName("android.os.SystemProperties");
Method get = cSystemProperties.getMethod("get", String.class);
return (String) get.invoke(null, systemProperty);
}
private static boolean isAdreno740(){
try {
BufferedReader br = new BufferedReader(
new FileReader("/sys/class/kgsl/kgsl-3d0/gpu_model")
);
String gpuRenderer = br.readLine();
return gpuRenderer != null &&
gpuRenderer.toLowerCase().contains("adreno") &&
gpuRenderer.contains("740");
} catch (IOException e) {
// If it doesn't exist, we definitely aren't on 740
return false;
}
}
/**
* Detects whether or not you are on OneUI and using Adreno 740
* <a href="https://gitlab.freedesktop.org/mesa/mesa/-/blob/main/src/freedreno/common/freedreno_devices.py?ref_type=heads#L1007-L1009">
* Mesa sets it to 0 by default due to vendor quirks
* </a>
* It is possible that OneUI simply deviates from this commonality, hence why
* <a href="https://github.com/K11MCH1/AdrenoToolsDrivers/releases/tag/v26.0.0-rc07">
* this is a common fix
* </a>
* @return Whether or not to export FD_DEV_FEATURES=enable_ubwc_flag_hint=1
*/
public static boolean shouldUseUBWC() {
try {
boolean isSamsung = Build.MANUFACTURER.equalsIgnoreCase("samsung");
boolean isOneUI = !systemPropertiesGet("ro.build.version.oneui").isBlank();
return isOneUI && isSamsung && isAdreno740();
} catch (Exception e) {
return false;
}
}
/**
* @return The selected "Custom path" of the current profile
*/
@NonNull
private static File getGameDir() {
return getGameDirPath(LauncherProfiles.getCurrentProfile());
}
/**
* Searches for mod in mods directory of current selected profile
* Not case-sensitive
* @param filenames Filename(s) of the .jar mod(s)
* @return Whether or not the .jar is found
*/
public static boolean hasMods(String... filenames) {
File gameDir = getGameDir();
File modsDir = new File(gameDir, "mods");
File[] modFiles = modsDir.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
if (modFiles == null) return false;
for (File file : modFiles) {
for (String filename : filenames)
if (file.getName().toLowerCase().contains(filename.toLowerCase())) return true;
}
return false;
}
/**
* Tries to delete any sodium related mods of the currently selected profile via string matching
* the files in the mods folder.
*/
public static void deleteSodiumMods() {
File modsDir = new File(getGameDir(), "mods");
File[] mods = modsDir.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
if(mods == null) ;
for(File file : mods) {
String name = file.getName().toLowerCase();
if(name.contains("sodium") ||
name.contains("beddium") || // Also covers embeddium
name.contains("rubidium") ||
name.contains("xenon") || // Name conflicts with another mod
name.contains("celeritas") ||
name.contains("relictium") ||
name.contains("vintagium") ||
name.contains("podium") ||
name.contains("indium") ||
name.contains("lazurite") ||
name.contains("iris") ||
name.contains("monocle") ||
name.contains("voxy") ||
name.contains("nvidium") ||
name.contains("chloride") ||
name.contains("bedrodium") ||
name.contains("substrate") || // Name conflicts with another mod
name.contains("blendium") ||
name.contains("ryoamium")
// The name conflicts are for pretty dead mods so we ignore them.
// I doubt they're using some mod with less than 5k downloads with sodium.
) if(!file.delete())
throw new RuntimeException("Failed to delete Sodium and related mods!");
}
}
/**
* Search for TouchController mod to automatically enable TouchController mod support.
*
* @param gameDir current game directory
* @return whether TouchController is found
*/
public static boolean hasTouchController(File gameDir) {
File modsDir = new File(gameDir, "mods");
File[] mods = modsDir.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
if (mods == null) {
return false;
}
for (File file : mods) {
String name = file.getName().toLowerCase(Locale.ROOT);
if (name.contains("touchcontroller")) {
return true;
}
}
return false;
}
/**
* Initialize OpenGL and do checks to see if the GPU of the device is affected by the render
* distance issue.
* Currently only checks whether the user has an Adreno GPU capable of OpenGL ES 3.
* This issue is caused by a very severe limit on the amount of GL buffer names that could be allocated
* by the Adreno properietary GLES driver.
* @return whether the GPU is affected by the Large Thin Wrapper render distance issue on vanilla
*/
private static boolean affectedByRenderDistanceIssue() {
GLInfoUtils.GLInfo info = GLInfoUtils.getGlInfo();
return info.isAdreno() && info.glesMajorVersion >= 3;
}
private static String[] sodiumMods = {"sodium", "embeddium", "rubidium", "xenon"};
private static boolean affectedByLTWRenderDistanceIssue() {
if(!"opengles3_ltw".equals(Tools.LOCAL_RENDERER)) return false;
if(!affectedByRenderDistanceIssue()) return false;
if(hasMods(sodiumMods)) return false;
int renderDistance;
try {
MCOptionUtils.load();
String renderDistanceString = MCOptionUtils.get("renderDistance");
renderDistance = Integer.parseInt(renderDistanceString);
}catch (Exception e) {
Log.e("Tools", "Failed to check render distance", e);
renderDistance = 12; // Assume Minecraft's default render distance
}
// 7 is the render distance "magic number" above which MC creates too many buffers
// for Adreno's OpenGL ES implementation
return renderDistance > 7;
}
public static void launchMinecraft(final AppCompatActivity activity, MinecraftAccount minecraftAccount,
MinecraftProfile minecraftProfile, String versionId, int versionJavaRequirement) throws Throwable {
int freeDeviceMemory = getFreeDeviceMemory(activity);
int localeString;
int freeAddressSpace = Architecture.is32BitsDevice() ? getMaxContinuousAddressSpaceSize() : -1;
Log.i("MemStat", "Free RAM: " + freeDeviceMemory + " Addressable: " + freeAddressSpace);
if(freeDeviceMemory > freeAddressSpace && freeAddressSpace != -1) {
freeDeviceMemory = freeAddressSpace;
localeString = R.string.address_memory_warning_msg;
} else {
localeString = R.string.memory_warning_msg;
}
if(LauncherPreferences.PREF_RAM_ALLOCATION > freeDeviceMemory) {
int finalDeviceMemory = freeDeviceMemory;
LifecycleAwareAlertDialog.DialogCreator dialogCreator = (dialog, builder) ->
builder.setMessage(activity.getString(localeString, finalDeviceMemory, LauncherPreferences.PREF_RAM_ALLOCATION))
.setPositiveButton(android.R.string.ok, (d, w)->{});
if(LifecycleAwareAlertDialog.haltOnDialog(activity.getLifecycle(), activity, dialogCreator)) {
return; // If the dialog's lifecycle has ended, return without
// actually launching the game, thus giving us the opportunity
// to start after the activity is shown again
}
}
LauncherProfiles.load();
File gamedir = Tools.getGameDirPath(minecraftProfile);
startControllableMitigation(activity, gamedir);
startOldLegacy4JMitigation(activity, gamedir);
if(affectedByLTWRenderDistanceIssue()) {
LifecycleAwareAlertDialog.DialogCreator dialogCreator = ((alertDialog, dialogBuilder) ->
dialogBuilder.setMessage(activity.getString(R.string.ltw_render_distance_warning_msg))
.setPositiveButton(android.R.string.ok, (d, w)->{}));
if(LifecycleAwareAlertDialog.haltOnDialog(activity.getLifecycle(), activity, dialogCreator)) {
return;
}
// If the code goes here, it means that the user clicked "OK". Fix the render distance.
try {
MCOptionUtils.set("renderDistance", "7");
MCOptionUtils.save();
}catch (Exception e) {
Log.e("Tools", "Failed to fix render distance setting", e);
}
}
Runtime runtime = MultiRTUtils.forceReread(Tools.pickRuntime(minecraftProfile, versionJavaRequirement));
JMinecraftVersionList.Version versionInfo = Tools.getVersionInfo(versionId);
// Pre-process specific files
disableSplash(gamedir);
String[] launchArgs = getMinecraftClientArgs(minecraftAccount, versionInfo, gamedir);
// Select the appropriate openGL version
OldVersionsUtils.selectOpenGlVersion(versionInfo);
String launchClasspath = generateLaunchClasspath(versionInfo, versionId);
List<String> javaArgList = new ArrayList<>();
getCacioJavaArgs(javaArgList, runtime.javaVersion == 8, activity);
if (versionInfo.logging != null) {
String configFile = Tools.DIR_DATA + "/security/" + versionInfo.logging.client.file.id.replace("client", "log4j-rce-patch");
if (!new File(configFile).exists()) {
configFile = Tools.DIR_GAME_NEW + "/" + versionInfo.logging.client.file.id;
}
javaArgList.add("-Dlog4j.configurationFile=" + configFile);
}
File versionSpecificNativesDir = new File(Tools.DIR_CACHE, "natives/"+versionId);
StringBuilder javaLibraryPath = new StringBuilder();
// Add which lwjgl natives to use into classpath
javaLibraryPath.append(lwjglNativesDir).append(":");
// Add JNA native if needed
javaLibraryPath.append(Tools.NATIVE_LIB_DIR).append(":");
if(versionSpecificNativesDir.exists()) {
String dirPath = versionSpecificNativesDir.getAbsolutePath();
javaLibraryPath.append(dirPath).append(":");
javaArgList.add("-Djna.boot.library.path="+dirPath);
}
javaArgList.add("-Djava.library.path="+javaLibraryPath);
javaArgList.addAll(Arrays.asList(getMinecraftJVMArgs(versionId, gamedir)));
javaArgList.add("-cp"); javaArgList.add(launchClasspath);
// Some modloaders (babric) don't fully respect java.libary.path and only use the native lib dir
// This arg makes them use it. LWJGL prioritizes this path during native loading as well.
javaArgList.add("-Dorg.lwjgl.librarypath="+lwjglNativesDir);
// Forge 1.6.4 crash mitigation
// https://github.com/MinecraftForge/FML/blob/f1b3381e61fac1a0ae90f521223c6bc613eb4888/common/cpw/mods/fml/common/asm/FMLSanityChecker.java#L192-L208
// It for some reason fails certification and crashes because it thinks Minecraft is corrupted.
// This also has no loading screen as a result.
javaArgList.add("-Dfml.ignoreInvalidMinecraftCertificates=true");
// imgui-java set library name to use. This because Axiom uses a fork with different library naming
// logic that doesn't seem to appear in the main repository. I'm not gonna work with that.
javaArgList.add("-Dimgui.library.name=imgui-java");
// We use an abomination to support all DH versions with a single library.
javaArgList.add("-DZstdNativePath="+Tools.NATIVE_LIB_DIR+"/libzstd-jni-1.5.7-6-dhcompat.so");
// We only ever reach this point when user has already used the force run switch
boolean hasSodiumMod = false;
for (String modName : sodiumMods) {
if (hasMods(sodiumMods)) {
hasSodiumMod = true;
File mixinPropertiesConfigFile = new File(getGameDir(), "config/" + modName + "-mixins.properties");
// Write mixin configs to somewhat help stability. We don't want more people complaining.
String[] propertiesToAdd = {
"mixin.features.buffer_builder.intrinsics=false",
"mixin.features.chunk_rendering=false"
};
List<String> mixinPropertiesConfigStrings = null;
try {
mixinPropertiesConfigStrings = org.apache.commons.io.FileUtils.readLines(mixinPropertiesConfigFile, "UTF-8");
} catch (IOException ignored) {}
if (mixinPropertiesConfigStrings == null) {
mixinPropertiesConfigStrings = new ArrayList<>();
}
for (String newLine : propertiesToAdd) {
if (!mixinPropertiesConfigStrings.contains(newLine)) {
mixinPropertiesConfigStrings.add(newLine);
}
}
try {
org.apache.commons.io.FileUtils.writeLines(mixinPropertiesConfigFile, mixinPropertiesConfigStrings);
} catch (IOException ignored) {} // If we can't write it, we tried our best.
}
}
// We use a janky lwjgl setup. We don't want more people complaining it crashes.
if (hasSodiumMod) javaArgList.add("-Dsodium.checks.issue2561=false");
javaArgList.add(versionInfo.mainClass);
javaArgList.addAll(Arrays.asList(launchArgs));
// ctx.appendlnToLog("full args: "+javaArgList.toString());
String args = LauncherPreferences.PREF_CUSTOM_JAVA_ARGS;
if(Tools.isValidString(minecraftProfile.javaArgs)) args = minecraftProfile.javaArgs;
FFmpegPlugin.discover(activity);
JREUtils.launchJavaVM(activity, runtime, gamedir, javaArgList, args);
// If we returned, this means that the JVM exit dialog has been shown and we don't need to be active anymore.
// We never return otherwise. The process will be killed anyway, and thus we will become inactive
}
private static Logger.eventLogListener controllableMitigationLogListener;
/*
* This is does not work when debugging. This is not reliable.
* This is a monstrosity that races the mod, trying to ensure that when the folder is checked
* after extraction but before dlopen, it is empty, so it loads the bundled SDL2 we have instead
*/
private static void startControllableMitigation(Activity activity ,File gamedir) {
String TAG = "ControllableMitigation";
File deleted = new File(gamedir + "/controllable_natives/SDL");
boolean hasControllable = false;
File modsDir = new File(gamedir, "mods");
File[] mods = modsDir.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
if (mods != null) {
for (File file : mods) {
String name = file.getName();
if (name.contains("controllable")) {
hasControllable = true;
break;
}
}
}
if (hasControllable) {
Tools.runOnUiThread(() -> {
Tools.dialog(activity, activity.getString(R.string.global_warning), activity.getString(R.string.controllableFound));
});
Thread mitigationThread = new Thread(() -> {
// This is total garbage but it seems to be the best jank for the job
Log.i(TAG, "Controllable detected! Starting mitigation thread");
try {org.apache.commons.io.FileUtils.deleteDirectory(deleted);} catch (IOException ignored) {}
while (!Thread.currentThread().isInterrupted()) {
// Looks for controllable_natives/SDL/<sdl_version_number>/libSDL2.so and
// deletes it. We can assume array index 0 because this dir gets fully deleted
// before the loop is started.
if (deleted.isDirectory()) {
if (deleted.listFiles().length > 0) {
if (deleted.listFiles()[0].listFiles().length > 0) {
if (deleted.listFiles()[0].listFiles()[0].exists()) {
deleted.listFiles()[0].listFiles()[0].delete();
break;
}
}
}
}
}
// We can end here because SdlNativeLibraryLoader only extracts libSDL2.so once
// If NativeLibrary can't find it in the folder to load() it uses java.library.path
Log.i(TAG, "Success! Ending Controllable crash mitigation..");
});
mitigationThread.start();
controllableMitigationLogListener = loggedLine -> {
// Hard off switch if it somehow didn't delete anything, just in case.
if (loggedLine.contains("Sound engine started") && mitigationThread.isAlive()) {
Log.i(TAG, "Nothing happened. Ending Controllable crash mitigation..");
Logger.removeLogListener(controllableMitigationLogListener);
mitigationThread.interrupt();
}
};
Logger.addLogListener(controllableMitigationLogListener);
}
}
private static Logger.eventLogListener oldL4JMitigationLogListener;
/// TODO: Remove when the time is right
/**
* Legacy4J for a long time had broken SDL detection for android, we need to check and
* accommodate this for now. At least until the broken logic are on versions considered
* obsolete.
* <p>
* This is of course, very jank, it does not work for anything below 1.7.5 but why is anyone
* on that version anyway? Legacy4J has LTS for like all the versions.
*/
private static void startOldLegacy4JMitigation(Activity activity, File gamedir) {
boolean hasLegacy4J = false;
File modsDir = new File(gamedir, "mods");
File[] mods = modsDir.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
if(mods != null) {
for (File file : mods) {
String name = file.getName();
if (name.contains("Legacy4J")) {
hasLegacy4J = true;
break;
}
}
}
if (hasLegacy4J) {
String TAG = "OldLegacy4JMitigation";
Log.i(TAG, "Legacy4J detected!");
oldL4JMitigationLogListener = loggedLine -> {
if (LauncherPreferences.PREF_GAMEPAD_SDL_PASSTHRU && loggedLine.contains("literal{SDL3 (isXander's libsdl4j)} isn't supported in this system. GLFW will be used instead.")) {
Log.i(TAG, "Old version of Legacy4J detected! Force enabling SDL");
Tools.SDL.initializeControllerSubsystems();
Tools.runOnUiThread(() -> {
Tools.dialog(activity, activity.getString(R.string.global_warning), activity.getString(R.string.oldL4JFound));
});
Logger.removeLogListener(oldL4JMitigationLogListener);
} else if (LauncherPreferences.PREF_GAMEPAD_SDL_PASSTHRU && loggedLine.contains("Added SDL Controller Mappings")) {
Log.i(TAG, "Fixed version of Legacy4J detected! Have fun!");
Logger.removeLogListener(oldL4JMitigationLogListener);
}
};
Logger.addLogListener(oldL4JMitigationLogListener);
}
}
public static File getGameDirPath(@NonNull MinecraftProfile minecraftProfile){
if(minecraftProfile.gameDir != null){
if(minecraftProfile.gameDir.startsWith(Tools.LAUNCHERPROFILES_RTPREFIX))
return new File(minecraftProfile.gameDir.replace(Tools.LAUNCHERPROFILES_RTPREFIX,Tools.DIR_GAME_HOME+"/"));
else
return new File(Tools.DIR_GAME_HOME,minecraftProfile.gameDir);
}
return new File(Tools.DIR_GAME_NEW);
}
public static void buildNotificationChannel(Context context){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return;
NotificationChannel channel = new NotificationChannel(
context.getString(R.string.notif_channel_id),
context.getString(R.string.notif_channel_name), NotificationManager.IMPORTANCE_DEFAULT);
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.createNotificationChannel(channel);
}
public static void disableSplash(File dir) {
File configDir = new File(dir, "config");
if(FileUtils.ensureDirectorySilently(configDir)) {
File forgeSplashFile = new File(dir, "config/splash.properties");
String forgeSplashContent = "enabled=true";
try {
if (forgeSplashFile.exists()) {
forgeSplashContent = Tools.read(forgeSplashFile.getAbsolutePath());
}
if (forgeSplashContent.contains("enabled=true")) {
Tools.write(forgeSplashFile.getAbsolutePath(),
forgeSplashContent.replace("enabled=true", "enabled=false"));
}
} catch (IOException e) {
Log.w(Tools.APP_NAME, "Could not disable Forge 1.12.2 and below splash screen!", e);
}
} else {
Log.w(Tools.APP_NAME, "Failed to create the configuration directory");
}
}
public static void getCacioJavaArgs(List<String> javaArgList, boolean isJava8, Activity activity) {
// Caciocavallo config AWT-enabled version
javaArgList.add("-Djava.awt.headless=false");
javaArgList.add("-Dcacio.managed.screensize=" + AWTCanvasView.AWT_CANVAS_WIDTH + "x" + AWTCanvasView.AWT_CANVAS_HEIGHT);
javaArgList.add("-Dcacio.font.fontmanager=sun.awt.X11FontManager");
javaArgList.add("-Dcacio.font.fontscaler=sun.font.FreetypeFontScaler");
javaArgList.add("-Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel");
if (isJava8) {
javaArgList.add("-Dawt.toolkit=net.java.openjdk.cacio.ctc.CTCToolkit");
javaArgList.add("-Djava.awt.graphicsenv=net.java.openjdk.cacio.ctc.CTCGraphicsEnvironment");
} else {
File caciocavavallo17Dir = new File(Tools.DIR_GAME_HOME, "caciocavallo17");
File[] caciocavallo17Jars = caciocavavallo17Dir.listFiles((f, s) ->s.contains("cacio-tta"));
if(caciocavallo17Jars == null || caciocavallo17Jars.length < 1) {
// We wanna avoid the launch being interrupted so we extract again if it isn't found
AsyncAssetManager.unpackComponents(activity);
caciocavallo17Jars = caciocavavallo17Dir.listFiles((f, s) ->s.contains("cacio-tta"));
if(caciocavallo17Jars == null || caciocavallo17Jars.length < 1)
throw new RuntimeException("Failed to extract required assets!");
}
javaArgList.add("-javaagent:"+caciocavallo17Jars[0].getAbsolutePath());
javaArgList.add("-Dawt.toolkit=com.github.caciocavallosilano.cacio.ctc.CTCToolkit");
javaArgList.add("-Djava.awt.graphicsenv=com.github.caciocavallosilano.cacio.ctc.CTCGraphicsEnvironment");
// This approach breaks kilt so we use an agent instead
// javaArgList.add("-Djava.system.class.loader=com.github.caciocavallosilano.cacio.ctc.CTCPreloadClassLoader");
javaArgList.add("--add-exports=java.desktop/java.awt=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/java.awt.peer=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/sun.awt.image=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/sun.java2d=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/java.awt.dnd.peer=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/sun.awt=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/sun.awt.event=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/sun.awt.datatransfer=ALL-UNNAMED");
javaArgList.add("--add-exports=java.desktop/sun.font=ALL-UNNAMED");
javaArgList.add("--add-exports=java.base/sun.security.action=ALL-UNNAMED");
javaArgList.add("--add-opens=java.base/java.util=ALL-UNNAMED");
javaArgList.add("--add-opens=java.desktop/java.awt=ALL-UNNAMED");
javaArgList.add("--add-opens=java.desktop/sun.font=ALL-UNNAMED");
javaArgList.add("--add-opens=java.desktop/sun.java2d=ALL-UNNAMED");
javaArgList.add("--add-opens=java.base/java.lang.reflect=ALL-UNNAMED");
// Opens the java.net package to Arc DNS injector on Java 9+
javaArgList.add("--add-opens=java.base/java.net=ALL-UNNAMED");
}
StringBuilder cacioClasspath = new StringBuilder();
cacioClasspath.append("-Xbootclasspath/").append(isJava8 ? "p" : "a");
File cacioDir = new File(DIR_GAME_HOME + "/caciocavallo" + (isJava8 ? "" : "17"));
File[] cacioFiles = cacioDir.listFiles();
if (cacioFiles != null) {
for (File file : cacioFiles) {
if (file.getName().endsWith(".jar")) {
cacioClasspath.append(":").append(file.getAbsolutePath());
}
}
}
javaArgList.add(cacioClasspath.toString());
}
public static String[] getMinecraftJVMArgs(String versionName, File gameDir) {
JMinecraftVersionList.Version versionInfo = Tools.getVersionInfo(versionName, true);
if (versionInfo.arguments == null || versionInfo.arguments.jvm == null)
return new String[0];
Map<String, String> varArgMap = new ArrayMap<>();
varArgMap.put("classpath_separator", ":");
varArgMap.put("library_directory", DIR_HOME_LIBRARY);
varArgMap.put("version_name", versionInfo.id);
varArgMap.put("natives_directory", Tools.DIR_CACHE.getAbsolutePath());
List<String> minecraftArgs = new ArrayList<>();
for (Object arg : versionInfo.arguments.jvm) {
if (arg instanceof String) {
// These are defined later on
if (((String) arg).contains("java.library.path")) {
continue;
}
if (arg.equals("-cp")) {
continue;
}
if (arg.equals("${classpath}")){
continue;
}
// Should fix Forge 1.17.1-37.0.12 and older from crashing
// Fixed in forge on https://github.com/MinecraftForge/MinecraftForge/pull/7919
// Released as Forge 1.17.1-37.0.13 in https://maven.minecraftforge.net/net/minecraftforge/forge/1.17.1-37.0.13/forge-1.17.1-37.0.13-changelog.txt
// yes this duplicates it, it's fine.
// FIXME: Workaround old bootstraplauncher <0.1.17 buggy behaviour. See FCL workaround
// https://github.com/FCL-Team/FoldCraftLauncher/blob/00e96bcf8ddc8a550e9aba6091a73d5bee973b54/FCLCore/src/main/java/com/tungsten/fclcore/download/MaintainTask.java#L198-L200
if (((String) arg).startsWith("-DignoreList=")){
minecraftArgs.add(arg+",${version_name}.jar");
continue;
}
// TODO: Implement adding launcher brand and version
if (((String) arg).contains("minecraft.launcher.brand") ||
((String) arg).contains("minecraft.launcher.version")) {
continue;
}
minecraftArgs.add((String) arg);
} //TODO: implement (?maybe?)
}
return JSONUtils.insertJSONValueList(minecraftArgs.toArray(new String[0]), varArgMap);
}
public static String[] getMinecraftClientArgs(MinecraftAccount profile, JMinecraftVersionList.Version versionInfo, File gameDir) {
String username = profile.username.replace("Demo.", "");
String versionName = versionInfo.id;
if (versionInfo.inheritsFrom != null) {
versionName = versionInfo.inheritsFrom;
}
String userType = "mojang";
try {
Date creationDate = DateUtils.getOriginalReleaseDate(versionInfo);
// Minecraft 22w43a which adds chat reporting (and signing) was released on
// 26th October 2022. So, if the date is not before that (meaning it is equal or higher)
// change the userType to MSA to fix the missing signature
if(creationDate != null && !DateUtils.dateBefore(creationDate, 2022, 9, 26)) {
userType = "msa";
}
}catch (ParseException e) {
Log.e("CheckForProfileKey", "Failed to determine profile creation date, using \"mojang\"", e);
}
Map<String, String> varArgMap = new ArrayMap<>();
varArgMap.put("auth_session", profile.accessToken); // For legacy versions of MC
varArgMap.put("auth_access_token", profile.accessToken);
varArgMap.put("auth_player_name", username);
varArgMap.put("auth_uuid", profile.profileId.replace("-", ""));
varArgMap.put("auth_xuid", profile.xuid);
varArgMap.put("assets_root", Tools.ASSETS_PATH);
varArgMap.put("assets_index_name", versionInfo.assets);
varArgMap.put("game_assets", Tools.ASSETS_PATH);
varArgMap.put("game_directory", gameDir.getAbsolutePath());
varArgMap.put("user_properties", "{}");
varArgMap.put("user_type", userType);
varArgMap.put("version_name", versionName);
varArgMap.put("version_type", versionInfo.type);
List<String> minecraftArgs = new ArrayList<>();
if (versionInfo.arguments != null) {
// Support Minecraft 1.13+
for (Object arg : versionInfo.arguments.game) {
if (arg instanceof String) {
minecraftArgs.add((String) arg);
} //TODO: implement else clause
}
}
String mcArguments = versionInfo.minecraftArguments == null ?
fromStringArray(minecraftArgs.toArray(new String[0])):
versionInfo.minecraftArguments;
if(profile.isDemo()) mcArguments += " --demo";
return JSONUtils.insertJSONValueList(splitAndFilterEmpty(mcArguments), varArgMap);
}
public static String fromStringArray(String[] strArr) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < strArr.length; i++) {
if (i > 0) builder.append(" ");
builder.append(strArr[i]);
}
return builder.toString();
}
private static String[] splitAndFilterEmpty(String argStr) {
List<String> strList = new ArrayList<>();
for (String arg : argStr.split(" ")) {
if (!arg.isEmpty()) {
strList.add(arg);
}
}
//strList.add("--fullscreen");
return strList.toArray(new String[0]);
}
public static String artifactToPath(DependentLibrary library) {
if (library.downloads != null &&
library.downloads.artifact != null &&
library.downloads.artifact.path != null)
return library.downloads.artifact.path;
String[] libInfos = library.name.split(":");
return libInfos[0].replaceAll("\\.", "/") + "/" + libInfos[1] + "/" + libInfos[2] + "/" + libInfos[1] + "-" + libInfos[2] + (libInfos.length == 4 ? "-" + libInfos[3] : "") + ".jar";
}
private static String getLibClasspath(JMinecraftVersionList.Version info){
StringBuilder libClasspath = new StringBuilder();
String[] classpath = generateLibClasspath(info);
for (String jarFile : classpath) {
libClasspath.append(jarFile).append(":");
}
// Remove the ':' at the end
libClasspath.setLength(libClasspath.length() - 1);
return libClasspath.toString();
}
public static String getClientClasspath(String version) {
return DIR_HOME_VERSION + "/" + version + "/" + version + ".jar";
}
public static String generateLaunchClasspath(JMinecraftVersionList.Version info, String actualname) {
StringBuilder launchClasspath = new StringBuilder(); //versnDir + "/" + version + "/" + version + ".jar:";
String libClasspath = getLibClasspath(info); // Sets lwjglVersion, janky, but we can't get it any simpler
String internalLwjglVersion = iLwjglVersion >= 341 ? "3.4.1" : "3.3.3";
File lwjgl3Folder = new File(Tools.DIR_GAME_HOME, "lwjgl3/"+internalLwjglVersion);
String lwjglCore = lwjgl3Folder.getAbsolutePath() + "/lwjgl.jar";
String lwjglMerged = lwjgl3Folder.getAbsolutePath() + "/lwjgl-"+internalLwjglVersion+"-merged-modules";
String lwjglxFile = lwjgl3Folder + "/lwjgl-lwjglx.jar";
launchClasspath.append(lwjglCore).append(":");
// 2nd in priority in case we need to merge lwjgl.jar again for testing
launchClasspath.append(lwjglMerged).append(":");
File[] lwjglModules = lwjgl3Folder.listFiles(pathname ->
pathname.getName().endsWith(".jar") &&
// Exclude our two special jars which goes first and last
!pathname.getName().equals("lwjgl.jar") &&
!pathname.getName().endsWith("lwjglx.jar"));
if (lwjglModules != null) {
for (File lwjglModule : lwjglModules)
launchClasspath.append(lwjglModule.getAbsolutePath()).append(":");
} else Log.e("generateLaunchClasspath", "lwjgl modules are missing from components!");
launchClasspath.append(libClasspath).append(":");
launchClasspath.append(getClientClasspath(actualname));
// Anything LWJGL2 gets LWJGLX
if (iLwjglVersion <= 299) launchClasspath.append(":").append(lwjglxFile);
return launchClasspath.toString();
}
public static DisplayMetrics getDisplayMetrics(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
if(SDK_INT >= Build.VERSION_CODES.N && (activity.isInMultiWindowMode() || activity.isInPictureInPictureMode())){
//For devices with free form/split screen, we need window size, not screen size.
displayMetrics = activity.getResources().getDisplayMetrics();
}else{
if (SDK_INT >= Build.VERSION_CODES.R) {
activity.getDisplay().getRealMetrics(displayMetrics);
} else { // Removed the clause for devices with unofficial notch support, since it also ruins all devices with virtual nav bars before P
activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
}
if(!PREF_IGNORE_NOTCH){
//Remove notch width when it isn't ignored.
if(activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
displayMetrics.heightPixels -= PREF_NOTCH_SIZE;
else
displayMetrics.widthPixels -= PREF_NOTCH_SIZE;
}
}
currentDisplayMetrics = displayMetrics;
return displayMetrics;
}
public static void setFullscreen(Activity activity, boolean fullscreen) {
final View decorView = activity.getWindow().getDecorView();
View.OnSystemUiVisibilityChangeListener visibilityChangeListener = visibility -> {
boolean multiWindowMode = SDK_INT >= 24 && activity.isInMultiWindowMode();
// When in multi-window mode, asking for fullscreen makes no sense (cause the launcher runs in a window)
// So, ignore the fullscreen setting when activity is in multi window mode
if(fullscreen && !multiWindowMode){
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
}else{
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
};
decorView.setOnSystemUiVisibilityChangeListener(visibilityChangeListener);
visibilityChangeListener.onSystemUiVisibilityChange(decorView.getSystemUiVisibility()); //call it once since the UI state may not change after the call, so the activity wont become fullscreen
}
public static DisplayMetrics currentDisplayMetrics;
public static void updateWindowSize(Activity activity) {
currentDisplayMetrics = getDisplayMetrics(activity);
View dimensionView = activity.findViewById(R.id.dimension_tracker);
if(dimensionView != null) {
int width = dimensionView.getWidth();
int height = dimensionView.getHeight();
if(width != 0 && height != 0) {
Log.i("Tools", "Using dimension_tracker for display dimensions; W="+width+" H="+height);
CallbackBridge.physicalWidth = width;
CallbackBridge.physicalHeight = height;
return;
}else{
Log.e("Tools","Dimension tracker detected but dimensions out of date. Please check usage.", new Exception());
}
}
CallbackBridge.physicalWidth = currentDisplayMetrics.widthPixels;
CallbackBridge.physicalHeight = currentDisplayMetrics.heightPixels;
}
public static float dpToPx(float dp) {
//Better hope for the currentDisplayMetrics to be good
return dp * currentDisplayMetrics.density;
}
public static float pxToDp(float px){
//Better hope for the currentDisplayMetrics to be good
return px / currentDisplayMetrics.density;
}
public static void copyAssetFile(Context ctx, String fileName, String output, boolean overwrite) throws IOException {
copyAssetFile(ctx, fileName, output, new File(fileName).getName(), overwrite);
}
public static void copyAssetFile(Context ctx, String fileName, String output, String outputName, boolean overwrite) throws IOException {