-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathTools.java
1408 lines (1238 loc) · 64.6 KB
/
Tools.java
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.PojavApplication.sExecutorService;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_IGNORE_NOTCH;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_NOTCH_SIZE;
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.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.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.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.lwjgl.glfw.CallbackBridge;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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.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 = "PojavLauncher";
public static final Gson GLOBAL_GSON = new GsonBuilder().setPrettyPrinting().create();
public static final String URL_HOME = "https://pojavlauncherteam.github.io";
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 = "pojav://";
// New since 3.3.1
public static String DIR_ACCOUNT_NEW;
public static String DIR_GAME_HOME = Environment.getExternalStorageDirectory().getAbsolutePath() + "/games/PojavLauncher";
public static String DIR_GAME_NEW;
// 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;
private static File getPojavStorageRoot(Context ctx) {
if(SDK_INT >= 29) {
return ctx.getExternalFilesDir(null);
}else{
return new File(Environment.getExternalStorageDirectory(),"games/PojavLauncher");
}
}
/**
* 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";
}
/**
* Optimization mods based on Sodium can mitigate the render distance issue. Check if Sodium
* or its derivative is currently installed to skip the render distance check.
* @param gameDir current game directory
* @return whether sodium or a sodium-based mod is installed
*/
private static boolean hasSodium(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();
if(name.contains("sodium") ||
name.contains("embeddium") ||
name.contains("rubidium")) 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 boolean checkRenderDistance(File gamedir) {
if(!"opengles3_ltw".equals(Tools.LOCAL_RENDERER)) return false;
if(!affectedByRenderDistanceIssue()) return false;
if(hasSodium(gamedir)) 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);
if(checkRenderDistance(gamedir)) {
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);
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);
}
javaArgList.addAll(Arrays.asList(getMinecraftJVMArgs(versionId, gamedir)));
javaArgList.add("-cp");
javaArgList.add(launchClassPath + ":" + getLWJGL3ClassPath());
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
}
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) {
// 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 {
javaArgList.add("-Dawt.toolkit=com.github.caciocavallosilano.cacio.ctc.CTCToolkit");
javaArgList.add("-Djava.awt.graphicsenv=com.github.caciocavallosilano.cacio.ctc.CTCGraphicsEnvironment");
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);
// Parse Forge 1.17+ additional JVM Arguments
if (versionInfo.inheritsFrom == null || 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.NATIVE_LIB_DIR);
List<String> minecraftArgs = new ArrayList<>();
if (versionInfo.arguments != null) {
for (Object arg : versionInfo.arguments.jvm) {
if (arg instanceof String) {
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;
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
}
}
return JSONUtils.insertJSONValueList(
splitAndFilterEmpty(
versionInfo.minecraftArguments == null ?
fromStringArray(minecraftArgs.toArray(new String[0])):
versionInfo.minecraftArguments
), 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] + ".jar";
}
public static String getClientClasspath(String version) {
return DIR_HOME_VERSION + "/" + version + "/" + version + ".jar";
}
private static String getLWJGL3ClassPath() {
StringBuilder libStr = new StringBuilder();
File lwjgl3Folder = new File(Tools.DIR_GAME_HOME, "lwjgl3");
File[] lwjgl3Files = lwjgl3Folder.listFiles();
if (lwjgl3Files != null) {
for (File file: lwjgl3Files) {
if (file.getName().endsWith(".jar")) {
libStr.append(file.getAbsolutePath()).append(":");
}
}
}
// Remove the ':' at the end
libStr.setLength(libStr.length() - 1);
return libStr.toString();
}
private final static boolean isClientFirst = false;
public static String generateLaunchClassPath(JMinecraftVersionList.Version info, String actualname) {
StringBuilder finalClasspath = new StringBuilder(); //versnDir + "/" + version + "/" + version + ".jar:";
String[] classpath = generateLibClasspath(info);
if (isClientFirst) {
finalClasspath.append(getClientClasspath(actualname));
}
for (String jarFile : classpath) {
if (!FileUtils.exists(jarFile)) {
Log.d(APP_NAME, "Ignored non-exists file: " + jarFile);
continue;
}
finalClasspath.append((isClientFirst ? ":" : "")).append(jarFile).append(!isClientFirst ? ":" : "");
}
if (!isClientFirst) {
finalClasspath.append(getClientClasspath(actualname));
}
return finalClasspath.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 {
File parentFolder = new File(output);
FileUtils.ensureDirectory(parentFolder);
File destinationFile = new File(output, outputName);
if(!destinationFile.exists() || overwrite){
try(InputStream inputStream = ctx.getAssets().open(fileName)) {
try (OutputStream outputStream = new FileOutputStream(destinationFile)){
IOUtils.copy(inputStream, outputStream);
}
}
}
}
public static String printToString(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
throwable.printStackTrace(printWriter);
printWriter.close();
return stringWriter.toString();
}
public static void showError(Context ctx, Throwable e) {
showError(ctx, e, false);
}
public static void showError(final Context ctx, final Throwable e, final boolean exitIfOk) {
showError(ctx, R.string.global_error, null ,e, exitIfOk, false);
}
public static void showError(final Context ctx, final int rolledMessage, final Throwable e) {
showError(ctx, R.string.global_error, ctx.getString(rolledMessage), e, false, false);
}
public static void showError(final Context ctx, final String rolledMessage, final Throwable e) {
showError(ctx, R.string.global_error, rolledMessage, e, false, false);
}
public static void showError(final Context ctx, final String rolledMessage, final Throwable e, boolean exitIfOk) {
showError(ctx, R.string.global_error, rolledMessage, e, exitIfOk, false);
}
public static void showError(final Context ctx, final int titleId, final Throwable e, final boolean exitIfOk) {
showError(ctx, titleId, null, e, exitIfOk, false);
}
private static void showError(final Context ctx, final int titleId, final String rolledMessage, final Throwable e, final boolean exitIfOk, final boolean showMore) {
if(e instanceof ContextExecutorTask) {
ContextExecutor.execute((ContextExecutorTask) e);
return;
}
e.printStackTrace();
Runnable runnable = () -> {
final String errMsg = showMore ? printToString(e) : rolledMessage != null ? rolledMessage : e.getMessage();
AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
.setTitle(titleId)
.setMessage(errMsg)
.setPositiveButton(android.R.string.ok, (p1, p2) -> {
if(exitIfOk) {
if (ctx instanceof MainActivity) {
fullyExit();
} else if (ctx instanceof Activity) {
((Activity) ctx).finish();
}
}
})
.setNegativeButton(showMore ? R.string.error_show_less : R.string.error_show_more, (p1, p2) -> showError(ctx, titleId, rolledMessage, e, exitIfOk, !showMore))
.setNeutralButton(android.R.string.copy, (p1, p2) -> {
ClipboardManager mgr = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
mgr.setPrimaryClip(ClipData.newPlainText("error", printToString(e)));
if(exitIfOk) {
if (ctx instanceof MainActivity) {
fullyExit();
} else {
((Activity) ctx).finish();
}
}
})
.setCancelable(!exitIfOk);
try {
builder.show();
} catch (Throwable th) {
th.printStackTrace();
}
};
if (ctx instanceof Activity) {
((Activity) ctx).runOnUiThread(runnable);
} else {
runnable.run();
}
}
/**
* Show the error remotely in a context-aware fashion. Has generally the same behaviour as
* Tools.showError when in an activity, but when not in one, sends a notification that opens an
* activity and calls Tools.showError().
* NOTE: If the Throwable is a ContextExecutorTask and when not in an activity,
* its executeWithApplication() method will never be called.
* @param e the error (throwable)
*/
public static void showErrorRemote(Throwable e) {
showErrorRemote(null, e);
}
public static void showErrorRemote(Context context, int rolledMessage, Throwable e) {
showErrorRemote(context.getString(rolledMessage), e);
}
public static void showErrorRemote(String rolledMessage, Throwable e) {
// I WILL embrace layer violations because Android's concept of layers is STUPID
// We live in the same process anyway, why make it any more harder with this needless
// abstraction?
// Add your Context-related rage here
ContextExecutor.execute(new ShowErrorActivity.RemoteErrorTask(e, rolledMessage));
}
public static void dialogOnUiThread(final Activity activity, final CharSequence title, final CharSequence message) {
activity.runOnUiThread(()->dialog(activity, title, message));
}
public static void dialog(final Context context, final CharSequence title, final CharSequence message) {
new AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.show();
}
public static void openURL(Activity act, String url) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
act.startActivity(browserIntent);
}
private static boolean checkRules(JMinecraftVersionList.Arguments.ArgValue.ArgRules[] rules) {
if(rules == null) return true; // always allow
for (JMinecraftVersionList.Arguments.ArgValue.ArgRules rule : rules) {
if (rule.action.equals("allow") && rule.os != null && rule.os.name.equals("osx")) {
return false; //disallow
}
}
return true; // allow if none match
}
public static void preProcessLibraries(DependentLibrary[] libraries) {
for (int i = 0; i < libraries.length; i++) {
DependentLibrary libItem = libraries[i];
String[] version = libItem.name.split(":")[2].split("\\.");
if (libItem.name.startsWith("net.java.dev.jna:jna:")) {
// Special handling for LabyMod 1.8.9, Forge 1.12.2(?) and oshi
// we have libjnidispatch 5.13.0 in jniLibs directory
if (Integer.parseInt(version[0]) >= 5 && Integer.parseInt(version[1]) >= 13) continue;
Log.d(APP_NAME, "Library " + libItem.name + " has been changed to version 5.13.0");
createLibraryInfo(libItem);
libItem.name = "net.java.dev.jna:jna:5.13.0";
libItem.downloads.artifact.path = "net/java/dev/jna/jna/5.13.0/jna-5.13.0.jar";
libItem.downloads.artifact.sha1 = "1200e7ebeedbe0d10062093f32925a912020e747";
libItem.downloads.artifact.url = "https://repo1.maven.org/maven2/net/java/dev/jna/jna/5.13.0/jna-5.13.0.jar";
} else if (libItem.name.startsWith("com.github.oshi:oshi-core:")) {
//if (Integer.parseInt(version[0]) >= 6 && Integer.parseInt(version[1]) >= 3) return;
// FIXME: ensure compatibility
if (Integer.parseInt(version[0]) != 6 || Integer.parseInt(version[1]) != 2) continue;
Log.d(APP_NAME, "Library " + libItem.name + " has been changed to version 6.3.0");
createLibraryInfo(libItem);
libItem.name = "com.github.oshi:oshi-core:6.3.0";
libItem.downloads.artifact.path = "com/github/oshi/oshi-core/6.3.0/oshi-core-6.3.0.jar";
libItem.downloads.artifact.sha1 = "9e98cf55be371cafdb9c70c35d04ec2a8c2b42ac";
libItem.downloads.artifact.url = "https://repo1.maven.org/maven2/com/github/oshi/oshi-core/6.3.0/oshi-core-6.3.0.jar";
} else if (libItem.name.startsWith("org.ow2.asm:asm-all:")) {
// Early versions of the ASM library get repalced with 5.0.4 because Pojav's LWJGL is compiled for
// Java 8, which is not supported by old ASM versions. Mod loaders like Forge, which depend on this
// library, often include lwjgl in their class transformations, which causes errors with old ASM versions.
if(Integer.parseInt(version[0]) >= 5) continue;
Log.d(APP_NAME, "Library " + libItem.name + " has been changed to version 5.0.4");
createLibraryInfo(libItem);
libItem.name = "org.ow2.asm:asm-all:5.0.4";
libItem.url = null;
libItem.downloads.artifact.path = "org/ow2/asm/asm-all/5.0.4/asm-all-5.0.4.jar";
libItem.downloads.artifact.sha1 = "e6244859997b3d4237a552669279780876228909";
libItem.downloads.artifact.url = "https://repo1.maven.org/maven2/org/ow2/asm/asm-all/5.0.4/asm-all-5.0.4.jar";
}
}
}
private static void createLibraryInfo(DependentLibrary library) {
if(library.downloads == null || library.downloads.artifact == null)
library.downloads = new DependentLibrary.LibraryDownloads(new MinecraftLibraryArtifact());
}
public static String[] generateLibClasspath(JMinecraftVersionList.Version info) {
List<String> libDir = new ArrayList<>();
for (DependentLibrary libItem: info.libraries) {
if(!checkRules(libItem.rules)) continue;
libDir.add(Tools.DIR_HOME_LIBRARY + "/" + artifactToPath(libItem));
}
return libDir.toArray(new String[0]);
}
public static JMinecraftVersionList.Version getVersionInfo(String versionName) {
return getVersionInfo(versionName, false);
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static JMinecraftVersionList.Version getVersionInfo(String versionName, boolean skipInheriting) {
try {
JMinecraftVersionList.Version customVer = Tools.GLOBAL_GSON.fromJson(read(DIR_HOME_VERSION + "/" + versionName + "/" + versionName + ".json"), JMinecraftVersionList.Version.class);
if (skipInheriting || customVer.inheritsFrom == null || customVer.inheritsFrom.equals(customVer.id)) {
preProcessLibraries(customVer.libraries);
} else {
JMinecraftVersionList.Version inheritsVer;
//If it won't download, just search for it
try{
inheritsVer = Tools.GLOBAL_GSON.fromJson(read(DIR_HOME_VERSION + "/" + customVer.inheritsFrom + "/" + customVer.inheritsFrom + ".json"), JMinecraftVersionList.Version.class);
}catch(IOException e) {
throw new RuntimeException("Can't find the source version for "+ versionName +" (req version="+customVer.inheritsFrom+")");
}
//inheritsVer.inheritsFrom = inheritsVer.id;
insertSafety(inheritsVer, customVer,
"assetIndex", "assets", "id",
"mainClass", "minecraftArguments",
"releaseTime", "time", "type"
);
// Go through the libraries, remove the ones overridden by the custom version
List<DependentLibrary> inheritLibraryList = new ArrayList<>(Arrays.asList(inheritsVer.libraries));
outer_loop:
for(DependentLibrary library : customVer.libraries){
// Clean libraries overridden by the custom version
String libName = library.name.substring(0, library.name.lastIndexOf(":"));
for(DependentLibrary inheritLibrary : inheritLibraryList) {
String inheritLibName = inheritLibrary.name.substring(0, inheritLibrary.name.lastIndexOf(":"));
if(libName.equals(inheritLibName)){
Log.d(APP_NAME, "Library " + libName + ": Replaced version " +
libName.substring(libName.lastIndexOf(":") + 1) + " with " +
inheritLibName.substring(inheritLibName.lastIndexOf(":") + 1));
// Remove the library , superseded by the overriding libs
inheritLibraryList.remove(inheritLibrary);
continue outer_loop;
}
}
}
// Fuse libraries
inheritLibraryList.addAll(Arrays.asList(customVer.libraries));
inheritsVer.libraries = inheritLibraryList.toArray(new DependentLibrary[0]);
preProcessLibraries(inheritsVer.libraries);
// Inheriting Minecraft 1.13+ with append custom args
if (inheritsVer.arguments != null && customVer.arguments != null) {
List totalArgList = new ArrayList(Arrays.asList(inheritsVer.arguments.game));
int nskip = 0;
for (int i = 0; i < customVer.arguments.game.length; i++) {
if (nskip > 0) {
nskip--;
continue;
}
Object perCustomArg = customVer.arguments.game[i];
if (perCustomArg instanceof String) {
String perCustomArgStr = (String) perCustomArg;
// Check if there is a duplicate argument on combine
if (perCustomArgStr.startsWith("--") && totalArgList.contains(perCustomArgStr)) {
perCustomArg = customVer.arguments.game[i + 1];
if (perCustomArg instanceof String) {
perCustomArgStr = (String) perCustomArg;
// If the next is argument value, skip it
if (!perCustomArgStr.startsWith("--")) {
nskip++;
}
}
} else {
totalArgList.add(perCustomArgStr);
}
} else if (!totalArgList.contains(perCustomArg)) {
totalArgList.add(perCustomArg);
}
}
inheritsVer.arguments.game = totalArgList.toArray(new Object[0]);
}
customVer = inheritsVer;
}
// LabyMod 4 sets version instead of majorVersion
if (customVer.javaVersion != null && customVer.javaVersion.majorVersion == 0) {
customVer.javaVersion.majorVersion = customVer.javaVersion.version;
}
return customVer;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Prevent NullPointerException
private static void insertSafety(JMinecraftVersionList.Version targetVer, JMinecraftVersionList.Version fromVer, String... keyArr) {
for (String key : keyArr) {
Object value = null;
try {
Field fieldA = fromVer.getClass().getDeclaredField(key);
value = fieldA.get(fromVer);
if (((value instanceof String) && !((String) value).isEmpty()) || value != null) {
Field fieldB = targetVer.getClass().getDeclaredField(key);
fieldB.set(targetVer, value);
}
} catch (Throwable th) {
Log.w(Tools.APP_NAME, "Unable to insert " + key + "=" + value, th);
}
}
}
public static String read(InputStream is) throws IOException {
String readResult = IOUtils.toString(is, StandardCharsets.UTF_8);
is.close();
return readResult;
}
public static String read(String path) throws IOException {
return read(new FileInputStream(path));
}
public static String read(File path) throws IOException {
return read(new FileInputStream(path));
}