file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
CallbackBridge.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/org/lwjgl/glfw/CallbackBridge.java
package org.lwjgl.glfw; import net.kdt.pojavlaunch.*; import android.content.*; import android.view.Choreographer; import androidx.annotation.Nullable; import java.util.ArrayList; import dalvik.annotation.optimization.CriticalNative; public class CallbackBridge { public static final Choreographer sChoreographer = Choreographer.getInstance(); private static boolean isGrabbing = false; private static final ArrayList<GrabListener> grabListeners = new ArrayList<>(); public static final int CLIPBOARD_COPY = 2000; public static final int CLIPBOARD_PASTE = 2001; public static final int CLIPBOARD_OPEN = 2002; public static volatile int windowWidth, windowHeight; public static volatile int physicalWidth, physicalHeight; public static float mouseX, mouseY; public volatile static boolean holdingAlt, holdingCapslock, holdingCtrl, holdingNumlock, holdingShift; public static void putMouseEventWithCoords(int button, float x, float y) { putMouseEventWithCoords(button, true, x, y); sChoreographer.postFrameCallbackDelayed(l -> putMouseEventWithCoords(button, false, x, y), 33); } public static void putMouseEventWithCoords(int button, boolean isDown, float x, float y /* , int dz, long nanos */) { sendCursorPos(x, y); sendMouseKeycode(button, CallbackBridge.getCurrentMods(), isDown); } public static void sendCursorPos(float x, float y) { mouseX = x; mouseY = y; nativeSendCursorPos(mouseX, mouseY); } public static void sendKeycode(int keycode, char keychar, int scancode, int modifiers, boolean isDown) { // TODO CHECK: This may cause input issue, not receive input! if(keycode != 0) nativeSendKey(keycode,scancode,isDown ? 1 : 0, modifiers); if(isDown && keychar != '\u0000') { nativeSendCharMods(keychar,modifiers); nativeSendChar(keychar); } } public static void sendChar(char keychar, int modifiers){ nativeSendCharMods(keychar,modifiers); nativeSendChar(keychar); } public static void sendKeyPress(int keyCode, int modifiers, boolean status) { sendKeyPress(keyCode, 0, modifiers, status); } public static void sendKeyPress(int keyCode, int scancode, int modifiers, boolean status) { sendKeyPress(keyCode, '\u0000', scancode, modifiers, status); } public static void sendKeyPress(int keyCode, char keyChar, int scancode, int modifiers, boolean status) { CallbackBridge.sendKeycode(keyCode, keyChar, scancode, modifiers, status); } public static void sendKeyPress(int keyCode) { sendKeyPress(keyCode, CallbackBridge.getCurrentMods(), true); sendKeyPress(keyCode, CallbackBridge.getCurrentMods(), false); } public static void sendMouseButton(int button, boolean status) { CallbackBridge.sendMouseKeycode(button, CallbackBridge.getCurrentMods(), status); } public static void sendMouseKeycode(int button, int modifiers, boolean isDown) { // if (isGrabbing()) DEBUG_STRING.append("MouseGrabStrace: " + android.util.Log.getStackTraceString(new Throwable()) + "\n"); nativeSendMouseButton(button, isDown ? 1 : 0, modifiers); } public static void sendMouseKeycode(int keycode) { sendMouseKeycode(keycode, CallbackBridge.getCurrentMods(), true); sendMouseKeycode(keycode, CallbackBridge.getCurrentMods(), false); } public static void sendScroll(double xoffset, double yoffset) { nativeSendScroll(xoffset, yoffset); } public static void sendUpdateWindowSize(int w, int h) { nativeSendScreenSize(w, h); } public static boolean isGrabbing() { // Avoid going through the JNI each time. return isGrabbing; } // Called from JRE side @SuppressWarnings("unused") public static @Nullable String accessAndroidClipboard(int type, String copy) { switch (type) { case CLIPBOARD_COPY: MainActivity.GLOBAL_CLIPBOARD.setPrimaryClip(ClipData.newPlainText("Copy", copy)); return null; case CLIPBOARD_PASTE: if (MainActivity.GLOBAL_CLIPBOARD.hasPrimaryClip() && MainActivity.GLOBAL_CLIPBOARD.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) { return MainActivity.GLOBAL_CLIPBOARD.getPrimaryClip().getItemAt(0).getText().toString(); } else { return ""; } case CLIPBOARD_OPEN: MainActivity.openLink(copy); return null; default: return null; } } public static int getCurrentMods() { int currMods = 0; if (holdingAlt) { currMods |= LwjglGlfwKeycode.GLFW_MOD_ALT; } if (holdingCapslock) { currMods |= LwjglGlfwKeycode.GLFW_MOD_CAPS_LOCK; } if (holdingCtrl) { currMods |= LwjglGlfwKeycode.GLFW_MOD_CONTROL; } if (holdingNumlock) { currMods |= LwjglGlfwKeycode.GLFW_MOD_NUM_LOCK; } if (holdingShift) { currMods |= LwjglGlfwKeycode.GLFW_MOD_SHIFT; } return currMods; } public static void setModifiers(int keyCode, boolean isDown){ switch (keyCode){ case LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT: CallbackBridge.holdingShift = isDown; return; case LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL: CallbackBridge.holdingCtrl = isDown; return; case LwjglGlfwKeycode.GLFW_KEY_LEFT_ALT: CallbackBridge.holdingAlt = isDown; return; case LwjglGlfwKeycode.GLFW_KEY_CAPS_LOCK: CallbackBridge.holdingCapslock = isDown; return; case LwjglGlfwKeycode.GLFW_KEY_NUM_LOCK: CallbackBridge.holdingNumlock = isDown; } } //Called from JRE side @SuppressWarnings("unused") private static void onGrabStateChanged(final boolean grabbing) { isGrabbing = grabbing; sChoreographer.postFrameCallbackDelayed((time) -> { // If the grab re-changed, skip notify process if(isGrabbing != grabbing) return; System.out.println("Grab changed : " + grabbing); synchronized (grabListeners) { for (GrabListener g : grabListeners) g.onGrabState(grabbing); } }, 16); } public static void addGrabListener(GrabListener listener) { synchronized (grabListeners) { listener.onGrabState(isGrabbing); grabListeners.add(listener); } } public static void removeGrabListener(GrabListener listener) { synchronized (grabListeners) { grabListeners.remove(listener); } } @CriticalNative public static native void nativeSetUseInputStackQueue(boolean useInputStackQueue); @CriticalNative private static native boolean nativeSendChar(char codepoint); // GLFW: GLFWCharModsCallback deprecated, but is Minecraft still use? @CriticalNative private static native boolean nativeSendCharMods(char codepoint, int mods); @CriticalNative private static native void nativeSendKey(int key, int scancode, int action, int mods); // private static native void nativeSendCursorEnter(int entered); @CriticalNative private static native void nativeSendCursorPos(float x, float y); @CriticalNative private static native void nativeSendMouseButton(int button, int action, int mods); @CriticalNative private static native void nativeSendScroll(double xoffset, double yoffset); @CriticalNative private static native void nativeSendScreenSize(int width, int height); public static native void nativeSetWindowAttrib(int attrib, int value); static { System.loadLibrary("pojavexec"); } }
8,015
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Tools.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Tools.java
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.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.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.JREUtils; import net.kdt.pojavlaunch.utils.JSONUtils; 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.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.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); } /** * Since some constant requires the use of the Context object * You can call this function to initialize them. * Any value (in)directly dependant on DIR_DATA should be set only here. */ public static void initContextConstants(Context ctx){ DIR_CACHE = ctx.getCacheDir(); DIR_DATA = ctx.getFilesDir().getParent(); MULTIRT_HOME = DIR_DATA+"/runtimes"; 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"; NATIVE_LIB_DIR = ctx.getApplicationInfo().nativeLibraryDir; } public static void launchMinecraft(final AppCompatActivity activity, MinecraftAccount minecraftAccount, MinecraftProfile minecraftProfile, String versionId, int versionJavaRequirement) throws Throwable { int freeDeviceMemory = getFreeDeviceMemory(activity); if(LauncherPreferences.PREF_RAM_ALLOCATION > freeDeviceMemory) { LifecycleAwareAlertDialog.DialogCreator dialogCreator = (dialog, builder) -> builder.setMessage(activity.getString(R.string.memory_warning_msg, freeDeviceMemory, 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 } } Runtime runtime = MultiRTUtils.forceReread(Tools.pickRuntime(minecraftProfile, versionJavaRequirement)); JMinecraftVersionList.Version versionInfo = Tools.getVersionInfo(versionId); LauncherProfiles.load(); File gamedir = Tools.getGameDirPath(minecraftProfile); // 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(getLWJGL3ClassPath() + ":" + launchClassPath); 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 -> { if(fullscreen){ 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); 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) { 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) { 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)); } public static void write(String path, String content) throws IOException { File file = new File(path); FileUtils.ensureParentDirectory(file); try(FileOutputStream outStream = new FileOutputStream(file)) { IOUtils.write(content, outStream); } } public static void downloadFile(String urlInput, String nameOutput) throws IOException { File file = new File(nameOutput); DownloadUtils.downloadFile(urlInput, file); } public interface DownloaderFeedback { void updateProgress(int curr, int max); } public static boolean compareSHA1(File f, String sourceSHA) { try { String sha1_dst; try (InputStream is = new FileInputStream(f)) { sha1_dst = new String(Hex.encodeHex(org.apache.commons.codec.digest.DigestUtils.sha1(is))); } if(sourceSHA != null) { return sha1_dst.equalsIgnoreCase(sourceSHA); } else{ return true; // fake match } }catch (IOException e) { Log.i("SHA1","Fake-matching a hash due to a read error",e); return true; } } public static void ignoreNotch(boolean shouldIgnore, Activity ctx){ if (SDK_INT >= P) { if (shouldIgnore) { ctx.getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES; } else { ctx.getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER; } ctx.getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN); Tools.updateWindowSize(ctx); } } public static int getTotalDeviceMemory(Context ctx){ ActivityManager actManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); actManager.getMemoryInfo(memInfo); return (int) (memInfo.totalMem / 1048576L); } public static int getFreeDeviceMemory(Context ctx){ ActivityManager actManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); actManager.getMemoryInfo(memInfo); return (int) (memInfo.availMem / 1048576L); } public static int getDisplayFriendlyRes(int displaySideRes, float scaling){ displaySideRes *= scaling; if(displaySideRes % 2 != 0) displaySideRes --; return displaySideRes; } public static String getFileName(Context ctx, Uri uri) { Cursor c = ctx.getContentResolver().query(uri, null, null, null, null); if(c == null) return uri.getLastPathSegment(); // idk myself but it happens on asus file manager c.moveToFirst(); int columnIndex = c.getColumnIndex(OpenableColumns.DISPLAY_NAME); if(columnIndex == -1) return uri.getLastPathSegment(); String fileName = c.getString(columnIndex); c.close(); return fileName; } /** Swap the main fragment with another */ public static void swapFragment(FragmentActivity fragmentActivity , Class<? extends Fragment> fragmentClass, @Nullable String fragmentTag, @Nullable Bundle bundle) { // When people tab out, it might happen //TODO handle custom animations fragmentActivity.getSupportFragmentManager().beginTransaction() .setReorderingAllowed(true) .addToBackStack(fragmentClass.getName()) .replace(R.id.container_fragment, fragmentClass, bundle, fragmentTag).commit(); } public static void backToMainMenu(FragmentActivity fragmentActivity) { fragmentActivity.getSupportFragmentManager() .popBackStack("ROOT", 0); } /** Remove the current fragment */ public static void removeCurrentFragment(FragmentActivity fragmentActivity){ fragmentActivity.getSupportFragmentManager().popBackStack(); } public static void installMod(Activity activity, boolean customJavaArgs) { if (MultiRTUtils.getExactJreName(8) == null) { Toast.makeText(activity, R.string.multirt_nojava8rt, Toast.LENGTH_LONG).show(); return; } if(!customJavaArgs){ // Launch the intent to get the jar file if(!(activity instanceof LauncherActivity)) throw new IllegalStateException("Cannot start Mod Installer without LauncherActivity"); LauncherActivity launcherActivity = (LauncherActivity)activity; launcherActivity.modInstallerLauncher.launch(null); return; } // install mods with custom arguments final EditText editText = new EditText(activity); editText.setSingleLine(); editText.setHint("-jar/-cp /path/to/file.jar ..."); AlertDialog.Builder builder = new AlertDialog.Builder(activity) .setTitle(R.string.alerttitle_installmod) .setNegativeButton(android.R.string.cancel, null) .setView(editText) .setPositiveButton(android.R.string.ok, (di, i) -> { Intent intent = new Intent(activity, JavaGUILauncherActivity.class); intent.putExtra("javaArgs", editText.getText().toString()); activity.startActivity(intent); }); builder.show(); } /** Display and return a progress dialog, instructing to wait */ public static ProgressDialog getWaitingDialog(Context ctx, int message){ final ProgressDialog barrier = new ProgressDialog(ctx); barrier.setMessage(ctx.getString(message)); barrier.setProgressStyle(ProgressDialog.STYLE_SPINNER); barrier.setCancelable(false); barrier.show(); return barrier; } /** Launch the mod installer activity. The Uri must be from our own content provider or * from ACTION_OPEN_DOCUMENT */ public static void launchModInstaller(Activity activity, @NonNull Uri uri){ Intent intent = new Intent(activity, JavaGUILauncherActivity.class); intent.putExtra("modUri", uri); activity.startActivity(intent); } public static void installRuntimeFromUri(Context context, Uri uri){ sExecutorService.execute(() -> { try { String name = getFileName(context, uri); MultiRTUtils.installRuntimeNamed( NATIVE_LIB_DIR, context.getContentResolver().openInputStream(uri), name); MultiRTUtils.postPrepare(name); } catch (IOException e) { Tools.showError(context, e); } }); } public static String extractUntilCharacter(String input, String whatFor, char terminator) { int whatForStart = input.indexOf(whatFor); if(whatForStart == -1) return null; whatForStart += whatFor.length(); int terminatorIndex = input.indexOf(terminator, whatForStart); if(terminatorIndex == -1) return null; return input.substring(whatForStart, terminatorIndex); } public static boolean isValidString(String string) { return string != null && !string.isEmpty(); } public static String getRuntimeName(String prefixedName) { if(prefixedName == null) return prefixedName; if(!prefixedName.startsWith(Tools.LAUNCHERPROFILES_RTPREFIX)) return null; return prefixedName.substring(Tools.LAUNCHERPROFILES_RTPREFIX.length()); } public static String getSelectedRuntime(MinecraftProfile minecraftProfile) { String runtime = LauncherPreferences.PREF_DEFAULT_RUNTIME; String profileRuntime = getRuntimeName(minecraftProfile.javaDir); if(profileRuntime != null) { if(MultiRTUtils.forceReread(profileRuntime).versionString != null) { runtime = profileRuntime; } } return runtime; } public static void runOnUiThread(Runnable runnable) { MAIN_HANDLER.post(runnable); } public static @NonNull String pickRuntime(MinecraftProfile minecraftProfile, int targetJavaVersion) { String runtime = getSelectedRuntime(minecraftProfile); String profileRuntime = getRuntimeName(minecraftProfile.javaDir); Runtime pickedRuntime = MultiRTUtils.read(runtime); if(runtime == null || pickedRuntime.javaVersion == 0 || pickedRuntime.javaVersion < targetJavaVersion) { String preferredRuntime = MultiRTUtils.getNearestJreName(targetJavaVersion); if(preferredRuntime == null) throw new RuntimeException("Failed to autopick runtime!"); if(profileRuntime != null) minecraftProfile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX+preferredRuntime; runtime = preferredRuntime; } return runtime; } /** Triggers the share intent chooser, with the latestlog file attached to it */ public static void shareLog(Context context){ Uri contentUri = DocumentsContract.buildDocumentUri(context.getString(R.string.storageProviderAuthorities), Tools.DIR_GAME_HOME + "/latestlog.txt"); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shareIntent.setType("text/plain"); Intent sendIntent = Intent.createChooser(shareIntent, "latestlog.txt"); context.startActivity(sendIntent); } /** Mesure the textview height, given its current parameters */ public static int mesureTextviewHeight(TextView t) { int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(t.getWidth(), View.MeasureSpec.AT_MOST); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); t.measure(widthMeasureSpec, heightMeasureSpec); return t.getMeasuredHeight(); } /** * Check if the device is one of the devices that may be affected by the hanging linker issue. * The device is affected if the linker causes the process to lock up when dlopen() is called within * dl_iterate_phdr(). * For now, the only affected firmware that I know of is Android 5.1, EMUI 3.1 on MTK-based Huawei * devices. * @return if the device is affected by the hanging linker issue. */ public static boolean deviceHasHangingLinker() { // Android Oreo and onwards have GSIs and most phone firmwares at that point were not modified // *that* intrusively. So assume that we are not affected. if(SDK_INT >= Build.VERSION_CODES.O) return false; // Since the affected function in LWJGL is rarely used (and when used, it's mainly for debug prints) // we can make the search scope a bit more broad and check if we are running on a Huawei device. return Build.MANUFACTURER.toLowerCase(Locale.ROOT).contains("huawei"); } public static class RenderersList { public final List<String> rendererIds; public final String[] rendererDisplayNames; public RenderersList(List<String> rendererIds, String[] rendererDisplayNames) { this.rendererIds = rendererIds; this.rendererDisplayNames = rendererDisplayNames; } } public static boolean checkVulkanSupport(PackageManager packageManager) { if(SDK_INT >= Build.VERSION_CODES.N) { return packageManager.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_LEVEL) && packageManager.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION); } return false; } public static <T> T getWeakReference(WeakReference<T> weakReference) { if(weakReference == null) return null; return weakReference.get(); } /** Return the renderers that are compatible with this device */ public static RenderersList getCompatibleRenderers(Context context) { if(sCompatibleRenderers != null) return sCompatibleRenderers; Resources resources = context.getResources(); String[] defaultRenderers = resources.getStringArray(R.array.renderer_values); String[] defaultRendererNames = resources.getStringArray(R.array.renderer); boolean deviceHasVulkan = checkVulkanSupport(context.getPackageManager()); // Currently, only 32-bit x86 does not have the Zink binary boolean deviceHasZinkBinary = !(Architecture.is32BitsDevice() && Architecture.isx86Device()); List<String> rendererIds = new ArrayList<>(defaultRenderers.length); List<String> rendererNames = new ArrayList<>(defaultRendererNames.length); for(int i = 0; i < defaultRenderers.length; i++) { String rendererId = defaultRenderers[i]; if(rendererId.contains("vulkan") && !deviceHasVulkan) continue; if(rendererId.contains("zink") && !deviceHasZinkBinary) continue; rendererIds.add(rendererId); rendererNames.add(defaultRendererNames[i]); } sCompatibleRenderers = new RenderersList(rendererIds, rendererNames.toArray(new String[0])); return sCompatibleRenderers; } /** Checks if the renderer Id is compatible with the current device */ public static boolean checkRendererCompatible(Context context, String rendererName) { return getCompatibleRenderers(context).rendererIds.contains(rendererName); } /** Releases the cache of compatible renderers. */ public static void releaseRenderersCache() { sCompatibleRenderers = null; System.gc(); } }
55,528
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Architecture.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Architecture.java
package net.kdt.pojavlaunch; import android.os.Build; /** * This class aims at providing a simple and easy way to deal with the device architecture. */ public class Architecture { public static final int UNSUPPORTED_ARCH = -1; public static final int ARCH_ARM64 = 0x1; public static final int ARCH_ARM = 0x2; public static final int ARCH_X86 = 0x4; public static final int ARCH_X86_64 = 0x8; /** * Tell us if the device supports 64 bits architecture * @return If the device supports 64 bits architecture */ public static boolean is64BitsDevice(){ return Build.SUPPORTED_64_BIT_ABIS.length != 0; } /** * Tell us if the device supports 32 bits architecture * Note, that a 64 bits device won't be reported as supporting 32 bits. * @return If the device supports 32 bits architecture */ public static boolean is32BitsDevice(){ return !is64BitsDevice(); } /** * Tells the device supported architecture. * Since mips(/64) has been phased out long ago, is isn't checked here. * * @return ARCH_ARM || ARCH_ARM64 || ARCH_X86 || ARCH_86_64 */ public static int getDeviceArchitecture(){ if(isx86Device()){ return is64BitsDevice() ? ARCH_X86_64 : ARCH_X86; } return is64BitsDevice() ? ARCH_ARM64 : ARCH_ARM; } /** * Tell is the device is based on an x86 processor. * It doesn't tell if the device is 64 or 32 bits. * @return Whether or not the device is x86 based. */ public static boolean isx86Device(){ //We check the whole range of supported ABIs, //Since asus zenfones can place arm before their native instruction set. String[] ABI = is64BitsDevice() ? Build.SUPPORTED_64_BIT_ABIS : Build.SUPPORTED_32_BIT_ABIS; int comparedArch = is64BitsDevice() ? ARCH_X86_64 : ARCH_X86; for (String str : ABI) { if (archAsInt(str) == comparedArch) return true; } return false; } /** * Convert an architecture from a String to an int. * @param arch The architecture as a String * @return The architecture as an int, can be UNSUPPORTED_ARCH if unknown. */ public static int archAsInt(String arch){ arch = arch.toLowerCase().trim().replace(" ", ""); if(arch.contains("arm64") || arch.equals("aarch64")) return ARCH_ARM64; if(arch.contains("arm") || arch.equals("aarch32")) return ARCH_ARM; if(arch.contains("x86_64") || arch.contains("amd64")) return ARCH_X86_64; if(arch.contains("x86") || (arch.startsWith("i") && arch.endsWith("86"))) return ARCH_X86; //Shouldn't happen return UNSUPPORTED_ARCH; } /** * Convert to a string an architecture. * @param arch The architecture as an int. * @return "arm64" || "arm" || "x86_64" || "x86" || "UNSUPPORTED_ARCH" */ public static String archAsString(int arch){ if(arch == ARCH_ARM64) return "arm64"; if(arch == ARCH_ARM) return "arm"; if(arch == ARCH_X86_64) return "x86_64"; if(arch == ARCH_X86) return "x86"; return "UNSUPPORTED_ARCH"; } }
2,900
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JAssets.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/JAssets.java
package net.kdt.pojavlaunch; import androidx.annotation.Keep; import com.google.gson.annotations.SerializedName; import java.util.Map; @Keep public class JAssets { /* Used by older versions of mc, when the files were named and under .minecraft/resources */ @SerializedName("map_to_resources") public boolean mapToResources; public Map<String, JAssetInfo> objects; /* Used by the legacy.json (~1.6.X) asset file, used for paths at the root of the .minecraft/assets folder */ public boolean virtual; }
527
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
PojavApplication.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/PojavApplication.java
package net.kdt.pojavlaunch; import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK; import android.app.*; import android.content.*; import android.content.pm.*; import android.content.res.*; import android.os.*; import androidx.core.app.*; import android.util.*; import java.io.*; import java.text.*; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import net.kdt.pojavlaunch.lifecycle.ContextExecutor; import net.kdt.pojavlaunch.tasks.AsyncAssetManager; import net.kdt.pojavlaunch.utils.*; import net.kdt.pojavlaunch.utils.FileUtils; public class PojavApplication extends Application { public static final String CRASH_REPORT_TAG = "PojavCrashReport"; public static final ExecutorService sExecutorService = new ThreadPoolExecutor(4, 4, 500, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()); @Override public void onCreate() { ContextExecutor.setApplication(this); Thread.setDefaultUncaughtExceptionHandler((thread, th) -> { boolean storagePermAllowed = (Build.VERSION.SDK_INT < 23 || Build.VERSION.SDK_INT >= 29 || ActivityCompat.checkSelfPermission(PojavApplication.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) && Tools.checkStorageRoot(PojavApplication.this); File crashFile = new File(storagePermAllowed ? Tools.DIR_GAME_HOME : Tools.DIR_DATA, "latestcrash.txt"); try { // Write to file, since some devices may not able to show error FileUtils.ensureParentDirectory(crashFile); PrintStream crashStream = new PrintStream(crashFile); crashStream.append("PojavLauncher crash report\n"); crashStream.append(" - Time: ").append(DateFormat.getDateTimeInstance().format(new Date())).append("\n"); crashStream.append(" - Device: ").append(Build.PRODUCT).append(" ").append(Build.MODEL).append("\n"); crashStream.append(" - Android version: ").append(Build.VERSION.RELEASE).append("\n"); crashStream.append(" - Crash stack trace:\n"); crashStream.append(" - Launcher version: " + BuildConfig.VERSION_NAME + "\n"); crashStream.append(Log.getStackTraceString(th)); crashStream.close(); } catch (Throwable throwable) { Log.e(CRASH_REPORT_TAG, " - Exception attempt saving crash stack trace:", throwable); Log.e(CRASH_REPORT_TAG, " - The crash stack trace was:", th); } FatalErrorActivity.showError(PojavApplication.this, crashFile.getAbsolutePath(), storagePermAllowed, th); MainActivity.fullyExit(); }); try { super.onCreate(); Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent(); Tools.DIR_CACHE = getCacheDir(); Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts"; Tools.DEVICE_ARCHITECTURE = Architecture.getDeviceArchitecture(); //Force x86 lib directory for Asus x86 based zenfones if(Architecture.isx86Device() && Architecture.is32BitsDevice()){ String originalJNIDirectory = getApplicationInfo().nativeLibraryDir; getApplicationInfo().nativeLibraryDir = originalJNIDirectory.substring(0, originalJNIDirectory.lastIndexOf("/")) .concat("/x86"); } AsyncAssetManager.unpackRuntime(getAssets()); } catch (Throwable throwable) { Intent ferrorIntent = new Intent(this, FatalErrorActivity.class); ferrorIntent.putExtra("throwable", throwable); ferrorIntent.setFlags(FLAG_ACTIVITY_NEW_TASK); startActivity(ferrorIntent); } } @Override public void onTerminate() { super.onTerminate(); ContextExecutor.clearApplication(); } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(LocaleUtils.setLocale(base)); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); LocaleUtils.setLocale(this); } }
3,932
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
EfficientAndroidLWJGLKeycode.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/EfficientAndroidLWJGLKeycode.java
package net.kdt.pojavlaunch; import static org.lwjgl.glfw.CallbackBridge.sendKeyPress; import android.view.KeyEvent; import org.lwjgl.glfw.CallbackBridge; import java.util.Arrays; public class EfficientAndroidLWJGLKeycode { //This old version of this class was using an ArrayMap, a generic Key -> Value data structure. //The key being the android keycode from a KeyEvent //The value its LWJGL equivalent. private static final int KEYCODE_COUNT = 106; private static final int[] sAndroidKeycodes = new int[KEYCODE_COUNT]; private static final short[] sLwjglKeycodes = new short[KEYCODE_COUNT]; private static String[] androidKeyNameArray; /* = new String[androidKeycodes.length]; */ private static int mTmpCount = 0; static { /* BINARY SEARCH IS PERFORMED ON THE androidKeycodes ARRAY ! WHEN ADDING A MAPPING, ADD IT SO THE androidKeycodes ARRAY STAYS SORTED ! */ // Mapping Android Keycodes to LWJGL Keycodes add(KeyEvent.KEYCODE_UNKNOWN, LwjglGlfwKeycode.GLFW_KEY_UNKNOWN); add(KeyEvent.KEYCODE_HOME, LwjglGlfwKeycode.GLFW_KEY_HOME); // Escape key add(KeyEvent.KEYCODE_BACK, LwjglGlfwKeycode.GLFW_KEY_ESCAPE); // 0-9 keys add(KeyEvent.KEYCODE_0, LwjglGlfwKeycode.GLFW_KEY_0); //7 add(KeyEvent.KEYCODE_1, LwjglGlfwKeycode.GLFW_KEY_1); add(KeyEvent.KEYCODE_2, LwjglGlfwKeycode.GLFW_KEY_2); add(KeyEvent.KEYCODE_3, LwjglGlfwKeycode.GLFW_KEY_3); add(KeyEvent.KEYCODE_4, LwjglGlfwKeycode.GLFW_KEY_4); add(KeyEvent.KEYCODE_5, LwjglGlfwKeycode.GLFW_KEY_5); add(KeyEvent.KEYCODE_6, LwjglGlfwKeycode.GLFW_KEY_6); add(KeyEvent.KEYCODE_7, LwjglGlfwKeycode.GLFW_KEY_7); add(KeyEvent.KEYCODE_8, LwjglGlfwKeycode.GLFW_KEY_8); add(KeyEvent.KEYCODE_9, LwjglGlfwKeycode.GLFW_KEY_9); //16 add(KeyEvent.KEYCODE_POUND, LwjglGlfwKeycode.GLFW_KEY_3); // Arrow keys add(KeyEvent.KEYCODE_DPAD_UP, LwjglGlfwKeycode.GLFW_KEY_UP); //19 add(KeyEvent.KEYCODE_DPAD_DOWN, LwjglGlfwKeycode.GLFW_KEY_DOWN); add(KeyEvent.KEYCODE_DPAD_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT); add(KeyEvent.KEYCODE_DPAD_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT); //22 // A-Z keys add(KeyEvent.KEYCODE_A, LwjglGlfwKeycode.GLFW_KEY_A); //29 add(KeyEvent.KEYCODE_B, LwjglGlfwKeycode.GLFW_KEY_B); add(KeyEvent.KEYCODE_C, LwjglGlfwKeycode.GLFW_KEY_C); add(KeyEvent.KEYCODE_D, LwjglGlfwKeycode.GLFW_KEY_D); add(KeyEvent.KEYCODE_E, LwjglGlfwKeycode.GLFW_KEY_E); add(KeyEvent.KEYCODE_F, LwjglGlfwKeycode.GLFW_KEY_F); add(KeyEvent.KEYCODE_G, LwjglGlfwKeycode.GLFW_KEY_G); add(KeyEvent.KEYCODE_H, LwjglGlfwKeycode.GLFW_KEY_H); add(KeyEvent.KEYCODE_I, LwjglGlfwKeycode.GLFW_KEY_I); add(KeyEvent.KEYCODE_J, LwjglGlfwKeycode.GLFW_KEY_J); add(KeyEvent.KEYCODE_K, LwjglGlfwKeycode.GLFW_KEY_K); add(KeyEvent.KEYCODE_L, LwjglGlfwKeycode.GLFW_KEY_L); add(KeyEvent.KEYCODE_M, LwjglGlfwKeycode.GLFW_KEY_M); add(KeyEvent.KEYCODE_N, LwjglGlfwKeycode.GLFW_KEY_N); add(KeyEvent.KEYCODE_O, LwjglGlfwKeycode.GLFW_KEY_O); add(KeyEvent.KEYCODE_P, LwjglGlfwKeycode.GLFW_KEY_P); add(KeyEvent.KEYCODE_Q, LwjglGlfwKeycode.GLFW_KEY_Q); add(KeyEvent.KEYCODE_R, LwjglGlfwKeycode.GLFW_KEY_R); add(KeyEvent.KEYCODE_S, LwjglGlfwKeycode.GLFW_KEY_S); add(KeyEvent.KEYCODE_T, LwjglGlfwKeycode.GLFW_KEY_T); add(KeyEvent.KEYCODE_U, LwjglGlfwKeycode.GLFW_KEY_U); add(KeyEvent.KEYCODE_V, LwjglGlfwKeycode.GLFW_KEY_V); add(KeyEvent.KEYCODE_W, LwjglGlfwKeycode.GLFW_KEY_W); add(KeyEvent.KEYCODE_X, LwjglGlfwKeycode.GLFW_KEY_X); add(KeyEvent.KEYCODE_Y, LwjglGlfwKeycode.GLFW_KEY_Y); add(KeyEvent.KEYCODE_Z, LwjglGlfwKeycode.GLFW_KEY_Z); //54 add(KeyEvent.KEYCODE_COMMA, LwjglGlfwKeycode.GLFW_KEY_COMMA); add(KeyEvent.KEYCODE_PERIOD, LwjglGlfwKeycode.GLFW_KEY_PERIOD); // Alt keys add(KeyEvent.KEYCODE_ALT_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT_ALT); add(KeyEvent.KEYCODE_ALT_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT_ALT); // Shift keys add(KeyEvent.KEYCODE_SHIFT_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT); add(KeyEvent.KEYCODE_SHIFT_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT_SHIFT); add(KeyEvent.KEYCODE_TAB, LwjglGlfwKeycode.GLFW_KEY_TAB); add(KeyEvent.KEYCODE_SPACE, LwjglGlfwKeycode.GLFW_KEY_SPACE); add(KeyEvent.KEYCODE_ENTER, LwjglGlfwKeycode.GLFW_KEY_ENTER); //66 add(KeyEvent.KEYCODE_DEL, LwjglGlfwKeycode.GLFW_KEY_BACKSPACE); // Backspace add(KeyEvent.KEYCODE_GRAVE, LwjglGlfwKeycode.GLFW_KEY_GRAVE_ACCENT); add(KeyEvent.KEYCODE_MINUS, LwjglGlfwKeycode.GLFW_KEY_MINUS); add(KeyEvent.KEYCODE_EQUALS, LwjglGlfwKeycode.GLFW_KEY_EQUAL); add(KeyEvent.KEYCODE_LEFT_BRACKET, LwjglGlfwKeycode.GLFW_KEY_LEFT_BRACKET); add(KeyEvent.KEYCODE_RIGHT_BRACKET, LwjglGlfwKeycode.GLFW_KEY_RIGHT_BRACKET); add(KeyEvent.KEYCODE_BACKSLASH, LwjglGlfwKeycode.GLFW_KEY_BACKSLASH); add(KeyEvent.KEYCODE_SEMICOLON, LwjglGlfwKeycode.GLFW_KEY_SEMICOLON); //74 add(KeyEvent.KEYCODE_APOSTROPHE, LwjglGlfwKeycode.GLFW_KEY_APOSTROPHE); add(KeyEvent.KEYCODE_SLASH, LwjglGlfwKeycode.GLFW_KEY_SLASH); //76 add(KeyEvent.KEYCODE_AT, LwjglGlfwKeycode.GLFW_KEY_2); add(KeyEvent.KEYCODE_PLUS, LwjglGlfwKeycode.GLFW_KEY_KP_ADD); // Page keys add(KeyEvent.KEYCODE_PAGE_UP, LwjglGlfwKeycode.GLFW_KEY_PAGE_UP); //92 add(KeyEvent.KEYCODE_PAGE_DOWN, LwjglGlfwKeycode.GLFW_KEY_PAGE_DOWN); add(KeyEvent.KEYCODE_ESCAPE, LwjglGlfwKeycode.GLFW_KEY_ESCAPE); // Control keys add(KeyEvent.KEYCODE_CTRL_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL); add(KeyEvent.KEYCODE_CTRL_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT_CONTROL); add(KeyEvent.KEYCODE_CAPS_LOCK, LwjglGlfwKeycode.GLFW_KEY_CAPS_LOCK); add(KeyEvent.KEYCODE_BREAK, LwjglGlfwKeycode.GLFW_KEY_PAUSE); add(KeyEvent.KEYCODE_MOVE_HOME, LwjglGlfwKeycode.GLFW_KEY_HOME); add(KeyEvent.KEYCODE_MOVE_END, LwjglGlfwKeycode.GLFW_KEY_END); add(KeyEvent.KEYCODE_INSERT, LwjglGlfwKeycode.GLFW_KEY_INSERT); // Fn keys add(KeyEvent.KEYCODE_F1, LwjglGlfwKeycode.GLFW_KEY_F1); //131 add(KeyEvent.KEYCODE_F2, LwjglGlfwKeycode.GLFW_KEY_F2); add(KeyEvent.KEYCODE_F3, LwjglGlfwKeycode.GLFW_KEY_F3); add(KeyEvent.KEYCODE_F4, LwjglGlfwKeycode.GLFW_KEY_F4); add(KeyEvent.KEYCODE_F5, LwjglGlfwKeycode.GLFW_KEY_F5); add(KeyEvent.KEYCODE_F6, LwjglGlfwKeycode.GLFW_KEY_F6); add(KeyEvent.KEYCODE_F7, LwjglGlfwKeycode.GLFW_KEY_F7); add(KeyEvent.KEYCODE_F8, LwjglGlfwKeycode.GLFW_KEY_F8); add(KeyEvent.KEYCODE_F9, LwjglGlfwKeycode.GLFW_KEY_F9); add(KeyEvent.KEYCODE_F10, LwjglGlfwKeycode.GLFW_KEY_F10); add(KeyEvent.KEYCODE_F11, LwjglGlfwKeycode.GLFW_KEY_F11); add(KeyEvent.KEYCODE_F12, LwjglGlfwKeycode.GLFW_KEY_F12); //142 // Num keys add(KeyEvent.KEYCODE_NUM_LOCK, LwjglGlfwKeycode.GLFW_KEY_NUM_LOCK); //143 add(KeyEvent.KEYCODE_NUMPAD_0, LwjglGlfwKeycode.GLFW_KEY_KP_0); add(KeyEvent.KEYCODE_NUMPAD_1, LwjglGlfwKeycode.GLFW_KEY_KP_1); add(KeyEvent.KEYCODE_NUMPAD_2, LwjglGlfwKeycode.GLFW_KEY_KP_2); add(KeyEvent.KEYCODE_NUMPAD_3, LwjglGlfwKeycode.GLFW_KEY_KP_3); add(KeyEvent.KEYCODE_NUMPAD_4, LwjglGlfwKeycode.GLFW_KEY_KP_4); add(KeyEvent.KEYCODE_NUMPAD_5, LwjglGlfwKeycode.GLFW_KEY_KP_5); add(KeyEvent.KEYCODE_NUMPAD_6, LwjglGlfwKeycode.GLFW_KEY_KP_6); add(KeyEvent.KEYCODE_NUMPAD_7, LwjglGlfwKeycode.GLFW_KEY_KP_7); add(KeyEvent.KEYCODE_NUMPAD_8, LwjglGlfwKeycode.GLFW_KEY_KP_8); add(KeyEvent.KEYCODE_NUMPAD_9, LwjglGlfwKeycode.GLFW_KEY_KP_9); add(KeyEvent.KEYCODE_NUMPAD_DIVIDE, LwjglGlfwKeycode.GLFW_KEY_KP_DIVIDE); add(KeyEvent.KEYCODE_NUMPAD_MULTIPLY, LwjglGlfwKeycode.GLFW_KEY_KP_MULTIPLY); add(KeyEvent.KEYCODE_NUMPAD_SUBTRACT, LwjglGlfwKeycode.GLFW_KEY_KP_SUBTRACT); add(KeyEvent.KEYCODE_NUMPAD_ADD, LwjglGlfwKeycode.GLFW_KEY_KP_ADD); add(KeyEvent.KEYCODE_NUMPAD_DOT, LwjglGlfwKeycode.GLFW_KEY_KP_DECIMAL); add(KeyEvent.KEYCODE_NUMPAD_COMMA, LwjglGlfwKeycode.GLFW_KEY_COMMA); add(KeyEvent.KEYCODE_NUMPAD_ENTER, LwjglGlfwKeycode.GLFW_KEY_KP_ENTER); add(KeyEvent.KEYCODE_NUMPAD_EQUALS, LwjglGlfwKeycode.GLFW_KEY_EQUAL); //161 } public static boolean containsIndex(int index){ return index >= 0; } public static String[] generateKeyName() { if (androidKeyNameArray == null) { androidKeyNameArray = new String[sAndroidKeycodes.length]; for(int i=0; i < androidKeyNameArray.length; ++i){ androidKeyNameArray[i] = KeyEvent.keyCodeToString(sAndroidKeycodes[i]).replace("KEYCODE_", ""); } } return androidKeyNameArray; } public static void execKey(KeyEvent keyEvent, int valueIndex) { //valueIndex points to where the value is stored in the array. CallbackBridge.holdingAlt = keyEvent.isAltPressed(); CallbackBridge.holdingCapslock = keyEvent.isCapsLockOn(); CallbackBridge.holdingCtrl = keyEvent.isCtrlPressed(); CallbackBridge.holdingNumlock = keyEvent.isNumLockOn(); CallbackBridge.holdingShift = keyEvent.isShiftPressed(); System.out.println(keyEvent.getKeyCode() + " " +keyEvent.getDisplayLabel()); char key = (char)(keyEvent.getUnicodeChar() != 0 ? keyEvent.getUnicodeChar() : '\u0000'); sendKeyPress( getValueByIndex(valueIndex), key, 0, CallbackBridge.getCurrentMods(), keyEvent.getAction() == KeyEvent.ACTION_DOWN); } public static void execKeyIndex(int index){ //Send a quick key press. sendKeyPress(getValueByIndex(index)); } public static int getValueByIndex(int index) { return sLwjglKeycodes[index]; } public static int getIndexByKey(int key){ return Arrays.binarySearch(sAndroidKeycodes, key); } /** @return the index at which the key is in the array, searching linearly */ public static int getIndexByValue(int lwjglKey) { //You should avoid using this function on performance critical areas for (int i = 0; i < sLwjglKeycodes.length; i++) { if(sLwjglKeycodes[i] == lwjglKey) return i; } return 0; } private static void add(int androidKeycode, short LWJGLKeycode){ sAndroidKeycodes[mTmpCount] = androidKeycode; sLwjglKeycodes[mTmpCount] = LWJGLKeycode; mTmpCount ++; } }
10,899
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JMinecraftVersionList.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/JMinecraftVersionList.java
package net.kdt.pojavlaunch; import androidx.annotation.Keep; import java.util.*; import net.kdt.pojavlaunch.value.*; @Keep @SuppressWarnings("unused") // all unused fields here are parts of JSON structures public class JMinecraftVersionList { public Map<String, String> latest; public Version[] versions; @Keep public static class FileProperties { public String id, sha1, url; public long size; } @Keep public static class Version extends FileProperties { // Since 1.13, so it's one of ways to check public Arguments arguments; public AssetIndex assetIndex; public String assets; public Map<String, MinecraftClientInfo> downloads; public String inheritsFrom; public JavaVersionInfo javaVersion; public DependentLibrary[] libraries; public LoggingConfig logging; public String mainClass; public String minecraftArguments; public int minimumLauncherVersion; public String releaseTime; public String time; public String type; } @Keep public static class JavaVersionInfo { public String component; public int majorVersion; public int version; // parameter used by LabyMod 4 } @Keep public static class LoggingConfig { public LoggingClientConfig client; @Keep public static class LoggingClientConfig { public String argument; public FileProperties file; public String type; } } // Since 1.13 @Keep public static class Arguments { public Object[] game; public Object[] jvm; @Keep public static class ArgValue { public ArgRules[] rules; public String value; // TLauncher styled argument... public String[] values; @Keep public static class ArgRules { public String action; public String features; public ArgOS os; @Keep public static class ArgOS { public String name; public String version; } } } } @Keep public static class AssetIndex extends FileProperties { public long totalSize; } }
2,373
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FatalErrorActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/FatalErrorActivity.java
package net.kdt.pojavlaunch; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; public class FatalErrorActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if(extras == null) { finish(); return; } boolean storageAllow = extras.getBoolean("storageAllow", false); Throwable throwable = (Throwable) extras.getSerializable("throwable"); final String stackTrace = throwable != null ? Tools.printToString(throwable) : "<null>"; String strSavePath = extras.getString("savePath"); String errHeader = storageAllow ? "Crash stack trace saved to " + strSavePath + "." : "Storage permission is required to save crash stack trace!"; new AlertDialog.Builder(this) .setTitle(R.string.error_fatal) .setMessage(errHeader + "\n\n" + stackTrace) .setPositiveButton(android.R.string.ok, (p1, p2) -> finish()) .setNegativeButton(R.string.global_restart, (p1, p2) -> startActivity(new Intent(FatalErrorActivity.this, LauncherActivity.class))) .setNeutralButton(android.R.string.copy, (p1, p2) -> { ClipboardManager mgr = (ClipboardManager) FatalErrorActivity.this.getSystemService(CLIPBOARD_SERVICE); mgr.setPrimaryClip(ClipData.newPlainText("error", stackTrace)); finish(); }) .setCancelable(false) .show(); } public static void showError(Context ctx, String savePath, boolean storageAllow, Throwable th) { Intent fatalErrorIntent = new Intent(ctx, FatalErrorActivity.class); fatalErrorIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); fatalErrorIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); fatalErrorIntent.putExtra("throwable", th); fatalErrorIntent.putExtra("savePath", savePath); fatalErrorIntent.putExtra("storageAllow", storageAllow); ctx.startActivity(fatalErrorIntent); } }
2,091
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
TestStorageActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/TestStorageActivity.java
package net.kdt.pojavlaunch; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import net.kdt.pojavlaunch.tasks.AsyncAssetManager; public class TestStorageActivity extends Activity { private final int REQUEST_STORAGE_REQUEST_CODE = 1; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(Build.VERSION.SDK_INT >= 23 && Build.VERSION.SDK_INT < 29 && !isStorageAllowed(this)) requestStoragePermission(); else exit(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode == REQUEST_STORAGE_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { exit(); } else { Toast.makeText(this, R.string.toast_permission_denied, Toast.LENGTH_LONG).show(); requestStoragePermission(); } } } public static boolean isStorageAllowed(Context context) { //Getting the permission status int result1 = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE); int result2 = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE); //If permission is granted returning true return result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED; } private void requestStoragePermission() { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_REQUEST_CODE); } private void exit() { if(!Tools.checkStorageRoot(this)) { startActivity(new Intent(this, MissingStorageActivity.class)); return; } //Only run them once we get a definitive green light to use storage AsyncAssetManager.unpackComponents(this); AsyncAssetManager.unpackSingleFiles(this); Intent intent = new Intent(this, LauncherActivity.class); startActivity(intent); finish(); } }
2,694
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MissingStorageActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/MissingStorageActivity.java
package net.kdt.pojavlaunch; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class MissingStorageActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.storage_test_no_sdcard); } }
350
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LwjglGlfwKeycode.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/LwjglGlfwKeycode.java
// Keycodes from https://github.com/glfw/glfw/blob/master/include/GLFW/glfw3.h /*-************************************************************************ * GLFW 3.4 - www.glfw.org * A library for OpenGL, window and input *------------------------------------------------------------------------ * Copyright (c) 2002-2006 Marcus Geelnard * Copyright (c) 2006-2019 Camilla Löwy <[email protected]> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would * be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not * be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * *************************************************************************/ package net.kdt.pojavlaunch; @SuppressWarnings("unused") public class LwjglGlfwKeycode { /** The unknown key. */ public static final short GLFW_KEY_UNKNOWN = 0; // should be -1 /** Printable keys. */ public static final short GLFW_KEY_SPACE = 32, GLFW_KEY_APOSTROPHE = 39, GLFW_KEY_COMMA = 44, GLFW_KEY_MINUS = 45, GLFW_KEY_PERIOD = 46, GLFW_KEY_SLASH = 47, GLFW_KEY_0 = 48, GLFW_KEY_1 = 49, GLFW_KEY_2 = 50, GLFW_KEY_3 = 51, GLFW_KEY_4 = 52, GLFW_KEY_5 = 53, GLFW_KEY_6 = 54, GLFW_KEY_7 = 55, GLFW_KEY_8 = 56, GLFW_KEY_9 = 57, GLFW_KEY_SEMICOLON = 59, GLFW_KEY_EQUAL = 61, GLFW_KEY_A = 65, GLFW_KEY_B = 66, GLFW_KEY_C = 67, GLFW_KEY_D = 68, GLFW_KEY_E = 69, GLFW_KEY_F = 70, GLFW_KEY_G = 71, GLFW_KEY_H = 72, GLFW_KEY_I = 73, GLFW_KEY_J = 74, GLFW_KEY_K = 75, GLFW_KEY_L = 76, GLFW_KEY_M = 77, GLFW_KEY_N = 78, GLFW_KEY_O = 79, GLFW_KEY_P = 80, GLFW_KEY_Q = 81, GLFW_KEY_R = 82, GLFW_KEY_S = 83, GLFW_KEY_T = 84, GLFW_KEY_U = 85, GLFW_KEY_V = 86, GLFW_KEY_W = 87, GLFW_KEY_X = 88, GLFW_KEY_Y = 89, GLFW_KEY_Z = 90, GLFW_KEY_LEFT_BRACKET = 91, GLFW_KEY_BACKSLASH = 92, GLFW_KEY_RIGHT_BRACKET = 93, GLFW_KEY_GRAVE_ACCENT = 96, GLFW_KEY_WORLD_1 = 161, GLFW_KEY_WORLD_2 = 162; /** Function keys. */ public static final short GLFW_KEY_ESCAPE = 256, GLFW_KEY_ENTER = 257, GLFW_KEY_TAB = 258, GLFW_KEY_BACKSPACE = 259, GLFW_KEY_INSERT = 260, GLFW_KEY_DELETE = 261, GLFW_KEY_RIGHT = 262, GLFW_KEY_LEFT = 263, GLFW_KEY_DOWN = 264, GLFW_KEY_UP = 265, GLFW_KEY_PAGE_UP = 266, GLFW_KEY_PAGE_DOWN = 267, GLFW_KEY_HOME = 268, GLFW_KEY_END = 269, GLFW_KEY_CAPS_LOCK = 280, GLFW_KEY_SCROLL_LOCK = 281, GLFW_KEY_NUM_LOCK = 282, GLFW_KEY_PRINT_SCREEN = 283, GLFW_KEY_PAUSE = 284, GLFW_KEY_F1 = 290, GLFW_KEY_F2 = 291, GLFW_KEY_F3 = 292, GLFW_KEY_F4 = 293, GLFW_KEY_F5 = 294, GLFW_KEY_F6 = 295, GLFW_KEY_F7 = 296, GLFW_KEY_F8 = 297, GLFW_KEY_F9 = 298, GLFW_KEY_F10 = 299, GLFW_KEY_F11 = 300, GLFW_KEY_F12 = 301, GLFW_KEY_F13 = 302, GLFW_KEY_F14 = 303, GLFW_KEY_F15 = 304, GLFW_KEY_F16 = 305, GLFW_KEY_F17 = 306, GLFW_KEY_F18 = 307, GLFW_KEY_F19 = 308, GLFW_KEY_F20 = 309, GLFW_KEY_F21 = 310, GLFW_KEY_F22 = 311, GLFW_KEY_F23 = 312, GLFW_KEY_F24 = 313, GLFW_KEY_F25 = 314, GLFW_KEY_KP_0 = 320, GLFW_KEY_KP_1 = 321, GLFW_KEY_KP_2 = 322, GLFW_KEY_KP_3 = 323, GLFW_KEY_KP_4 = 324, GLFW_KEY_KP_5 = 325, GLFW_KEY_KP_6 = 326, GLFW_KEY_KP_7 = 327, GLFW_KEY_KP_8 = 328, GLFW_KEY_KP_9 = 329, GLFW_KEY_KP_DECIMAL = 330, GLFW_KEY_KP_DIVIDE = 331, GLFW_KEY_KP_MULTIPLY = 332, GLFW_KEY_KP_SUBTRACT = 333, GLFW_KEY_KP_ADD = 334, GLFW_KEY_KP_ENTER = 335, GLFW_KEY_KP_EQUAL = 336, GLFW_KEY_LEFT_SHIFT = 340, GLFW_KEY_LEFT_CONTROL = 341, GLFW_KEY_LEFT_ALT = 342, GLFW_KEY_LEFT_SUPER = 343, GLFW_KEY_RIGHT_SHIFT = 344, GLFW_KEY_RIGHT_CONTROL = 345, GLFW_KEY_RIGHT_ALT = 346, GLFW_KEY_RIGHT_SUPER = 347, GLFW_KEY_MENU = 348, GLFW_KEY_LAST = GLFW_KEY_MENU; /** If this bit is set one or more Shift keys were held down. */ public static final int GLFW_MOD_SHIFT = 0x1; /** If this bit is set one or more Control keys were held down. */ public static final int GLFW_MOD_CONTROL = 0x2; /** If this bit is set one or more Alt keys were held down. */ public static final int GLFW_MOD_ALT = 0x4; /** If this bit is set one or more Super keys were held down. */ public static final int GLFW_MOD_SUPER = 0x8; /** If this bit is set the Caps Lock key is enabled and the LOCK_KEY_MODS input mode is set. */ public static final int GLFW_MOD_CAPS_LOCK = 0x10; /** If this bit is set the Num Lock key is enabled and the LOCK_KEY_MODS input mode is set. */ public static final int GLFW_MOD_NUM_LOCK = 0x20; /** Mouse buttons. See <a target="_blank" href="http://www.glfw.org/docs/latest/input.html#input_mouse_button">mouse button input</a> for how these are used. */ public static final short GLFW_MOUSE_BUTTON_1 = 0, GLFW_MOUSE_BUTTON_2 = 1, GLFW_MOUSE_BUTTON_3 = 2, GLFW_MOUSE_BUTTON_4 = 3, GLFW_MOUSE_BUTTON_5 = 4, GLFW_MOUSE_BUTTON_6 = 5, GLFW_MOUSE_BUTTON_7 = 6, GLFW_MOUSE_BUTTON_8 = 7, GLFW_MOUSE_BUTTON_LAST = GLFW_MOUSE_BUTTON_8, GLFW_MOUSE_BUTTON_LEFT = GLFW_MOUSE_BUTTON_1, GLFW_MOUSE_BUTTON_RIGHT = GLFW_MOUSE_BUTTON_2, GLFW_MOUSE_BUTTON_MIDDLE = GLFW_MOUSE_BUTTON_3; public static final int GLFW_VISIBLE = 0x20004, GLFW_HOVERED = 0x2000B; }
7,325
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
SingleTapConfirm.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/SingleTapConfirm.java
package net.kdt.pojavlaunch; import android.view.*; import android.view.GestureDetector.*; public class SingleTapConfirm extends SimpleOnGestureListener { @Override public boolean onSingleTapUp(MotionEvent event) { return true; } }
239
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ImportControlActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/ImportControlActivity.java
package net.kdt.pojavlaunch; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.Toast; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.utils.FileUtils; import org.apache.commons.io.IOUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * An activity dedicated to importing control files. */ @SuppressWarnings("IOStreamConstructor") public class ImportControlActivity extends Activity { private Uri mUriData; private boolean mHasIntentChanged = true; private volatile boolean mIsFileVerified = false; private EditText mEditText; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Tools.initContextConstants(getApplicationContext()); setContentView(R.layout.activity_import_control); mEditText = findViewById(R.id.editText_import_control_file_name); } /** * Override the previous loaded intent * @param intent the intent used to replace the old one. */ @Override protected void onNewIntent(Intent intent) { if(intent != null) setIntent(intent); mHasIntentChanged = true; } /** * Update all over again if the intent changed. */ @Override protected void onPostResume() { super.onPostResume(); if(!mHasIntentChanged) return; mIsFileVerified = false; getUriData(); if(mUriData == null) { finishAndRemoveTask(); return; } mEditText.setText(trimFileName(Tools.getFileName(this, mUriData))); mHasIntentChanged = false; //Import and verify thread //Kill the app if the file isn't valid. new Thread(() -> { importControlFile(); if(verify())mIsFileVerified = true; else runOnUiThread(() -> { Toast.makeText( ImportControlActivity.this, getText(R.string.import_control_invalid_file), Toast.LENGTH_SHORT).show(); finishAndRemoveTask(); }); }).start(); //Auto show the keyboard Tools.MAIN_HANDLER.postDelayed(() -> { InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0); mEditText.setSelection(mEditText.getText().length()); }, 100); } /** * Start the import. * @param view the view which called the function */ public void startImport(View view) { String fileName = trimFileName(mEditText.getText().toString()); //Step 1 check for suffixes. if(!isFileNameValid(fileName)){ Toast.makeText(this, getText(R.string.import_control_invalid_name), Toast.LENGTH_SHORT).show(); return; } if(!mIsFileVerified){ Toast.makeText(this, getText(R.string.import_control_verifying_file), Toast.LENGTH_LONG).show(); return; } new File(Tools.CTRLMAP_PATH + "/TMP_IMPORT_FILE.json").renameTo(new File(Tools.CTRLMAP_PATH + "/" + fileName + ".json")); Toast.makeText(getApplicationContext(), getText(R.string.import_control_done), Toast.LENGTH_SHORT).show(); finishAndRemoveTask(); } /** * Copy a the file from the Intent data with a provided name into the controlmap folder. */ private void importControlFile(){ InputStream is; try { is = getContentResolver().openInputStream(mUriData); OutputStream os = new FileOutputStream(Tools.CTRLMAP_PATH + "/" + "TMP_IMPORT_FILE" + ".json"); IOUtils.copy(is, os); os.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Tell if the clean version of the filename is valid. * @param fileName the string to test * @return whether the filename is valid */ private static boolean isFileNameValid(String fileName){ fileName = trimFileName(fileName); if(fileName.isEmpty()) return false; return !FileUtils.exists(Tools.CTRLMAP_PATH + "/" + fileName + ".json"); } /** * Remove or undesirable chars from the string * @param fileName The string to trim * @return The trimmed string */ private static String trimFileName(String fileName){ return fileName .replace(".json", "") .replaceAll("%..", "/") .replace("/", "") .replace("\\", "") .trim(); } /** * Tries to get an Uri from the various sources */ private void getUriData(){ mUriData = getIntent().getData(); if(mUriData != null) return; try { mUriData = getIntent().getClipData().getItemAt(0).getUri(); }catch (Exception ignored){} } /** * Verify if the control file is valid * @return Whether the control file is valid */ private static boolean verify(){ try{ String jsonLayoutData = Tools.read(Tools.CTRLMAP_PATH + "/TMP_IMPORT_FILE.json"); JSONObject layoutJobj = new JSONObject(jsonLayoutData); return layoutJobj.has("version") && layoutJobj.has("mControlDataList"); }catch (JSONException | IOException e) { e.printStackTrace(); return false; } } }
5,887
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GrabListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/GrabListener.java
package net.kdt.pojavlaunch; public interface GrabListener { void onGrabState(boolean isGrabbing); }
106
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AWTInputBridge.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/AWTInputBridge.java
package net.kdt.pojavlaunch; public class AWTInputBridge { public static final int EVENT_TYPE_CHAR = 1000; public static final int EVENT_TYPE_CURSOR_POS = 1003; public static final int EVENT_TYPE_KEY = 1005; public static final int EVENT_TYPE_MOUSE_BUTTON = 1006; public static void sendKey(char keychar, int keycode) { // TODO: Android -> AWT keycode mapping nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, 1, 0); nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, 0, 0); } public static void sendKey(char keychar, int keycode, int state) { // TODO: Android -> AWT keycode mapping nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, state, 0); } public static void sendChar(char keychar){ nativeSendData(EVENT_TYPE_CHAR, (int) keychar, 0, 0, 0); } public static void sendMousePress(int awtButtons, boolean isDown) { nativeSendData(EVENT_TYPE_MOUSE_BUTTON, awtButtons, isDown ? 1 : 0, 0, 0); } public static void sendMousePress(int awtButtons) { sendMousePress(awtButtons, true); sendMousePress(awtButtons, false); } public static void sendMousePos(int x, int y) { nativeSendData(EVENT_TYPE_CURSOR_POS, x, y, 0, 0); } static { System.loadLibrary("pojavexec_awt"); } public static native void nativeSendData(int type, int i1, int i2, int i3, int i4); public static native void nativeClipboardReceived(String data, String mimeTypeSub); public static native void nativeMoveWindow(int xoff, int yoff); }
1,619
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CriticalNativeTest.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/CriticalNativeTest.java
package net.kdt.pojavlaunch; import dalvik.annotation.optimization.CriticalNative; public class CriticalNativeTest { @CriticalNative public static native void testCriticalNative(int arg0, int arg1); public static void invokeTest() { testCriticalNative(0, 0); } }
289
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ShowErrorActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/ShowErrorActivity.java
package net.kdt.pojavlaunch; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask; import net.kdt.pojavlaunch.utils.NotificationUtils; import java.io.Serializable; public class ShowErrorActivity extends Activity { private static final String ERROR_ACTIVITY_REMOTE_TASK = "remoteTask"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); if(intent == null) { finish(); return; } RemoteErrorTask remoteErrorTask = (RemoteErrorTask) intent.getSerializableExtra(ERROR_ACTIVITY_REMOTE_TASK); if(remoteErrorTask == null) { finish(); return; } remoteErrorTask.executeWithActivity(this); } public static class RemoteErrorTask implements ContextExecutorTask, Serializable { private final Throwable mThrowable; private final String mRolledMsg; public RemoteErrorTask(Throwable mThrowable, String mRolledMsg) { this.mThrowable = mThrowable; this.mRolledMsg = mRolledMsg; } @Override public void executeWithActivity(Activity activity) { if(mThrowable instanceof ContextExecutorTask) { ((ContextExecutorTask)mThrowable).executeWithActivity(activity); }else { Tools.showError(activity, mRolledMsg, mThrowable, activity instanceof ShowErrorActivity); } } @Override public void executeWithApplication(Context context) { Intent showErrorIntent = new Intent(context, ShowErrorActivity.class); showErrorIntent.putExtra(ERROR_ACTIVITY_REMOTE_TASK, this); NotificationUtils.sendBasicNotification(context, R.string.notif_error_occured, R.string.notif_error_occured_desc, showErrorIntent, NotificationUtils.PENDINGINTENT_CODE_SHOW_ERROR, NotificationUtils.NOTIFICATION_ID_SHOW_ERROR ); } } /** * Install remote dialog handling onto a dialog. This should be used when the dialog is planned to be presented * through Tools.showError or Tools.showErrorRemote as a Throwable implementing a ContextExecutorTask. * @param callerActivity the activity provided by the ContextExecutorTask.executeWithActivity * @param builder the alert dialog builder. */ public static void installRemoteDialogHandling(Activity callerActivity, @NonNull AlertDialog.Builder builder) { if (callerActivity instanceof ShowErrorActivity) { builder.setOnDismissListener(d -> callerActivity.finish()); } } }
2,999
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MainActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/MainActivity.java
package net.kdt.pojavlaunch; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_SUSTAINED_PERFORMANCE; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_USE_ALTERNATE_SURFACE; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_VIRTUAL_MOUSE_START; import static org.lwjgl.glfw.CallbackBridge.sendKeyPress; import static org.lwjgl.glfw.CallbackBridge.windowHeight; import static org.lwjgl.glfw.CallbackBridge.windowWidth; import android.app.Activity; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.IBinder; import android.provider.DocumentsContract; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.webkit.MimeTypeMap; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.drawerlayout.widget.DrawerLayout; import com.kdt.LoggerView; import net.kdt.pojavlaunch.customcontrols.ControlButtonMenuListener; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlDrawerData; import net.kdt.pojavlaunch.customcontrols.ControlJoystickData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.CustomControls; import net.kdt.pojavlaunch.customcontrols.EditorExitable; import net.kdt.pojavlaunch.customcontrols.keyboard.LwjglCharSender; import net.kdt.pojavlaunch.customcontrols.keyboard.TouchCharInput; import net.kdt.pojavlaunch.customcontrols.mouse.Touchpad; import net.kdt.pojavlaunch.lifecycle.ContextExecutor; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.services.GameService; import net.kdt.pojavlaunch.utils.JREUtils; import net.kdt.pojavlaunch.utils.MCOptionUtils; import net.kdt.pojavlaunch.value.MinecraftAccount; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import org.lwjgl.glfw.CallbackBridge; import java.io.File; import java.io.IOException; public class MainActivity extends BaseActivity implements ControlButtonMenuListener, EditorExitable, ServiceConnection { public static volatile ClipboardManager GLOBAL_CLIPBOARD; public static final String INTENT_MINECRAFT_VERSION = "intent_version"; volatile public static boolean isInputStackCall; public static TouchCharInput touchCharInput; private MinecraftGLSurface minecraftGLView; private static Touchpad touchpad; private LoggerView loggerView; private DrawerLayout drawerLayout; private ListView navDrawer; private View mDrawerPullButton; private GyroControl mGyroControl = null; public static ControlLayout mControlLayout; MinecraftProfile minecraftProfile; private ArrayAdapter<String> gameActionArrayAdapter; private AdapterView.OnItemClickListener gameActionClickListener; public ArrayAdapter<String> ingameControlsEditorArrayAdapter; public AdapterView.OnItemClickListener ingameControlsEditorListener; private GameService.LocalBinder mServiceBinder; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); minecraftProfile = LauncherProfiles.getCurrentProfile(); MCOptionUtils.load(Tools.getGameDirPath(minecraftProfile).getAbsolutePath()); Intent gameServiceIntent = new Intent(this, GameService.class); // Start the service a bit early ContextCompat.startForegroundService(this, gameServiceIntent); initLayout(R.layout.activity_basemain); CallbackBridge.addGrabListener(touchpad); CallbackBridge.addGrabListener(minecraftGLView); if(LauncherPreferences.PREF_ENABLE_GYRO) mGyroControl = new GyroControl(this); // Enabling this on TextureView results in a broken white result if(PREF_USE_ALTERNATE_SURFACE) getWindow().setBackgroundDrawable(null); else getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK)); // Set the sustained performance mode for available APIs if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) getWindow().setSustainedPerformanceMode(PREF_SUSTAINED_PERFORMANCE); ingameControlsEditorArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.menu_customcontrol)); ingameControlsEditorListener = (parent, view, position, id) -> { switch(position) { case 0: mControlLayout.addControlButton(new ControlData("New")); break; case 1: mControlLayout.addDrawer(new ControlDrawerData()); break; case 2: mControlLayout.addJoystickButton(new ControlJoystickData()); break; case 3: mControlLayout.openLoadDialog(); break; case 4: mControlLayout.openSaveDialog(this); break; case 5: mControlLayout.openSetDefaultDialog(); break; case 6: mControlLayout.openExitDialog(this); } }; // Recompute the gui scale when options are changed MCOptionUtils.MCOptionListener optionListener = MCOptionUtils::getMcScale; MCOptionUtils.addMCOptionListener(optionListener); mControlLayout.setModifiable(false); // Set the activity for the executor. Must do this here, or else Tools.showErrorRemote() may not // execute the correct method ContextExecutor.setActivity(this); //Now, attach to the service. The game will only start when this happens, to make sure that we know the right state. bindService(gameServiceIntent, this, 0); } protected void initLayout(int resId) { setContentView(resId); bindValues(); mControlLayout.setMenuListener(this); mDrawerPullButton.setOnClickListener(v -> onClickedMenu()); drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); try { File latestLogFile = new File(Tools.DIR_GAME_HOME, "latestlog.txt"); if(!latestLogFile.exists() && !latestLogFile.createNewFile()) throw new IOException("Failed to create a new log file"); Logger.begin(latestLogFile.getAbsolutePath()); // FIXME: is it safe for multi thread? GLOBAL_CLIPBOARD = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); touchCharInput.setCharacterSender(new LwjglCharSender()); if(minecraftProfile.pojavRendererName != null) { Log.i("RdrDebug","__P_renderer="+minecraftProfile.pojavRendererName); Tools.LOCAL_RENDERER = minecraftProfile.pojavRendererName; } setTitle("Minecraft " + minecraftProfile.lastVersionId); // Minecraft 1.13+ String version = getIntent().getStringExtra(INTENT_MINECRAFT_VERSION); version = version == null ? minecraftProfile.lastVersionId : version; JMinecraftVersionList.Version mVersionInfo = Tools.getVersionInfo(version); isInputStackCall = mVersionInfo.arguments != null; CallbackBridge.nativeSetUseInputStackQueue(isInputStackCall); Tools.getDisplayMetrics(this); windowWidth = Tools.getDisplayFriendlyRes(currentDisplayMetrics.widthPixels, 1f); windowHeight = Tools.getDisplayFriendlyRes(currentDisplayMetrics.heightPixels, 1f); // Menu gameActionArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.menu_ingame)); gameActionClickListener = (parent, view, position, id) -> { switch(position) { case 0: dialogForceClose(MainActivity.this); break; case 1: openLogOutput(); break; case 2: dialogSendCustomKey(); break; case 3: adjustMouseSpeedLive(); break; case 4: adjustGyroSensitivityLive(); break; case 5: openCustomControls(); break; } drawerLayout.closeDrawers(); }; navDrawer.setAdapter(gameActionArrayAdapter); navDrawer.setOnItemClickListener(gameActionClickListener); drawerLayout.closeDrawers(); final String finalVersion = version; minecraftGLView.setSurfaceReadyListener(() -> { try { // Setup virtual mouse right before launching if (PREF_VIRTUAL_MOUSE_START) { touchpad.post(() -> touchpad.switchState()); } runCraft(finalVersion, mVersionInfo); }catch (Throwable e){ Tools.showErrorRemote(e); } }); } catch (Throwable e) { Tools.showError(this, e, true); } } private void loadControls() { try { // Load keys mControlLayout.loadLayout( minecraftProfile.controlFile == null ? LauncherPreferences.PREF_DEFAULTCTRL_PATH : Tools.CTRLMAP_PATH + "/" + minecraftProfile.controlFile); } catch(IOException e) { try { Log.w("MainActivity", "Unable to load the control file, loading the default now", e); mControlLayout.loadLayout(Tools.CTRLDEF_FILE); } catch (IOException ioException) { Tools.showError(this, ioException); } } catch (Throwable th) { Tools.showError(this, th); } mDrawerPullButton.setVisibility(mControlLayout.hasMenuButton() ? View.GONE : View.VISIBLE); mControlLayout.toggleControlVisible(); } @Override public void onAttachedToWindow() { LauncherPreferences.computeNotchSize(this); loadControls(); } /** Boilerplate binding */ private void bindValues(){ mControlLayout = findViewById(R.id.main_control_layout); minecraftGLView = findViewById(R.id.main_game_render_view); touchpad = findViewById(R.id.main_touchpad); drawerLayout = findViewById(R.id.main_drawer_options); navDrawer = findViewById(R.id.main_navigation_view); loggerView = findViewById(R.id.mainLoggerView); mControlLayout = findViewById(R.id.main_control_layout); touchCharInput = findViewById(R.id.mainTouchCharInput); mDrawerPullButton = findViewById(R.id.drawer_button); } @Override public void onResume() { super.onResume(); if(mGyroControl != null) mGyroControl.enable(); CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 1); } @Override protected void onPause() { if(mGyroControl != null) mGyroControl.disable(); if (CallbackBridge.isGrabbing()){ sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ESCAPE); } CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 0); super.onPause(); } @Override protected void onStart() { super.onStart(); CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_VISIBLE, 1); } @Override protected void onStop() { CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_VISIBLE, 0); super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); CallbackBridge.removeGrabListener(touchpad); CallbackBridge.removeGrabListener(minecraftGLView); ContextExecutor.clearActivity(); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); if(mGyroControl != null) mGyroControl.updateOrientation(); Tools.updateWindowSize(this); minecraftGLView.refreshSize(); runOnUiThread(() -> mControlLayout.refreshControlButtonPositions()); } @Override protected void onPostResume() { super.onPostResume(); if(minecraftGLView != null) // Useful when backing out of the app Tools.MAIN_HANDLER.postDelayed(() -> minecraftGLView.refreshSize(), 500); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == Activity.RESULT_OK) { // Reload PREF_DEFAULTCTRL_PATH LauncherPreferences.loadPreferences(getApplicationContext()); try { mControlLayout.loadLayout(LauncherPreferences.PREF_DEFAULTCTRL_PATH); } catch (IOException e) { e.printStackTrace(); } } } public static void fullyExit() { android.os.Process.killProcess(android.os.Process.myPid()); } public static boolean isAndroid8OrHigher() { return Build.VERSION.SDK_INT >= 26; } private void runCraft(String versionId, JMinecraftVersionList.Version version) throws Throwable { if(Tools.LOCAL_RENDERER == null) { Tools.LOCAL_RENDERER = LauncherPreferences.PREF_RENDERER; } if(!Tools.checkRendererCompatible(this, Tools.LOCAL_RENDERER)) { Tools.RenderersList renderersList = Tools.getCompatibleRenderers(this); String firstCompatibleRenderer = renderersList.rendererIds.get(0); Log.w("runCraft","Incompatible renderer "+Tools.LOCAL_RENDERER+ " will be replaced with "+firstCompatibleRenderer); Tools.LOCAL_RENDERER = firstCompatibleRenderer; Tools.releaseRenderersCache(); } MinecraftAccount minecraftAccount = PojavProfile.getCurrentProfileContent(this, null); Logger.appendToLog("--------- beginning with launcher debug"); printLauncherInfo(versionId, Tools.isValidString(minecraftProfile.javaArgs) ? minecraftProfile.javaArgs : LauncherPreferences.PREF_CUSTOM_JAVA_ARGS); JREUtils.redirectAndPrintJRELog(); LauncherProfiles.load(); int requiredJavaVersion = 8; if(version.javaVersion != null) requiredJavaVersion = version.javaVersion.majorVersion; Tools.launchMinecraft(this, minecraftAccount, minecraftProfile, versionId, requiredJavaVersion); //Note that we actually stall in the above function, even if the game crashes. But let's be safe. Tools.runOnUiThread(()-> mServiceBinder.isActive = false); } private void printLauncherInfo(String gameVersion, String javaArguments) { Logger.appendToLog("Info: Launcher version: " + BuildConfig.VERSION_NAME); Logger.appendToLog("Info: Architecture: " + Architecture.archAsString(Tools.DEVICE_ARCHITECTURE)); Logger.appendToLog("Info: Device model: " + Build.MANUFACTURER + " " +Build.MODEL); Logger.appendToLog("Info: API version: " + Build.VERSION.SDK_INT); Logger.appendToLog("Info: Selected Minecraft version: " + gameVersion); Logger.appendToLog("Info: Custom Java arguments: \"" + javaArguments + "\""); } private void dialogSendCustomKey() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.control_customkey); dialog.setItems(EfficientAndroidLWJGLKeycode.generateKeyName(), (dInterface, position) -> EfficientAndroidLWJGLKeycode.execKeyIndex(position)); dialog.show(); } boolean isInEditor; private void openCustomControls() { if(ingameControlsEditorListener == null || ingameControlsEditorArrayAdapter == null) return; mControlLayout.setModifiable(true); navDrawer.setAdapter(ingameControlsEditorArrayAdapter); navDrawer.setOnItemClickListener(ingameControlsEditorListener); mDrawerPullButton.setVisibility(View.VISIBLE); isInEditor = true; } private void openLogOutput() { loggerView.setVisibility(View.VISIBLE); } public static void toggleMouse(Context ctx) { if (CallbackBridge.isGrabbing()) return; Toast.makeText(ctx, touchpad.switchState() ? R.string.control_mouseon : R.string.control_mouseoff, Toast.LENGTH_SHORT).show(); } public static void dialogForceClose(Context ctx) { new AlertDialog.Builder(ctx) .setMessage(R.string.mcn_exit_confirm) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, (p1, p2) -> { try { fullyExit(); } catch (Throwable th) { Log.w(Tools.APP_NAME, "Could not enable System.exit() method!", th); } }).show(); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if(isInEditor) { if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if(event.getAction() == KeyEvent.ACTION_DOWN) mControlLayout.askToExit(this); return true; } return super.dispatchKeyEvent(event); } boolean handleEvent; if(!(handleEvent = minecraftGLView.processKeyEvent(event))) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && !touchCharInput.isEnabled()) { if(event.getAction() != KeyEvent.ACTION_UP) return true; // We eat it anyway sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ESCAPE); return true; } } return handleEvent; } public static void switchKeyboardState() { if(touchCharInput != null) touchCharInput.switchKeyboardState(); } int tmpMouseSpeed; public void adjustMouseSpeedLive() { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(R.string.mcl_setting_title_mousespeed); View v = LayoutInflater.from(this).inflate(R.layout.dialog_live_mouse_speed_editor,null); final SeekBar sb = v.findViewById(R.id.mouseSpeed); final TextView tv = v.findViewById(R.id.mouseSpeedTV); sb.setMax(275); tmpMouseSpeed = (int) ((LauncherPreferences.PREF_MOUSESPEED*100)); sb.setProgress(tmpMouseSpeed-25); tv.setText(getString(R.string.percent_format, tmpMouseSpeed)); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { tmpMouseSpeed = i+25; tv.setText(getString(R.string.percent_format, tmpMouseSpeed)); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); b.setView(v); b.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> { LauncherPreferences.PREF_MOUSESPEED = ((float)tmpMouseSpeed)/100f; LauncherPreferences.DEFAULT_PREF.edit().putInt("mousespeed",tmpMouseSpeed).apply(); dialogInterface.dismiss(); System.gc(); }); b.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> { dialogInterface.dismiss(); System.gc(); }); b.show(); } int tmpGyroSensitivity; public void adjustGyroSensitivityLive() { if(!LauncherPreferences.PREF_ENABLE_GYRO) { Toast.makeText(this, R.string.toast_turn_on_gyro, Toast.LENGTH_LONG).show(); return; } AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(R.string.preference_gyro_sensitivity_title); View v = LayoutInflater.from(this).inflate(R.layout.dialog_live_mouse_speed_editor,null); final SeekBar sb = v.findViewById(R.id.mouseSpeed); final TextView tv = v.findViewById(R.id.mouseSpeedTV); sb.setMax(275); tmpGyroSensitivity = (int) ((LauncherPreferences.PREF_GYRO_SENSITIVITY*100)); sb.setProgress(tmpGyroSensitivity -25); tv.setText(getString(R.string.percent_format, tmpGyroSensitivity)); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { tmpGyroSensitivity = i+25; tv.setText(getString(R.string.percent_format, tmpGyroSensitivity)); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) {} }); b.setView(v); b.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> { LauncherPreferences.PREF_GYRO_SENSITIVITY = ((float) tmpGyroSensitivity)/100f; LauncherPreferences.DEFAULT_PREF.edit().putInt("gyroSensitivity", tmpGyroSensitivity).apply(); dialogInterface.dismiss(); System.gc(); }); b.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> { dialogInterface.dismiss(); System.gc(); }); b.show(); } private static void setUri(Context context, String input, Intent intent) { if(input.startsWith("file:")) { int truncLength = 5; if(input.startsWith("file://")) truncLength = 7; input = input.substring(truncLength); Log.i("MainActivity", input); boolean isDirectory = new File(input).isDirectory(); if(isDirectory) { intent.setType(DocumentsContract.Document.MIME_TYPE_DIR); }else{ String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(input); if(extension != null) type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if(type == null) type = "*/*"; intent.setType(type); } intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); intent.setData(DocumentsContract.buildDocumentUri( context.getString(R.string.storageProviderAuthorities), input )); return; } intent.setDataAndType(Uri.parse(input), "*/*"); } public static void openLink(String link) { Context ctx = touchpad.getContext(); // no more better way to obtain a context statically ((Activity)ctx).runOnUiThread(() -> { try { Intent intent = new Intent(Intent.ACTION_VIEW); setUri(ctx, link, intent); ctx.startActivity(intent); } catch (Throwable th) { Tools.showError(ctx, th); } }); } @SuppressWarnings("unused") //TODO: actually use it public static void openPath(String path) { Context ctx = touchpad.getContext(); // no more better way to obtain a context statically ((Activity)ctx).runOnUiThread(() -> { try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(DocumentsContract.buildDocumentUri(ctx.getString(R.string.storageProviderAuthorities), path), "*/*"); ctx.startActivity(intent); } catch (Throwable th) { Tools.showError(ctx, th); } }); } public static void querySystemClipboard() { Tools.runOnUiThread(()->{ ClipData clipData = GLOBAL_CLIPBOARD.getPrimaryClip(); if(clipData == null) { AWTInputBridge.nativeClipboardReceived(null, null); return; } ClipData.Item firstClipItem = clipData.getItemAt(0); //TODO: coerce to HTML if the clip item is styled CharSequence clipItemText = firstClipItem.getText(); if(clipItemText == null) { AWTInputBridge.nativeClipboardReceived(null, null); return; } AWTInputBridge.nativeClipboardReceived(clipItemText.toString(), "plain"); }); } public static void putClipboardData(String data, String mimeType) { Tools.runOnUiThread(()-> { ClipData clipData = null; switch(mimeType) { case "text/plain": clipData = ClipData.newPlainText("AWT Paste", data); break; case "text/html": clipData = ClipData.newHtmlText("AWT Paste", data, data); } if(clipData != null) GLOBAL_CLIPBOARD.setPrimaryClip(clipData); }); } @Override public void onClickedMenu() { drawerLayout.openDrawer(navDrawer); navDrawer.requestLayout(); } @Override public void exitEditor() { try { MainActivity.mControlLayout.loadLayout((CustomControls)null); MainActivity.mControlLayout.setModifiable(false); System.gc(); MainActivity.mControlLayout.loadLayout( minecraftProfile.controlFile == null ? LauncherPreferences.PREF_DEFAULTCTRL_PATH : Tools.CTRLMAP_PATH + "/" + minecraftProfile.controlFile); mDrawerPullButton.setVisibility(mControlLayout.hasMenuButton() ? View.GONE : View.VISIBLE); } catch (IOException e) { Tools.showError(this,e); } //((MainActivity) this).mControlLayout.loadLayout((CustomControls)null); navDrawer.setAdapter(gameActionArrayAdapter); navDrawer.setOnItemClickListener(gameActionClickListener); isInEditor = false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { GameService.LocalBinder localBinder = (GameService.LocalBinder) service; mServiceBinder = localBinder; minecraftGLView.start(localBinder.isActive, touchpad); localBinder.isActive = true; } @Override public void onServiceDisconnected(ComponentName name) { } }
27,001
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CustomControlsActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/CustomControlsActivity.java
package net.kdt.pojavlaunch; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.DocumentsContract; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.drawerlayout.widget.DrawerLayout; import net.kdt.pojavlaunch.customcontrols.ControlData; import net.kdt.pojavlaunch.customcontrols.ControlDrawerData; import net.kdt.pojavlaunch.customcontrols.ControlJoystickData; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.EditorExitable; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import java.io.IOException; public class CustomControlsActivity extends BaseActivity implements EditorExitable { private DrawerLayout mDrawerLayout; private ListView mDrawerNavigationView; private ControlLayout mControlLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_custom_controls); mControlLayout = findViewById(R.id.customctrl_controllayout); mDrawerLayout = findViewById(R.id.customctrl_drawerlayout); mDrawerNavigationView = findViewById(R.id.customctrl_navigation_view); View mPullDrawerButton = findViewById(R.id.drawer_button); mPullDrawerButton.setOnClickListener(v -> mDrawerLayout.openDrawer(mDrawerNavigationView)); mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); mDrawerNavigationView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.menu_customcontrol_customactivity))); mDrawerNavigationView.setOnItemClickListener((parent, view, position, id) -> { switch(position) { case 0: mControlLayout.addControlButton(new ControlData("New")); break; case 1: mControlLayout.addDrawer(new ControlDrawerData()); break; case 2: mControlLayout.addJoystickButton(new ControlJoystickData()); break; case 3: mControlLayout.openLoadDialog(); break; case 4: mControlLayout.openSaveDialog(this); break; case 5: mControlLayout.openSetDefaultDialog(); break; case 6: // Saving the currently shown control try { Uri contentUri = DocumentsContract.buildDocumentUri(getString(R.string.storageProviderAuthorities), mControlLayout.saveToDirectory(mControlLayout.mLayoutFileName)); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); shareIntent.setType("application/json"); startActivity(shareIntent); Intent sendIntent = Intent.createChooser(shareIntent, mControlLayout.mLayoutFileName); startActivity(sendIntent); }catch (Exception e) { Tools.showError(this, e); } break; } mDrawerLayout.closeDrawers(); }); mControlLayout.setModifiable(true); try { mControlLayout.loadLayout(LauncherPreferences.PREF_DEFAULTCTRL_PATH); }catch (IOException e) { Tools.showError(this, e); } } @Override public void onBackPressed() { mControlLayout.askToExit(this); } @Override public void exitEditor() { super.onBackPressed(); } }
3,250
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JRE17Util.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/JRE17Util.java
package net.kdt.pojavlaunch; import static net.kdt.pojavlaunch.Architecture.archAsString; import android.app.Activity; import android.content.res.AssetManager; import android.util.Log; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.multirt.Runtime; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import java.io.IOException; public class JRE17Util { public static final String NEW_JRE_NAME = "Internal-17"; public static boolean checkInternalNewJre(AssetManager assetManager) { String launcher_jre17_version; String installed_jre17_version = MultiRTUtils.__internal__readBinpackVersion(NEW_JRE_NAME); try { launcher_jre17_version = Tools.read(assetManager.open("components/jre-new/version")); }catch (IOException exc) { //we don't have a runtime included! return installed_jre17_version != null; //if we have one installed -> return true -> proceed (no updates but the current one should be functional) //if we don't -> return false -> Cannot find compatible Java runtime } if(!launcher_jre17_version.equals(installed_jre17_version)) // this implicitly checks for null, so it will unpack the runtime even if we don't have one installed return unpackJre17(assetManager, launcher_jre17_version); else return true; } private static boolean unpackJre17(AssetManager assetManager, String rt_version) { try { MultiRTUtils.installRuntimeNamedBinpack( assetManager.open("components/jre-new/universal.tar.xz"), assetManager.open("components/jre-new/bin-" + archAsString(Tools.DEVICE_ARCHITECTURE) + ".tar.xz"), "Internal-17", rt_version); MultiRTUtils.postPrepare("Internal-17"); return true; }catch (IOException e) { Log.e("JRE17Auto", "Internal JRE unpack failed", e); return false; } } public static boolean isInternalNewJRE(String s_runtime) { Runtime runtime = MultiRTUtils.read(s_runtime); if(runtime == null) return false; return NEW_JRE_NAME.equals(runtime.name); } /** @return true if everything is good, false otherwise. */ public static boolean installNewJreIfNeeded(Activity activity, JMinecraftVersionList.Version versionInfo) { //Now we have the reliable information to check if our runtime settings are good enough if (versionInfo.javaVersion == null || versionInfo.javaVersion.component.equalsIgnoreCase("jre-legacy")) return true; LauncherProfiles.load(); MinecraftProfile minecraftProfile = LauncherProfiles.getCurrentProfile(); String selectedRuntime = Tools.getSelectedRuntime(minecraftProfile); Runtime runtime = MultiRTUtils.read(selectedRuntime); if (runtime.javaVersion >= versionInfo.javaVersion.majorVersion) { return true; } String appropriateRuntime = MultiRTUtils.getNearestJreName(versionInfo.javaVersion.majorVersion); if (appropriateRuntime != null) { if (JRE17Util.isInternalNewJRE(appropriateRuntime)) { JRE17Util.checkInternalNewJre(activity.getAssets()); } minecraftProfile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX + appropriateRuntime; LauncherProfiles.load(); } else { if (versionInfo.javaVersion.majorVersion <= 17) { // there's a chance we have an internal one for this case if (!JRE17Util.checkInternalNewJre(activity.getAssets())){ showRuntimeFail(activity, versionInfo); return false; } else { minecraftProfile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX + JRE17Util.NEW_JRE_NAME; LauncherProfiles.load(); } } else { showRuntimeFail(activity, versionInfo); return false; } } return true; } private static void showRuntimeFail(Activity activity, JMinecraftVersionList.Version verInfo) { Tools.dialogOnUiThread(activity, activity.getString(R.string.global_error), activity.getString(R.string.multirt_nocompartiblert, verInfo.javaVersion.majorVersion)); } }
4,464
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GyroControl.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/GyroControl.java
package net.kdt.pojavlaunch; import android.app.Activity; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.view.OrientationEventListener; import android.view.Surface; import android.view.WindowManager; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import org.lwjgl.glfw.CallbackBridge; import java.util.Arrays; public class GyroControl implements SensorEventListener, GrabListener { /* How much distance has to be moved before taking into account the gyro */ private static final float SINGLE_AXIS_LOW_PASS_THRESHOLD = 1.13F; private static final float MULTI_AXIS_LOW_PASS_THRESHOLD = 1.3F; private final WindowManager mWindowManager; private int mSurfaceRotation; private final SensorManager mSensorManager; private final Sensor mSensor; private final OrientationCorrectionListener mCorrectionListener; private boolean mShouldHandleEvents; private boolean mFirstPass; private float xFactor; // -1 or 1 depending on device orientation private float yFactor; private boolean mSwapXY; private final float[] mPreviousRotation = new float[16]; private final float[] mCurrentRotation = new float[16]; private final float[] mAngleDifference = new float[3]; /* Used to average the last values, if smoothing is enabled */ private final float[][] mAngleBuffer = new float[ LauncherPreferences.PREF_GYRO_SMOOTHING ? 2 : 1 ][3]; private float xTotal = 0; private float yTotal = 0; private float xAverage = 0; private float yAverage = 0; private int mHistoryIndex = -1; /* Store the gyro movement under the threshold */ private float mStoredX = 0; private float mStoredY = 0; public GyroControl(Activity activity) { mWindowManager = activity.getWindowManager(); mSurfaceRotation = -10; mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR); mCorrectionListener = new OrientationCorrectionListener(activity); updateOrientation(); } public void enable() { if(mSensor == null) return; mFirstPass = true; mSensorManager.registerListener(this, mSensor, 1000 * LauncherPreferences.PREF_GYRO_SAMPLE_RATE); mCorrectionListener.enable(); mShouldHandleEvents = CallbackBridge.isGrabbing(); CallbackBridge.addGrabListener(this); } public void disable() { if(mSensor == null) return; mSensorManager.unregisterListener(this); mCorrectionListener.disable(); resetDamper(); CallbackBridge.removeGrabListener(this); } @Override public void onSensorChanged(SensorEvent sensorEvent) { if (!mShouldHandleEvents) return; // Copy the old array content System.arraycopy(mCurrentRotation, 0, mPreviousRotation, 0, 16); SensorManager.getRotationMatrixFromVector(mCurrentRotation, sensorEvent.values); if(mFirstPass){ // Setup initial position mFirstPass = false; return; } SensorManager.getAngleChange(mAngleDifference, mCurrentRotation, mPreviousRotation); damperValue(mAngleDifference); mStoredX += xAverage * 1000 * LauncherPreferences.PREF_GYRO_SENSITIVITY; mStoredY += yAverage * 1000 * LauncherPreferences.PREF_GYRO_SENSITIVITY; boolean updatePosition = false; float absX = Math.abs(mStoredX); float absY = Math.abs(mStoredY); if(absX + absY > MULTI_AXIS_LOW_PASS_THRESHOLD) { CallbackBridge.mouseX -= ((mSwapXY ? mStoredY : mStoredX) * xFactor); CallbackBridge.mouseY += ((mSwapXY ? mStoredX : mStoredY) * yFactor); mStoredX = 0; mStoredY = 0; updatePosition = true; } else { if(Math.abs(mStoredX) > SINGLE_AXIS_LOW_PASS_THRESHOLD){ CallbackBridge.mouseX -= ((mSwapXY ? mStoredY : mStoredX) * xFactor); mStoredX = 0; updatePosition = true; } if(Math.abs(mStoredY) > SINGLE_AXIS_LOW_PASS_THRESHOLD) { CallbackBridge.mouseY += ((mSwapXY ? mStoredX : mStoredY) * yFactor); mStoredY = 0; updatePosition = true; } } if(updatePosition){ CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY); } } /** Update the axis mapping in accordance to activity rotation, used for initial rotation */ public void updateOrientation(){ int rotation = mWindowManager.getDefaultDisplay().getRotation(); mSurfaceRotation = rotation; switch (rotation){ case Surface.ROTATION_0: mSwapXY = true; xFactor = 1; yFactor = 1; break; case Surface.ROTATION_90: mSwapXY = false; xFactor = -1; yFactor = 1; break; case Surface.ROTATION_180: mSwapXY = true; xFactor = -1; yFactor = -1; break; case Surface.ROTATION_270: mSwapXY = false; xFactor = 1; yFactor = -1; break; } if(LauncherPreferences.PREF_GYRO_INVERT_X) xFactor *= -1; if(LauncherPreferences.PREF_GYRO_INVERT_Y) yFactor *= -1; } @Override public void onAccuracyChanged(Sensor sensor, int i) {} @Override public void onGrabState(boolean isGrabbing) { mFirstPass = true; mShouldHandleEvents = isGrabbing; } /** * Compute the moving average of the gyroscope to reduce jitter * @param newAngleDifference The new angle difference */ private void damperValue(float[] newAngleDifference){ mHistoryIndex ++; if(mHistoryIndex >= mAngleBuffer.length) mHistoryIndex = 0; xTotal -= mAngleBuffer[mHistoryIndex][1]; yTotal -= mAngleBuffer[mHistoryIndex][2]; System.arraycopy(newAngleDifference, 0, mAngleBuffer[mHistoryIndex], 0, 3); xTotal += mAngleBuffer[mHistoryIndex][1]; yTotal += mAngleBuffer[mHistoryIndex][2]; // compute the moving average xAverage = xTotal / mAngleBuffer.length; yAverage = yTotal / mAngleBuffer.length; } /** Reset the moving average data */ private void resetDamper(){ mHistoryIndex = -1; xTotal = 0; yTotal = 0; xAverage = 0; yAverage = 0; for(float[] oldAngle : mAngleBuffer){ Arrays.fill(oldAngle, 0); } } class OrientationCorrectionListener extends OrientationEventListener { public OrientationCorrectionListener(Context context) { super(context, SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onOrientationChanged(int i) { // Force to wait to be in game before setting factors // Theoretically, one could use the whole interface in portrait... if(!mShouldHandleEvents) return; if(i == OrientationEventListener.ORIENTATION_UNKNOWN) { return; //change nothing } switch (mSurfaceRotation){ case Surface.ROTATION_90: case Surface.ROTATION_270: mSwapXY = false; if(225 < i && i < 315) { xFactor = -1; yFactor = 1; }else if(45 < i && i < 135) { xFactor = 1; yFactor = -1; } break; case Surface.ROTATION_0: case Surface.ROTATION_180: mSwapXY = true; if((315 < i && i <= 360) || (i < 45) ) { xFactor = 1; yFactor = 1; }else if(135 < i && i < 225) { xFactor = -1; yFactor = -1; } break; } if(LauncherPreferences.PREF_GYRO_INVERT_X) xFactor *= -1; if(LauncherPreferences.PREF_GYRO_INVERT_Y) yFactor *= -1; } } }
8,572
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ExitActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/ExitActivity.java
package net.kdt.pojavlaunch; import static net.kdt.pojavlaunch.Tools.shareLog; import android.annotation.SuppressLint; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Keep; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; @Keep public class ExitActivity extends AppCompatActivity { @SuppressLint("StringFormatInvalid") //invalid on some translations but valid on most, cant fix that atm @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); int code = -1; Bundle extras = getIntent().getExtras(); if(extras != null) { code = extras.getInt("code",-1); } new AlertDialog.Builder(this) .setMessage(getString(R.string.mcn_exit_title,code)) .setPositiveButton(R.string.main_share_logs, (dialog, which) -> shareLog(this)) .setOnDismissListener(dialog -> ExitActivity.this.finish()) .show(); } public static void showExitMessage(Context ctx, int code) { Intent i = new Intent(ctx,ExitActivity.class); i.putExtra("code",code); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ctx.startActivity(i); } }
1,469
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JavaGUILauncherActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/JavaGUILauncherActivity.java
package net.kdt.pojavlaunch; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.content.ClipboardManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import androidx.activity.OnBackPressedCallback; import com.kdt.LoggerView; import net.kdt.pojavlaunch.customcontrols.keyboard.AwtCharSender; import net.kdt.pojavlaunch.customcontrols.keyboard.TouchCharInput; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.multirt.Runtime; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.JREUtils; import net.kdt.pojavlaunch.utils.MathUtils; import org.apache.commons.io.IOUtils; import org.lwjgl.glfw.CallbackBridge; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouchListener { private AWTCanvasView mTextureView; private LoggerView mLoggerView; private TouchCharInput mTouchCharInput; private LinearLayout mTouchPad; private ImageView mMousePointerImageView; private GestureDetector mGestureDetector; private boolean mIsVirtualMouseEnabled; @SuppressLint("ClickableViewAccessibility") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_java_gui_launcher); try { File latestLogFile = new File(Tools.DIR_GAME_HOME, "latestlog.txt"); if (!latestLogFile.exists() && !latestLogFile.createNewFile()) throw new IOException("Failed to create a new log file"); Logger.begin(latestLogFile.getAbsolutePath()); }catch (IOException e) { Tools.showError(this, e, true); } MainActivity.GLOBAL_CLIPBOARD = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); mTouchCharInput = findViewById(R.id.awt_touch_char); mTouchCharInput.setCharacterSender(new AwtCharSender()); mTouchPad = findViewById(R.id.main_touchpad); mLoggerView = findViewById(R.id.launcherLoggerView); mMousePointerImageView = findViewById(R.id.main_mouse_pointer); mTextureView = findViewById(R.id.installmod_surfaceview); mGestureDetector = new GestureDetector(this, new SingleTapConfirm()); mTouchPad.setFocusable(false); mTouchPad.setVisibility(View.GONE); findViewById(R.id.installmod_mouse_pri).setOnTouchListener(this); findViewById(R.id.installmod_mouse_sec).setOnTouchListener(this); findViewById(R.id.installmod_window_moveup).setOnTouchListener(this); findViewById(R.id.installmod_window_movedown).setOnTouchListener(this); findViewById(R.id.installmod_window_moveleft).setOnTouchListener(this); findViewById(R.id.installmod_window_moveright).setOnTouchListener(this); mMousePointerImageView.post(() -> { ViewGroup.LayoutParams params = mMousePointerImageView.getLayoutParams(); params.width = (int) (36 / 100f * LauncherPreferences.PREF_MOUSESCALE); params.height = (int) (54 / 100f * LauncherPreferences.PREF_MOUSESCALE); }); mTouchPad.setOnTouchListener(new View.OnTouchListener() { float prevX = 0, prevY = 0; @Override public boolean onTouch(View v, MotionEvent event) { // MotionEvent reports input details from the touch screen // and other input controls. In this case, you are only // interested in events where the touch position changed. // int index = event.getActionIndex(); int action = event.getActionMasked(); float x = event.getX(); float y = event.getY(); float mouseX, mouseY; mouseX = mMousePointerImageView.getX(); mouseY = mMousePointerImageView.getY(); if (mGestureDetector.onTouchEvent(event)) { sendScaledMousePosition(mouseX,mouseY); AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON1_DOWN_MASK); } else { if (action == MotionEvent.ACTION_MOVE) { // 2 mouseX = Math.max(0, Math.min(CallbackBridge.physicalWidth, mouseX + x - prevX)); mouseY = Math.max(0, Math.min(CallbackBridge.physicalHeight, mouseY + y - prevY)); placeMouseAt(mouseX, mouseY); sendScaledMousePosition(mouseX, mouseY); } } prevY = y; prevX = x; return true; } }); mTextureView.setOnTouchListener((v, event) -> { float x = event.getX(); float y = event.getY(); if (mGestureDetector.onTouchEvent(event)) { sendScaledMousePosition(x + mTextureView.getX(), y); AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON1_DOWN_MASK); return true; } switch (event.getActionMasked()) { case MotionEvent.ACTION_UP: // 1 case MotionEvent.ACTION_CANCEL: // 3 case MotionEvent.ACTION_POINTER_UP: // 6 break; case MotionEvent.ACTION_MOVE: // 2 sendScaledMousePosition(x + mTextureView.getX(), y); break; } return true; }); try { placeMouseAt(CallbackBridge.physicalWidth / 2f, CallbackBridge.physicalHeight / 2f); Bundle extras = getIntent().getExtras(); if(extras == null) { finish(); return; } final String javaArgs = extras.getString("javaArgs"); final Uri resourceUri = (Uri) extras.getParcelable("modUri"); if(extras.getBoolean("openLogOutput", false)) openLogOutput(null); if (javaArgs != null) { startModInstaller(null, javaArgs); }else if(resourceUri != null) { ProgressDialog barrierDialog = Tools.getWaitingDialog(this, R.string.multirt_progress_caching); PojavApplication.sExecutorService.execute(()->{ startModInstallerWithUri(resourceUri); runOnUiThread(barrierDialog::dismiss); }); } } catch (Throwable th) { Tools.showError(this, th, true); } getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { MainActivity.dialogForceClose(JavaGUILauncherActivity.this); } }); } private void startModInstallerWithUri(Uri uri) { try { File cacheFile = new File(getCacheDir(), "mod-installer-temp"); InputStream contentStream = getContentResolver().openInputStream(uri); try (FileOutputStream fileOutputStream = new FileOutputStream(cacheFile)) { IOUtils.copy(contentStream, fileOutputStream); } contentStream.close(); startModInstaller(cacheFile, null); }catch (IOException e) { Tools.showError(this, e, true); } } private void startModInstaller(File modFile, String javaArgs) { new Thread(() -> { Runtime runtime = pickJreForMod(modFile); launchJavaRuntime(runtime, modFile, javaArgs); }, "JREMainThread").start(); } private Runtime pickJreForMod(File modFile) { String jreName = LauncherPreferences.PREF_DEFAULT_RUNTIME; if(modFile != null) { int javaVersion = getJavaVersion(modFile); if(javaVersion != -1) { String autoselectRuntime = MultiRTUtils.getNearestJreName(javaVersion); if (autoselectRuntime != null) jreName = autoselectRuntime; } } return MultiRTUtils.forceReread(jreName); } @Override public void onResume() { super.onResume(); final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; final View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(uiOptions); } @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent e) { boolean isDown; switch (e.getActionMasked()) { case MotionEvent.ACTION_DOWN: // 0 case MotionEvent.ACTION_POINTER_DOWN: // 5 isDown = true; break; case MotionEvent.ACTION_UP: // 1 case MotionEvent.ACTION_CANCEL: // 3 case MotionEvent.ACTION_POINTER_UP: // 6 isDown = false; break; default: return false; } switch (v.getId()) { case R.id.installmod_mouse_pri: AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON1_DOWN_MASK, isDown); break; case R.id.installmod_mouse_sec: AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON3_DOWN_MASK, isDown); break; } if(isDown) switch(v.getId()) { case R.id.installmod_window_moveup: AWTInputBridge.nativeMoveWindow(0, -10); break; case R.id.installmod_window_movedown: AWTInputBridge.nativeMoveWindow(0, 10); break; case R.id.installmod_window_moveleft: AWTInputBridge.nativeMoveWindow(-10, 0); break; case R.id.installmod_window_moveright: AWTInputBridge.nativeMoveWindow(10, 0); break; } return true; } public void placeMouseAt(float x, float y) { mMousePointerImageView.setX(x); mMousePointerImageView.setY(y); } @SuppressWarnings("SuspiciousNameCombination") void sendScaledMousePosition(float x, float y){ // Clamp positions to the borders of the usable view, then scale them x = androidx.core.math.MathUtils.clamp(x, mTextureView.getX(), mTextureView.getX() + mTextureView.getWidth()); y = androidx.core.math.MathUtils.clamp(y, mTextureView.getY(), mTextureView.getY() + mTextureView.getHeight()); AWTInputBridge.sendMousePos( (int) MathUtils.map(x, mTextureView.getX(), mTextureView.getX() + mTextureView.getWidth(), 0, AWTCanvasView.AWT_CANVAS_WIDTH), (int) MathUtils.map(y, mTextureView.getY(), mTextureView.getY() + mTextureView.getHeight(), 0, AWTCanvasView.AWT_CANVAS_HEIGHT) ); } public void forceClose(View v) { MainActivity.dialogForceClose(this); } public void openLogOutput(View v) { mLoggerView.setVisibility(View.VISIBLE); } public void toggleVirtualMouse(View v) { mIsVirtualMouseEnabled = !mIsVirtualMouseEnabled; mTouchPad.setVisibility(mIsVirtualMouseEnabled ? View.VISIBLE : View.GONE); Toast.makeText(this, mIsVirtualMouseEnabled ? R.string.control_mouseon : R.string.control_mouseoff, Toast.LENGTH_SHORT).show(); } public void launchJavaRuntime(Runtime runtime, File modFile, String javaArgs) { JREUtils.redirectAndPrintJRELog(); try { List<String> javaArgList = new ArrayList<>(); // Enable Caciocavallo Tools.getCacioJavaArgs(javaArgList,runtime.javaVersion == 8); if (javaArgs != null) { javaArgList.addAll(Arrays.asList(javaArgs.split(" "))); } else { javaArgList.add("-jar"); javaArgList.add(modFile.getAbsolutePath()); } if (LauncherPreferences.PREF_JAVA_SANDBOX) { Collections.reverse(javaArgList); javaArgList.add("-Xbootclasspath/a:" + Tools.DIR_DATA + "/security/pro-grade.jar"); javaArgList.add("-Djava.security.manager=net.sourceforge.prograde.sm.ProGradeJSM"); javaArgList.add("-Djava.security.policy=" + Tools.DIR_DATA + "/security/java_sandbox.policy"); Collections.reverse(javaArgList); } Logger.appendToLog("Info: Java arguments: " + Arrays.toString(javaArgList.toArray(new String[0]))); JREUtils.launchJavaVM(this, runtime,null,javaArgList, LauncherPreferences.PREF_CUSTOM_JAVA_ARGS); } catch (Throwable th) { Tools.showError(this, th, true); } } public void toggleKeyboard(View view) { mTouchCharInput.switchKeyboardState(); } public void performCopy(View view) { AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 1); AWTInputBridge.sendKey(' ', AWTInputEvent.VK_C); AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 0); } public void performPaste(View view) { AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 1); AWTInputBridge.sendKey(' ', AWTInputEvent.VK_V); AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 0); } public int getJavaVersion(File modFile) { try (ZipFile zipFile = new ZipFile(modFile)){ ZipEntry manifest = zipFile.getEntry("META-INF/MANIFEST.MF"); if(manifest == null) return -1; String manifestString = Tools.read(zipFile.getInputStream(manifest)); String mainClass = Tools.extractUntilCharacter(manifestString, "Main-Class:", '\n'); if(mainClass == null) return -1; mainClass = mainClass.trim().replace('.', '/') + ".class"; ZipEntry mainClassFile = zipFile.getEntry(mainClass); if(mainClassFile == null) return -1; InputStream classStream = zipFile.getInputStream(mainClassFile); byte[] bytesWeNeed = new byte[8]; int readCount = classStream.read(bytesWeNeed); classStream.close(); if(readCount < 8) return -1; ByteBuffer byteBuffer = ByteBuffer.wrap(bytesWeNeed); if(byteBuffer.getInt() != 0xCAFEBABE) return -1; short minorVersion = byteBuffer.getShort(); short majorVersion = byteBuffer.getShort(); Log.i("JavaGUILauncher", majorVersion+","+minorVersion); return classVersionToJavaVersion(majorVersion); }catch (Exception e) { e.printStackTrace(); return -1; } } public static int classVersionToJavaVersion(int majorVersion) { if(majorVersion < 46) return 2; // there isn't even an arm64 port of jre 1.1 (or anything before 1.8 in fact) return majorVersion - 44; } }
15,457
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/LauncherActivity.java
package net.kdt.pojavlaunch; import android.Manifest; import android.app.NotificationManager; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentContainerView; import androidx.fragment.app.FragmentManager; import com.kdt.mcgui.ProgressLayout; import com.kdt.mcgui.mcAccountSpinner; import net.kdt.pojavlaunch.contracts.OpenDocumentWithExtension; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.extra.ExtraListener; import net.kdt.pojavlaunch.fragments.MainMenuFragment; import net.kdt.pojavlaunch.fragments.MicrosoftLoginFragment; import net.kdt.pojavlaunch.fragments.SelectAuthFragment; import net.kdt.pojavlaunch.lifecycle.ContextAwareDoneListener; import net.kdt.pojavlaunch.lifecycle.ContextExecutor; import net.kdt.pojavlaunch.modloaders.modpacks.ModloaderInstallTracker; import net.kdt.pojavlaunch.modloaders.modpacks.imagecache.IconCacheJanitor; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.prefs.screens.LauncherPreferenceFragment; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.progresskeeper.TaskCountListener; import net.kdt.pojavlaunch.services.ProgressServiceKeeper; import net.kdt.pojavlaunch.tasks.AsyncMinecraftDownloader; import net.kdt.pojavlaunch.tasks.AsyncVersionList; import net.kdt.pojavlaunch.tasks.MinecraftDownloader; import net.kdt.pojavlaunch.utils.NotificationUtils; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import java.lang.ref.WeakReference; public class LauncherActivity extends BaseActivity { public static final String SETTING_FRAGMENT_TAG = "SETTINGS_FRAGMENT"; public final ActivityResultLauncher<Object> modInstallerLauncher = registerForActivityResult(new OpenDocumentWithExtension("jar"), (data)->{ if(data != null) Tools.launchModInstaller(this, data); }); private mcAccountSpinner mAccountSpinner; private FragmentContainerView mFragmentView; private ImageButton mSettingsButton, mDeleteAccountButton; private ProgressLayout mProgressLayout; private ProgressServiceKeeper mProgressServiceKeeper; private ModloaderInstallTracker mInstallTracker; private NotificationManager mNotificationManager; /* Allows to switch from one button "type" to another */ private final FragmentManager.FragmentLifecycleCallbacks mFragmentCallbackListener = new FragmentManager.FragmentLifecycleCallbacks() { @Override public void onFragmentResumed(@NonNull FragmentManager fm, @NonNull Fragment f) { mSettingsButton.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), f instanceof MainMenuFragment ? R.drawable.ic_menu_settings : R.drawable.ic_menu_home)); } }; /* Listener for the back button in settings */ private final ExtraListener<String> mBackPreferenceListener = (key, value) -> { if(value.equals("true")) onBackPressed(); return false; }; /* Listener for the auth method selection screen */ private final ExtraListener<Boolean> mSelectAuthMethod = (key, value) -> { Fragment fragment = getSupportFragmentManager().findFragmentById(mFragmentView.getId()); // Allow starting the add account only from the main menu, should it be moved to fragment itself ? if(!(fragment instanceof MainMenuFragment)) return false; Tools.swapFragment(this, SelectAuthFragment.class, SelectAuthFragment.TAG, null); return false; }; /* Listener for the settings fragment */ private final View.OnClickListener mSettingButtonListener = v -> { Fragment fragment = getSupportFragmentManager().findFragmentById(mFragmentView.getId()); if(fragment instanceof MainMenuFragment){ Tools.swapFragment(this, LauncherPreferenceFragment.class, SETTING_FRAGMENT_TAG, null); } else{ // The setting button doubles as a home button now Tools.backToMainMenu(this); } }; /* Listener for account deletion */ private final View.OnClickListener mAccountDeleteButtonListener = v -> new AlertDialog.Builder(this) .setMessage(R.string.warning_remove_account) .setPositiveButton(android.R.string.cancel, null) .setNeutralButton(R.string.global_delete, (dialog, which) -> mAccountSpinner.removeCurrentAccount()) .show(); private final ExtraListener<Boolean> mLaunchGameListener = (key, value) -> { if(mProgressLayout.hasProcesses()){ Toast.makeText(this, R.string.tasks_ongoing, Toast.LENGTH_LONG).show(); return false; } String selectedProfile = LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,""); if (LauncherProfiles.mainProfileJson == null || !LauncherProfiles.mainProfileJson.profiles.containsKey(selectedProfile)){ Toast.makeText(this, R.string.error_no_version, Toast.LENGTH_LONG).show(); return false; } MinecraftProfile prof = LauncherProfiles.mainProfileJson.profiles.get(selectedProfile); if (prof == null || prof.lastVersionId == null || "Unknown".equals(prof.lastVersionId)){ Toast.makeText(this, R.string.error_no_version, Toast.LENGTH_LONG).show(); return false; } if(mAccountSpinner.getSelectedAccount() == null){ Toast.makeText(this, R.string.no_saved_accounts, Toast.LENGTH_LONG).show(); ExtraCore.setValue(ExtraConstants.SELECT_AUTH_METHOD, true); return false; } String normalizedVersionId = AsyncMinecraftDownloader.normalizeVersionId(prof.lastVersionId); JMinecraftVersionList.Version mcVersion = AsyncMinecraftDownloader.getListedVersion(normalizedVersionId); new MinecraftDownloader().start( this, mcVersion, normalizedVersionId, new ContextAwareDoneListener(this, normalizedVersionId) ); return false; }; private final TaskCountListener mDoubleLaunchPreventionListener = taskCount -> { // Hide the notification that starts the game if there are tasks executing. // Prevents the user from trying to launch the game with tasks ongoing. if(taskCount > 0) { Tools.runOnUiThread(() -> mNotificationManager.cancel(NotificationUtils.NOTIFICATION_ID_GAME_START) ); } }; private ActivityResultLauncher<String> mRequestNotificationPermissionLauncher; private WeakReference<Runnable> mRequestNotificationPermissionRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pojav_launcher); FragmentManager fragmentManager = getSupportFragmentManager(); // If we don't have a back stack root yet... if(fragmentManager.getBackStackEntryCount() < 1) { // Manually add the first fragment to the backstack to get easily back to it // There must be a better way to handle the root though... // (artDev: No, there is not. I've spent days researching this for another unrelated project.) fragmentManager.beginTransaction() .setReorderingAllowed(true) .addToBackStack("ROOT") .add(R.id.container_fragment, MainMenuFragment.class, null, "ROOT").commit(); } IconCacheJanitor.runJanitor(); mRequestNotificationPermissionLauncher = registerForActivityResult( new ActivityResultContracts.RequestPermission(), isAllowed -> { if(!isAllowed) handleNoNotificationPermission(); else { Runnable runnable = Tools.getWeakReference(mRequestNotificationPermissionRunnable); if(runnable != null) runnable.run(); } } ); getWindow().setBackgroundDrawable(null); bindViews(); checkNotificationPermission(); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); ProgressKeeper.addTaskCountListener(mDoubleLaunchPreventionListener); ProgressKeeper.addTaskCountListener((mProgressServiceKeeper = new ProgressServiceKeeper(this))); mSettingsButton.setOnClickListener(mSettingButtonListener); mDeleteAccountButton.setOnClickListener(mAccountDeleteButtonListener); ProgressKeeper.addTaskCountListener(mProgressLayout); ExtraCore.addExtraListener(ExtraConstants.BACK_PREFERENCE, mBackPreferenceListener); ExtraCore.addExtraListener(ExtraConstants.SELECT_AUTH_METHOD, mSelectAuthMethod); ExtraCore.addExtraListener(ExtraConstants.LAUNCH_GAME, mLaunchGameListener); new AsyncVersionList().getVersionList(versions -> ExtraCore.setValue(ExtraConstants.RELEASE_TABLE, versions), false); mInstallTracker = new ModloaderInstallTracker(this); mProgressLayout.observe(ProgressLayout.DOWNLOAD_MINECRAFT); mProgressLayout.observe(ProgressLayout.UNPACK_RUNTIME); mProgressLayout.observe(ProgressLayout.INSTALL_MODPACK); mProgressLayout.observe(ProgressLayout.AUTHENTICATE_MICROSOFT); mProgressLayout.observe(ProgressLayout.DOWNLOAD_VERSION_LIST); } @Override protected void onResume() { super.onResume(); ContextExecutor.setActivity(this); mInstallTracker.attach(); } @Override protected void onPause() { super.onPause(); ContextExecutor.clearActivity(); mInstallTracker.detach(); } @Override public boolean setFullscreen() { return false; } @Override protected void onStart() { super.onStart(); getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentCallbackListener, true); } @Override protected void onDestroy() { super.onDestroy(); mProgressLayout.cleanUpObservers(); ProgressKeeper.removeTaskCountListener(mProgressLayout); ProgressKeeper.removeTaskCountListener(mProgressServiceKeeper); ExtraCore.removeExtraListenerFromValue(ExtraConstants.BACK_PREFERENCE, mBackPreferenceListener); ExtraCore.removeExtraListenerFromValue(ExtraConstants.SELECT_AUTH_METHOD, mSelectAuthMethod); ExtraCore.removeExtraListenerFromValue(ExtraConstants.LAUNCH_GAME, mLaunchGameListener); getSupportFragmentManager().unregisterFragmentLifecycleCallbacks(mFragmentCallbackListener); } /** Custom implementation to feel more natural when a backstack isn't present */ @Override public void onBackPressed() { MicrosoftLoginFragment fragment = (MicrosoftLoginFragment) getVisibleFragment(MicrosoftLoginFragment.TAG); if(fragment != null){ if(fragment.canGoBack()){ fragment.goBack(); return; } } // Check if we are at the root then if(getVisibleFragment("ROOT") != null){ finish(); } super.onBackPressed(); } @Override public void onAttachedToWindow() { LauncherPreferences.computeNotchSize(this); } @SuppressWarnings("SameParameterValue") private Fragment getVisibleFragment(String tag){ Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag); if(fragment != null && fragment.isVisible()) { return fragment; } return null; } @SuppressWarnings("unused") private Fragment getVisibleFragment(int id){ Fragment fragment = getSupportFragmentManager().findFragmentById(id); if(fragment != null && fragment.isVisible()) { return fragment; } return null; } private void checkNotificationPermission() { if(LauncherPreferences.PREF_SKIP_NOTIFICATION_PERMISSION_CHECK || checkForNotificationPermission()) { return; } if(ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.POST_NOTIFICATIONS)) { showNotificationPermissionReasoning(); return; } askForNotificationPermission(null); } private void showNotificationPermissionReasoning() { new AlertDialog.Builder(this) .setTitle(R.string.notification_permission_dialog_title) .setMessage(R.string.notification_permission_dialog_text) .setPositiveButton(android.R.string.ok, (d, w) -> askForNotificationPermission(null)) .setNegativeButton(android.R.string.cancel, (d, w)-> handleNoNotificationPermission()) .show(); } private void handleNoNotificationPermission() { LauncherPreferences.PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = true; LauncherPreferences.DEFAULT_PREF.edit() .putBoolean(LauncherPreferences.PREF_KEY_SKIP_NOTIFICATION_CHECK, true) .apply(); Toast.makeText(this, R.string.notification_permission_toast, Toast.LENGTH_LONG).show(); } public boolean checkForNotificationPermission() { return Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission( this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_DENIED; } public void askForNotificationPermission(Runnable onSuccessRunnable) { if(Build.VERSION.SDK_INT < 33) return; if(onSuccessRunnable != null) { mRequestNotificationPermissionRunnable = new WeakReference<>(onSuccessRunnable); } mRequestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS); } /** Stuff all the view boilerplate here */ private void bindViews(){ mFragmentView = findViewById(R.id.container_fragment); mSettingsButton = findViewById(R.id.setting_button); mDeleteAccountButton = findViewById(R.id.delete_account_button); mAccountSpinner = findViewById(R.id.account_spinner); mProgressLayout = findViewById(R.id.progress_layout); } }
14,989
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
TapDetector.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/TapDetector.java
package net.kdt.pojavlaunch; import android.view.MotionEvent; import static android.view.MotionEvent.ACTION_DOWN; import static android.view.MotionEvent.ACTION_POINTER_DOWN; import static android.view.MotionEvent.ACTION_POINTER_UP; import static android.view.MotionEvent.ACTION_UP; /** * Class aiming at better detecting X-tap events regardless of the POINTERS * Only uses the least amount of events possible, * since we aren't guaranteed to have all events in order */ public class TapDetector { public final static int DETECTION_METHOD_DOWN = 0x1; public final static int DETECTION_METHOD_UP = 0x2; public final static int DETECTION_METHOD_BOTH = 0x3; //Unused for now private final static int TAP_MIN_DELTA_MS = 10; private final static int TAP_MAX_DELTA_MS = 300; private final static int TAP_SLOP_SQUARE_PX = (int) Math.pow(Tools.dpToPx(100), 2); private final int mTapNumberToDetect; private int mCurrentTapNumber = 0; private final int mDetectionMethod; private long mLastEventTime = 0; private float mLastX = 9999; private float mLastY = 9999; /** * @param tapNumberToDetect How many taps are needed before onTouchEvent returns True. * @param detectionMethod Method used to detect touches. See DETECTION_METHOD constants above. */ public TapDetector(int tapNumberToDetect, int detectionMethod){ this.mDetectionMethod = detectionMethod; //We expect both ACTION_DOWN and ACTION_UP for the DETECTION_METHOD_BOTH this.mTapNumberToDetect = detectBothTouch() ? 2*tapNumberToDetect : tapNumberToDetect; } /** * A function to call when you have a touch event. * @param e The MotionEvent to inspect * @return whether or not a X-tap happened for a pointer */ public boolean onTouchEvent(MotionEvent e){ int eventAction = e.getActionMasked(); int pointerIndex = -1; //Get the event to look forward if(detectDownTouch()){ if(eventAction == ACTION_DOWN) pointerIndex = 0; else if(eventAction == ACTION_POINTER_DOWN) pointerIndex = e.getActionIndex(); } if(detectUpTouch()){ if(eventAction == ACTION_UP) pointerIndex = 0; else if(eventAction == ACTION_POINTER_UP) pointerIndex = e.getActionIndex(); } if(pointerIndex == -1) return false; // Useless event //Store current event info float eventX = e.getX(pointerIndex); float eventY = e.getY(pointerIndex); long eventTime = e.getEventTime(); //Compute deltas long deltaTime = eventTime - mLastEventTime; int deltaX = (int) mLastX - (int) eventX; int deltaY = (int) mLastY - (int) eventY; //Store current event info to persist on next event mLastEventTime = eventTime; mLastX = eventX; mLastY = eventY; //Check for high enough speed and precision if(mCurrentTapNumber > 0){ if ((deltaTime < TAP_MIN_DELTA_MS || deltaTime > TAP_MAX_DELTA_MS) || ((deltaX*deltaX + deltaY*deltaY) > TAP_SLOP_SQUARE_PX)) { // We invalidate previous taps, not this one though mCurrentTapNumber = 0; } } //A worthy tap happened mCurrentTapNumber += 1; if(mCurrentTapNumber >= mTapNumberToDetect){ resetTapDetectionState(); return true; } //If not enough taps are reached return false; } /** * Reset the double tap values. */ private void resetTapDetectionState(){ mCurrentTapNumber = 0; mLastEventTime = 0; mLastX = 9999; mLastY = 9999; } private boolean detectDownTouch(){ return (mDetectionMethod & DETECTION_METHOD_DOWN) == DETECTION_METHOD_DOWN; } private boolean detectUpTouch(){ return (mDetectionMethod & DETECTION_METHOD_UP) == DETECTION_METHOD_UP; } private boolean detectBothTouch(){ return mDetectionMethod == DETECTION_METHOD_BOTH; } }
4,086
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
PojavProfile.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/PojavProfile.java
package net.kdt.pojavlaunch; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.value.MinecraftAccount; public class PojavProfile { private static final String PROFILE_PREF = "pojav_profile"; private static final String PROFILE_PREF_FILE = "file"; public static SharedPreferences getPrefs(Context ctx) { return ctx.getSharedPreferences(PROFILE_PREF, Context.MODE_PRIVATE); } public static MinecraftAccount getCurrentProfileContent(@NonNull Context ctx, @Nullable String profileName) { return MinecraftAccount.load(profileName == null ? getCurrentProfileName(ctx) : profileName); } public static String getCurrentProfileName(Context ctx) { String name = getPrefs(ctx).getString(PROFILE_PREF_FILE, ""); // A dirty fix if (!name.isEmpty() && name.startsWith(Tools.DIR_ACCOUNT_NEW) && name.endsWith(".json")) { name = name.substring(0, name.length() - 5).replace(Tools.DIR_ACCOUNT_NEW, "").replace(".json", ""); setCurrentProfile(ctx, name); } return name; } public static void setCurrentProfile(@NonNull Context ctx, @Nullable Object obj) { SharedPreferences.Editor pref = getPrefs(ctx).edit(); try { if (obj instanceof String) { String acc = (String) obj; pref.putString(PROFILE_PREF_FILE, acc); //MinecraftAccount.clearTempAccount(); } else if (obj == null) { pref.putString(PROFILE_PREF_FILE, ""); } else { throw new IllegalArgumentException("Profile must be String.class or null"); } } finally { pref.apply(); } } }
1,713
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
Logger.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/Logger.java
package net.kdt.pojavlaunch; import androidx.annotation.Keep; /** Singleton class made to log on one file * The singleton part can be removed but will require more implementation from the end-dev */ @Keep public class Logger { /** Print the text to the log file if not censored */ public static native void appendToLog(String text); /** Reset the log file, effectively erasing any previous logs */ public static native void begin(String logFilePath); /** Small listener for anything listening to the log */ public interface eventLogListener { void onEventLogged(String text); } /** Link a log listener to the logger */ public static native void setLogListener(eventLogListener logListener); }
745
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JAssetInfo.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/JAssetInfo.java
package net.kdt.pojavlaunch; import androidx.annotation.Keep; @Keep public class JAssetInfo { public String hash; public int size; }
140
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
BaseActivity.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/BaseActivity.java
package net.kdt.pojavlaunch; import android.content.*; import android.os.*; import androidx.appcompat.app.*; import net.kdt.pojavlaunch.utils.*; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_IGNORE_NOTCH; public abstract class BaseActivity extends AppCompatActivity { @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(LocaleUtils.setLocale(newBase)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LocaleUtils.setLocale(this); Tools.setFullscreen(this, setFullscreen()); Tools.updateWindowSize(this); } /** @return Whether the activity should be set as a fullscreen one */ public boolean setFullscreen(){ return true; } @Override public void startActivity(Intent i) { super.startActivity(i); //new Throwable("StartActivity").printStackTrace(); } @Override protected void onResume() { super.onResume(); if(!Tools.checkStorageRoot(this)) { startActivity(new Intent(this, MissingStorageActivity.class)); finish(); } } @Override protected void onPostResume() { super.onPostResume(); Tools.setFullscreen(this, setFullscreen()); Tools.ignoreNotch(PREF_IGNORE_NOTCH,this); } }
1,397
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AWTInputEvent.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/AWTInputEvent.java
package net.kdt.pojavlaunch; /* * Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ @SuppressWarnings("unused") public class AWTInputEvent { // InputEvent /** * This flag indicates that the Shift key was down when the event * occurred. */ public static final int SHIFT_MASK = 1; //first bit /** * This flag indicates that the Control key was down when the event * occurred. */ public static final int CTRL_MASK = 1 << 1; /** * This flag indicates that the Meta key was down when the event * occurred. For mouse events, this flag indicates that the right * button was pressed or released. */ public static final int META_MASK = 1 << 2; /** * This flag indicates that the Alt key was down when * the event occurred. For mouse events, this flag indicates that the * middle mouse button was pressed or released. */ public static final int ALT_MASK = 1 << 3; /** * The AltGraph key modifier constant. */ public static final int ALT_GRAPH_MASK = 1 << 5; /** * The Mouse Button1 modifier constant. * It is recommended that BUTTON1_DOWN_MASK be used instead. */ public static final int BUTTON1_MASK = 1 << 4; /** * The Mouse Button2 modifier constant. * It is recommended that BUTTON2_DOWN_MASK be used instead. * Note that BUTTON2_MASK has the same value as ALT_MASK. */ public static final int BUTTON2_MASK = ALT_MASK; /** * The Mouse Button3 modifier constant. * It is recommended that BUTTON3_DOWN_MASK be used instead. * Note that BUTTON3_MASK has the same value as META_MASK. */ public static final int BUTTON3_MASK = META_MASK; /** * The Shift key extended modifier constant. * @since 1.4 */ public static final int SHIFT_DOWN_MASK = 1 << 6; /** * The Control key extended modifier constant. * @since 1.4 */ public static final int CTRL_DOWN_MASK = 1 << 7; /** * The Meta key extended modifier constant. * @since 1.4 */ public static final int META_DOWN_MASK = 1 << 8; /** * The Alt key extended modifier constant. * @since 1.4 */ public static final int ALT_DOWN_MASK = 1 << 9; /** * The Mouse Button1 extended modifier constant. * @since 1.4 */ public static final int BUTTON1_DOWN_MASK = 1 << 10; /** * The Mouse Button2 extended modifier constant. * @since 1.4 */ public static final int BUTTON2_DOWN_MASK = 1 << 11; /** * The Mouse Button3 extended modifier constant. * @since 1.4 */ public static final int BUTTON3_DOWN_MASK = 1 << 12; /** * The AltGraph key extended modifier constant. * @since 1.4 */ public static final int ALT_GRAPH_DOWN_MASK = 1 << 13; // KeyEvent /** * The first number in the range of ids used for key events. */ public static final int KEY_FIRST = 400; /** * The last number in the range of ids used for key events. */ public static final int KEY_LAST = 402; /** * The "key typed" event. This event is generated when a character is * entered. In the simplest case, it is produced by a single key press. * Often, however, characters are produced by series of key presses, and * the mapping from key pressed events to key typed events may be * many-to-one or many-to-many. */ public static final int KEY_TYPED = KEY_FIRST; /** * The "key pressed" event. This event is generated when a key * is pushed down. */ public static final int KEY_PRESSED = 1 + KEY_FIRST; //Event.KEY_PRESS /** * The "key released" event. This event is generated when a key * is let up. */ public static final int KEY_RELEASED = 2 + KEY_FIRST; //Event.KEY_RELEASE /* Virtual key codes. */ public static final int VK_ENTER = '\n'; public static final int VK_BACK_SPACE = '\b'; public static final int VK_TAB = '\t'; public static final int VK_CANCEL = 0x03; public static final int VK_CLEAR = 0x0C; public static final int VK_SHIFT = 0x10; public static final int VK_CONTROL = 0x11; public static final int VK_ALT = 0x12; public static final int VK_PAUSE = 0x13; public static final int VK_CAPS_LOCK = 0x14; public static final int VK_ESCAPE = 0x1B; public static final int VK_SPACE = 0x20; public static final int VK_PAGE_UP = 0x21; public static final int VK_PAGE_DOWN = 0x22; public static final int VK_END = 0x23; public static final int VK_HOME = 0x24; /** * Constant for the non-numpad <b>left</b> arrow key. * @see #VK_KP_LEFT */ public static final int VK_LEFT = 0x25; /** * Constant for the non-numpad <b>up</b> arrow key. * @see #VK_KP_UP */ public static final int VK_UP = 0x26; /** * Constant for the non-numpad <b>right</b> arrow key. * @see #VK_KP_RIGHT */ public static final int VK_RIGHT = 0x27; /** * Constant for the non-numpad <b>down</b> arrow key. * @see #VK_KP_DOWN */ public static final int VK_DOWN = 0x28; /** * Constant for the comma key, "," */ public static final int VK_COMMA = 0x2C; /** * Constant for the minus key, "-" * @since 1.2 */ public static final int VK_MINUS = 0x2D; /** * Constant for the period key, "." */ public static final int VK_PERIOD = 0x2E; /** * Constant for the forward slash key, "/" */ public static final int VK_SLASH = 0x2F; /** VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */ public static final int VK_0 = 0x30; public static final int VK_1 = 0x31; public static final int VK_2 = 0x32; public static final int VK_3 = 0x33; public static final int VK_4 = 0x34; public static final int VK_5 = 0x35; public static final int VK_6 = 0x36; public static final int VK_7 = 0x37; public static final int VK_8 = 0x38; public static final int VK_9 = 0x39; /** * Constant for the semicolon key, ";" */ public static final int VK_SEMICOLON = 0x3B; /** * Constant for the equals key, "=" */ public static final int VK_EQUALS = 0x3D; /** VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */ public static final int VK_A = 0x41; public static final int VK_B = 0x42; public static final int VK_C = 0x43; public static final int VK_D = 0x44; public static final int VK_E = 0x45; public static final int VK_F = 0x46; public static final int VK_G = 0x47; public static final int VK_H = 0x48; public static final int VK_I = 0x49; public static final int VK_J = 0x4A; public static final int VK_K = 0x4B; public static final int VK_L = 0x4C; public static final int VK_M = 0x4D; public static final int VK_N = 0x4E; public static final int VK_O = 0x4F; public static final int VK_P = 0x50; public static final int VK_Q = 0x51; public static final int VK_R = 0x52; public static final int VK_S = 0x53; public static final int VK_T = 0x54; public static final int VK_U = 0x55; public static final int VK_V = 0x56; public static final int VK_W = 0x57; public static final int VK_X = 0x58; public static final int VK_Y = 0x59; public static final int VK_Z = 0x5A; /** * Constant for the open bracket key, "[" */ public static final int VK_OPEN_BRACKET = 0x5B; /** * Constant for the back slash key, "\" */ public static final int VK_BACK_SLASH = 0x5C; /** * Constant for the close bracket key, "]" */ public static final int VK_CLOSE_BRACKET = 0x5D; public static final int VK_NUMPAD0 = 0x60; public static final int VK_NUMPAD1 = 0x61; public static final int VK_NUMPAD2 = 0x62; public static final int VK_NUMPAD3 = 0x63; public static final int VK_NUMPAD4 = 0x64; public static final int VK_NUMPAD5 = 0x65; public static final int VK_NUMPAD6 = 0x66; public static final int VK_NUMPAD7 = 0x67; public static final int VK_NUMPAD8 = 0x68; public static final int VK_NUMPAD9 = 0x69; public static final int VK_MULTIPLY = 0x6A; public static final int VK_ADD = 0x6B; /** * This constant is obsolete, and is included only for backwards * compatibility. * @see #VK_SEPARATOR */ public static final int VK_SEPARATER = 0x6C; /** * Constant for the Numpad Separator key. * @since 1.4 */ public static final int VK_SEPARATOR = VK_SEPARATER; public static final int VK_SUBTRACT = 0x6D; public static final int VK_DECIMAL = 0x6E; public static final int VK_DIVIDE = 0x6F; public static final int VK_DELETE = 0x7F; /* ASCII DEL */ public static final int VK_NUM_LOCK = 0x90; public static final int VK_SCROLL_LOCK = 0x91; /** Constant for the F1 function key. */ public static final int VK_F1 = 0x70; /** Constant for the F2 function key. */ public static final int VK_F2 = 0x71; /** Constant for the F3 function key. */ public static final int VK_F3 = 0x72; /** Constant for the F4 function key. */ public static final int VK_F4 = 0x73; /** Constant for the F5 function key. */ public static final int VK_F5 = 0x74; /** Constant for the F6 function key. */ public static final int VK_F6 = 0x75; /** Constant for the F7 function key. */ public static final int VK_F7 = 0x76; /** Constant for the F8 function key. */ public static final int VK_F8 = 0x77; /** Constant for the F9 function key. */ public static final int VK_F9 = 0x78; /** Constant for the F10 function key. */ public static final int VK_F10 = 0x79; /** Constant for the F11 function key. */ public static final int VK_F11 = 0x7A; /** Constant for the F12 function key. */ public static final int VK_F12 = 0x7B; /** * Constant for the F13 function key. * @since 1.2 */ /* F13 - F24 are used on IBM 3270 keyboard; use random range for constants. */ public static final int VK_F13 = 0xF000; /** * Constant for the F14 function key. * @since 1.2 */ public static final int VK_F14 = 0xF001; /** * Constant for the F15 function key. * @since 1.2 */ public static final int VK_F15 = 0xF002; /** * Constant for the F16 function key. * @since 1.2 */ public static final int VK_F16 = 0xF003; /** * Constant for the F17 function key. * @since 1.2 */ public static final int VK_F17 = 0xF004; /** * Constant for the F18 function key. * @since 1.2 */ public static final int VK_F18 = 0xF005; /** * Constant for the F19 function key. * @since 1.2 */ public static final int VK_F19 = 0xF006; /** * Constant for the F20 function key. * @since 1.2 */ public static final int VK_F20 = 0xF007; /** * Constant for the F21 function key. * @since 1.2 */ public static final int VK_F21 = 0xF008; /** * Constant for the F22 function key. * @since 1.2 */ public static final int VK_F22 = 0xF009; /** * Constant for the F23 function key. * @since 1.2 */ public static final int VK_F23 = 0xF00A; /** * Constant for the F24 function key. * @since 1.2 */ public static final int VK_F24 = 0xF00B; public static final int VK_PRINTSCREEN = 0x9A; public static final int VK_INSERT = 0x9B; public static final int VK_HELP = 0x9C; public static final int VK_META = 0x9D; public static final int VK_BACK_QUOTE = 0xC0; public static final int VK_QUOTE = 0xDE; /** * Constant for the numeric keypad <b>up</b> arrow key. * @see #VK_UP * @since 1.2 */ public static final int VK_KP_UP = 0xE0; /** * Constant for the numeric keypad <b>down</b> arrow key. * @see #VK_DOWN * @since 1.2 */ public static final int VK_KP_DOWN = 0xE1; /** * Constant for the numeric keypad <b>left</b> arrow key. * @see #VK_LEFT * @since 1.2 */ public static final int VK_KP_LEFT = 0xE2; /** * Constant for the numeric keypad <b>right</b> arrow key. * @see #VK_RIGHT * @since 1.2 */ public static final int VK_KP_RIGHT = 0xE3; /* For European keyboards */ /** @since 1.2 */ public static final int VK_DEAD_GRAVE = 0x80; /** @since 1.2 */ public static final int VK_DEAD_ACUTE = 0x81; /** @since 1.2 */ public static final int VK_DEAD_CIRCUMFLEX = 0x82; /** @since 1.2 */ public static final int VK_DEAD_TILDE = 0x83; /** @since 1.2 */ public static final int VK_DEAD_MACRON = 0x84; /** @since 1.2 */ public static final int VK_DEAD_BREVE = 0x85; /** @since 1.2 */ public static final int VK_DEAD_ABOVEDOT = 0x86; /** @since 1.2 */ public static final int VK_DEAD_DIAERESIS = 0x87; /** @since 1.2 */ public static final int VK_DEAD_ABOVERING = 0x88; /** @since 1.2 */ public static final int VK_DEAD_DOUBLEACUTE = 0x89; /** @since 1.2 */ public static final int VK_DEAD_CARON = 0x8a; /** @since 1.2 */ public static final int VK_DEAD_CEDILLA = 0x8b; /** @since 1.2 */ public static final int VK_DEAD_OGONEK = 0x8c; /** @since 1.2 */ public static final int VK_DEAD_IOTA = 0x8d; /** @since 1.2 */ public static final int VK_DEAD_VOICED_SOUND = 0x8e; /** @since 1.2 */ public static final int VK_DEAD_SEMIVOICED_SOUND = 0x8f; /** @since 1.2 */ public static final int VK_AMPERSAND = 0x96; /** @since 1.2 */ public static final int VK_ASTERISK = 0x97; /** @since 1.2 */ public static final int VK_QUOTEDBL = 0x98; /** @since 1.2 */ public static final int VK_LESS = 0x99; /** @since 1.2 */ public static final int VK_GREATER = 0xa0; /** @since 1.2 */ public static final int VK_BRACELEFT = 0xa1; /** @since 1.2 */ public static final int VK_BRACERIGHT = 0xa2; /** * Constant for the "@" key. * @since 1.2 */ public static final int VK_AT = 0x0200; /** * Constant for the ":" key. * @since 1.2 */ public static final int VK_COLON = 0x0201; /** * Constant for the "^" key. * @since 1.2 */ public static final int VK_CIRCUMFLEX = 0x0202; /** * Constant for the "$" key. * @since 1.2 */ public static final int VK_DOLLAR = 0x0203; /** * Constant for the Euro currency sign key. * @since 1.2 */ public static final int VK_EURO_SIGN = 0x0204; /** * Constant for the "!" key. * @since 1.2 */ public static final int VK_EXCLAMATION_MARK = 0x0205; /** * Constant for the inverted exclamation mark key. * @since 1.2 */ public static final int VK_INVERTED_EXCLAMATION_MARK = 0x0206; /** * Constant for the "(" key. * @since 1.2 */ public static final int VK_LEFT_PARENTHESIS = 0x0207; /** * Constant for the "#" key. * @since 1.2 */ public static final int VK_NUMBER_SIGN = 0x0208; /** * Constant for the "+" key. * @since 1.2 */ public static final int VK_PLUS = 0x0209; /** * Constant for the ")" key. * @since 1.2 */ public static final int VK_RIGHT_PARENTHESIS = 0x020A; /** * Constant for the "_" key. * @since 1.2 */ public static final int VK_UNDERSCORE = 0x020B; /** * Constant for the Microsoft Windows "Windows" key. * It is used for both the left and right version of the key. * see getKeyLocation * @since 1.5 */ public static final int VK_WINDOWS = 0x020C; /** * Constant for the Microsoft Windows Context Menu key. * @since 1.5 */ public static final int VK_CONTEXT_MENU = 0x020D; /* for input method support on Asian Keyboards */ /* not clear what this means - listed in Microsoft Windows API */ public static final int VK_FINAL = 0x0018; /** Constant for the Convert function key. */ /* Japanese PC 106 keyboard, Japanese Solaris keyboard: henkan */ public static final int VK_CONVERT = 0x001C; /** Constant for the Don't Convert function key. */ /* Japanese PC 106 keyboard: muhenkan */ public static final int VK_NONCONVERT = 0x001D; /** Constant for the Accept or Commit function key. */ /* Japanese Solaris keyboard: kakutei */ public static final int VK_ACCEPT = 0x001E; /* not clear what this means - listed in Microsoft Windows API */ public static final int VK_MODECHANGE = 0x001F; /* replaced by VK_KANA_LOCK for Microsoft Windows and Solaris; might still be used on other platforms */ public static final int VK_KANA = 0x0015; /* replaced by VK_INPUT_METHOD_ON_OFF for Microsoft Windows and Solaris; might still be used for other platforms */ public static final int VK_KANJI = 0x0019; /** * Constant for the Alphanumeric function key. * @since 1.2 */ /* Japanese PC 106 keyboard: eisuu */ public static final int VK_ALPHANUMERIC = 0x00F0; /** * Constant for the Katakana function key. * @since 1.2 */ /* Japanese PC 106 keyboard: katakana */ public static final int VK_KATAKANA = 0x00F1; /** * Constant for the Hiragana function key. * @since 1.2 */ /* Japanese PC 106 keyboard: hiragana */ public static final int VK_HIRAGANA = 0x00F2; /** * Constant for the Full-Width Characters function key. * @since 1.2 */ /* Japanese PC 106 keyboard: zenkaku */ public static final int VK_FULL_WIDTH = 0x00F3; /** * Constant for the Half-Width Characters function key. * @since 1.2 */ /* Japanese PC 106 keyboard: hankaku */ public static final int VK_HALF_WIDTH = 0x00F4; /** * Constant for the Roman Characters function key. * @since 1.2 */ /* Japanese PC 106 keyboard: roumaji */ public static final int VK_ROMAN_CHARACTERS = 0x00F5; /** * Constant for the All Candidates function key. * @since 1.2 */ /* Japanese PC 106 keyboard - VK_CONVERT + ALT: zenkouho */ public static final int VK_ALL_CANDIDATES = 0x0100; /** * Constant for the Previous Candidate function key. * @since 1.2 */ /* Japanese PC 106 keyboard - VK_CONVERT + SHIFT: maekouho */ public static final int VK_PREVIOUS_CANDIDATE = 0x0101; /** * Constant for the Code Input function key. * @since 1.2 */ /* Japanese PC 106 keyboard - VK_ALPHANUMERIC + ALT: kanji bangou */ public static final int VK_CODE_INPUT = 0x0102; /** * Constant for the Japanese-Katakana function key. * This key switches to a Japanese input method and selects its Katakana input mode. * @since 1.2 */ /* Japanese Macintosh keyboard - VK_JAPANESE_HIRAGANA + SHIFT */ public static final int VK_JAPANESE_KATAKANA = 0x0103; /** * Constant for the Japanese-Hiragana function key. * This key switches to a Japanese input method and selects its Hiragana input mode. * @since 1.2 */ /* Japanese Macintosh keyboard */ public static final int VK_JAPANESE_HIRAGANA = 0x0104; /** * Constant for the Japanese-Roman function key. * This key switches to a Japanese input method and selects its Roman-Direct input mode. * @since 1.2 */ /* Japanese Macintosh keyboard */ public static final int VK_JAPANESE_ROMAN = 0x0105; /** * Constant for the locking Kana function key. * This key locks the keyboard into a Kana layout. * @since 1.3 */ /* Japanese PC 106 keyboard with special Windows driver - eisuu + Control; Japanese Solaris keyboard: kana */ public static final int VK_KANA_LOCK = 0x0106; /** * Constant for the input method on/off key. * @since 1.3 */ /* Japanese PC 106 keyboard: kanji. Japanese Solaris keyboard: nihongo */ public static final int VK_INPUT_METHOD_ON_OFF = 0x0107; /* for Sun keyboards */ /** @since 1.2 */ public static final int VK_CUT = 0xFFD1; /** @since 1.2 */ public static final int VK_COPY = 0xFFCD; /** @since 1.2 */ public static final int VK_PASTE = 0xFFCF; /** @since 1.2 */ public static final int VK_UNDO = 0xFFCB; /** @since 1.2 */ public static final int VK_AGAIN = 0xFFC9; /** @since 1.2 */ public static final int VK_FIND = 0xFFD0; /** @since 1.2 */ public static final int VK_PROPS = 0xFFCA; /** @since 1.2 */ public static final int VK_STOP = 0xFFC8; /** * Constant for the Compose function key. * @since 1.2 */ public static final int VK_COMPOSE = 0xFF20; /** * Constant for the AltGraph function key. * @since 1.2 */ public static final int VK_ALT_GRAPH = 0xFF7E; /** * Constant for the Begin key. * @since 1.5 */ public static final int VK_BEGIN = 0xFF58; /** * This value is used to indicate that the keyCode is unknown. * KEY_TYPED events do not have a keyCode value; this value * is used instead. */ public static final int VK_UNDEFINED = 0x0; /** * KEY_PRESSED and KEY_RELEASED events which do not map to a * valid Unicode character use this for the keyChar value. */ public static final char CHAR_UNDEFINED = 0xFFFF; /** * A constant indicating that the keyLocation is indeterminate * or not relevant. * <code>KEY_TYPED</code> events do not have a keyLocation; this value * is used instead. * @since 1.4 */ public static final int KEY_LOCATION_UNKNOWN = 0; /** * A constant indicating that the key pressed or released * is not distinguished as the left or right version of a key, * and did not originate on the numeric keypad (or did not * originate with a virtual key corresponding to the numeric * keypad). * @since 1.4 */ public static final int KEY_LOCATION_STANDARD = 1; /** * A constant indicating that the key pressed or released is in * the left key location (there is more than one possible location * for this key). Example: the left shift key. * @since 1.4 */ public static final int KEY_LOCATION_LEFT = 2; /** * A constant indicating that the key pressed or released is in * the right key location (there is more than one possible location * for this key). Example: the right shift key. * @since 1.4 */ public static final int KEY_LOCATION_RIGHT = 3; /** * A constant indicating that the key event originated on the * numeric keypad or with a virtual key corresponding to the * numeric keypad. * @since 1.4 */ public static final int KEY_LOCATION_NUMPAD = 4; // MOUSE /** * The first number in the range of ids used for mouse events. */ public static final int MOUSE_FIRST = 500; /** * The last number in the range of ids used for mouse events. */ public static final int MOUSE_LAST = 507; /** * The "mouse clicked" event. This <code>MouseEvent</code> * occurs when a mouse button is pressed and released. */ public static final int MOUSE_CLICKED = MOUSE_FIRST; /** * The "mouse pressed" event. This <code>MouseEvent</code> * occurs when a mouse button is pushed down. */ public static final int MOUSE_PRESSED = 1 + MOUSE_FIRST; //Event.MOUSE_DOWN /** * The "mouse released" event. This <code>MouseEvent</code> * occurs when a mouse button is let up. */ public static final int MOUSE_RELEASED = 2 + MOUSE_FIRST; //Event.MOUSE_UP /** * The "mouse moved" event. This <code>MouseEvent</code> * occurs when the mouse position changes. */ public static final int MOUSE_MOVED = 3 + MOUSE_FIRST; //Event.MOUSE_MOVE /** * The "mouse entered" event. This <code>MouseEvent</code> * occurs when the mouse cursor enters the unobscured part of component's * geometry. */ public static final int MOUSE_ENTERED = 4 + MOUSE_FIRST; //Event.MOUSE_ENTER /** * The "mouse exited" event. This <code>MouseEvent</code> * occurs when the mouse cursor exits the unobscured part of component's * geometry. */ public static final int MOUSE_EXITED = 5 + MOUSE_FIRST; //Event.MOUSE_EXIT /** * The "mouse dragged" event. This <code>MouseEvent</code> * occurs when the mouse position changes while a mouse button is pressed. */ public static final int MOUSE_DRAGGED = 6 + MOUSE_FIRST; //Event.MOUSE_DRAG /** * The "mouse wheel" event. This is the only <code>MouseWheelEvent</code>. * It occurs when a mouse equipped with a wheel has its wheel rotated. * @since 1.4 */ public static final int MOUSE_WHEEL = 7 + MOUSE_FIRST; /** * Indicates no mouse buttons; used by getButton. * @since 1.4 */ public static final int NOBUTTON = 0; /** * Indicates mouse button #1; used by getButton. * @since 1.4 */ public static final int BUTTON1 = 1; /** * Indicates mouse button #2; used by getButton. * @since 1.4 */ public static final int BUTTON2 = 2; /** * Indicates mouse button #3; used by getButton. * @since 1.4 */ public static final int BUTTON3 = 3; }
29,299
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AWTCanvasView.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/AWTCanvasView.java
package net.kdt.pojavlaunch; import android.content.*; import android.graphics.*; import android.text.*; import android.util.*; import android.view.*; import java.util.*; import net.kdt.pojavlaunch.utils.*; public class AWTCanvasView extends TextureView implements TextureView.SurfaceTextureListener, Runnable { public static final int AWT_CANVAS_WIDTH = 720; public static final int AWT_CANVAS_HEIGHT = 600; private static final int MAX_SIZE = 100; private static final double NANOS = 1000000000.0; private boolean mIsDestroyed = false; private final TextPaint mFpsPaint; // Temporary count fps https://stackoverflow.com/a/13729241 private final LinkedList<Long> mTimes = new LinkedList<Long>(){{add(System.nanoTime());}}; public AWTCanvasView(Context ctx) { this(ctx, null); } public AWTCanvasView(Context ctx, AttributeSet attrs) { super(ctx, attrs); mFpsPaint = new TextPaint(); mFpsPaint.setColor(Color.WHITE); mFpsPaint.setTextSize(20); setSurfaceTextureListener(this); post(this::refreshSize); } @Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int w, int h) { getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT); mIsDestroyed = false; new Thread(this, "AndroidAWTRenderer").start(); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { mIsDestroyed = true; return true; } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int w, int h) { getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT); } @Override public void onSurfaceTextureUpdated(SurfaceTexture texture) { getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT); } @Override public void run() { Canvas canvas; Surface surface = new Surface(getSurfaceTexture()); Bitmap rgbArrayBitmap = Bitmap.createBitmap(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT, Bitmap.Config.ARGB_8888); Paint paint = new Paint(); try { while (!mIsDestroyed && surface.isValid()) { canvas = surface.lockCanvas(null); canvas.drawRGB(0, 0, 0); int[] rgbArray = JREUtils.renderAWTScreenFrame(/* canvas, mWidth, mHeight */); boolean mDrawing = rgbArray != null; if (rgbArray != null) { canvas.save(); rgbArrayBitmap.setPixels(rgbArray, 0, AWT_CANVAS_WIDTH, 0, 0, AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT); canvas.drawBitmap(rgbArrayBitmap, 0, 0, paint); canvas.restore(); } canvas.drawText("FPS: " + (Math.round(fps() * 10) / 10) + ", drawing=" + mDrawing, 0, 20, mFpsPaint); surface.unlockCanvasAndPost(canvas); } } catch (Throwable throwable) { Tools.showError(getContext(), throwable); } rgbArrayBitmap.recycle(); surface.release(); } /** Calculates and returns frames per second */ private double fps() { long lastTime = System.nanoTime(); double difference = (lastTime - mTimes.getFirst()) / NANOS; mTimes.addLast(lastTime); int size = mTimes.size(); if (size > MAX_SIZE) { mTimes.removeFirst(); } return difference > 0 ? mTimes.size() / difference : 0.0; } /** Make the view fit the proper aspect ratio of the surface */ private void refreshSize(){ ViewGroup.LayoutParams layoutParams = getLayoutParams(); if(getHeight() < getWidth()){ layoutParams.width = AWT_CANVAS_WIDTH * getHeight() / AWT_CANVAS_HEIGHT; }else{ layoutParams.height = AWT_CANVAS_HEIGHT * getWidth() / AWT_CANVAS_WIDTH; } setLayoutParams(layoutParams); } }
4,030
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftGLSurface.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/MinecraftGLSurface.java
package net.kdt.pojavlaunch; import static net.kdt.pojavlaunch.MainActivity.touchCharInput; import static net.kdt.pojavlaunch.utils.MCOptionUtils.getMcScale; import static org.lwjgl.glfw.CallbackBridge.sendMouseButton; import static org.lwjgl.glfw.CallbackBridge.windowHeight; import static org.lwjgl.glfw.CallbackBridge.windowWidth; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.graphics.SurfaceTexture; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.TextureView; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import net.kdt.pojavlaunch.customcontrols.ControlLayout; import net.kdt.pojavlaunch.customcontrols.gamepad.Gamepad; import net.kdt.pojavlaunch.customcontrols.mouse.AbstractTouchpad; import net.kdt.pojavlaunch.customcontrols.mouse.AndroidPointerCapture; import net.kdt.pojavlaunch.customcontrols.mouse.InGUIEventProcessor; import net.kdt.pojavlaunch.customcontrols.mouse.InGameEventProcessor; import net.kdt.pojavlaunch.customcontrols.mouse.TouchEventProcessor; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.JREUtils; import net.kdt.pojavlaunch.utils.MCOptionUtils; import org.lwjgl.glfw.CallbackBridge; import fr.spse.gamepad_remapper.RemapperManager; import fr.spse.gamepad_remapper.RemapperView; /** * Class dealing with showing minecraft surface and taking inputs to dispatch them to minecraft */ public class MinecraftGLSurface extends View implements GrabListener { /* Gamepad object for gamepad inputs, instantiated on need */ private Gamepad mGamepad = null; /* The RemapperView.Builder object allows you to set which buttons to remap */ private final RemapperManager mInputManager = new RemapperManager(getContext(), new RemapperView.Builder(null) .remapA(true) .remapB(true) .remapX(true) .remapY(true) .remapLeftJoystick(true) .remapRightJoystick(true) .remapStart(true) .remapSelect(true) .remapLeftShoulder(true) .remapRightShoulder(true) .remapLeftTrigger(true) .remapRightTrigger(true)); /* Resolution scaler option, allow downsizing a window */ private final float mScaleFactor = LauncherPreferences.PREF_SCALE_FACTOR/100f; /* Sensitivity, adjusted according to screen size */ private final double mSensitivityFactor = (1.4 * (1080f/ Tools.getDisplayMetrics((Activity) getContext()).heightPixels)); /* Surface ready listener, used by the activity to launch minecraft */ SurfaceReadyListener mSurfaceReadyListener = null; final Object mSurfaceReadyListenerLock = new Object(); /* View holding the surface, either a SurfaceView or a TextureView */ View mSurface; private final InGameEventProcessor mIngameProcessor = new InGameEventProcessor(mSensitivityFactor); private final InGUIEventProcessor mInGUIProcessor = new InGUIEventProcessor(mScaleFactor); private TouchEventProcessor mCurrentTouchProcessor = mInGUIProcessor; private AndroidPointerCapture mPointerCapture; private boolean mLastGrabState = false; public MinecraftGLSurface(Context context) { this(context, null); } public MinecraftGLSurface(Context context, AttributeSet attributeSet) { super(context, attributeSet); setFocusable(true); } @RequiresApi(api = Build.VERSION_CODES.O) private void setUpPointerCapture(AbstractTouchpad touchpad) { if(mPointerCapture != null) mPointerCapture.detach(); mPointerCapture = new AndroidPointerCapture(touchpad, this, mScaleFactor); } /** Initialize the view and all its settings * @param isAlreadyRunning set to true to tell the view that the game is already running * (only updates the window without calling the start listener) * @param touchpad the optional cursor-emulating touchpad, used for touch event processing * when the cursor is not grabbed */ public void start(boolean isAlreadyRunning, AbstractTouchpad touchpad){ if(MainActivity.isAndroid8OrHigher()) setUpPointerCapture(touchpad); mInGUIProcessor.setAbstractTouchpad(touchpad); if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){ SurfaceView surfaceView = new SurfaceView(getContext()); mSurface = surfaceView; surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() { private boolean isCalled = isAlreadyRunning; @Override public void surfaceCreated(@NonNull SurfaceHolder holder) { if(isCalled) { JREUtils.setupBridgeWindow(surfaceView.getHolder().getSurface()); return; } isCalled = true; realStart(surfaceView.getHolder().getSurface()); } @Override public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) { refreshSize(); } @Override public void surfaceDestroyed(@NonNull SurfaceHolder holder) {} }); ((ViewGroup)getParent()).addView(surfaceView); }else{ TextureView textureView = new TextureView(getContext()); textureView.setOpaque(true); textureView.setAlpha(1.0f); mSurface = textureView; textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() { private boolean isCalled = isAlreadyRunning; @Override public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) { Surface tSurface = new Surface(surface); if(isCalled) { JREUtils.setupBridgeWindow(tSurface); return; } isCalled = true; realStart(tSurface); } @Override public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) { refreshSize(); } @Override public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) { return true; } @Override public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {} }); ((ViewGroup)getParent()).addView(textureView); } } /** * The touch event for both grabbed an non-grabbed mouse state on the touch screen * Does not cover the virtual mouse touchpad */ @Override @SuppressWarnings("accessibility") public boolean onTouchEvent(MotionEvent e) { // Kinda need to send this back to the layout if(((ControlLayout)getParent()).getModifiable()) return false; // Looking for a mouse to handle, won't have an effect if no mouse exists. for (int i = 0; i < e.getPointerCount(); i++) { int toolType = e.getToolType(i); if(toolType == MotionEvent.TOOL_TYPE_MOUSE) { if(MainActivity.isAndroid8OrHigher() && mPointerCapture != null) { mPointerCapture.handleAutomaticCapture(); return true; } }else if(toolType != MotionEvent.TOOL_TYPE_STYLUS) continue; // Mouse found if(CallbackBridge.isGrabbing()) return false; CallbackBridge.sendCursorPos( e.getX(i) * mScaleFactor, e.getY(i) * mScaleFactor); return true; //mouse event handled successfully } if (mIngameProcessor == null || mInGUIProcessor == null) return true; return mCurrentTouchProcessor.processTouchEvent(e); } /** * The event for mouse/joystick movements */ @SuppressLint("NewApi") @Override public boolean dispatchGenericMotionEvent(MotionEvent event) { int mouseCursorIndex = -1; if(Gamepad.isGamepadEvent(event)){ if(mGamepad == null){ mGamepad = new Gamepad(this, event.getDevice()); } mInputManager.handleMotionEventInput(getContext(), event, mGamepad); return true; } for(int i = 0; i < event.getPointerCount(); i++) { if(event.getToolType(i) != MotionEvent.TOOL_TYPE_MOUSE && event.getToolType(i) != MotionEvent.TOOL_TYPE_STYLUS ) continue; // Mouse found mouseCursorIndex = i; break; } if(mouseCursorIndex == -1) return false; // we cant consoom that, theres no mice! // Make sure we grabbed the mouse if necessary updateGrabState(CallbackBridge.isGrabbing()); switch(event.getActionMasked()) { case MotionEvent.ACTION_HOVER_MOVE: CallbackBridge.mouseX = (event.getX(mouseCursorIndex) * mScaleFactor); CallbackBridge.mouseY = (event.getY(mouseCursorIndex) * mScaleFactor); CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY); return true; case MotionEvent.ACTION_SCROLL: CallbackBridge.sendScroll((double) event.getAxisValue(MotionEvent.AXIS_HSCROLL), (double) event.getAxisValue(MotionEvent.AXIS_VSCROLL)); return true; case MotionEvent.ACTION_BUTTON_PRESS: return sendMouseButtonUnconverted(event.getActionButton(),true); case MotionEvent.ACTION_BUTTON_RELEASE: return sendMouseButtonUnconverted(event.getActionButton(),false); default: return false; } } /** The event for keyboard/ gamepad button inputs */ public boolean processKeyEvent(KeyEvent event) { //Log.i("KeyEvent", event.toString()); //Filtering useless events by order of probability int eventKeycode = event.getKeyCode(); if(eventKeycode == KeyEvent.KEYCODE_UNKNOWN) return true; if(eventKeycode == KeyEvent.KEYCODE_VOLUME_DOWN) return false; if(eventKeycode == KeyEvent.KEYCODE_VOLUME_UP) return false; if(event.getRepeatCount() != 0) return true; int action = event.getAction(); if(action == KeyEvent.ACTION_MULTIPLE) return true; // Ignore the cancelled up events. They occur when the user switches layouts. // In accordance with https://developer.android.com/reference/android/view/KeyEvent#FLAG_CANCELED if(action == KeyEvent.ACTION_UP && (event.getFlags() & KeyEvent.FLAG_CANCELED) != 0) return true; //Sometimes, key events comes from SOME keys of the software keyboard //Even weirder, is is unknown why a key or another is selected to trigger a keyEvent if((event.getFlags() & KeyEvent.FLAG_SOFT_KEYBOARD) == KeyEvent.FLAG_SOFT_KEYBOARD){ if(eventKeycode == KeyEvent.KEYCODE_ENTER) return true; //We already listen to it. touchCharInput.dispatchKeyEvent(event); return true; } //Sometimes, key events may come from the mouse if(event.getDevice() != null && ( (event.getSource() & InputDevice.SOURCE_MOUSE_RELATIVE) == InputDevice.SOURCE_MOUSE_RELATIVE || (event.getSource() & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) ){ if(eventKeycode == KeyEvent.KEYCODE_BACK){ sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, event.getAction() == KeyEvent.ACTION_DOWN); return true; } } if(Gamepad.isGamepadEvent(event)){ if(mGamepad == null){ mGamepad = new Gamepad(this, event.getDevice()); } mInputManager.handleKeyEventInput(getContext(), event, mGamepad); return true; } int index = EfficientAndroidLWJGLKeycode.getIndexByKey(eventKeycode); if(EfficientAndroidLWJGLKeycode.containsIndex(index)) { EfficientAndroidLWJGLKeycode.execKey(event, index); return true; } // Some events will be generated an infinite number of times when no consumed return (event.getFlags() & KeyEvent.FLAG_FALLBACK) == KeyEvent.FLAG_FALLBACK; } /** Convert the mouse button, then send it * @return Whether the event was processed */ public static boolean sendMouseButtonUnconverted(int button, boolean status) { int glfwButton = -256; switch (button) { case MotionEvent.BUTTON_PRIMARY: glfwButton = LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT; break; case MotionEvent.BUTTON_TERTIARY: glfwButton = LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_MIDDLE; break; case MotionEvent.BUTTON_SECONDARY: glfwButton = LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT; break; } if(glfwButton == -256) return false; sendMouseButton(glfwButton, status); return true; } /** Called when the size need to be set at any point during the surface lifecycle **/ public void refreshSize(){ windowWidth = Tools.getDisplayFriendlyRes(Tools.currentDisplayMetrics.widthPixels, mScaleFactor); windowHeight = Tools.getDisplayFriendlyRes(Tools.currentDisplayMetrics.heightPixels, mScaleFactor); if(mSurface == null){ Log.w("MGLSurface", "Attempt to refresh size on null surface"); return; } if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){ SurfaceView view = (SurfaceView) mSurface; if(view.getHolder() != null){ view.getHolder().setFixedSize(windowWidth, windowHeight); } }else{ TextureView view = (TextureView)mSurface; if(view.getSurfaceTexture() != null){ view.getSurfaceTexture().setDefaultBufferSize(windowWidth, windowHeight); } } CallbackBridge.sendUpdateWindowSize(windowWidth, windowHeight); } private void realStart(Surface surface){ // Initial size set refreshSize(); //Load Minecraft options: MCOptionUtils.set("fullscreen", "off"); MCOptionUtils.set("overrideWidth", String.valueOf(windowWidth)); MCOptionUtils.set("overrideHeight", String.valueOf(windowHeight)); MCOptionUtils.save(); getMcScale(); JREUtils.setupBridgeWindow(surface); new Thread(() -> { try { // Wait until the listener is attached synchronized(mSurfaceReadyListenerLock) { if(mSurfaceReadyListener == null) mSurfaceReadyListenerLock.wait(); } mSurfaceReadyListener.isReady(); } catch (Throwable e) { Tools.showError(getContext(), e, true); } }, "JVM Main thread").start(); } @Override public void onGrabState(boolean isGrabbing) { post(()->updateGrabState(isGrabbing)); } private TouchEventProcessor pickEventProcessor(boolean isGrabbing) { return isGrabbing ? mIngameProcessor : mInGUIProcessor; } private void updateGrabState(boolean isGrabbing) { if(mLastGrabState != isGrabbing) { mCurrentTouchProcessor.cancelPendingActions(); mCurrentTouchProcessor = pickEventProcessor(isGrabbing); mLastGrabState = isGrabbing; } } /** A small interface called when the listener is ready for the first time */ public interface SurfaceReadyListener { void isReady(); } public void setSurfaceReadyListener(SurfaceReadyListener listener){ synchronized (mSurfaceReadyListenerLock) { mSurfaceReadyListener = listener; mSurfaceReadyListenerLock.notifyAll(); } } }
16,565
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProgressListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/authenticator/listener/ProgressListener.java
package net.kdt.pojavlaunch.authenticator.listener; /** Called when a step is started, guaranteed to be in the UI Thread */ public interface ProgressListener { /** */ void onLoginProgress(int step); }
209
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DoneListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/authenticator/listener/DoneListener.java
package net.kdt.pojavlaunch.authenticator.listener; import net.kdt.pojavlaunch.value.MinecraftAccount; /** Called when the login is done and the account received. guaranteed to be on the UI Thread */ public interface DoneListener { void onLoginDone(MinecraftAccount account); }
284
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ErrorListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/authenticator/listener/ErrorListener.java
package net.kdt.pojavlaunch.authenticator.listener; /** Called when there is a complete failure, guaranteed to be on the UI Thread */ public interface ErrorListener { void onLoginError(Throwable errorMessage); }
218
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
PresentedException.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/authenticator/microsoft/PresentedException.java
package net.kdt.pojavlaunch.authenticator.microsoft; import android.content.Context; public class PresentedException extends RuntimeException { final int localizationStringId; final Object[] extraArgs; public PresentedException(int localizationStringId, Object... extraArgs) { this.localizationStringId = localizationStringId; this.extraArgs = extraArgs; } public PresentedException(Throwable throwable, int localizationStringId, Object... extraArgs) { super(throwable); this.localizationStringId = localizationStringId; this.extraArgs = extraArgs; } public String toString(Context context) { return context.getString(localizationStringId, extraArgs); } }
741
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MicrosoftBackgroundLogin.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/authenticator/microsoft/MicrosoftBackgroundLogin.java
package net.kdt.pojavlaunch.authenticator.microsoft; import static net.kdt.pojavlaunch.PojavApplication.sExecutorService; import android.util.ArrayMap; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.authenticator.listener.DoneListener; import net.kdt.pojavlaunch.authenticator.listener.ErrorListener; import net.kdt.pojavlaunch.authenticator.listener.ProgressListener; import net.kdt.pojavlaunch.value.MinecraftAccount; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.Map; /** Allow to perform a background login on a given account */ // TODO handle connection errors ! public class MicrosoftBackgroundLogin { private static final String authTokenUrl = "https://login.live.com/oauth20_token.srf"; private static final String xblAuthUrl = "https://user.auth.xboxlive.com/user/authenticate"; private static final String xstsAuthUrl = "https://xsts.auth.xboxlive.com/xsts/authorize"; private static final String mcLoginUrl = "https://api.minecraftservices.com/authentication/login_with_xbox"; private static final String mcProfileUrl = "https://api.minecraftservices.com/minecraft/profile"; private static final String mcStoreUrl = "https://api.minecraftservices.com/entitlements/mcstore"; private final boolean mIsRefresh; private final String mAuthCode; private static final Map<Long, Integer> XSTS_ERRORS; static { XSTS_ERRORS = new ArrayMap<>(); XSTS_ERRORS.put(2148916233L, R.string.xerr_no_account); XSTS_ERRORS.put(2148916235L, R.string.xerr_not_available); XSTS_ERRORS.put(2148916236L ,R.string.xerr_adult_verification); XSTS_ERRORS.put(2148916237L ,R.string.xerr_adult_verification); XSTS_ERRORS.put(2148916238L ,R.string.xerr_child); } /* Fields used to fill the account */ public String msRefreshToken; public String mcName; public String mcToken; public String mcUuid; public boolean doesOwnGame; public long expiresAt; public MicrosoftBackgroundLogin(boolean isRefresh, String authCode){ mIsRefresh = isRefresh; mAuthCode = authCode; } /** Performs a full login, calling back listeners appropriately */ public void performLogin(@Nullable final ProgressListener progressListener, @Nullable final DoneListener doneListener, @Nullable final ErrorListener errorListener){ sExecutorService.execute(() -> { try { notifyProgress(progressListener, 1); String accessToken = acquireAccessToken(mIsRefresh, mAuthCode); notifyProgress(progressListener, 2); String xboxLiveToken = acquireXBLToken(accessToken); notifyProgress(progressListener, 3); String[] xsts = acquireXsts(xboxLiveToken); notifyProgress(progressListener, 4); String mcToken = acquireMinecraftToken(xsts[0], xsts[1]); notifyProgress(progressListener, 5); fetchOwnedItems(mcToken); checkMcProfile(mcToken); MinecraftAccount acc = MinecraftAccount.load(mcName); if(acc == null) acc = new MinecraftAccount(); if (doesOwnGame) { acc.xuid = xsts[0]; acc.clientToken = "0"; /* FIXME */ acc.accessToken = mcToken; acc.username = mcName; acc.profileId = mcUuid; acc.isMicrosoft = true; acc.msaRefreshToken = msRefreshToken; acc.expiresAt = expiresAt; acc.updateSkinFace(); } acc.save(); if(doneListener != null) { MinecraftAccount finalAcc = acc; Tools.runOnUiThread(() -> doneListener.onLoginDone(finalAcc)); } }catch (Exception e){ Log.e("MicroAuth", "Exception thrown during authentication", e); if(errorListener != null) Tools.runOnUiThread(() -> errorListener.onLoginError(e)); } ProgressLayout.clearProgress(ProgressLayout.AUTHENTICATE_MICROSOFT); }); } public String acquireAccessToken(boolean isRefresh, String authcode) throws IOException, JSONException { URL url = new URL(authTokenUrl); Log.i("MicrosoftLogin", "isRefresh=" + isRefresh + ", authCode= "+authcode); String formData = convertToFormData( "client_id", "00000000402b5328", isRefresh ? "refresh_token" : "code", authcode, "grant_type", isRefresh ? "refresh_token" : "authorization_code", "redirect_url", "https://login.live.com/oauth20_desktop.srf", "scope", "service::user.auth.xboxlive.com::MBI_SSL" ); Log.i("MicroAuth", formData); //да пошла yf[eq1 она ваша джава 11 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(formData.getBytes(StandardCharsets.UTF_8).length)); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); try(OutputStream wr = conn.getOutputStream()) { wr.write(formData.getBytes(StandardCharsets.UTF_8)); } if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) { JSONObject jo = new JSONObject(Tools.read(conn.getInputStream())); msRefreshToken = jo.getString("refresh_token"); conn.disconnect(); Log.i("MicrosoftLogin","Acess Token = " + jo.getString("access_token")); return jo.getString("access_token"); //acquireXBLToken(jo.getString("access_token")); }else{ throw getResponseThrowable(conn); } } private String acquireXBLToken(String accessToken) throws IOException, JSONException { URL url = new URL(xblAuthUrl); JSONObject data = new JSONObject(); JSONObject properties = new JSONObject(); properties.put("AuthMethod", "RPS"); properties.put("SiteName", "user.auth.xboxlive.com"); properties.put("RpsTicket", accessToken); data.put("Properties",properties); data.put("RelyingParty", "http://auth.xboxlive.com"); data.put("TokenType", "JWT"); String req = data.toString(); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); setCommonProperties(conn, req); conn.connect(); try(OutputStream wr = conn.getOutputStream()) { wr.write(req.getBytes(StandardCharsets.UTF_8)); } if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) { JSONObject jo = new JSONObject(Tools.read(conn.getInputStream())); conn.disconnect(); Log.i("MicrosoftLogin","Xbl Token = "+jo.getString("Token")); return jo.getString("Token"); //acquireXsts(jo.getString("Token")); }else{ throw getResponseThrowable(conn); } } /** @return [uhs, token]*/ private @NonNull String[] acquireXsts(String xblToken) throws IOException, JSONException { URL url = new URL(xstsAuthUrl); JSONObject data = new JSONObject(); JSONObject properties = new JSONObject(); properties.put("SandboxId", "RETAIL"); properties.put("UserTokens", new JSONArray(Collections.singleton(xblToken))); data.put("Properties", properties); data.put("RelyingParty", "rp://api.minecraftservices.com/"); data.put("TokenType", "JWT"); String req = data.toString(); Log.i("MicroAuth", req); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); setCommonProperties(conn, req); Log.i("MicroAuth", conn.getRequestMethod()); conn.connect(); try(OutputStream wr = conn.getOutputStream()) { wr.write(req.getBytes(StandardCharsets.UTF_8)); } if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) { JSONObject jo = new JSONObject(Tools.read(conn.getInputStream())); String uhs = jo.getJSONObject("DisplayClaims").getJSONArray("xui").getJSONObject(0).getString("uhs"); String token = jo.getString("Token"); conn.disconnect(); Log.i("MicrosoftLogin","Xbl Xsts = " + token + "; Uhs = " + uhs); return new String[]{uhs, token}; //acquireMinecraftToken(uhs,jo.getString("Token")); }else if(conn.getResponseCode() == 401) { String responseContents = Tools.read(conn.getErrorStream()); JSONObject jo = new JSONObject(responseContents); long xerr = jo.optLong("XErr", -1); Integer locale_id = XSTS_ERRORS.get(xerr); if(locale_id != null) { throw new PresentedException(new RuntimeException(responseContents), locale_id); } throw new PresentedException(new RuntimeException(responseContents), R.string.xerr_unknown, xerr); }else{ throw getResponseThrowable(conn); } } private String acquireMinecraftToken(String xblUhs, String xblXsts) throws IOException, JSONException { URL url = new URL(mcLoginUrl); JSONObject data = new JSONObject(); data.put("identityToken", "XBL3.0 x=" + xblUhs + ";" + xblXsts); String req = data.toString(); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); setCommonProperties(conn, req); conn.connect(); try(OutputStream wr = conn.getOutputStream()) { wr.write(req.getBytes(StandardCharsets.UTF_8)); } if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) { expiresAt = System.currentTimeMillis() + 86400000; JSONObject jo = new JSONObject(Tools.read(conn.getInputStream())); conn.disconnect(); Log.i("MicrosoftLogin","MC token: "+jo.getString("access_token")); mcToken = jo.getString("access_token"); //checkMcProfile(jo.getString("access_token")); return jo.getString("access_token"); }else{ throw getResponseThrowable(conn); } } private void fetchOwnedItems(String mcAccessToken) throws IOException { URL url = new URL(mcStoreUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestProperty("Authorization", "Bearer " + mcAccessToken); conn.setUseCaches(false); conn.connect(); if(conn.getResponseCode() < 200 || conn.getResponseCode() >= 300) { throw getResponseThrowable(conn); } // We don't need any data from this request, it just needs to happen in order for // the MS servers to work properly. The data from this is practically useless // as it does not indicate whether the user owns the game through Game Pass. } private void checkMcProfile(String mcAccessToken) throws IOException, JSONException { URL url = new URL(mcProfileUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestProperty("Authorization", "Bearer " + mcAccessToken); conn.setUseCaches(false); conn.connect(); if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) { String s= Tools.read(conn.getInputStream()); conn.disconnect(); Log.i("MicrosoftLogin","profile:" + s); JSONObject jsonObject = new JSONObject(s); String name = (String) jsonObject.get("name"); String uuid = (String) jsonObject.get("id"); String uuidDashes = uuid.replaceFirst( "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" ); doesOwnGame = true; Log.i("MicrosoftLogin","UserName = " + name); Log.i("MicrosoftLogin","Uuid Minecraft = " + uuidDashes); mcName=name; mcUuid=uuidDashes; }else{ Log.i("MicrosoftLogin","It seems that this Microsoft Account does not own the game."); doesOwnGame = false; throw new PresentedException(new RuntimeException(conn.getResponseMessage()), R.string.minecraft_not_owned); //throwResponseError(conn); } } /** Wrapper to ease notifying the listener */ private void notifyProgress(@Nullable ProgressListener listener, int step){ if(listener != null){ Tools.runOnUiThread(() -> listener.onLoginProgress(step)); } ProgressLayout.setProgress(ProgressLayout.AUTHENTICATE_MICROSOFT, step*20); } /** Set common properties for the connection. Given that all requests are POST, interactivity is always enabled */ private static void setCommonProperties(HttpURLConnection conn, String formData) { conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("charset", "utf-8"); try { conn.setRequestProperty("Content-Length", Integer.toString(formData.getBytes(StandardCharsets.UTF_8).length)); conn.setRequestMethod("POST"); }catch (ProtocolException e) { Log.e("MicrosoftAuth", e.toString()); } conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); } /** * @param data A series a strings: key1, value1, key2, value2... * @return the data converted as a form string for a POST request */ private static String convertToFormData(String... data) throws UnsupportedEncodingException { StringBuilder builder = new StringBuilder(); for(int i=0; i<data.length; i+=2){ if (builder.length() > 0) builder.append("&"); builder.append(URLEncoder.encode(data[i], "UTF-8")) .append("=") .append(URLEncoder.encode(data[i+1], "UTF-8")); } return builder.toString(); } private RuntimeException getResponseThrowable(HttpURLConnection conn) throws IOException { Log.i("MicrosoftLogin", "Error code: " + conn.getResponseCode() + ": " + conn.getResponseMessage()); if(conn.getResponseCode() == 429) { return new PresentedException(R.string.microsoft_login_retry_later); } return new RuntimeException(conn.getResponseMessage()); } }
15,495
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ExtraListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraListener.java
package net.kdt.pojavlaunch.extra; import androidx.annotation.NonNull; /** * Listener class for the ExtraCore * An ExtraListener can listen to a virtually unlimited amount of values */ public interface ExtraListener<T> { /** * Called upon a new value being set * @param key The name of the value * @param value The new value as a string * @return Whether you consume the Listener (stop listening) */ @SuppressWarnings("SameReturnValue") boolean onValueSet(String key, @NonNull T value); }
532
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ExtraConstants.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraConstants.java
package net.kdt.pojavlaunch.extra; public class ExtraConstants { /* ExtraCore constant: a HashMap for converting values such as latest-snapshot or latest-release to actual game version names */ public static final String RELEASE_TABLE = "release_table"; /* ExtraCore constant: Serpent's back button tracking thing */ public static final String BACK_PREFERENCE = "back_preference"; /* ExtraCore constant: The OPENGL version that should be exposed */ public static final String OPEN_GL_VERSION = "open_gl_version"; /* ExtraCore constant: When the microsoft authentication via webview is done */ public static final String MICROSOFT_LOGIN_TODO = "webview_login_done"; /* ExtraCore constant: Mojang or "local" authentication to perform */ public static final String MOJANG_LOGIN_TODO = "mojang_login_todo"; /* ExtraCore constant: Add minecraft account procedure, the user has to select between mojang or microsoft */ public static final String SELECT_AUTH_METHOD = "start_login_procedure"; /* ExtraCore constant: Selected file or folder, as a String */ public static final String FILE_SELECTOR = "file_selector"; /* ExtraCore constant: Need to refresh the version spinner, selecting the uuid at the same time. Can be DELETED_PROFILE */ public static final String REFRESH_VERSION_SPINNER = "refresh_version"; /* ExtraCore Constant: When we want to launch the game */ public static final String LAUNCH_GAME = "launch_game"; }
1,496
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ExtraCore.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraCore.java
package net.kdt.pojavlaunch.extra; import java.lang.ref.WeakReference; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; /** * Class providing callback across all of a program * to allow easy thread safe implementations of UI update without context leak * It is also perfectly engineered to make it unpleasant to use. * * This class uses a singleton pattern to simplify access to it */ @SuppressWarnings({"rawtypes", "unchecked"}) public final class ExtraCore { // No unwanted instantiation private ExtraCore(){} // Singleton instance private static volatile ExtraCore sExtraCoreSingleton = null; // Store the key-value pair private final Map<String, Object> mValueMap = new ConcurrentHashMap<>(); // Store what each ExtraListener listen to private final Map<String, ConcurrentLinkedQueue<WeakReference<ExtraListener>>> mListenerMap = new ConcurrentHashMap<>(); // All public methods will pass through this one private static ExtraCore getInstance(){ if(sExtraCoreSingleton == null){ synchronized(ExtraCore.class){ if(sExtraCoreSingleton == null){ sExtraCoreSingleton = new ExtraCore(); } } } return sExtraCoreSingleton; } /** * Set the value associated to a key and trigger all listeners * @param key The key * @param value The value */ public static void setValue(String key, Object value){ if(value == null || key == null) return; // null values create an NPE on insertion getInstance().mValueMap.put(key, value); ConcurrentLinkedQueue<WeakReference<ExtraListener>> extraListenerList = getInstance().mListenerMap.get(key); if(extraListenerList == null) return; //No listeners for(WeakReference<ExtraListener> listener : extraListenerList){ if(listener.get() == null){ extraListenerList.remove(listener); continue; } //Notify the listener about a state change and remove it if asked for if(listener.get().onValueSet(key, value)){ ExtraCore.removeExtraListenerFromValue(key, listener.get()); } } } /** @return The value behind the key */ public static Object getValue(String key){ return getInstance().mValueMap.get(key); } /** @return The value behind the key, or the default value */ public static Object getValue(String key, Object defaultValue){ Object value = getInstance().mValueMap.get(key); return value != null ? value : defaultValue; } /** Remove the key and its value from the valueMap */ public static void removeValue(String key){ getInstance().mValueMap.remove(key); } public static Object consumeValue(String key){ Object value = getInstance().mValueMap.get(key); getInstance().mValueMap.remove(key); return value; } /** Remove all values */ public static void removeAllValues(){ getInstance().mValueMap.clear(); } /** * Link an ExtraListener to a value * @param key The value key to look for * @param listener The ExtraListener to link */ public static void addExtraListener(String key, ExtraListener listener){ ConcurrentLinkedQueue<WeakReference<ExtraListener>> listenerList = getInstance().mListenerMap.get(key); // Look for new sets if(listenerList == null){ listenerList = new ConcurrentLinkedQueue<>(); getInstance().mListenerMap.put(key, listenerList); } // This is kinda naive, I should look for duplicates listenerList.add(new WeakReference<>(listener)); } /** * Unlink an ExtraListener from a value. * Unlink null references found along the way * @param key The value key to ignore now * @param listener The ExtraListener to unlink */ public static void removeExtraListenerFromValue(String key, ExtraListener listener){ ConcurrentLinkedQueue<WeakReference<ExtraListener>> listenerList = getInstance().mListenerMap.get(key); // Look for new sets if(listenerList == null){ listenerList = new ConcurrentLinkedQueue<>(); getInstance().mListenerMap.put(key, listenerList); } // Removes all occurrences of ExtraListener and all null references for(WeakReference<ExtraListener> listenerWeakReference : listenerList){ ExtraListener actualListener = listenerWeakReference.get(); if(actualListener == null || actualListener == listener){ listenerList.remove(listenerWeakReference); } } } /** * Unlink all ExtraListeners from a value * @param key The key to which ExtraListener are linked */ public static void removeAllExtraListenersFromValue(String key){ ConcurrentLinkedQueue<WeakReference<ExtraListener>> listenerList = getInstance().mListenerMap.get(key); // Look for new sets if(listenerList == null){ listenerList = new ConcurrentLinkedQueue<>(); getInstance().mListenerMap.put(key, listenerList); } listenerList.clear(); } /** * Remove all ExtraListeners from listening to any value */ public static void removeAllExtraListeners(){ getInstance().mListenerMap.clear(); } }
5,540
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ContextAwareDoneListener.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/lifecycle/ContextAwareDoneListener.java
package net.kdt.pojavlaunch.lifecycle; import static net.kdt.pojavlaunch.MainActivity.INTENT_MINECRAFT_VERSION; import android.app.Activity; import android.content.Context; import android.content.Intent; import net.kdt.pojavlaunch.MainActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.lifecycle.ContextExecutor; import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import net.kdt.pojavlaunch.tasks.AsyncMinecraftDownloader; import net.kdt.pojavlaunch.utils.NotificationUtils; public class ContextAwareDoneListener implements AsyncMinecraftDownloader.DoneListener, ContextExecutorTask { private final String mErrorString; private final String mNormalizedVersionid; public ContextAwareDoneListener(Context baseContext, String versionId) { this.mErrorString = baseContext.getString(R.string.mc_download_failed); this.mNormalizedVersionid = versionId; } private Intent createGameStartIntent(Context context) { Intent mainIntent = new Intent(context, MainActivity.class); mainIntent.putExtra(INTENT_MINECRAFT_VERSION, mNormalizedVersionid); mainIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); return mainIntent; } @Override public void onDownloadDone() { ProgressKeeper.waitUntilDone(()->ContextExecutor.execute(this)); } @Override public void onDownloadFailed(Throwable throwable) { Tools.showErrorRemote(mErrorString, throwable); } @Override public void executeWithActivity(Activity activity) { try { Intent gameStartIntent = createGameStartIntent(activity); activity.startActivity(gameStartIntent); activity.finish(); android.os.Process.killProcess(android.os.Process.myPid()); //You should kill yourself, NOW! } catch (Throwable e) { Tools.showError(activity.getBaseContext(), e); } } @Override public void executeWithApplication(Context context) { Intent gameStartIntent = createGameStartIntent(context); // Since the game is a separate process anyway, it does not matter if it gets invoked // from somewhere other than the launcher activity. // The only problem may arise if the launcher starts doing something when the user starts the notification. // So, the notification is automatically removed once there are tasks ongoing in the ProgressKeeper NotificationUtils.sendBasicNotification(context, R.string.notif_download_finished, R.string.notif_download_finished_desc, gameStartIntent, NotificationUtils.PENDINGINTENT_CODE_GAME_START, NotificationUtils.NOTIFICATION_ID_GAME_START ); // You should keep yourself safe, NOW! // otherwise android does weird things... } }
2,970
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ContextExecutor.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/lifecycle/ContextExecutor.java
package net.kdt.pojavlaunch.lifecycle; import android.app.Activity; import android.app.Application; import net.kdt.pojavlaunch.Tools; import java.lang.ref.WeakReference; public class ContextExecutor { private static WeakReference<Application> sApplication; private static WeakReference<Activity> sActivity; /** * Schedules a ContextExecutorTask to be executed. For more info on tasks, please read * ContextExecutorTask.java * @param contextExecutorTask the task to be executed */ public static void execute(ContextExecutorTask contextExecutorTask) { Tools.runOnUiThread(()->executeOnUiThread(contextExecutorTask)); } private static void executeOnUiThread(ContextExecutorTask contextExecutorTask) { Activity activity = Tools.getWeakReference(sActivity); if(activity != null) { contextExecutorTask.executeWithActivity(activity); return; } Application application = Tools.getWeakReference(sApplication); if(application != null) { contextExecutorTask.executeWithApplication(application); }else { throw new RuntimeException("ContextExecutor.execute() called before Application.onCreate!"); } } /** * Set the Activity that this ContextExecutor will use for executing tasks * @param activity the activity to be used */ public static void setActivity(Activity activity) { sActivity = new WeakReference<>(activity); } /** * Clear the Activity previously set, so thet ContextExecutor won't use it to execute tasks. */ public static void clearActivity() { if(sActivity != null) sActivity.clear(); } /** * Set the Application that will be used to execute tasks if the Activity won't be available. * @param application the application to use as the fallback */ public static void setApplication(Application application) { sApplication = new WeakReference<>(application); } /** * Clear the Application previously set, so that ContextExecutor will notify the user of a critical error * that is executing code after the application is ended by the system. */ public static void clearApplication() { if(sApplication != null) sApplication.clear(); } }
2,366
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ContextExecutorTask.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/lifecycle/ContextExecutorTask.java
package net.kdt.pojavlaunch.lifecycle; import android.app.Activity; import android.content.Context; /** * A ContextExecutorTask is a task that can dynamically change its behaviour, based on the context * used for its execution. This can be used to implement for ex. error/finish notifications from * background threads that may live with the Service after the activity that started them died. */ public interface ContextExecutorTask { /** * ContextExecutor will execute this function first if a foreground Activity that was attached to the * ContextExecutor is available. * @param activity the activity */ void executeWithActivity(Activity activity); /** * ContextExecutor will execute this function if a foreground Activity is not available, but the app * is still running. * @param context the application context */ void executeWithApplication(Context context); }
930
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LifecycleAwareAlertDialog.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/lifecycle/LifecycleAwareAlertDialog.java
package net.kdt.pojavlaunch.lifecycle; import android.content.Context; import android.content.DialogInterface; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleEventObserver; import androidx.lifecycle.LifecycleOwner; import net.kdt.pojavlaunch.Tools; import java.util.concurrent.atomic.AtomicBoolean; /** * A class that implements a form of lifecycle awareness for AlertDialog */ public abstract class LifecycleAwareAlertDialog implements LifecycleEventObserver { private Lifecycle mLifecycle; private AlertDialog mDialog; private boolean mLifecycleEnded = false; /** * Show the lifecycle-aware dialog. * Note that the DialogCreator may not be always invoked. * @param lifecycle the lifecycle to follow * @param context the context for the dialog * @param dialogCreator an interface used to create the dialog. * Note that any dismiss listeners added to the dialog must be wrapped * with wrapDismissListener(). */ public void show(Lifecycle lifecycle, Context context, DialogCreator dialogCreator) { this.mLifecycleEnded = false; this.mLifecycle = lifecycle; if(mLifecycle.getCurrentState().equals(Lifecycle.State.DESTROYED)) { this.mLifecycleEnded = true; dialogHidden(mLifecycleEnded); return; } AlertDialog.Builder builder = new AlertDialog.Builder(context); // Install the default cancel/dismiss handling builder.setOnDismissListener(wrapDismissListener(null)); dialogCreator.createDialog(this, builder); mLifecycle.addObserver(this); mDialog = builder.show(); } /** * Invoked when the dialog gets hidden either by cancel()/dismiss(), or if a lifecycle event * happens. * @param lifecycleEnded if the dialog was hidden due to a lifecycle event */ abstract protected void dialogHidden(boolean lifecycleEnded); protected void dispatchDialogHidden() { new Exception().printStackTrace(); dialogHidden(mLifecycleEnded); mLifecycle.removeObserver(this); } public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { if(event.equals(Lifecycle.Event.ON_DESTROY)) { mDialog.dismiss(); mLifecycleEnded = true; } } /** * Wrap an OnDismissListener for use with this LifecycleAwareAlertDialog. Pass null to only invoke the * default dialog hidden handling. * @param listener your listener * @return the wrapped listener */ public DialogInterface.OnDismissListener wrapDismissListener(DialogInterface.OnCancelListener listener) { return dialog -> { dispatchDialogHidden(); if(listener != null) listener.onCancel(dialog); }; } public interface DialogCreator { /** * This methods is called when the LifecycleAwareAlertDialog needs to set up its dialog. * @param alertDialog an instance of LifecycleAwareAlertDialog for wrapping listeners * @param dialogBuilder the AlertDialog builder */ void createDialog(LifecycleAwareAlertDialog alertDialog, AlertDialog.Builder dialogBuilder); } /** * Show a dialog and halt the current thread until the dialog gets closed either due to user action or a lifecycle event. * @param lifecycle the Lifecycle object that this dialog will track to automatically close upon destruction * @param context the context used to show the dialog * @param dialogCreator a DialogCreator that creates the dialog * @return true if the dialog was automatically dismissed due to a lifecycle event. This may happen * before the dialog creator is used, so make sure to to handle the return value of the function. * false otherwise * @throws InterruptedException if the thread was interrupted while waiting for the dialog */ public static boolean haltOnDialog(Lifecycle lifecycle, Context context, DialogCreator dialogCreator) throws InterruptedException { Object waitLock = new Object(); AtomicBoolean hasLifecycleEnded = new AtomicBoolean(false); // This runnable is moved here in order to reduce bracket/lambda hell Runnable showDialogRunnable = () -> { LifecycleAwareAlertDialog lifecycleAwareDialog = new LifecycleAwareAlertDialog() { @Override protected void dialogHidden(boolean lifecycleEnded) { hasLifecycleEnded.set(lifecycleEnded); synchronized(waitLock){waitLock.notifyAll();} } }; lifecycleAwareDialog.show(lifecycle, context, dialogCreator); }; synchronized (waitLock) { Tools.runOnUiThread(showDialogRunnable); // the wait() method makes the thread wait on the end of the synchronized block. // so we put it here to make sure that the thread won't get notified before wait() // is called waitLock.wait(); } return hasLifecycleEnded.get(); } }
5,306
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftClientInfo.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/MinecraftClientInfo.java
package net.kdt.pojavlaunch.value; import androidx.annotation.Keep; @Keep public class MinecraftClientInfo { public String sha1; public int size; public String url; }
172
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftAccount.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/MinecraftAccount.java
package net.kdt.pojavlaunch.value; import android.graphics.BitmapFactory; import android.util.Log; import net.kdt.pojavlaunch.*; import net.kdt.pojavlaunch.utils.FileUtils; import java.io.*; import com.google.gson.*; import android.graphics.Bitmap; import android.util.Base64; import androidx.annotation.Keep; import org.apache.commons.io.IOUtils; @SuppressWarnings("IOStreamConstructor") @Keep public class MinecraftAccount { public String accessToken = "0"; // access token public String clientToken = "0"; // clientID: refresh and invalidate public String profileId = "00000000-0000-0000-0000-000000000000"; // profile UUID, for obtaining skin public String username = "Steve"; public String selectedVersion = "1.7.10"; public boolean isMicrosoft = false; public String msaRefreshToken = "0"; public String xuid; public long expiresAt; public String skinFaceBase64; private Bitmap mFaceCache; void updateSkinFace(String uuid) { try { File skinFile = getSkinFaceFile(username); Tools.downloadFile("https://mc-heads.net/head/" + uuid + "/100", skinFile.getAbsolutePath()); Log.i("SkinLoader", "Update skin face success"); } catch (IOException e) { // Skin refresh limit, no internet connection, etc... // Simply ignore updating skin face Log.w("SkinLoader", "Could not update skin face", e); } } public boolean isLocal(){ return accessToken.equals("0"); } public void updateSkinFace() { updateSkinFace(profileId); } public String save(String outPath) throws IOException { Tools.write(outPath, Tools.GLOBAL_GSON.toJson(this)); return username; } public String save() throws IOException { return save(Tools.DIR_ACCOUNT_NEW + "/" + username + ".json"); } public static MinecraftAccount parse(String content) throws JsonSyntaxException { return Tools.GLOBAL_GSON.fromJson(content, MinecraftAccount.class); } public static MinecraftAccount load(String name) { if(!accountExists(name)) return null; try { MinecraftAccount acc = parse(Tools.read(Tools.DIR_ACCOUNT_NEW + "/" + name + ".json")); if (acc.accessToken == null) { acc.accessToken = "0"; } if (acc.clientToken == null) { acc.clientToken = "0"; } if (acc.profileId == null) { acc.profileId = "00000000-0000-0000-0000-000000000000"; } if (acc.username == null) { acc.username = "0"; } if (acc.selectedVersion == null) { acc.selectedVersion = "1.7.10"; } if (acc.msaRefreshToken == null) { acc.msaRefreshToken = "0"; } return acc; } catch(IOException | JsonSyntaxException e) { Log.e(MinecraftAccount.class.getName(), "Caught an exception while loading the profile",e); return null; } } public Bitmap getSkinFace(){ if(isLocal()) return null; File skinFaceFile = getSkinFaceFile(username); if (!skinFaceFile.exists()) { // Legacy version, storing the head inside the json as base 64 if(skinFaceBase64 == null) return null; byte[] faceIconBytes = Base64.decode(skinFaceBase64, Base64.DEFAULT); return BitmapFactory.decodeByteArray(faceIconBytes, 0, faceIconBytes.length); } else { if(mFaceCache == null) { mFaceCache = BitmapFactory.decodeFile(skinFaceFile.getAbsolutePath()); } } return mFaceCache; } public static Bitmap getSkinFace(String username) { return BitmapFactory.decodeFile(getSkinFaceFile(username).getAbsolutePath()); } private static File getSkinFaceFile(String username) { return new File(Tools.DIR_CACHE, username + ".png"); } private static boolean accountExists(String username){ return new File(Tools.DIR_ACCOUNT_NEW + "/" + username + ".json").exists(); } }
4,238
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftLibraryArtifact.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/MinecraftLibraryArtifact.java
package net.kdt.pojavlaunch.value; import androidx.annotation.Keep; @Keep public class MinecraftLibraryArtifact extends MinecraftClientInfo { public String path; }
167
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DependentLibrary.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/DependentLibrary.java
package net.kdt.pojavlaunch.value; import androidx.annotation.Keep; import net.kdt.pojavlaunch.JMinecraftVersionList.Arguments.ArgValue.ArgRules; @Keep public class DependentLibrary { public ArgRules[] rules; public String name; public LibraryDownloads downloads; public String url; @Keep public static class LibraryDownloads { public final MinecraftLibraryArtifact artifact; public LibraryDownloads(MinecraftLibraryArtifact artifact) { this.artifact = artifact; } } }
504
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftProfile.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/MinecraftProfile.java
package net.kdt.pojavlaunch.value.launcherprofiles; import androidx.annotation.Keep; @Keep public class MinecraftProfile { public String name; public String type; public String created; public String lastUsed; public String icon; public String lastVersionId; public String gameDir; public String javaDir; public String javaArgs; public String logConfig; public boolean logConfigIsXML; public String pojavRendererName; public String controlFile; public MinecraftResolution[] resolution; public static MinecraftProfile createTemplate(){ MinecraftProfile TEMPLATE = new MinecraftProfile(); TEMPLATE.name = "New"; TEMPLATE.lastVersionId = "latest-release"; return TEMPLATE; } public static MinecraftProfile getDefaultProfile(){ MinecraftProfile defaultProfile = new MinecraftProfile(); defaultProfile.name = "Default"; defaultProfile.lastVersionId = "1.7.10"; return defaultProfile; } public MinecraftProfile(){} public MinecraftProfile(MinecraftProfile profile){ name = profile.name; type = profile.type; created = profile.created; lastUsed = profile.lastUsed; icon = profile.icon; lastVersionId = profile.lastVersionId; gameDir = profile.gameDir; javaDir = profile.javaDir; javaArgs = profile.javaArgs; logConfig = profile.logConfig; logConfigIsXML = profile.logConfigIsXML; pojavRendererName = profile.pojavRendererName; controlFile = profile.controlFile; resolution = profile.resolution; } }
1,465
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherProfiles.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/LauncherProfiles.java
package net.kdt.pojavlaunch.value.launcherprofiles; import android.util.Log; import androidx.annotation.NonNull; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class LauncherProfiles { public static MinecraftLauncherProfiles mainProfileJson; private static final File launcherProfilesFile = new File(Tools.DIR_GAME_NEW, "launcher_profiles.json"); /** Reload the profile from the file, creating a default one if necessary */ public static void load(){ if (launcherProfilesFile.exists()) { try { mainProfileJson = Tools.GLOBAL_GSON.fromJson(Tools.read(launcherProfilesFile.getAbsolutePath()), MinecraftLauncherProfiles.class); } catch (IOException e) { Log.e(LauncherProfiles.class.toString(), "Failed to load file: ", e); throw new RuntimeException(e); } } // Fill with default if (mainProfileJson == null) mainProfileJson = new MinecraftLauncherProfiles(); if (mainProfileJson.profiles == null) mainProfileJson.profiles = new HashMap<>(); if (mainProfileJson.profiles.size() == 0) mainProfileJson.profiles.put(UUID.randomUUID().toString(), MinecraftProfile.getDefaultProfile()); // Normalize profile names from mod installers if(normalizeProfileIds(mainProfileJson)){ write(); load(); } } /** Apply the current configuration into a file */ public static void write() { try { Tools.write(launcherProfilesFile.getAbsolutePath(), mainProfileJson.toJson()); } catch (IOException e) { Log.e(LauncherProfiles.class.toString(), "Failed to write profile file", e); throw new RuntimeException(e); } } public static @NonNull MinecraftProfile getCurrentProfile() { if(mainProfileJson == null) LauncherProfiles.load(); String defaultProfileName = LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE, ""); MinecraftProfile profile = mainProfileJson.profiles.get(defaultProfileName); if(profile == null) throw new RuntimeException("The current profile stopped existing :("); return profile; } /** * Insert a new profile into the profile map * @param minecraftProfile the profile to insert */ public static void insertMinecraftProfile(MinecraftProfile minecraftProfile) { mainProfileJson.profiles.put(getFreeProfileKey(), minecraftProfile); } /** * Pick an unused normalized key to store a new profile with * @return an unused key */ public static String getFreeProfileKey() { Map<String, MinecraftProfile> profileMap = mainProfileJson.profiles; String freeKey = UUID.randomUUID().toString(); while(profileMap.get(freeKey) != null) freeKey = UUID.randomUUID().toString(); return freeKey; } /** * For all keys to be UUIDs, effectively isolating profile created by installers * This avoids certain profiles to be erased by the installer * @return Whether some profiles have been normalized */ private static boolean normalizeProfileIds(MinecraftLauncherProfiles launcherProfiles){ boolean hasNormalized = false; ArrayList<String> keys = new ArrayList<>(); // Detect denormalized keys for(String profileKey : launcherProfiles.profiles.keySet()){ try{ if(!UUID.fromString(profileKey).toString().equals(profileKey)) keys.add(profileKey); }catch (IllegalArgumentException exception){ keys.add(profileKey); Log.w(LauncherProfiles.class.toString(), "Illegal profile uuid: " + profileKey); } } // Swap the new keys for(String profileKey : keys){ MinecraftProfile currentProfile = launcherProfiles.profiles.get(profileKey); insertMinecraftProfile(currentProfile); launcherProfiles.profiles.remove(profileKey); hasNormalized = true; } return hasNormalized; } }
4,345
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftResolution.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/MinecraftResolution.java
package net.kdt.pojavlaunch.value.launcherprofiles; import androidx.annotation.Keep; @Keep public class MinecraftResolution { public int width; public int height; }
169
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftSelectedUser.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/MinecraftSelectedUser.java
package net.kdt.pojavlaunch.value.launcherprofiles; import androidx.annotation.Keep; @Keep public class MinecraftSelectedUser { public String account; public String profile; }
180
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftAuthenticationDatabase.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/MinecraftAuthenticationDatabase.java
package net.kdt.pojavlaunch.value.launcherprofiles; import androidx.annotation.Keep; @Keep public class MinecraftAuthenticationDatabase { public String accessToken; public String displayName; public String username; public String uuid; // public MinecraftProfile[] profiles; }
290
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftLauncherSettings.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/MinecraftLauncherSettings.java
package net.kdt.pojavlaunch.value.launcherprofiles; import androidx.annotation.Keep; @Keep public class MinecraftLauncherSettings { public boolean enableSnapshots; public boolean enableAdvanced; public boolean keepLauncherOpen; public boolean showGameLog; public String locale; public boolean showMenu; public boolean enableHistorical; public String profileSorting; public boolean crashAssistance; public boolean enableAnalytics; }
444
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftLauncherProfiles.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/value/launcherprofiles/MinecraftLauncherProfiles.java
package net.kdt.pojavlaunch.value.launcherprofiles; import androidx.annotation.Keep; import java.util.*; import net.kdt.pojavlaunch.*; @Keep public class MinecraftLauncherProfiles { public Map<String, MinecraftProfile> profiles = new HashMap<>(); public boolean profilesWereMigrated; public String clientToken; public Map<String, MinecraftAuthenticationDatabase> authenticationDatabase; // public Map launcherVersion; public MinecraftLauncherSettings settings; // public Map analyticsToken; public int analyticsFailcount; public MinecraftSelectedUser selectedUser; public String toJson() { return Tools.GLOBAL_GSON.toJson(this); } }
665
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MirrorTamperedException.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/mirrors/MirrorTamperedException.java
package net.kdt.pojavlaunch.mirrors; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.text.Html; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.ShowErrorActivity; import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask; import net.kdt.pojavlaunch.prefs.LauncherPreferences; public class MirrorTamperedException extends Exception implements ContextExecutorTask { // Do not change. Android really hates when this value changes for some reason. private static final long serialVersionUID = -7482301619612640658L; @Override public void executeWithActivity(Activity activity) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.dl_tampered_manifest_title); builder.setMessage(Html.fromHtml(activity.getString(R.string.dl_tampered_manifest))); addButtons(builder); ShowErrorActivity.installRemoteDialogHandling(activity, builder); builder.show(); } private void addButtons(AlertDialog.Builder builder) { builder.setPositiveButton(R.string.dl_switch_to_official_site,(d,w)->{ LauncherPreferences.DEFAULT_PREF.edit().putString("downloadSource", "default").apply(); LauncherPreferences.PREF_DOWNLOAD_SOURCE = "default"; }); builder.setNegativeButton(R.string.dl_turn_off_manifest_checks,(d,w)->{ LauncherPreferences.DEFAULT_PREF.edit().putBoolean("verifyManifest", false).apply(); LauncherPreferences.PREF_VERIFY_MANIFEST = false; }); builder.setNeutralButton(android.R.string.cancel, (d,w)->{}); } @Override public void executeWithApplication(Context context) {} }
1,746
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DownloadMirror.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/mirrors/DownloadMirror.java
package net.kdt.pojavlaunch.mirrors; import android.util.Log; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.DownloadUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; public class DownloadMirror { public static final int DOWNLOAD_CLASS_LIBRARIES = 0; public static final int DOWNLOAD_CLASS_METADATA = 1; public static final int DOWNLOAD_CLASS_ASSETS = 2; private static final String URL_PROTOCOL_TAIL = "://"; private static final String[] MIRROR_BMCLAPI = { "https://bmclapi2.bangbang93.com/maven", "https://bmclapi2.bangbang93.com", "https://bmclapi2.bangbang93.com/assets" }; /** * Download a file with the current mirror. If the file is missing on the mirror, * fall back to the official source. * @param downloadClass Class of the download. Can either be DOWNLOAD_CLASS_LIBRARIES, * DOWNLOAD_CLASS_METADATA or DOWNLOAD_CLASS_ASSETS * @param urlInput The original (Mojang) URL for the download * @param outputFile The output file for the download * @param buffer The shared buffer * @param monitor The download monitor. */ public static void downloadFileMirrored(int downloadClass, String urlInput, File outputFile, @Nullable byte[] buffer, Tools.DownloaderFeedback monitor) throws IOException { try { DownloadUtils.downloadFileMonitored(getMirrorMapping(downloadClass, urlInput), outputFile, buffer, monitor); return; }catch (FileNotFoundException e) { Log.w("DownloadMirror", "Cannot find the file on the mirror", e); Log.i("DownloadMirror", "Failling back to default source"); } DownloadUtils.downloadFileMonitored(urlInput, outputFile, buffer, monitor); } /** * Download a file with the current mirror. If the file is missing on the mirror, * fall back to the official source. * @param downloadClass Class of the download. Can either be DOWNLOAD_CLASS_LIBRARIES, * DOWNLOAD_CLASS_METADATA or DOWNLOAD_CLASS_ASSETS * @param urlInput The original (Mojang) URL for the download * @param outputFile The output file for the download */ public static void downloadFileMirrored(int downloadClass, String urlInput, File outputFile) throws IOException { try { DownloadUtils.downloadFile(getMirrorMapping(downloadClass, urlInput), outputFile); return; }catch (FileNotFoundException e) { Log.w("DownloadMirror", "Cannot find the file on the mirror", e); Log.i("DownloadMirror", "Failling back to default source"); } DownloadUtils.downloadFile(urlInput, outputFile); } /** * Check if the current download source is a mirror and not an official source. * @return true if the source is a mirror, false otherwise */ public static boolean isMirrored() { return !LauncherPreferences.PREF_DOWNLOAD_SOURCE.equals("default"); } private static String[] getMirrorSettings() { switch (LauncherPreferences.PREF_DOWNLOAD_SOURCE) { case "bmclapi": return MIRROR_BMCLAPI; case "default": default: return null; } } private static String getMirrorMapping(int downloadClass, String mojangUrl) throws MalformedURLException{ String[] mirrorSettings = getMirrorSettings(); if(mirrorSettings == null) return mojangUrl; int urlTail = getBaseUrlTail(mojangUrl); String baseUrl = mojangUrl.substring(0, urlTail); String path = mojangUrl.substring(urlTail); switch(downloadClass) { case DOWNLOAD_CLASS_ASSETS: case DOWNLOAD_CLASS_METADATA: baseUrl = mirrorSettings[downloadClass]; break; case DOWNLOAD_CLASS_LIBRARIES: if(!baseUrl.endsWith("libraries.minecraft.net")) break; baseUrl = mirrorSettings[downloadClass]; break; } return baseUrl + path; } private static int getBaseUrlTail(String wholeUrl) throws MalformedURLException{ int protocolNameEnd = wholeUrl.indexOf(URL_PROTOCOL_TAIL); if(protocolNameEnd == -1) throw new MalformedURLException("No protocol, or non path-based URL"); protocolNameEnd += URL_PROTOCOL_TAIL.length(); int hostnameEnd = wholeUrl.indexOf('/', protocolNameEnd); if(protocolNameEnd >= wholeUrl.length() || hostnameEnd == protocolNameEnd) throw new MalformedURLException("No hostname"); if(hostnameEnd == -1) hostnameEnd = wholeUrl.length(); return hostnameEnd; } }
5,007
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FolderProvider.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/scoped/FolderProvider.java
package net.kdt.pojavlaunch.scoped; import android.annotation.TargetApi; import android.content.res.AssetFileDescriptor; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Point; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.provider.DocumentsContract; import android.provider.DocumentsContract.Document; import android.provider.DocumentsContract.Root; import android.provider.DocumentsProvider; import android.util.Log; import android.webkit.MimeTypeMap; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * A document provider for the Storage Access Framework which exposes the files in the * $HOME/ directory to other apps. * <p/> * Note that this replaces providing an activity matching the ACTION_GET_CONTENT intent: * <p/> * "A document provider and ACTION_GET_CONTENT should be considered mutually exclusive. If you * support both of them simultaneously, your app will appear twice in the system picker UI, * offering two different ways of accessing your stored data. This would be confusing for users." * - <a href="http://developer.android.com/guide/topics/providers/document-provider.html#43">...</a> */ public class FolderProvider extends DocumentsProvider { private static final String ALL_MIME_TYPES = "*/*"; private static final File BASE_DIR = new File(Tools.DIR_GAME_HOME); // The default columns to return information about a root if no specific // columns are requested in a query. private static final String[] DEFAULT_ROOT_PROJECTION = new String[]{ Root.COLUMN_ROOT_ID, Root.COLUMN_MIME_TYPES, Root.COLUMN_FLAGS, Root.COLUMN_ICON, Root.COLUMN_TITLE, Root.COLUMN_SUMMARY, Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES }; // The default columns to return information about a document if no specific // columns are requested in a query. private static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[]{ Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME, Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE }; @Override public Cursor queryRoots(String[] projection) { final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_ROOT_PROJECTION); final String applicationName = getContext().getString(R.string.app_short_name); final MatrixCursor.RowBuilder row = result.newRow(); row.add(Root.COLUMN_ROOT_ID, getDocIdForFile(BASE_DIR)); row.add(Root.COLUMN_DOCUMENT_ID, getDocIdForFile(BASE_DIR)); row.add(Root.COLUMN_SUMMARY, null); row.add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_SEARCH | Root.FLAG_SUPPORTS_IS_CHILD); row.add(Root.COLUMN_TITLE, applicationName); row.add(Root.COLUMN_MIME_TYPES, ALL_MIME_TYPES); row.add(Root.COLUMN_AVAILABLE_BYTES, BASE_DIR.getFreeSpace()); row.add(Root.COLUMN_ICON, R.mipmap.ic_launcher); return result; } @Override public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); includeFile(result, documentId, null); return result; } @Override public Cursor queryChildDocuments(String parentDocumentId, String[] projection, String sortOrder) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); final File parent = getFileForDocId(parentDocumentId); final File[] children = parent.listFiles(); if(children == null) throw new FileNotFoundException("Unable to list files in "+parent.getAbsolutePath()); for (File file : children) { includeFile(result, null, file); } return result; } @Override public ParcelFileDescriptor openDocument(final String documentId, String mode, CancellationSignal signal) throws FileNotFoundException { final File file = getFileForDocId(documentId); final int accessMode = ParcelFileDescriptor.parseMode(mode); return ParcelFileDescriptor.open(file, accessMode); } @Override public AssetFileDescriptor openDocumentThumbnail(String documentId, Point sizeHint, CancellationSignal signal) throws FileNotFoundException { final File file = getFileForDocId(documentId); final ParcelFileDescriptor pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); return new AssetFileDescriptor(pfd, 0, file.length()); } @Override public boolean onCreate() { return true; } @Override public String createDocument(String parentDocumentId, String mimeType, String displayName) throws FileNotFoundException { File newFile = new File(parentDocumentId, displayName); int noConflictId = 2; while (newFile.exists()) { newFile = new File(parentDocumentId, displayName + " (" + noConflictId++ + ")"); } try { boolean succeeded; if (Document.MIME_TYPE_DIR.equals(mimeType)) { succeeded = newFile.mkdir(); } else { succeeded = newFile.createNewFile(); } if (!succeeded) { throw new FileNotFoundException("Failed to create document with id " + newFile.getPath()); } } catch (IOException e) { throw new FileNotFoundException("Failed to create document with id " + newFile.getPath()); } return newFile.getPath(); } @Override public String renameDocument(String documentId, String displayName) throws FileNotFoundException { File sourceFile = getFileForDocId(documentId); File sourceParent = sourceFile.getParentFile(); if(sourceParent == null) throw new FileNotFoundException("Cannot rename root"); File targetFile = new File(getDocIdForFile(sourceParent) + "/" + displayName); if(!sourceFile.renameTo(targetFile)){ throw new FileNotFoundException("Couldn't rename the document with id" + documentId); } return getDocIdForFile(targetFile); } @Override public String moveDocument(String sourceDocumentId, String sourceParentDocumentId, String targetParentDocumentId) throws FileNotFoundException { File sourceFile = getFileForDocId(sourceParentDocumentId + sourceDocumentId); File targetFile = new File(targetParentDocumentId + sourceDocumentId); if(!sourceFile.renameTo(targetFile)){ throw new FileNotFoundException("Failed to move the document with id " + sourceFile.getPath()); } return getDocIdForFile(targetFile); } @Override public void removeDocument(String documentId, String parentDocumentId) throws FileNotFoundException { deleteDocument(parentDocumentId + "/" + documentId); } @Override public void deleteDocument(String documentId) throws FileNotFoundException { File file = getFileForDocId(documentId); if(file.isDirectory()){ try { FileUtils.deleteDirectory(file); } catch (IOException e) { throw new FileNotFoundException("Failed to delete document with id " + documentId); } }else{ if (!file.delete()) { throw new FileNotFoundException("Failed to delete document with id " + documentId); } } } @Override public String getDocumentType(String documentId) throws FileNotFoundException { Log.i("FolderPRovider", "getDocumentType("+documentId+")"); File file = getFileForDocId(documentId); return getMimeType(file); } @Override public Cursor querySearchDocuments(String rootId, String query, String[] projection) throws FileNotFoundException { final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION); final File parent = getFileForDocId(rootId); // This example implementation searches file names for the query and doesn't rank search // results, so we can stop as soon as we find a sufficient number of matches. Other // implementations might rank results and use other data about files, rather than the file // name, to produce a match. final LinkedList<File> pending = new LinkedList<>(); pending.add(parent); final int MAX_SEARCH_RESULTS = 50; while (!pending.isEmpty() && result.getCount() < MAX_SEARCH_RESULTS) { final File file = pending.removeFirst(); // Avoid directories outside the $HOME directory linked with symlinks (to avoid e.g. search // through the whole SD card). boolean isInsideHome; try { isInsideHome = file.getCanonicalPath().startsWith(Tools.DIR_GAME_HOME); } catch (IOException e) { isInsideHome = true; } if (isInsideHome) { if (file.isDirectory()) { File[] listing = file.listFiles(); if(listing != null) Collections.addAll(pending, listing); } else { if (file.getName().toLowerCase().contains(query)) { includeFile(result, null, file); } } } } return result; } @Override public boolean isChildDocument(String parentDocumentId, String documentId) { return documentId.startsWith(parentDocumentId); } /** * Get the document id given a file. This document id must be consistent across time as other * applications may save the ID and use it to reference documents later. * <p/> * The reverse of @{link #getFileForDocId}. */ private static String getDocIdForFile(File file) { return file.getAbsolutePath(); } /** * Get the file given a document id (the reverse of {@link #getDocIdForFile(File)}). */ private static File getFileForDocId(String docId) throws FileNotFoundException { final File f = new File(docId); if (!f.exists()) throw new FileNotFoundException(f.getAbsolutePath() + " not found"); return f; } private static String getMimeType(File file) { if (file.isDirectory()) { return Document.MIME_TYPE_DIR; } else { final String name = file.getName(); final int lastDot = name.lastIndexOf('.'); if (lastDot >= 0) { final String extension = name.substring(lastDot + 1).toLowerCase(); final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); if (mime != null) return mime; } return "application/octet-stream"; } } /** * Add a representation of a file to a cursor. * * @param result the cursor to modify * @param docId the document ID representing the desired file (may be null if given file) * @param file the File object representing the desired file (may be null if given docID) */ private void includeFile(MatrixCursor result, String docId, File file) throws FileNotFoundException { if (docId == null) { docId = getDocIdForFile(file); } else { file = getFileForDocId(docId); } int flags = 0; if (file.isDirectory()) { if (file.canWrite()) flags |= Document.FLAG_DIR_SUPPORTS_CREATE; } else if (file.canWrite()) { flags |= Document.FLAG_SUPPORTS_WRITE; } File parent = file.getParentFile(); if(parent != null) { // Only fails in one case: when the parent is /, which you can't delete. if(parent.canWrite()) flags |= Document.FLAG_SUPPORTS_DELETE; } final String displayName = file.getName(); final String mimeType = getMimeType(file); if (mimeType.startsWith("image/")) flags |= Document.FLAG_SUPPORTS_THUMBNAIL; final MatrixCursor.RowBuilder row = result.newRow(); row.add(Document.COLUMN_DOCUMENT_ID, docId); row.add(Document.COLUMN_DISPLAY_NAME, displayName); row.add(Document.COLUMN_SIZE, file.length()); row.add(Document.COLUMN_MIME_TYPE, mimeType); row.add(Document.COLUMN_LAST_MODIFIED, file.lastModified()); row.add(Document.COLUMN_FLAGS, flags); row.add(Document.COLUMN_ICON, R.mipmap.ic_launcher); } @Override @TargetApi(26) public DocumentsContract.Path findDocumentPath(@Nullable String parentDocumentId, String childDocumentId) throws FileNotFoundException { File source = BASE_DIR; if(parentDocumentId != null) source = getFileForDocId(parentDocumentId); File destination = getFileForDocId(childDocumentId); List<String> pathIds = new ArrayList<>(); while(!source.equals(destination) && destination != null) { pathIds.add(getDocIdForFile(destination)); destination = destination.getParentFile(); } pathIds.add(getDocIdForFile(source)); Collections.reverse(pathIds); Log.i("FolderProvider", pathIds.toString()); return new DocumentsContract.Path(getDocIdForFile(source), pathIds); } }
13,979
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AsyncAssetManager.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/tasks/AsyncAssetManager.java
package net.kdt.pojavlaunch.tasks; import static net.kdt.pojavlaunch.Architecture.archAsString; import static net.kdt.pojavlaunch.PojavApplication.sExecutorService; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class AsyncAssetManager { private AsyncAssetManager(){} /** * Attempt to install the java 8 runtime, if necessary * @param am App context */ public static void unpackRuntime(AssetManager am) { /* Check if JRE is included */ String rt_version = null; String current_rt_version = MultiRTUtils.__internal__readBinpackVersion("Internal"); try { rt_version = Tools.read(am.open("components/jre/version")); } catch (IOException e) { Log.e("JREAuto", "JRE was not included on this APK.", e); } String exactJREName = MultiRTUtils.getExactJreName(8); if(current_rt_version == null && exactJREName != null && !exactJREName.equals("Internal")/*this clause is for when the internal runtime is goofed*/) return; if(rt_version == null) return; if(rt_version.equals(current_rt_version)) return; // Install the runtime in an async manner, hope for the best String finalRt_version = rt_version; sExecutorService.execute(() -> { try { MultiRTUtils.installRuntimeNamedBinpack( am.open("components/jre/universal.tar.xz"), am.open("components/jre/bin-" + archAsString(Tools.DEVICE_ARCHITECTURE) + ".tar.xz"), "Internal", finalRt_version); MultiRTUtils.postPrepare("Internal"); }catch (IOException e) { Log.e("JREAuto", "Internal JRE unpack failed", e); } }); } /** Unpack single files, with no regard to version tracking */ public static void unpackSingleFiles(Context ctx){ ProgressLayout.setProgress(ProgressLayout.EXTRACT_SINGLE_FILES, 0); sExecutorService.execute(() -> { try { Tools.copyAssetFile(ctx, "options.txt", Tools.DIR_GAME_NEW, false); Tools.copyAssetFile(ctx, "default.json", Tools.CTRLMAP_PATH, false); Tools.copyAssetFile(ctx, "launcher_profiles.json", Tools.DIR_GAME_NEW, false); Tools.copyAssetFile(ctx,"resolv.conf",Tools.DIR_DATA, false); } catch (IOException e) { Log.e("AsyncAssetManager", "Failed to unpack critical components !"); } ProgressLayout.clearProgress(ProgressLayout.EXTRACT_SINGLE_FILES); }); } public static void unpackComponents(Context ctx){ ProgressLayout.setProgress(ProgressLayout.EXTRACT_COMPONENTS, 0); sExecutorService.execute(() -> { try { unpackComponent(ctx, "caciocavallo", false); unpackComponent(ctx, "caciocavallo17", false); // Since the Java module system doesn't allow multiple JARs to declare the same module, // we repack them to a single file here unpackComponent(ctx, "lwjgl3", false); unpackComponent(ctx, "security", true); unpackComponent(ctx, "arc_dns_injector", true); unpackComponent(ctx, "forge_installer", true); } catch (IOException e) { Log.e("AsyncAssetManager", "Failed o unpack components !",e ); } ProgressLayout.clearProgress(ProgressLayout.EXTRACT_COMPONENTS); }); } private static void unpackComponent(Context ctx, String component, boolean privateDirectory) throws IOException { AssetManager am = ctx.getAssets(); String rootDir = privateDirectory ? Tools.DIR_DATA : Tools.DIR_GAME_HOME; File versionFile = new File(rootDir + "/" + component + "/version"); InputStream is = am.open("components/" + component + "/version"); if(!versionFile.exists()) { if (versionFile.getParentFile().exists() && versionFile.getParentFile().isDirectory()) { FileUtils.deleteDirectory(versionFile.getParentFile()); } versionFile.getParentFile().mkdir(); Log.i("UnpackPrep", component + ": Pack was installed manually, or does not exist, unpacking new..."); String[] fileList = am.list("components/" + component); for(String s : fileList) { Tools.copyAssetFile(ctx, "components/" + component + "/" + s, rootDir + "/" + component, true); } } else { FileInputStream fis = new FileInputStream(versionFile); String release1 = Tools.read(is); String release2 = Tools.read(fis); if (!release1.equals(release2)) { if (versionFile.getParentFile().exists() && versionFile.getParentFile().isDirectory()) { FileUtils.deleteDirectory(versionFile.getParentFile()); } versionFile.getParentFile().mkdir(); String[] fileList = am.list("components/" + component); for (String fileName : fileList) { Tools.copyAssetFile(ctx, "components/" + component + "/" + fileName, rootDir + "/" + component, true); } } else { Log.i("UnpackPrep", component + ": Pack is up-to-date with the launcher, continuing..."); } } } }
5,803
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MinecraftDownloader.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/tasks/MinecraftDownloader.java
package net.kdt.pojavlaunch.tasks; import static net.kdt.pojavlaunch.PojavApplication.sExecutorService; import android.app.Activity; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.kdt.mcgui.ProgressLayout; import net.kdt.pojavlaunch.JAssetInfo; import net.kdt.pojavlaunch.JAssets; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.JRE17Util; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.mirrors.DownloadMirror; import net.kdt.pojavlaunch.mirrors.MirrorTamperedException; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.utils.DownloadUtils; import net.kdt.pojavlaunch.utils.FileUtils; import net.kdt.pojavlaunch.value.DependentLibrary; import net.kdt.pojavlaunch.value.MinecraftClientInfo; import net.kdt.pojavlaunch.value.MinecraftLibraryArtifact; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; public class MinecraftDownloader { public static final String MINECRAFT_RES = "https://resources.download.minecraft.net/"; private AtomicReference<Exception> mDownloaderThreadException; private ArrayList<DownloaderTask> mScheduledDownloadTasks; private AtomicLong mDownloadFileCounter; private AtomicLong mDownloadSizeCounter; private long mDownloadFileCount; private File mSourceJarFile; // The source client JAR picked during the inheritance process private File mTargetJarFile; // The destination client JAR to which the source will be copied to. private static final ThreadLocal<byte[]> sThreadLocalDownloadBuffer = new ThreadLocal<>(); /** * Start the game version download process on the global executor service. * @param activity Activity, used for automatic installation of JRE 17 if needed * @param version The JMinecraftVersionList.Version from the version list, if available * @param realVersion The version ID (necessary) * @param listener The download status listener */ public void start(@Nullable Activity activity, @Nullable JMinecraftVersionList.Version version, @NonNull String realVersion, // this was there for a reason @NonNull AsyncMinecraftDownloader.DoneListener listener) { sExecutorService.execute(() -> { try { downloadGame(activity, version, realVersion); listener.onDownloadDone(); }catch (Exception e) { listener.onDownloadFailed(e); } ProgressLayout.clearProgress(ProgressLayout.DOWNLOAD_MINECRAFT); }); } /** * Download the game version. * @param activity Activity, used for automatic installation of JRE 17 if needed * @param verInfo The JMinecraftVersionList.Version from the version list, if available * @param versionName The version ID (necessary) * @throws Exception when an exception occurs in the function body or in any of the downloading threads. */ private void downloadGame(Activity activity, JMinecraftVersionList.Version verInfo, String versionName) throws Exception { // Put up a dummy progress line, for the activity to start the service and do all the other necessary // work to keep the launcher alive. We will replace this line when we will start downloading stuff. ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, 0, R.string.newdl_starting); mTargetJarFile = createGameJarPath(versionName); mScheduledDownloadTasks = new ArrayList<>(); mDownloadFileCounter = new AtomicLong(0); mDownloadSizeCounter = new AtomicLong(0); mDownloaderThreadException = new AtomicReference<>(null); if(!downloadAndProcessMetadata(activity, verInfo, versionName)) { throw new RuntimeException(activity.getString(R.string.exception_failed_to_unpack_jre17)); } ArrayBlockingQueue<Runnable> taskQueue = new ArrayBlockingQueue<>(mScheduledDownloadTasks.size(), false); ThreadPoolExecutor downloaderPool = new ThreadPoolExecutor(4, 4, 500, TimeUnit.MILLISECONDS, taskQueue); // I have tried pre-filling the queue directly instead of doing this, but it didn't work. // What a shame. for(DownloaderTask scheduledTask : mScheduledDownloadTasks) downloaderPool.execute(scheduledTask); downloaderPool.shutdown(); try { while (mDownloaderThreadException.get() == null && !downloaderPool.awaitTermination(33, TimeUnit.MILLISECONDS)) { long dlFileCounter = mDownloadFileCounter.get(); int progress = (int)((dlFileCounter * 100L) / mDownloadFileCount); ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, progress, R.string.newdl_downloading_game_files, dlFileCounter, mDownloadFileCount, (double)mDownloadSizeCounter.get() / (1024d * 1024d)); } Exception thrownException = mDownloaderThreadException.get(); if(thrownException != null) { throw thrownException; } else { ensureJarFileCopy(); } }catch (InterruptedException e) { // Interrupted while waiting, which means that the download was cancelled. // Kill all downloading threads immediately, and ignore any exceptions thrown by them downloaderPool.shutdownNow(); } } private File createGameJsonPath(String versionId) { return new File(Tools.DIR_HOME_VERSION, versionId + File.separator + versionId + ".json"); } private File createGameJarPath(String versionId) { return new File(Tools.DIR_HOME_VERSION, versionId + File.separator + versionId + ".jar"); } /** * Ensure that there is a copy of the client JAR file in the version folder, if a copy is * needed. * @throws IOException if the copy fails */ private void ensureJarFileCopy() throws IOException { if(mSourceJarFile == null) return; if(mSourceJarFile.equals(mTargetJarFile)) return; if(mTargetJarFile.exists()) return; FileUtils.ensureParentDirectory(mTargetJarFile); Log.i("NewMCDownloader", "Copying " + mSourceJarFile.getName() + " to "+mTargetJarFile.getAbsolutePath()); org.apache.commons.io.FileUtils.copyFile(mSourceJarFile, mTargetJarFile, false); } private File downloadGameJson(JMinecraftVersionList.Version verInfo) throws IOException, MirrorTamperedException { File targetFile = createGameJsonPath(verInfo.id); if(verInfo.sha1 == null && targetFile.canRead() && targetFile.isFile()) return targetFile; FileUtils.ensureParentDirectory(targetFile); try { DownloadUtils.ensureSha1(targetFile, LauncherPreferences.PREF_VERIFY_MANIFEST ? verInfo.sha1 : null, () -> { ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, 0, R.string.newdl_downloading_metadata, targetFile.getName()); DownloadMirror.downloadFileMirrored(DownloadMirror.DOWNLOAD_CLASS_METADATA, verInfo.url, targetFile); return null; }); }catch (DownloadUtils.SHA1VerificationException e) { if(DownloadMirror.isMirrored()) throw new MirrorTamperedException(); else throw e; } return targetFile; } private JAssets downloadAssetsIndex(JMinecraftVersionList.Version verInfo) throws IOException{ JMinecraftVersionList.AssetIndex assetIndex = verInfo.assetIndex; if(assetIndex == null || verInfo.assets == null) return null; File targetFile = new File(Tools.ASSETS_PATH, "indexes"+ File.separator + verInfo.assets + ".json"); FileUtils.ensureParentDirectory(targetFile); DownloadUtils.ensureSha1(targetFile, assetIndex.sha1, ()-> { ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, 0, R.string.newdl_downloading_metadata, targetFile.getName()); DownloadMirror.downloadFileMirrored(DownloadMirror.DOWNLOAD_CLASS_METADATA, assetIndex.url, targetFile); return null; }); return Tools.GLOBAL_GSON.fromJson(Tools.read(targetFile), JAssets.class); } private MinecraftClientInfo getClientInfo(JMinecraftVersionList.Version verInfo) { Map<String, MinecraftClientInfo> downloads = verInfo.downloads; if(downloads == null) return null; return downloads.get("client"); } /** * Download (if necessary) and process a version's metadata, scheduling all downloads that this * version needs. * @param activity Activity, used for automatic installation of JRE 17 if needed * @param verInfo The JMinecraftVersionList.Version from the version list, if available * @param versionName The version ID (necessary) * @return false if JRE17 installation failed, true otherwise * @throws IOException if the download of any of the metadata files fails */ private boolean downloadAndProcessMetadata(Activity activity, JMinecraftVersionList.Version verInfo, String versionName) throws IOException, MirrorTamperedException { File versionJsonFile; if(verInfo != null) versionJsonFile = downloadGameJson(verInfo); else versionJsonFile = createGameJsonPath(versionName); if(versionJsonFile.canRead()) { verInfo = Tools.GLOBAL_GSON.fromJson(Tools.read(versionJsonFile), JMinecraftVersionList.Version.class); } else { throw new IOException("Unable to read Version JSON for version " + versionName); } if(activity != null && !JRE17Util.installNewJreIfNeeded(activity, verInfo)){ return false; } JAssets assets = downloadAssetsIndex(verInfo); if(assets != null) scheduleAssetDownloads(assets); MinecraftClientInfo minecraftClientInfo = getClientInfo(verInfo); if(minecraftClientInfo != null) scheduleGameJarDownload(minecraftClientInfo, versionName); if(verInfo.libraries != null) scheduleLibraryDownloads(verInfo.libraries); if(verInfo.logging != null) scheduleLoggingAssetDownloadIfNeeded(verInfo.logging); if(Tools.isValidString(verInfo.inheritsFrom)) { JMinecraftVersionList.Version inheritedVersion = AsyncMinecraftDownloader.getListedVersion(verInfo.inheritsFrom); // Infinite inheritance !?! :noway: return downloadAndProcessMetadata(activity, inheritedVersion, verInfo.inheritsFrom); } return true; } private void growDownloadList(int addedElementCount) { mScheduledDownloadTasks.ensureCapacity(mScheduledDownloadTasks.size() + addedElementCount); } private void scheduleDownload(File targetFile, int downloadClass, String url, String sha1, long size, boolean skipIfFailed) throws IOException { FileUtils.ensureParentDirectory(targetFile); mDownloadFileCount++; mScheduledDownloadTasks.add( new DownloaderTask(targetFile, downloadClass, url, sha1, size, skipIfFailed) ); } private void scheduleLibraryDownloads(DependentLibrary[] dependentLibraries) throws IOException { Tools.preProcessLibraries(dependentLibraries); growDownloadList(dependentLibraries.length); for(DependentLibrary dependentLibrary : dependentLibraries) { // Don't download lwjgl, we have our own bundled in. if(dependentLibrary.name.startsWith("org.lwjgl")) continue; String libArtifactPath = Tools.artifactToPath(dependentLibrary); String sha1 = null, url = null; long size = 0; boolean skipIfFailed = false; if(dependentLibrary.downloads != null) { if(dependentLibrary.downloads.artifact != null) { MinecraftLibraryArtifact artifact = dependentLibrary.downloads.artifact; sha1 = artifact.sha1; url = artifact.url; size = artifact.size; } else { // If the library has a downloads section but doesn't have an artifact in // it, it is likely natives-only, which means it can be skipped. Log.i("NewMCDownloader", "Skipped library " + dependentLibrary.name + " due to lack of artifact"); continue; } } if(url == null) { url = (dependentLibrary.url == null ? "https://libraries.minecraft.net/" : dependentLibrary.url.replace("http://","https://")) + libArtifactPath; skipIfFailed = true; } if(!LauncherPreferences.PREF_CHECK_LIBRARY_SHA) sha1 = null; scheduleDownload(new File(Tools.DIR_HOME_LIBRARY, libArtifactPath), DownloadMirror.DOWNLOAD_CLASS_LIBRARIES, url, sha1, size, skipIfFailed ); } } private void scheduleAssetDownloads(JAssets assets) throws IOException { Map<String, JAssetInfo> assetObjects = assets.objects; if(assetObjects == null) return; Set<String> assetNames = assetObjects.keySet(); growDownloadList(assetNames.size()); for(String asset : assetNames) { JAssetInfo assetInfo = assetObjects.get(asset); if(assetInfo == null) continue; File targetFile; String hashedPath = assetInfo.hash.substring(0, 2) + File.separator + assetInfo.hash; String basePath = assets.mapToResources ? Tools.OBSOLETE_RESOURCES_PATH : Tools.ASSETS_PATH; if(assets.virtual || assets.mapToResources) { targetFile = new File(basePath, asset); } else { targetFile = new File(basePath, "objects" + File.separator + hashedPath); } String sha1 = LauncherPreferences.PREF_CHECK_LIBRARY_SHA ? assetInfo.hash : null; scheduleDownload(targetFile, DownloadMirror.DOWNLOAD_CLASS_ASSETS, MINECRAFT_RES + hashedPath, sha1, assetInfo.size, false); } } private void scheduleLoggingAssetDownloadIfNeeded(JMinecraftVersionList.LoggingConfig loggingConfig) throws IOException { if(loggingConfig.client == null || loggingConfig.client.file == null) return; JMinecraftVersionList.FileProperties loggingFileProperties = loggingConfig.client.file; File internalLoggingConfig = new File(Tools.DIR_DATA + File.separator + "security", loggingFileProperties.id.replace("client", "log4j-rce-patch")); if(internalLoggingConfig.exists()) return; File destination = new File(Tools.DIR_GAME_NEW, loggingFileProperties.id); scheduleDownload(destination, DownloadMirror.DOWNLOAD_CLASS_LIBRARIES, loggingFileProperties.url, loggingFileProperties.sha1, loggingFileProperties.size, false); } private void scheduleGameJarDownload(MinecraftClientInfo minecraftClientInfo, String versionName) throws IOException { File clientJar = createGameJarPath(versionName); String clientSha1 = LauncherPreferences.PREF_CHECK_LIBRARY_SHA ? minecraftClientInfo.sha1 : null; growDownloadList(1); scheduleDownload(clientJar, DownloadMirror.DOWNLOAD_CLASS_LIBRARIES, minecraftClientInfo.url, clientSha1, minecraftClientInfo.size, false ); // Store the path of the JAR to copy it into our new version folder later. mSourceJarFile = clientJar; } private static byte[] getLocalBuffer() { byte[] tlb = sThreadLocalDownloadBuffer.get(); if(tlb != null) return tlb; tlb = new byte[32768]; sThreadLocalDownloadBuffer.set(tlb); return tlb; } private final class DownloaderTask implements Runnable, Tools.DownloaderFeedback { private final File mTargetPath; private final String mTargetUrl; private String mTargetSha1; private final int mDownloadClass; private final boolean mSkipIfFailed; private int mLastCurr; private final long mDownloadSize; DownloaderTask(File targetPath, int downloadClass, String targetUrl, String targetSha1, long downloadSize, boolean skipIfFailed) { this.mTargetPath = targetPath; this.mTargetUrl = targetUrl; this.mTargetSha1 = targetSha1; this.mDownloadClass = downloadClass; this.mDownloadSize = downloadSize; this.mSkipIfFailed = skipIfFailed; } @Override public void run() { try { runCatching(); }catch (Exception e) { mDownloaderThreadException.set(e); } } private void runCatching() throws Exception { if(Tools.isValidString(mTargetSha1)) { verifyFileSha1(); }else { mTargetSha1 = null; // Nullify SHA1 as DownloadUtils.ensureSha1 only checks for null, // not for string validity if(mTargetPath.exists()) finishWithoutDownloading(); else downloadFile(); } } private void verifyFileSha1() throws Exception { if(mTargetPath.isFile() && mTargetPath.canRead() && Tools.compareSHA1(mTargetPath, mTargetSha1)) { finishWithoutDownloading(); } else { // Rely on the download function to throw an IOE in case if the file is not // writable/not a file/etc... downloadFile(); } } private void downloadFile() throws Exception { try { DownloadUtils.ensureSha1(mTargetPath, mTargetSha1, () -> { DownloadMirror.downloadFileMirrored(mDownloadClass, mTargetUrl, mTargetPath, getLocalBuffer(), this); return null; }); }catch (Exception e) { if(!mSkipIfFailed) throw e; } mDownloadFileCounter.incrementAndGet(); } private void finishWithoutDownloading() { mDownloadFileCounter.incrementAndGet(); mDownloadSizeCounter.addAndGet(mDownloadSize); } @Override public void updateProgress(int curr, int max) { mDownloadSizeCounter.addAndGet(curr - mLastCurr); mLastCurr = curr; } } }
19,387
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AsyncMinecraftDownloader.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/tasks/AsyncMinecraftDownloader.java
package net.kdt.pojavlaunch.tasks; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; public class AsyncMinecraftDownloader { public static String normalizeVersionId(String versionString) { JMinecraftVersionList versionList = (JMinecraftVersionList) ExtraCore.getValue(ExtraConstants.RELEASE_TABLE); if(versionList == null || versionList.versions == null) return versionString; if("latest-release".equals(versionString)) versionString = versionList.latest.get("release"); if("latest-snapshot".equals(versionString)) versionString = versionList.latest.get("snapshot"); return versionString; } public static JMinecraftVersionList.Version getListedVersion(String normalizedVersionString) { JMinecraftVersionList versionList = (JMinecraftVersionList) ExtraCore.getValue(ExtraConstants.RELEASE_TABLE); if(versionList == null || versionList.versions == null) return null; // can't have listed versions if there's no list for(JMinecraftVersionList.Version version : versionList.versions) { if(version.id.equals(normalizedVersionString)) return version; } return null; } public interface DoneListener{ void onDownloadDone(); void onDownloadFailed(Throwable throwable); } }
1,393
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
AsyncVersionList.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/tasks/AsyncVersionList.java
package net.kdt.pojavlaunch.tasks; import static net.kdt.pojavlaunch.PojavApplication.sExecutorService; import static net.kdt.pojavlaunch.utils.DownloadUtils.downloadString; import android.util.Log; import androidx.annotation.Nullable; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; /** Class getting the version list, and that's all really */ public class AsyncVersionList { public void getVersionList(@Nullable VersionDoneListener listener, boolean secondPass){ sExecutorService.execute(() -> { File versionFile = new File(Tools.DIR_DATA + "/version_list.json"); JMinecraftVersionList versionList = null; try{ if(!versionFile.exists() || (System.currentTimeMillis() > versionFile.lastModified() + 86400000 )){ versionList = downloadVersionList(LauncherPreferences.PREF_VERSION_REPOS); } }catch (Exception e){ Log.e("AsyncVersionList", "Refreshing version list failed :" + e); e.printStackTrace(); } // Fallback when no network or not needed if (versionList == null) { try { versionList = Tools.GLOBAL_GSON.fromJson(new JsonReader(new FileReader(versionFile)), JMinecraftVersionList.class); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (JsonIOException | JsonSyntaxException e) { e.printStackTrace(); versionFile.delete(); if(!secondPass) getVersionList(listener, true); } } if(listener != null) listener.onVersionDone(versionList); }); } @SuppressWarnings("SameParameterValue") private JMinecraftVersionList downloadVersionList(String mirror){ JMinecraftVersionList list = null; try{ Log.i("ExtVL", "Syncing to external: " + mirror); String jsonString = downloadString(mirror); list = Tools.GLOBAL_GSON.fromJson(jsonString, JMinecraftVersionList.class); Log.i("ExtVL","Downloaded the version list, len=" + list.versions.length); // Then save the version list //TODO make it not save at times ? FileOutputStream fos = new FileOutputStream(Tools.DIR_DATA + "/version_list.json"); fos.write(jsonString.getBytes()); fos.close(); }catch (IOException e){ Log.e("AsyncVersionList", e.toString()); } return list; } /** Basic listener, acting as a callback */ public interface VersionDoneListener{ void onVersionDone(JMinecraftVersionList versions); } }
3,161
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
NotificationUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/NotificationUtils.java
package net.kdt.pojavlaunch.utils; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import androidx.core.app.NotificationCompat; import net.kdt.pojavlaunch.R; public class NotificationUtils { public static final int NOTIFICATION_ID_PROGRESS_SERVICE = 1; public static final int NOTIFICATION_ID_GAME_SERVICE = 2; public static final int NOTIFICATION_ID_DOWNLOAD_LISTENER = 3; public static final int NOTIFICATION_ID_SHOW_ERROR = 4; public static final int NOTIFICATION_ID_GAME_START = 5; public static final int PENDINGINTENT_CODE_KILL_PROGRESS_SERVICE = 1; public static final int PENDINGINTENT_CODE_KILL_GAME_SERVICE = 2; public static final int PENDINGINTENT_CODE_DOWNLOAD_SERVICE = 3; public static final int PENDINGINTENT_CODE_SHOW_ERROR = 4; public static final int PENDINGINTENT_CODE_GAME_START = 5; public static void sendBasicNotification(Context context, int contentTitle, int contentText, Intent actionIntent, int pendingIntentCode, int notificationId) { PendingIntent pendingIntent = PendingIntent.getActivity(context, pendingIntentCode, actionIntent, Build.VERSION.SDK_INT >=23 ? PendingIntent.FLAG_IMMUTABLE : 0); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, context.getString(R.string.notif_channel_id)); if(contentTitle != -1) notificationBuilder.setContentTitle(context.getString(contentTitle)); if(contentText != -1) notificationBuilder.setContentText(context.getString(contentText)); if(actionIntent != null) notificationBuilder.setContentIntent(pendingIntent); notificationBuilder.setSmallIcon(R.drawable.notif_icon); notificationManager.notify(notificationId, notificationBuilder.build()); } }
2,073
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MCOptionUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/MCOptionUtils.java
package net.kdt.pojavlaunch.utils; import static org.lwjgl.glfw.CallbackBridge.windowHeight; import static org.lwjgl.glfw.CallbackBridge.windowWidth; import android.os.Build; import android.os.FileObserver; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import net.kdt.pojavlaunch.Tools; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Objects; public class MCOptionUtils { private static final HashMap<String,String> sParameterMap = new HashMap<>(); private static final ArrayList<WeakReference<MCOptionListener>> sOptionListeners = new ArrayList<>(); private static FileObserver sFileObserver; private static String sOptionFolderPath = null; public interface MCOptionListener { /** Called when an option is changed. Don't know which one though */ void onOptionChanged(); } public static void load(){ load(sOptionFolderPath == null ? Tools.DIR_GAME_NEW : sOptionFolderPath); } public static void load(@NonNull String folderPath) { File optionFile = new File(folderPath + "/options.txt"); if(!optionFile.exists()) { try { // Needed for new instances I guess :think: optionFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } if(sFileObserver == null || !Objects.equals(sOptionFolderPath, folderPath)){ sOptionFolderPath = folderPath; setupFileObserver(); } sOptionFolderPath = folderPath; // Yeah I know, it may be redundant sParameterMap.clear(); try { BufferedReader reader = new BufferedReader(new FileReader(optionFile)); String line; while ((line = reader.readLine()) != null) { int firstColonIndex = line.indexOf(':'); if(firstColonIndex < 0) { Log.w(Tools.APP_NAME, "No colon on line \""+line+"\", skipping"); continue; } sParameterMap.put(line.substring(0,firstColonIndex), line.substring(firstColonIndex+1)); } reader.close(); } catch (IOException e) { Log.w(Tools.APP_NAME, "Could not load options.txt", e); } } public static void set(String key, String value) { sParameterMap.put(key,value); } /** Set an array of String, instead of a simple value. Not supported on all options */ public static void set(String key, List<String> values){ sParameterMap.put(key, values.toString()); } public static String get(String key){ return sParameterMap.get(key); } /** @return A list of values from an array stored as a string */ public static List<String> getAsList(String key){ String value = get(key); // Fallback if the value doesn't exist if (value == null) return new ArrayList<>(); // Remove the edges value = value.replace("[", "").replace("]", ""); if (value.isEmpty()) return new ArrayList<>(); return Arrays.asList(value.split(",")); } public static void save() { StringBuilder result = new StringBuilder(); for(String key : sParameterMap.keySet()) result.append(key) .append(':') .append(sParameterMap.get(key)) .append('\n'); try { sFileObserver.stopWatching(); Tools.write(sOptionFolderPath + "/options.txt", result.toString()); sFileObserver.startWatching(); } catch (IOException e) { Log.w(Tools.APP_NAME, "Could not save options.txt", e); } } /** @return The stored Minecraft GUI scale, also auto-computed if on auto-mode or improper setting */ public static int getMcScale() { String str = MCOptionUtils.get("guiScale"); int guiScale = (str == null ? 0 :Integer.parseInt(str)); int scale = Math.max(Math.min(windowWidth / 320, windowHeight / 240), 1); if(scale < guiScale || guiScale == 0){ guiScale = scale; } return guiScale; } /** Add a file observer to reload options on file change * Listeners get notified of the change */ private static void setupFileObserver(){ if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){ sFileObserver = new FileObserver(new File(sOptionFolderPath + "/options.txt"), FileObserver.MODIFY) { @Override public void onEvent(int i, @Nullable String s) { MCOptionUtils.load(); notifyListeners(); } }; }else{ sFileObserver = new FileObserver(sOptionFolderPath + "/options.txt", FileObserver.MODIFY) { @Override public void onEvent(int i, @Nullable String s) { MCOptionUtils.load(); notifyListeners(); } }; } sFileObserver.startWatching(); } /** Notify the option listeners */ public static void notifyListeners(){ for(WeakReference<MCOptionListener> weakReference : sOptionListeners){ MCOptionListener optionListener = weakReference.get(); if(optionListener == null) continue; optionListener.onOptionChanged(); } } /** Add an option listener, notice how we don't have a reference to it */ public static void addMCOptionListener(MCOptionListener listener){ sOptionListeners.add(new WeakReference<>(listener)); } /** Remove a listener from existence, or at least, its reference here */ public static void removeMCOptionListener(MCOptionListener listener){ for(WeakReference<MCOptionListener> weakReference : sOptionListeners){ MCOptionListener optionListener = weakReference.get(); if(optionListener == null) continue; if(optionListener == listener){ sOptionListeners.remove(weakReference); return; } } } }
6,407
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GsonJsonUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/GsonJsonUtils.java
package net.kdt.pojavlaunch.utils; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class GsonJsonUtils { /** * Safely converts a JsonElement into a JsonObject. * @param element the input JsonElement * @return the JsonObject if: * the JsonElement is not null * the JsonElement is not Json null * the JsonElement is a JsonObjet * null otherwise */ public static JsonObject getJsonObjectSafe(JsonElement element) { if(element == null) return null; if(element.isJsonNull() || !element.isJsonObject()) return null; return element.getAsJsonObject(); } /** * Safely gets a JsonElement from a JsonObject * @param jsonObject the input JsonObject * @param memberName the member name of the JsonElement * @return the JsonElement if: * the input JsonObject is not null * the input JsonObject contains an element with the specified memberName * the JsonElement is not Json null * null otherwise */ public static JsonElement getElementSafe(JsonObject jsonObject, String memberName) { if(jsonObject == null) return null; if(!jsonObject.has(memberName)) return null; JsonElement element = jsonObject.get(memberName); if(element.isJsonNull()) return null; return element; } /** * Safely gets a JsonObject from a JsonObject * @param jsonObject the input JsonObject * @param memberName the member name of the output JsonObject * @return the output JsonObject if: * the input JsonObject is not null * the input JsonObject contains an element with the specified memberName * the output JsonObject is not Json null * the output JsonObject is a JsonObjet * null otherwise */ public static JsonObject getJsonObjectSafe(JsonObject jsonObject, String memberName) { return getJsonObjectSafe(getElementSafe(jsonObject, memberName)); } /** * Safely gets a JsonArray from a JsonObject * @param jsonObject the input JsonObject * @param memberName the member name of the JsonArray * @return the JsonArray if: * the input JsonObject is not null * the input JsonObject contains an element with the specified memberName * the JsonArray is not Json null * the JsonArray is a JsonArray * null otherwise */ public static JsonArray getJsonArraySafe(JsonObject jsonObject, String memberName) { JsonElement jsonElement = getElementSafe(jsonObject, memberName); if(jsonElement == null || !jsonElement.isJsonArray()) return null; return jsonElement.getAsJsonArray(); } /** * Safely gets an int from a JsonObject * @param jsonObject the input JsonObject * @param memberName the member name of the int * @param onNullValue the value that will be returned if any of the checks fail * @return the int if: * the input JsonObject is not null * the input JsonObject contains an element with the specified memberName * the int is not Json null * the int is an actual integer * onNullValue otherwise */ public static int getIntSafe(JsonObject jsonObject, String memberName, int onNullValue) { JsonElement jsonElement = getElementSafe(jsonObject, memberName); if(jsonElement == null || !jsonElement.isJsonPrimitive()) return onNullValue; try { return jsonElement.getAsInt(); }catch (ClassCastException e) { return onNullValue; } } /** * Safely gets a String from a JsonObject * @param jsonObject the input JsonObject * @param memberName the member name of the int * @return the String if: * the input JsonObject is not null * the input JsonObject contains an element with the specified memberName * the String is not a Json null * the String is an actual String * null otherwise */ public static String getStringSafe(JsonObject jsonObject, String memberName) { JsonElement jsonElement = getElementSafe(jsonObject, memberName); if(jsonElement == null || !jsonElement.isJsonPrimitive()) return null; try { return jsonElement.getAsString(); }catch (ClassCastException e) { return null; } } }
4,617
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JREUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/JREUtils.java
package net.kdt.pojavlaunch.utils; import static net.kdt.pojavlaunch.Architecture.ARCH_X86; import static net.kdt.pojavlaunch.Architecture.is64BitsDevice; import static net.kdt.pojavlaunch.Tools.LOCAL_RENDERER; import static net.kdt.pojavlaunch.Tools.NATIVE_LIB_DIR; import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics; import static net.kdt.pojavlaunch.Tools.shareLog; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_DUMP_SHADERS; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_VSYNC_IN_ZINK; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_ZINK_PREFER_SYSTEM_DRIVER; import android.app.*; import android.content.*; import android.os.Build; import android.system.*; import android.util.*; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.oracle.dalvik.*; import java.io.*; import java.util.*; import net.kdt.pojavlaunch.*; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.lifecycle.LifecycleAwareAlertDialog; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.multirt.Runtime; import net.kdt.pojavlaunch.plugins.FFmpegPlugin; import net.kdt.pojavlaunch.prefs.*; import org.lwjgl.glfw.*; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; public class JREUtils { private JREUtils() {} public static String LD_LIBRARY_PATH; public static String jvmLibraryPath; public static String findInLdLibPath(String libName) { if(Os.getenv("LD_LIBRARY_PATH")==null) { try { if (LD_LIBRARY_PATH != null) { Os.setenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH, true); } }catch (ErrnoException e) { e.printStackTrace(); } return libName; } for (String libPath : Os.getenv("LD_LIBRARY_PATH").split(":")) { File f = new File(libPath, libName); if (f.exists() && f.isFile()) { return f.getAbsolutePath(); } } return libName; } public static ArrayList<File> locateLibs(File path) { ArrayList<File> returnValue = new ArrayList<>(); File[] list = path.listFiles(); if(list != null) { for(File f : list) { if(f.isFile() && f.getName().endsWith(".so")) { returnValue.add(f); }else if(f.isDirectory()) { returnValue.addAll(locateLibs(f)); } } } return returnValue; } public static void initJavaRuntime(String jreHome) { dlopen(findInLdLibPath("libjli.so")); if(!dlopen("libjvm.so")){ Log.w("DynamicLoader","Failed to load with no path, trying with full path"); dlopen(jvmLibraryPath+"/libjvm.so"); } dlopen(findInLdLibPath("libverify.so")); dlopen(findInLdLibPath("libjava.so")); // dlopen(findInLdLibPath("libjsig.so")); dlopen(findInLdLibPath("libnet.so")); dlopen(findInLdLibPath("libnio.so")); dlopen(findInLdLibPath("libawt.so")); dlopen(findInLdLibPath("libawt_headless.so")); dlopen(findInLdLibPath("libfreetype.so")); dlopen(findInLdLibPath("libfontmanager.so")); for(File f : locateLibs(new File(jreHome, Tools.DIRNAME_HOME_JRE))) { dlopen(f.getAbsolutePath()); } dlopen(NATIVE_LIB_DIR + "/libopenal.so"); } public static void redirectAndPrintJRELog() { Log.v("jrelog","Log starts here"); new Thread(new Runnable(){ int failTime = 0; ProcessBuilder logcatPb; @Override public void run() { try { if (logcatPb == null) { logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog:I", "LIBGL:I", "NativeInput").redirectErrorStream(true); } Log.i("jrelog-logcat","Clearing logcat"); new ProcessBuilder().command("logcat", "-c").redirectErrorStream(true).start(); Log.i("jrelog-logcat","Starting logcat"); java.lang.Process p = logcatPb.start(); byte[] buf = new byte[1024]; int len; while ((len = p.getInputStream().read(buf)) != -1) { String currStr = new String(buf, 0, len); Logger.appendToLog(currStr); } if (p.waitFor() != 0) { Log.e("jrelog-logcat", "Logcat exited with code " + p.exitValue()); failTime++; Log.i("jrelog-logcat", (failTime <= 10 ? "Restarting logcat" : "Too many restart fails") + " (attempt " + failTime + "/10"); if (failTime <= 10) { run(); } else { Logger.appendToLog("ERROR: Unable to get more log."); } } } catch (Throwable e) { Log.e("jrelog-logcat", "Exception on logging thread", e); Logger.appendToLog("Exception on logging thread:\n" + Log.getStackTraceString(e)); } } }).start(); Log.i("jrelog-logcat","Logcat thread started"); } public static void relocateLibPath(Runtime runtime, String jreHome) { String JRE_ARCHITECTURE = runtime.arch; if (Architecture.archAsInt(JRE_ARCHITECTURE) == ARCH_X86){ JRE_ARCHITECTURE = "i386/i486/i586"; } for (String arch : JRE_ARCHITECTURE.split("/")) { File f = new File(jreHome, "lib/" + arch); if (f.exists() && f.isDirectory()) { Tools.DIRNAME_HOME_JRE = "lib/" + arch; } } String libName = is64BitsDevice() ? "lib64" : "lib"; StringBuilder ldLibraryPath = new StringBuilder(); if(FFmpegPlugin.isAvailable) { ldLibraryPath.append(FFmpegPlugin.libraryPath).append(":"); } ldLibraryPath.append(jreHome) .append("/").append(Tools.DIRNAME_HOME_JRE) .append("/jli:").append(jreHome).append("/").append(Tools.DIRNAME_HOME_JRE) .append(":"); ldLibraryPath.append("/system/").append(libName).append(":") .append("/vendor/").append(libName).append(":") .append("/vendor/").append(libName).append("/hw:") .append(NATIVE_LIB_DIR); LD_LIBRARY_PATH = ldLibraryPath.toString(); } public static void setJavaEnvironment(Activity activity, String jreHome) throws Throwable { Map<String, String> envMap = new ArrayMap<>(); envMap.put("POJAV_NATIVEDIR", NATIVE_LIB_DIR); envMap.put("JAVA_HOME", jreHome); envMap.put("HOME", Tools.DIR_GAME_HOME); envMap.put("TMPDIR", Tools.DIR_CACHE.getAbsolutePath()); envMap.put("LIBGL_MIPMAP", "3"); // Prevent OptiFine (and other error-reporting stuff in Minecraft) from balooning the log envMap.put("LIBGL_NOERROR", "1"); // On certain GLES drivers, overloading default functions shader hack fails, so disable it envMap.put("LIBGL_NOINTOVLHACK", "1"); // Fix white color on banner and sheep, since GL4ES 1.1.5 envMap.put("LIBGL_NORMALIZE", "1"); if(PREF_DUMP_SHADERS) envMap.put("LIBGL_VGPU_DUMP", "1"); if(PREF_ZINK_PREFER_SYSTEM_DRIVER) envMap.put("POJAV_ZINK_PREFER_SYSTEM_DRIVER", "1"); if(PREF_VSYNC_IN_ZINK) envMap.put("POJAV_VSYNC_IN_ZINK", "1"); if(Tools.deviceHasHangingLinker()) envMap.put("POJAV_EMUI_ITERATOR_MITIGATE", "1"); // The OPEN GL version is changed according envMap.put("LIBGL_ES", (String) ExtraCore.getValue(ExtraConstants.OPEN_GL_VERSION)); envMap.put("FORCE_VSYNC", String.valueOf(LauncherPreferences.PREF_FORCE_VSYNC)); envMap.put("MESA_GLSL_CACHE_DIR", Tools.DIR_CACHE.getAbsolutePath()); envMap.put("force_glsl_extensions_warn", "true"); envMap.put("allow_higher_compat_version", "true"); envMap.put("allow_glsl_extension_directive_midshader", "true"); envMap.put("MESA_LOADER_DRIVER_OVERRIDE", "zink"); envMap.put("VTEST_SOCKET_NAME", new File(Tools.DIR_CACHE, ".virgl_test").getAbsolutePath()); envMap.put("LD_LIBRARY_PATH", LD_LIBRARY_PATH); envMap.put("PATH", jreHome + "/bin:" + Os.getenv("PATH")); if(FFmpegPlugin.isAvailable) { envMap.put("PATH", FFmpegPlugin.libraryPath+":"+envMap.get("PATH")); } if(LOCAL_RENDERER != null) { envMap.put("POJAV_RENDERER", LOCAL_RENDERER); if(LOCAL_RENDERER.equals("opengles3_desktopgl_angle_vulkan")) { envMap.put("LIBGL_ES", "3"); envMap.put("POJAVEXEC_EGL","libEGL_angle.so"); // Use ANGLE EGL } } if(LauncherPreferences.PREF_BIG_CORE_AFFINITY) envMap.put("POJAV_BIG_CORE_AFFINITY", "1"); envMap.put("AWTSTUB_WIDTH", Integer.toString(CallbackBridge.windowWidth > 0 ? CallbackBridge.windowWidth : CallbackBridge.physicalWidth)); envMap.put("AWTSTUB_HEIGHT", Integer.toString(CallbackBridge.windowHeight > 0 ? CallbackBridge.windowHeight : CallbackBridge.physicalHeight)); File customEnvFile = new File(Tools.DIR_GAME_HOME, "custom_env.txt"); if (customEnvFile.exists() && customEnvFile.isFile()) { BufferedReader reader = new BufferedReader(new FileReader(customEnvFile)); String line; while ((line = reader.readLine()) != null) { // Not use split() as only split first one int index = line.indexOf("="); envMap.put(line.substring(0, index), line.substring(index + 1)); } reader.close(); } if(!envMap.containsKey("LIBGL_ES") && LOCAL_RENDERER != null) { int glesMajor = getDetectedVersion(); Log.i("glesDetect","GLES version detected: "+glesMajor); if (glesMajor < 3) { //fallback to 2 since it's the minimum for the entire app envMap.put("LIBGL_ES","2"); } else if (LOCAL_RENDERER.startsWith("opengles")) { envMap.put("LIBGL_ES", LOCAL_RENDERER.replace("opengles", "").replace("_5", "")); } else { // TODO if can: other backends such as Vulkan. // Sure, they should provide GLES 3 support. envMap.put("LIBGL_ES", "3"); } } for (Map.Entry<String, String> env : envMap.entrySet()) { Logger.appendToLog("Added custom env: " + env.getKey() + "=" + env.getValue()); try { Os.setenv(env.getKey(), env.getValue(), true); }catch (NullPointerException exception){ Log.e("JREUtils", exception.toString()); } } File serverFile = new File(jreHome + "/" + Tools.DIRNAME_HOME_JRE + "/server/libjvm.so"); jvmLibraryPath = jreHome + "/" + Tools.DIRNAME_HOME_JRE + "/" + (serverFile.exists() ? "server" : "client"); Log.d("DynamicLoader","Base LD_LIBRARY_PATH: "+LD_LIBRARY_PATH); Log.d("DynamicLoader","Internal LD_LIBRARY_PATH: "+jvmLibraryPath+":"+LD_LIBRARY_PATH); setLdLibraryPath(jvmLibraryPath+":"+LD_LIBRARY_PATH); // return ldLibraryPath; } public static void launchJavaVM(final AppCompatActivity activity, final Runtime runtime, File gameDirectory, final List<String> JVMArgs, final String userArgsString) throws Throwable { String runtimeHome = MultiRTUtils.getRuntimeHome(runtime.name).getAbsolutePath(); JREUtils.relocateLibPath(runtime, runtimeHome); setJavaEnvironment(activity, runtimeHome); final String graphicsLib = loadGraphicsLibrary(); List<String> userArgs = getJavaArgs(activity, runtimeHome, userArgsString); //Remove arguments that can interfere with the good working of the launcher purgeArg(userArgs,"-Xms"); purgeArg(userArgs,"-Xmx"); purgeArg(userArgs,"-d32"); purgeArg(userArgs,"-d64"); purgeArg(userArgs, "-Xint"); purgeArg(userArgs, "-XX:+UseTransparentHugePages"); purgeArg(userArgs, "-XX:+UseLargePagesInMetaspace"); purgeArg(userArgs, "-XX:+UseLargePages"); purgeArg(userArgs, "-Dorg.lwjgl.opengl.libname"); //Add automatically generated args userArgs.add("-Xms" + LauncherPreferences.PREF_RAM_ALLOCATION + "M"); userArgs.add("-Xmx" + LauncherPreferences.PREF_RAM_ALLOCATION + "M"); if(LOCAL_RENDERER != null) userArgs.add("-Dorg.lwjgl.opengl.libname=" + graphicsLib); userArgs.addAll(JVMArgs); activity.runOnUiThread(() -> Toast.makeText(activity, activity.getString(R.string.autoram_info_msg,LauncherPreferences.PREF_RAM_ALLOCATION), Toast.LENGTH_SHORT).show()); System.out.println(JVMArgs); initJavaRuntime(runtimeHome); setupExitTrap(activity.getApplication()); chdir(gameDirectory == null ? Tools.DIR_GAME_NEW : gameDirectory.getAbsolutePath()); userArgs.add(0,"java"); //argv[0] is the program name according to C standard. final int exitCode = VMLauncher.launchJVM(userArgs.toArray(new String[0])); Logger.appendToLog("Java Exit code: " + exitCode); if (exitCode != 0) { LifecycleAwareAlertDialog.DialogCreator dialogCreator = (dialog, builder)-> builder.setMessage(activity.getString(R.string.mcn_exit_title, exitCode)) .setPositiveButton(R.string.main_share_logs, (dialogInterface, which)-> shareLog(activity)); LifecycleAwareAlertDialog.haltOnDialog(activity.getLifecycle(), activity, dialogCreator); } MainActivity.fullyExit(); } /** * Gives an argument list filled with both the user args * and the auto-generated ones (eg. the window resolution). * @param ctx The application context * @return A list filled with args. */ public static List<String> getJavaArgs(Context ctx, String runtimeHome, String userArgumentsString) { List<String> userArguments = parseJavaArguments(userArgumentsString); String resolvFile; resolvFile = new File(Tools.DIR_DATA,"resolv.conf").getAbsolutePath(); ArrayList<String> overridableArguments = new ArrayList<>(Arrays.asList( "-Djava.home=" + runtimeHome, "-Djava.io.tmpdir=" + Tools.DIR_CACHE.getAbsolutePath(), "-Djna.boot.library.path=" + NATIVE_LIB_DIR, "-Duser.home=" + Tools.DIR_GAME_HOME, "-Duser.language=" + System.getProperty("user.language"), "-Dos.name=Linux", "-Dos.version=Android-" + Build.VERSION.RELEASE, "-Dpojav.path.minecraft=" + Tools.DIR_GAME_NEW, "-Dpojav.path.private.account=" + Tools.DIR_ACCOUNT_NEW, "-Duser.timezone=" + TimeZone.getDefault().getID(), "-Dorg.lwjgl.vulkan.libname=libvulkan.so", //LWJGL 3 DEBUG FLAGS //"-Dorg.lwjgl.util.Debug=true", //"-Dorg.lwjgl.util.DebugFunctions=true", //"-Dorg.lwjgl.util.DebugLoader=true", // GLFW Stub width height "-Dglfwstub.windowWidth=" + Tools.getDisplayFriendlyRes(currentDisplayMetrics.widthPixels, LauncherPreferences.PREF_SCALE_FACTOR/100F), "-Dglfwstub.windowHeight=" + Tools.getDisplayFriendlyRes(currentDisplayMetrics.heightPixels, LauncherPreferences.PREF_SCALE_FACTOR/100F), "-Dglfwstub.initEgl=false", "-Dext.net.resolvPath=" +resolvFile, "-Dlog4j2.formatMsgNoLookups=true", //Log4j RCE mitigation "-Dnet.minecraft.clientmodname=" + Tools.APP_NAME, "-Dfml.earlyprogresswindow=false", //Forge 1.14+ workaround "-Dloader.disable_forked_guis=true" )); if(LauncherPreferences.PREF_ARC_CAPES) { overridableArguments.add("-javaagent:"+new File(Tools.DIR_DATA,"arc_dns_injector/arc_dns_injector.jar").getAbsolutePath()+"=23.95.137.176"); } List<String> additionalArguments = new ArrayList<>(); for(String arg : overridableArguments) { String strippedArg = arg.substring(0,arg.indexOf('=')); boolean add = true; for(String uarg : userArguments) { if(uarg.startsWith(strippedArg)) { add = false; break; } } if(add) additionalArguments.add(arg); else Log.i("ArgProcessor","Arg skipped: "+arg); } //Add all the arguments userArguments.addAll(additionalArguments); return userArguments; } /** * Parse and separate java arguments in a user friendly fashion * It supports multi line and absence of spaces between arguments * The function also supports auto-removal of improper arguments, although it may miss some. * * @param args The un-parsed argument list. * @return Parsed args as an ArrayList */ public static ArrayList<String> parseJavaArguments(String args){ ArrayList<String> parsedArguments = new ArrayList<>(0); args = args.trim().replace(" ", ""); //For each prefixes, we separate args. String[] separators = new String[]{"-XX:-","-XX:+", "-XX:","--", "-D", "-X", "-javaagent:", "-verbose"}; for(String prefix : separators){ while (true){ int start = args.indexOf(prefix); if(start == -1) break; //Get the end of the current argument by checking the nearest separator int end = -1; for(String separator: separators){ int tempEnd = args.indexOf(separator, start + prefix.length()); if(tempEnd == -1) continue; if(end == -1){ end = tempEnd; continue; } end = Math.min(end, tempEnd); } //Fallback if(end == -1) end = args.length(); //Extract it String parsedSubString = args.substring(start, end); args = args.replace(parsedSubString, ""); //Check if two args aren't bundled together by mistake if(parsedSubString.indexOf('=') == parsedSubString.lastIndexOf('=')) { int arraySize = parsedArguments.size(); if(arraySize > 0){ String lastString = parsedArguments.get(arraySize - 1); // Looking for list elements if(lastString.charAt(lastString.length() - 1) == ',' || parsedSubString.contains(",")){ parsedArguments.set(arraySize - 1, lastString + parsedSubString); continue; } } parsedArguments.add(parsedSubString); } else Log.w("JAVA ARGS PARSER", "Removed improper arguments: " + parsedSubString); } } return parsedArguments; } /** * Open the render library in accordance to the settings. * It will fallback if it fails to load the library. * @return The name of the loaded library */ public static String loadGraphicsLibrary(){ if(LOCAL_RENDERER == null) return null; String renderLibrary; switch (LOCAL_RENDERER){ case "opengles2": case "opengles2_5": case "opengles3": renderLibrary = "libgl4es_114.so"; break; case "vulkan_zink": renderLibrary = "libOSMesa.so"; break; case "opengles3_desktopgl_angle_vulkan" : renderLibrary = "libtinywrapper.so"; break; default: Log.w("RENDER_LIBRARY", "No renderer selected, defaulting to opengles2"); renderLibrary = "libgl4es_114.so"; break; } if (!dlopen(renderLibrary) && !dlopen(findInLdLibPath(renderLibrary))) { Log.e("RENDER_LIBRARY","Failed to load renderer " + renderLibrary + ". Falling back to GL4ES 1.1.4"); LOCAL_RENDERER = "opengles2"; renderLibrary = "libgl4es_114.so"; dlopen(NATIVE_LIB_DIR + "/libgl4es_114.so"); } return renderLibrary; } /** * Remove the argument from the list, if it exists * If the argument exists multiple times, they will all be removed. * @param argList The argument list to purge * @param argStart The argument to purge from the list. */ private static void purgeArg(List<String> argList, String argStart) { Iterator<String> args = argList.iterator(); while(args.hasNext()) { String arg = args.next(); if(arg.startsWith(argStart)) args.remove(); } } private static final int EGL_OPENGL_ES_BIT = 0x0001; private static final int EGL_OPENGL_ES2_BIT = 0x0004; private static final int EGL_OPENGL_ES3_BIT_KHR = 0x0040; @SuppressWarnings("SameParameterValue") private static boolean hasExtension(String extensions, String name) { int start = extensions.indexOf(name); while (start >= 0) { // check that we didn't find a prefix of a longer extension name int end = start + name.length(); if (end == extensions.length() || extensions.charAt(end) == ' ') { return true; } start = extensions.indexOf(name, end); } return false; } public static int getDetectedVersion() { /* * Get all the device configurations and check the EGL_RENDERABLE_TYPE attribute * to determine the highest ES version supported by any config. The * EGL_KHR_create_context extension is required to check for ES3 support; if the * extension is not present this test will fail to detect ES3 support. This * effectively makes the extension mandatory for ES3-capable devices. */ EGL10 egl = (EGL10) EGLContext.getEGL(); EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] numConfigs = new int[1]; if (egl.eglInitialize(display, null)) { try { boolean checkES3 = hasExtension(egl.eglQueryString(display, EGL10.EGL_EXTENSIONS), "EGL_KHR_create_context"); if (egl.eglGetConfigs(display, null, 0, numConfigs)) { EGLConfig[] configs = new EGLConfig[numConfigs[0]]; if (egl.eglGetConfigs(display, configs, numConfigs[0], numConfigs)) { int highestEsVersion = 0; int[] value = new int[1]; for (int i = 0; i < numConfigs[0]; i++) { if (egl.eglGetConfigAttrib(display, configs[i], EGL10.EGL_RENDERABLE_TYPE, value)) { if (checkES3 && ((value[0] & EGL_OPENGL_ES3_BIT_KHR) == EGL_OPENGL_ES3_BIT_KHR)) { if (highestEsVersion < 3) highestEsVersion = 3; } else if ((value[0] & EGL_OPENGL_ES2_BIT) == EGL_OPENGL_ES2_BIT) { if (highestEsVersion < 2) highestEsVersion = 2; } else if ((value[0] & EGL_OPENGL_ES_BIT) == EGL_OPENGL_ES_BIT) { if (highestEsVersion < 1) highestEsVersion = 1; } } else { Log.w("glesDetect", "Getting config attribute with " + "EGL10#eglGetConfigAttrib failed " + "(" + i + "/" + numConfigs[0] + "): " + egl.eglGetError()); } } return highestEsVersion; } else { Log.e("glesDetect", "Getting configs with EGL10#eglGetConfigs failed: " + egl.eglGetError()); return -1; } } else { Log.e("glesDetect", "Getting number of configs with EGL10#eglGetConfigs failed: " + egl.eglGetError()); return -2; } } finally { egl.eglTerminate(display); } } else { Log.e("glesDetect", "Couldn't initialize EGL."); return -3; } } public static native int chdir(String path); public static native boolean dlopen(String libPath); public static native void setLdLibraryPath(String ldLibraryPath); public static native void setupBridgeWindow(Object surface); public static native void releaseBridgeWindow(); public static native void setupExitTrap(Context context); // Obtain AWT screen pixels to render on Android SurfaceView public static native int[] renderAWTScreenFrame(/* Object canvas, int width, int height */); static { System.loadLibrary("pojavexec"); System.loadLibrary("pojavexec_awt"); dlopen("libxhook.so"); System.loadLibrary("istdio"); } }
26,269
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DownloadUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/DownloadUtils.java
package net.kdt.pojavlaunch.utils; import android.util.Log; import androidx.annotation.Nullable; import java.io.*; import java.net.*; import java.nio.charset.*; import java.util.concurrent.Callable; import net.kdt.pojavlaunch.*; import org.apache.commons.io.*; @SuppressWarnings("IOStreamConstructor") public class DownloadUtils { public static final String USER_AGENT = Tools.APP_NAME; public static void download(String url, OutputStream os) throws IOException { download(new URL(url), os); } public static void download(URL url, OutputStream os) throws IOException { InputStream is = null; try { // System.out.println("Connecting: " + url.toString()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT); conn.setConnectTimeout(10000); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Server returned HTTP " + conn.getResponseCode() + ": " + conn.getResponseMessage()); } is = conn.getInputStream(); IOUtils.copy(is, os); } catch (IOException e) { throw new IOException("Unable to download from " + url, e); } finally { if (is != null) { try { is.close(); } catch (Exception e) { e.printStackTrace(); } } } } public static String downloadString(String url) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); download(url, bos); bos.close(); return new String(bos.toByteArray(), StandardCharsets.UTF_8); } public static void downloadFile(String url, File out) throws IOException { FileUtils.ensureParentDirectory(out); try (FileOutputStream fileOutputStream = new FileOutputStream(out)) { download(url, fileOutputStream); } } public static void downloadFileMonitored(String urlInput, File outputFile, @Nullable byte[] buffer, Tools.DownloaderFeedback monitor) throws IOException { FileUtils.ensureParentDirectory(outputFile); HttpURLConnection conn = (HttpURLConnection) new URL(urlInput).openConnection(); InputStream readStr = conn.getInputStream(); try (FileOutputStream fos = new FileOutputStream(outputFile)) { int current; int overall = 0; int length = conn.getContentLength(); if (buffer == null) buffer = new byte[65535]; while ((current = readStr.read(buffer)) != -1) { overall += current; fos.write(buffer, 0, current); monitor.updateProgress(overall, length); } conn.disconnect(); } } public static <T> T downloadStringCached(String url, String cacheName, ParseCallback<T> parseCallback) throws IOException, ParseException{ File cacheDestination = new File(Tools.DIR_CACHE, "string_cache/"+cacheName); if(cacheDestination.isFile() && cacheDestination.canRead() && System.currentTimeMillis() < (cacheDestination.lastModified() + 86400000)) { try { String cachedString = Tools.read(new FileInputStream(cacheDestination)); return parseCallback.process(cachedString); }catch(IOException e) { Log.i("DownloadUtils", "Failed to read the cached file", e); }catch (ParseException e) { Log.i("DownloadUtils", "Failed to parse the cached file", e); } } String urlContent = DownloadUtils.downloadString(url); // if we download the file and fail parsing it, we will yeet outta there // and not cache the unparseable sting. We will return this after trying to save the downloaded // string into cache T parseResult = parseCallback.process(urlContent); boolean tryWriteCache; if(cacheDestination.exists()) { tryWriteCache = cacheDestination.canWrite(); } else { tryWriteCache = FileUtils.ensureParentDirectorySilently(cacheDestination); } if(tryWriteCache) try { Tools.write(cacheDestination.getAbsolutePath(), urlContent); }catch(IOException e) { Log.i("DownloadUtils", "Failed to cache the string", e); } return parseResult; } private static <T> T downloadFile(Callable<T> downloadFunction) throws IOException{ try { return downloadFunction.call(); } catch (IOException e){ throw e; } catch (Exception e) { throw new RuntimeException(e); } } private static boolean verifyFile(File file, String sha1) { return file.exists() && Tools.compareSHA1(file, sha1); } public static <T> T ensureSha1(File outputFile, @Nullable String sha1, Callable<T> downloadFunction) throws IOException { // Skip if needed if(sha1 == null) { // If the file exists and we don't know it's SHA1, don't try to redownload it. if(outputFile.exists()) return null; else return downloadFile(downloadFunction); } int attempts = 0; boolean fileOkay = verifyFile(outputFile, sha1); T result = null; while (attempts < 5 && !fileOkay){ attempts++; downloadFile(downloadFunction); fileOkay = verifyFile(outputFile, sha1); } if(!fileOkay) throw new SHA1VerificationException("SHA1 verifcation failed after 5 download attempts"); return result; } public interface ParseCallback<T> { T process(String input) throws ParseException; } public static class ParseException extends Exception { public ParseException(Exception e) { super(e); } } public static class SHA1VerificationException extends IOException { public SHA1VerificationException(String message) { super(message); } } }
6,365
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MathUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/MathUtils.java
package net.kdt.pojavlaunch.utils; public class MathUtils { //Ported from https://www.arduino.cc/reference/en/language/functions/math/map/ public static float map(float x, float in_min, float in_max, float out_min, float out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } /** Returns the distance between two points. */ public static float dist(float x1, float y1, float x2, float y2) { final float x = (x2 - x1); final float y = (y2 - y1); return (float) Math.hypot(x, y); } }
573
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
JSONUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/JSONUtils.java
package net.kdt.pojavlaunch.utils; import java.util.*; public class JSONUtils { public static String[] insertJSONValueList(String[] args, Map<String, String> keyValueMap) { for (int i = 0; i < args.length; i++) { args[i] = insertSingleJSONValue(args[i], keyValueMap); } return args; } public static String insertSingleJSONValue(String value, Map<String, String> keyValueMap) { String valueInserted = value; for (Map.Entry<String, String> keyValue : keyValueMap.entrySet()) { valueInserted = valueInserted.replace("${" + keyValue.getKey() + "}", keyValue.getValue() == null ? "" : keyValue.getValue()); } return valueInserted; } }
733
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
DateUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/DateUtils.java
package net.kdt.pojavlaunch.utils; import androidx.annotation.NonNull; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.Tools; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; // Utils for date-based activation for certain launcher workarounds. public class DateUtils { /** * Parse the release date of a game version from the JMinecraftVersionList.Version time or releaseTime fields * @param releaseTime the time or releaseTime string from JMinecraftVersionList.Version * @return the date object * @throws ParseException if date parsing fails */ public static Date parseReleaseDate(String releaseTime) throws ParseException { if(releaseTime == null) return null; int tIndexOf = releaseTime.indexOf('T'); if(tIndexOf != -1) releaseTime = releaseTime.substring(0, tIndexOf); return new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(releaseTime); } /** * Checks if the Date object is before the date denoted by * year, month, dayOfMonth parameters * @param date the Date object that we compare against * @param year the year * @param month the month (zero-based) * @param dayOfMonth the day of the month * @return true if the Date is before year, month, dayOfMonth, false otherwise */ public static boolean dateBefore(@NonNull Date date, int year, int month, int dayOfMonth) { return date.before(new Date(new GregorianCalendar(year, month, dayOfMonth).getTimeInMillis())); } /** * Extracts the original release date of a game version, ignoring any mods (if present) * @param gameVersion the JMinecraftVersionList.Version object * @return the game's original release date */ public static Date getOriginalReleaseDate(JMinecraftVersionList.Version gameVersion) throws ParseException { if(Tools.isValidString(gameVersion.inheritsFrom)) { gameVersion = Tools.getVersionInfo(gameVersion.inheritsFrom, true); }else { // The launcher's inheritor mutilates the version object, causing it to have the original // version's ID but modded version's dates. Work around it by re-reading the version without // inheriting. gameVersion = Tools.getVersionInfo(gameVersion.id, true); } return parseReleaseDate(gameVersion.releaseTime); } }
2,517
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MatrixUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/MatrixUtils.java
package net.kdt.pojavlaunch.utils; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; @SuppressWarnings("unused") public class MatrixUtils { /** * Transform the coordinates of the RectF using the supplied Matrix, and write the result back into * the RectF * @param inOutRect the RectF for this operation * @param transformMatrix the Matrix for transforming the Rect. */ public static void transformRect(Rect inOutRect, Matrix transformMatrix) { transformRect(inOutRect, inOutRect, transformMatrix); } /** * Transform the coordinates of the RectF using the supplied Matrix, and write the result back into * the RectF * @param inOutRect the RectF for this operation * @param transformMatrix the Matrix for transforming the Rect. */ public static void transformRect(RectF inOutRect, Matrix transformMatrix) { transformRect(inOutRect, inOutRect, transformMatrix); } /** * Transform the coordinates of the input RectF using the supplied Matrix, and write the result * into the output Rect * @param inRect the input RectF for this operation * @param outRect the output Rect for this operation * @param transformMatrix the Matrix for transforming the Rect. */ public static void transformRect(RectF inRect, Rect outRect, Matrix transformMatrix) { float[] inOutDecodeRect = createInOutDecodeRect(transformMatrix); if(inOutDecodeRect == null) return; writeInputRect(inOutDecodeRect, inRect); transformPoints(inOutDecodeRect, transformMatrix); readOutputRect(inOutDecodeRect, outRect); } /** * Transform the coordinates of the input Rect using the supplied Matrix, and write the result * into the output RectF * @param inRect the input Rect for this operation * @param outRect the output RectF for this operation * @param transformMatrix the Matrix for transforming the Rect. */ public static void transformRect(Rect inRect, RectF outRect, Matrix transformMatrix) { float[] inOutDecodeRect = createInOutDecodeRect(transformMatrix); if(inOutDecodeRect == null) return; writeInputRect(inOutDecodeRect, inRect); transformPoints(inOutDecodeRect, transformMatrix); readOutputRect(inOutDecodeRect, outRect); } /** * Transform the coordinates of the input Rect using the supplied Matrix, and write the result * into the output Rect * @param inRect the input Rect for this operation * @param outRect the output Rect for this operation * @param transformMatrix the Matrix for transforming the Rect. */ public static void transformRect(Rect inRect, Rect outRect, Matrix transformMatrix) { float[] inOutDecodeRect = createInOutDecodeRect(transformMatrix); if(inOutDecodeRect == null) return; writeInputRect(inOutDecodeRect, inRect); transformPoints(inOutDecodeRect, transformMatrix); readOutputRect(inOutDecodeRect, outRect); } /** * Transform the coordinates of the input RectF using the supplied Matrix, and write the result * into the output RectF * @param inRect the input RectF for this operation * @param outRect the output RectF for this operation * @param transformMatrix the Matrix for transforming the Rect. */ public static void transformRect(RectF inRect, RectF outRect, Matrix transformMatrix) { float[] inOutDecodeRect = createInOutDecodeRect(transformMatrix); if(inOutDecodeRect == null) return; writeInputRect(inOutDecodeRect, inRect); transformPoints(inOutDecodeRect, transformMatrix); readOutputRect(inOutDecodeRect, outRect); } // The group of functions below are used as building blocks of the transformRect() functions // in order to not repeat the same exact code a lot of times. private static void writeInputRect(float[] inOutDecodeRect, RectF inRect) { inOutDecodeRect[0] = inRect.left; inOutDecodeRect[1] = inRect.top; inOutDecodeRect[2] = inRect.right; inOutDecodeRect[3] = inRect.bottom; } private static void writeInputRect(float[] inOutDecodeRect, Rect inRect) { inOutDecodeRect[0] = inRect.left; inOutDecodeRect[1] = inRect.top; inOutDecodeRect[2] = inRect.right; inOutDecodeRect[3] = inRect.bottom; } private static void readOutputRect(float[] inOutDecodeRect, RectF outRect) { outRect.left = inOutDecodeRect[4]; outRect.top = inOutDecodeRect[5]; outRect.right = inOutDecodeRect[6]; outRect.bottom = inOutDecodeRect[7]; } private static void readOutputRect(float[] inOutDecodeRect, Rect outRect) { outRect.left = (int)inOutDecodeRect[4]; outRect.top = (int)inOutDecodeRect[5]; outRect.right = (int)inOutDecodeRect[6]; outRect.bottom = (int)inOutDecodeRect[7]; } private static float[] createInOutDecodeRect(Matrix transformMatrix) { if(transformMatrix.isIdentity()) return null; // We need an array of 8 floats because each point is two floats, // we need to transform two points and we need to have a separated input and output return new float[8]; } private static void transformPoints(float[] inOutDecodeRect, Matrix transformMatrix) { transformMatrix.mapPoints(inOutDecodeRect, 4, inOutDecodeRect, 0, 2); } /** * Invert the source matrix, and write the result into the destination matrix. * Android's integrated Matrix.invert() has some unexpected conditions when the matrix * can't be inverted, and in that case the method inverts the matrix by hand. * @param source Source matrix * @param destination The inverse of the source matrix * @throws IllegalArgumentException when the matrix is not invertible */ public static void inverse(Matrix source, Matrix destination) throws IllegalArgumentException { if(source.invert(destination)) return; float[] matrix = new float[9]; source.getValues(matrix); inverseMatrix(matrix); destination.setValues(matrix); } // This was made by ChatGPT and i have no clue what's happening here, but it works so eh private static void inverseMatrix(float[] matrix) { float determinant = matrix[0] * (matrix[4] * matrix[8] - matrix[5] * matrix[7]) - matrix[1] * (matrix[3] * matrix[8] - matrix[5] * matrix[6]) + matrix[2] * (matrix[3] * matrix[7] - matrix[4] * matrix[6]); if (determinant == 0) { throw new IllegalArgumentException("Matrix is not invertible"); } float invDet = 1 / determinant; float temp0 = (matrix[4] * matrix[8] - matrix[5] * matrix[7]); float temp1 = (matrix[2] * matrix[7] - matrix[1] * matrix[8]); float temp2 = (matrix[1] * matrix[5] - matrix[2] * matrix[4]); float temp3 = (matrix[5] * matrix[6] - matrix[3] * matrix[8]); float temp4 = (matrix[0] * matrix[8] - matrix[2] * matrix[6]); float temp5 = (matrix[2] * matrix[3] - matrix[0] * matrix[5]); float temp6 = (matrix[3] * matrix[7] - matrix[4] * matrix[6]); float temp7 = (matrix[1] * matrix[6] - matrix[0] * matrix[7]); float temp8 = (matrix[0] * matrix[4] - matrix[1] * matrix[3]); matrix[0] = temp0 * invDet; matrix[1] = temp1 * invDet; matrix[2] = temp2 * invDet; matrix[3] = temp3 * invDet; matrix[4] = temp4 * invDet; matrix[5] = temp5 * invDet; matrix[6] = temp6 * invDet; matrix[7] = temp7 * invDet; matrix[8] = temp8 * invDet; } }
7,784
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CropperUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/CropperUtils.java
package net.kdt.pojavlaunch.utils; import android.content.ContentResolver; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.net.Uri; import android.util.Log; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; import android.widget.ToggleButton; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.imgcropper.BitmapCropBehaviour; import net.kdt.pojavlaunch.imgcropper.CropperBehaviour; import net.kdt.pojavlaunch.imgcropper.CropperView; import net.kdt.pojavlaunch.imgcropper.RegionDecoderCropBehaviour; import java.io.IOException; import java.io.InputStream; public class CropperUtils { public static ActivityResultLauncher<?> registerCropper(Fragment fragment, final CropperListener cropperListener) { return fragment.registerForActivityResult(new ActivityResultContracts.OpenDocument(), (result)->{ Context context = fragment.getContext(); if(context == null) return; if (result == null) { Toast.makeText(context, R.string.cropper_select_cancelled, Toast.LENGTH_SHORT).show(); return; } openCropperDialog(context, result, cropperListener); }); } private static void openCropperDialog(Context context, Uri selectedUri, final CropperListener cropperListener) { ContentResolver contentResolver = context.getContentResolver(); AlertDialog dialog = new AlertDialog.Builder(context) .setTitle(R.string.cropper_title) .setView(R.layout.dialog_cropper) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(android.R.string.cancel, null) .show(); CropperView cropImageView = dialog.findViewById(R.id.crop_dialog_view); View finishProgressBar = dialog.findViewById(R.id.crop_dialog_progressbar); assert cropImageView != null; assert finishProgressBar != null; bindViews(dialog, cropImageView); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v->{ dialog.dismiss(); // I chose 70 dp here because it resolves to 192x192 on my device // (which has a typical screen density of 395 dpi) cropperListener.onCropped(cropImageView.crop((int) Tools.dpToPx(70))); }); PojavApplication.sExecutorService.execute(()->{ CropperBehaviour cropperBehaviour = null; try { cropperBehaviour = createBehaviour(cropImageView, contentResolver, selectedUri); }catch (Exception e) { cropperListener.onFailed(e); } CropperBehaviour finalBehaviour = cropperBehaviour; Tools.runOnUiThread(()->finishSetup(dialog, finishProgressBar, cropImageView, finalBehaviour)); }); } // Fixes the chin that the dialog has on my huawei fon private static void fixDialogHeight(AlertDialog dialog) { Window dialogWindow = dialog.getWindow(); if(dialogWindow != null) dialogWindow.setLayout( WindowManager.LayoutParams.MATCH_PARENT, // width WindowManager.LayoutParams.WRAP_CONTENT // height ); } private static void finishSetup(AlertDialog dialog, View progressBar, CropperView cropImageView, CropperBehaviour cropperBehaviour) { if(cropperBehaviour == null) { dialog.dismiss(); return; } progressBar.setVisibility(View.GONE); cropImageView.setCropperBehaviour(cropperBehaviour); cropperBehaviour.applyImage(); cropImageView.post(()->{ fixDialogHeight(dialog); cropImageView.requestLayout(); }); } private static CropperBehaviour createBehaviour(CropperView cropImageView, ContentResolver contentResolver, Uri selectedUri) throws Exception { try (InputStream inputStream = contentResolver.openInputStream(selectedUri)) { if(inputStream == null) return null; try { BitmapRegionDecoder regionDecoder = BitmapRegionDecoder.newInstance(inputStream, false); RegionDecoderCropBehaviour cropBehaviour = new RegionDecoderCropBehaviour(cropImageView); cropBehaviour.setRegionDecoder(regionDecoder); return cropBehaviour; }catch (IOException e) { // Catch IOE here to detect the case when BitmapRegionDecoder does not support this image format. // If it does not, we will just have to load the bitmap in full resolution using BitmapFactory. Log.w("CropperUtils", "Failed to load image into BitmapRegionDecoder", e); } } // We can safely re-open the stream here as ACTION_OPEN_DOCUMENT grants us long-term access // to the file that we have picked. try (InputStream inputStream = contentResolver.openInputStream(selectedUri)) { if(inputStream == null) return null; Bitmap originalBitmap = BitmapFactory.decodeStream(inputStream); BitmapCropBehaviour cropBehaviour = new BitmapCropBehaviour(cropImageView); cropBehaviour.setBitmap(originalBitmap); return cropBehaviour; } } private static void bindViews(AlertDialog alertDialog, CropperView imageCropperView) { ToggleButton horizontalLock = alertDialog.findViewById(R.id.crop_dialog_hlock); ToggleButton verticalLock = alertDialog.findViewById(R.id.crop_dialog_vlock); View reset = alertDialog.findViewById(R.id.crop_dialog_reset); assert horizontalLock != null; assert verticalLock != null; assert reset != null; horizontalLock.setOnClickListener(v-> imageCropperView.horizontalLock = horizontalLock.isChecked() ); verticalLock.setOnClickListener(v-> imageCropperView.verticalLock = verticalLock.isChecked() ); reset.setOnClickListener(v-> imageCropperView.resetTransforms() ); } @SuppressWarnings("unchecked") public static void startCropper(ActivityResultLauncher<?> resultLauncher) { ActivityResultLauncher<String[]> realResultLauncher = (ActivityResultLauncher<String[]>) resultLauncher; realResultLauncher.launch(new String[]{"image/*"}); } public interface CropperListener { void onCropped(Bitmap contentBitmap); void onFailed(Exception exception); } }
7,150
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ZipUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/ZipUtils.java
package net.kdt.pojavlaunch.utils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class ZipUtils { /** * Gets an InputStream for a given ZIP entry, throwing an IOException if the ZIP entry does not * exist. * @param zipFile The ZipFile to get the entry from * @param entryPath The full path inside of the ZipFile * @return The InputStream provided by the ZipFile * @throws IOException if the entry was not found */ public static InputStream getEntryStream(ZipFile zipFile, String entryPath) throws IOException{ ZipEntry entry = zipFile.getEntry(entryPath); if(entry == null) throw new IOException("No entry in ZIP file: "+entryPath); return zipFile.getInputStream(entry); } /** * Extracts all files in a ZipFile inside of a given directory to a given destination directory * How to specify dirName: * If you want to extract all files in the ZipFile, specify "" * If you want to extract a single directory, specify its full path followed by a trailing / * @param zipFile The ZipFile to extract files from * @param dirName The directory to extract the files from * @param destination The destination directory to extract the files into * @throws IOException if it was not possible to create a directory or file extraction failed */ public static void zipExtract(ZipFile zipFile, String dirName, File destination) throws IOException { Enumeration<? extends ZipEntry> zipEntries = zipFile.entries(); int dirNameLen = dirName.length(); while(zipEntries.hasMoreElements()) { ZipEntry zipEntry = zipEntries.nextElement(); String entryName = zipEntry.getName(); if(!entryName.startsWith(dirName) || zipEntry.isDirectory()) continue; File zipDestination = new File(destination, entryName.substring(dirNameLen)); FileUtils.ensureParentDirectory(zipDestination); try (InputStream inputStream = zipFile.getInputStream(zipEntry); OutputStream outputStream = new FileOutputStream(zipDestination)) { IOUtils.copy(inputStream, outputStream); } } } }
2,444
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FileUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/FileUtils.java
package net.kdt.pojavlaunch.utils; import java.io.File; import java.io.IOException; public class FileUtils { /** * Check if a file denoted by a String path exists. * @param filePath the path to check * @return whether it exists (same as File.exists() */ public static boolean exists(String filePath){ return new File(filePath).exists(); } /** * Get the file name from a path/URL string. * @param pathOrUrl the path or the URL of the file * @return the file's name */ public static String getFileName(String pathOrUrl) { int lastSlashIndex = pathOrUrl.lastIndexOf('/'); if(lastSlashIndex == -1) return null; return pathOrUrl.substring(lastSlashIndex); } /** * Ensure that a directory exists, is a directory and is writable. * @param targetFile the directory to check * @return if the check has succeeded */ public static boolean ensureDirectorySilently(File targetFile) { if(targetFile.isFile()) return false; if(targetFile.exists()) return targetFile.canWrite(); else return targetFile.mkdirs(); } /** * Ensure that the parent directory of a file exists and is writable * @param targetFile the File whose parent should be checked * @return if the check as succeeded */ public static boolean ensureParentDirectorySilently(File targetFile) { File parentFile = targetFile.getParentFile(); if(parentFile == null) return false; return ensureDirectorySilently(parentFile); } /** * Same as ensureDirectorySilently(), but throws an IOException telling why the check failed. * @param targetFile the directory to check * @throws IOException when the checks fail */ public static void ensureDirectory(File targetFile) throws IOException{ if(targetFile.isFile()) throw new IOException("Target directory is a file"); if(targetFile.exists()) { if(!targetFile.canWrite()) throw new IOException("Target directory is not writable"); }else if(!targetFile.mkdirs()) throw new IOException("Unable to create target directory"); } /** * Same as ensureParentDirectorySilently(), but throws an IOException telling why the check failed. * @param targetFile the File whose parent should be checked * @throws IOException when the checks fail */ public static void ensureParentDirectory(File targetFile) throws IOException{ File parentFile = targetFile.getParentFile(); if(parentFile == null) throw new IOException("targetFile does not have a parent"); ensureDirectory(parentFile); } }
2,697
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LocaleUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/LocaleUtils.java
package net.kdt.pojavlaunch.utils; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF; import android.content.*; import android.content.res.*; import android.os.Build; import android.os.LocaleList; import androidx.preference.*; import java.util.*; import net.kdt.pojavlaunch.prefs.*; public class LocaleUtils extends ContextWrapper { public LocaleUtils(Context base) { super(base); } public static ContextWrapper setLocale(Context context) { if (DEFAULT_PREF == null) { DEFAULT_PREF = PreferenceManager.getDefaultSharedPreferences(context); LauncherPreferences.loadPreferences(context); } if(DEFAULT_PREF.getBoolean("force_english", false)){ Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); configuration.setLocale(Locale.ENGLISH); Locale.setDefault(Locale.ENGLISH); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){ LocaleList localeList = new LocaleList(Locale.ENGLISH); LocaleList.setDefault(localeList); configuration.setLocales(localeList); } resources.updateConfiguration(configuration, resources.getDisplayMetrics()); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1){ context = context.createConfigurationContext(configuration); } } return new LocaleUtils(context); } }
1,535
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OldVersionsUtils.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/OldVersionsUtils.java
package net.kdt.pojavlaunch.utils; import android.util.Log; import net.kdt.pojavlaunch.JMinecraftVersionList; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import java.text.ParseException; import java.util.Date; /** Class here to help with various stuff to help run lower versions smoothly */ public class OldVersionsUtils { /** Lower minecraft versions fare better with opengl 1 * @param version The version about to be launched */ public static void selectOpenGlVersion(JMinecraftVersionList.Version version){ // 1309989600 is 2011-07-07 2011-07-07T22:00:00+00:00 String creationTime = version.time; if(!Tools.isValidString(creationTime)){ ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, "2"); return; } try { Date creationDate = DateUtils.parseReleaseDate(creationTime); if(creationDate == null) { Log.e("GL_SELECT", "Failed to parse version date"); ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, "2"); return; } String openGlVersion = DateUtils.dateBefore(creationDate, 2011, 6, 8) ? "1" : "2"; Log.i("GL_SELECT", openGlVersion); ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, openGlVersion); }catch (ParseException exception){ Log.e("GL_SELECT", exception.toString()); ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, "2"); } } }
1,581
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FilteredSubList.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/utils/FilteredSubList.java
package net.kdt.pojavlaunch.utils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Provide a "mostly immutable" view to a "mother" list, by reference. * The difference from List.sublist() is: * - the ability to apply a FILTER on listGeneration * - "immutability", you can't add elements to the list from here, but it is backed by the real list. * @param <E> */ public class FilteredSubList<E> extends AbstractList<E> implements List<E> { private final ArrayList<E> mArrayList; public FilteredSubList(E[] motherList, BasicPredicate<E> filter){ mArrayList = new ArrayList<>(); refresh(motherList, filter); } public void refresh(E[] motherArray, BasicPredicate<E> filter){ if(!mArrayList.isEmpty()) mArrayList.clear(); for(E item : motherArray){ if(filter.test(item)){ mArrayList.add(item); } } // Should we trim ? mArrayList.trimToSize(); } @Override public int size() { return mArrayList.size(); } @NonNull @Override public Iterator<E> iterator() { return mArrayList.iterator(); } @Override public boolean remove(@Nullable Object o) { return mArrayList.remove(o); } @Override public boolean removeAll(@NonNull Collection<?> c) { return mArrayList.removeAll(c); } @Override public boolean retainAll(@NonNull Collection<?> c) { return mArrayList.retainAll(c); } @Override public void clear() { mArrayList.clear(); } @Override public E get(int index) { return mArrayList.get(index); } @Override public E remove(int index) { return mArrayList.remove(index); } @NonNull @Override public ListIterator<E> listIterator() { return mArrayList.listIterator(); } @NonNull @Override public ListIterator<E> listIterator(int index) { return mArrayList.listIterator(index); } @NonNull @Override public List<E> subList(int fromIndex, int toIndex) { return mArrayList.subList(fromIndex, toIndex); } // Predicate is API 24+, so micro backport public interface BasicPredicate<E> { boolean test(E item); } }
2,487
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferences.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/LauncherPreferences.java
package net.kdt.pojavlaunch.prefs; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.P; import static net.kdt.pojavlaunch.Architecture.is32BitsDevice; import android.app.Activity; import android.content.*; import android.graphics.Rect; import android.os.Build; import android.util.Log; import net.kdt.pojavlaunch.*; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.utils.JREUtils; public class LauncherPreferences { public static final String PREF_KEY_CURRENT_PROFILE = "currentProfile"; public static final String PREF_KEY_SKIP_NOTIFICATION_CHECK = "skipNotificationPermissionCheck"; public static SharedPreferences DEFAULT_PREF; public static String PREF_RENDERER = "opengles2"; public static boolean PREF_VERTYPE_RELEASE = true; public static boolean PREF_VERTYPE_SNAPSHOT = false; public static boolean PREF_VERTYPE_OLDALPHA = false; public static boolean PREF_VERTYPE_OLDBETA = false; public static boolean PREF_HIDE_SIDEBAR = false; public static boolean PREF_IGNORE_NOTCH = false; public static int PREF_NOTCH_SIZE = 0; public static float PREF_BUTTONSIZE = 100f; public static float PREF_MOUSESCALE = 100f; public static int PREF_LONGPRESS_TRIGGER = 300; public static String PREF_DEFAULTCTRL_PATH = Tools.CTRLDEF_FILE; public static String PREF_CUSTOM_JAVA_ARGS; public static boolean PREF_FORCE_ENGLISH = false; public static final String PREF_VERSION_REPOS = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json"; public static boolean PREF_CHECK_LIBRARY_SHA = true; public static boolean PREF_DISABLE_GESTURES = false; public static boolean PREF_DISABLE_SWAP_HAND = false; public static float PREF_MOUSESPEED = 1f; public static int PREF_RAM_ALLOCATION; public static String PREF_DEFAULT_RUNTIME; public static boolean PREF_SUSTAINED_PERFORMANCE = false; public static boolean PREF_VIRTUAL_MOUSE_START = false; public static boolean PREF_ARC_CAPES = false; public static boolean PREF_USE_ALTERNATE_SURFACE = true; public static boolean PREF_JAVA_SANDBOX = true; public static int PREF_SCALE_FACTOR = 100; public static boolean PREF_ENABLE_GYRO = false; public static float PREF_GYRO_SENSITIVITY = 1f; public static int PREF_GYRO_SAMPLE_RATE = 16; public static boolean PREF_GYRO_SMOOTHING = true; public static boolean PREF_GYRO_INVERT_X = false; public static boolean PREF_GYRO_INVERT_Y = false; public static boolean PREF_FORCE_VSYNC = false; public static boolean PREF_BUTTON_ALL_CAPS = true; public static boolean PREF_DUMP_SHADERS = false; public static float PREF_DEADZONE_SCALE = 1f; public static boolean PREF_BIG_CORE_AFFINITY = false; public static boolean PREF_ZINK_PREFER_SYSTEM_DRIVER = false; public static boolean PREF_VERIFY_MANIFEST = true; public static String PREF_DOWNLOAD_SOURCE = "default"; public static boolean PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = false; public static boolean PREF_VSYNC_IN_ZINK = true; public static void loadPreferences(Context ctx) { //Required for the data folder. Tools.initContextConstants(ctx); PREF_RENDERER = DEFAULT_PREF.getString("renderer", "opengles2"); PREF_BUTTONSIZE = DEFAULT_PREF.getInt("buttonscale", 100); PREF_MOUSESCALE = DEFAULT_PREF.getInt("mousescale", 100); PREF_MOUSESPEED = ((float)DEFAULT_PREF.getInt("mousespeed",100))/100f; PREF_HIDE_SIDEBAR = DEFAULT_PREF.getBoolean("hideSidebar", false); PREF_IGNORE_NOTCH = DEFAULT_PREF.getBoolean("ignoreNotch", false); PREF_VERTYPE_RELEASE = DEFAULT_PREF.getBoolean("vertype_release", true); PREF_VERTYPE_SNAPSHOT = DEFAULT_PREF.getBoolean("vertype_snapshot", false); PREF_VERTYPE_OLDALPHA = DEFAULT_PREF.getBoolean("vertype_oldalpha", false); PREF_VERTYPE_OLDBETA = DEFAULT_PREF.getBoolean("vertype_oldbeta", false); PREF_LONGPRESS_TRIGGER = DEFAULT_PREF.getInt("timeLongPressTrigger", 300); PREF_DEFAULTCTRL_PATH = DEFAULT_PREF.getString("defaultCtrl", Tools.CTRLDEF_FILE); PREF_FORCE_ENGLISH = DEFAULT_PREF.getBoolean("force_english", false); PREF_CHECK_LIBRARY_SHA = DEFAULT_PREF.getBoolean("checkLibraries",true); PREF_DISABLE_GESTURES = DEFAULT_PREF.getBoolean("disableGestures",false); PREF_DISABLE_SWAP_HAND = DEFAULT_PREF.getBoolean("disableDoubleTap", false); PREF_RAM_ALLOCATION = DEFAULT_PREF.getInt("allocation", findBestRAMAllocation(ctx)); PREF_CUSTOM_JAVA_ARGS = DEFAULT_PREF.getString("javaArgs", ""); PREF_SUSTAINED_PERFORMANCE = DEFAULT_PREF.getBoolean("sustainedPerformance", false); PREF_VIRTUAL_MOUSE_START = DEFAULT_PREF.getBoolean("mouse_start", false); PREF_ARC_CAPES = DEFAULT_PREF.getBoolean("arc_capes",false); PREF_USE_ALTERNATE_SURFACE = DEFAULT_PREF.getBoolean("alternate_surface", false); PREF_JAVA_SANDBOX = DEFAULT_PREF.getBoolean("java_sandbox", true); PREF_SCALE_FACTOR = DEFAULT_PREF.getInt("resolutionRatio", 100); PREF_ENABLE_GYRO = DEFAULT_PREF.getBoolean("enableGyro", false); PREF_GYRO_SENSITIVITY = ((float)DEFAULT_PREF.getInt("gyroSensitivity", 100))/100f; PREF_GYRO_SAMPLE_RATE = DEFAULT_PREF.getInt("gyroSampleRate", 16); PREF_GYRO_SMOOTHING = DEFAULT_PREF.getBoolean("gyroSmoothing", true); PREF_GYRO_INVERT_X = DEFAULT_PREF.getBoolean("gyroInvertX", false); PREF_GYRO_INVERT_Y = DEFAULT_PREF.getBoolean("gyroInvertY", false); PREF_FORCE_VSYNC = DEFAULT_PREF.getBoolean("force_vsync", false); PREF_BUTTON_ALL_CAPS = DEFAULT_PREF.getBoolean("buttonAllCaps", true); PREF_DUMP_SHADERS = DEFAULT_PREF.getBoolean("dump_shaders", false); PREF_DEADZONE_SCALE = ((float) DEFAULT_PREF.getInt("gamepad_deadzone_scale", 100))/100f; PREF_BIG_CORE_AFFINITY = DEFAULT_PREF.getBoolean("bigCoreAffinity", false); PREF_ZINK_PREFER_SYSTEM_DRIVER = DEFAULT_PREF.getBoolean("zinkPreferSystemDriver", false); PREF_DOWNLOAD_SOURCE = DEFAULT_PREF.getString("downloadSource", "default"); PREF_VERIFY_MANIFEST = DEFAULT_PREF.getBoolean("verifyManifest", true); PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = DEFAULT_PREF.getBoolean(PREF_KEY_SKIP_NOTIFICATION_CHECK, false); PREF_VSYNC_IN_ZINK = DEFAULT_PREF.getBoolean("vsync_in_zink", true); String argLwjglLibname = "-Dorg.lwjgl.opengl.libname="; for (String arg : JREUtils.parseJavaArguments(PREF_CUSTOM_JAVA_ARGS)) { if (arg.startsWith(argLwjglLibname)) { // purge arg DEFAULT_PREF.edit().putString("javaArgs", PREF_CUSTOM_JAVA_ARGS.replace(arg, "")).apply(); } } if(DEFAULT_PREF.contains("defaultRuntime")) { PREF_DEFAULT_RUNTIME = DEFAULT_PREF.getString("defaultRuntime",""); }else{ if(MultiRTUtils.getRuntimes().size() < 1) { PREF_DEFAULT_RUNTIME = ""; return; } PREF_DEFAULT_RUNTIME = MultiRTUtils.getRuntimes().get(0).name; LauncherPreferences.DEFAULT_PREF.edit().putString("defaultRuntime",LauncherPreferences.PREF_DEFAULT_RUNTIME).apply(); } } /** * This functions aims at finding the best default RAM amount, * according to the RAM amount of the physical device. * Put not enough RAM ? Minecraft will lag and crash. * Put too much RAM ? * The GC will lag, android won't be able to breathe properly. * @param ctx Context needed to get the total memory of the device. * @return The best default value found. */ private static int findBestRAMAllocation(Context ctx){ int deviceRam = Tools.getTotalDeviceMemory(ctx); if (deviceRam < 1024) return 300; if (deviceRam < 1536) return 450; if (deviceRam < 2048) return 600; // Limit the max for 32 bits devices more harshly if (is32BitsDevice()) return 700; if (deviceRam < 3064) return 936; if (deviceRam < 4096) return 1148; if (deviceRam < 6144) return 1536; return 2048; //Default RAM allocation for 64 bits } /** Compute the notch size to avoid being out of bounds */ public static void computeNotchSize(Activity activity) { if (Build.VERSION.SDK_INT < P) return; try { if(SDK_INT >= Build.VERSION_CODES.S){ Rect notchRect = activity.getWindowManager().getCurrentWindowMetrics().getWindowInsets().getDisplayCutout().getBoundingRects().get(0); LauncherPreferences.PREF_NOTCH_SIZE = Math.min(notchRect.width(), notchRect.height()); Tools.updateWindowSize(activity); return; } Rect notchRect = activity.getWindow().getDecorView().getRootWindowInsets().getDisplayCutout().getBoundingRects().get(0); // Math min is to handle all rotations LauncherPreferences.PREF_NOTCH_SIZE = Math.min(notchRect.width(), notchRect.height()); }catch (Exception e){ Log.i("NOTCH DETECTION", "No notch detected, or the device if in split screen mode"); LauncherPreferences.PREF_NOTCH_SIZE = -1; } Tools.updateWindowSize(activity); } }
9,355
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
BackButtonPreference.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/BackButtonPreference.java
package net.kdt.pojavlaunch.prefs; import android.content.Context; import android.util.AttributeSet; import androidx.preference.Preference; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; public class BackButtonPreference extends Preference { public BackButtonPreference(Context context, AttributeSet attrs) { super(context, attrs); init(); } @SuppressWarnings("unused") public BackButtonPreference(Context context) { this(context, null); } private void init(){ if(getTitle() == null){ setTitle(R.string.preference_back_title); } if(getIcon() == null){ setIcon(R.drawable.ic_arrow_back_white); } } @Override protected void onClick() { // It is caught by an ExtraListener in the LauncherActivity ExtraCore.setValue(ExtraConstants.BACK_PREFERENCE, "true"); } }
974
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
GamepadRemapPreference.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/GamepadRemapPreference.java
package net.kdt.pojavlaunch.prefs; import android.content.Context; import android.util.AttributeSet; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.preference.Preference; import net.kdt.pojavlaunch.R; import fr.spse.gamepad_remapper.Remapper; public class GamepadRemapPreference extends Preference { public GamepadRemapPreference(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public GamepadRemapPreference(@NonNull Context context) { super(context); init(); } private void init(){ setOnPreferenceClickListener(preference -> { Remapper.wipePreferences(getContext()); Toast.makeText(getContext(), R.string.preference_controller_map_wiped, Toast.LENGTH_SHORT).show(); return true; }); } }
918
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
CustomSeekBarPreference.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/CustomSeekBarPreference.java
package net.kdt.pojavlaunch.prefs; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.preference.PreferenceViewHolder; import androidx.preference.SeekBarPreference; import net.kdt.pojavlaunch.R; public class CustomSeekBarPreference extends SeekBarPreference { /** The suffix displayed */ private String mSuffix = ""; /** Custom minimum value to provide the same behavior as the usual setMin */ private int mMin; /** The textview associated by default to the preference */ private TextView mTextView; @SuppressLint("PrivateResource") public CustomSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.SeekBarPreference, defStyleAttr, defStyleRes); mMin = a.getInt(R.styleable.SeekBarPreference_min, 0); a.recycle(); } public CustomSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) { this(context, attrs, defStyleAttr, 0); } public CustomSeekBarPreference(Context context, AttributeSet attrs) { this(context, attrs, R.attr.seekBarPreferenceStyle); } @SuppressWarnings("unused") public CustomSeekBarPreference(Context context) { this(context, null); } @Override public void setMin(int min) { //Note: since the max (setMax is a final function) is not taken into account properly, setting the min over the max may produce funky results super.setMin(min); if (min != mMin) mMin = min; } @Override public void onBindViewHolder(@NonNull PreferenceViewHolder view) { super.onBindViewHolder(view); TextView titleTextView = (TextView) view.findViewById(android.R.id.title); titleTextView.setTextColor(Color.WHITE); mTextView = (TextView) view.findViewById(R.id.seekbar_value); mTextView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START); SeekBar seekBar = (SeekBar) view.findViewById(R.id.seekbar); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progress += mMin; progress = progress / getSeekBarIncrement(); progress = progress * getSeekBarIncrement(); progress -= mMin; mTextView.setText(String.valueOf(progress + mMin)); updateTextViewWithSuffix(); } @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress = seekBar.getProgress() + mMin; progress /= getSeekBarIncrement(); progress *= getSeekBarIncrement(); progress -= mMin; setValue(progress + mMin); updateTextViewWithSuffix(); } }); updateTextViewWithSuffix(); } /** * Set a suffix to be appended on the TextView associated to the value * @param suffix The suffix to append as a String */ public void setSuffix(String suffix) { this.mSuffix = suffix; } /** * Convenience function to set both min and max at the same time. * @param min The minimum value * @param max The maximum value */ public void setRange(int min, int max){ setMin(min); setMax(max); } private void updateTextViewWithSuffix(){ if(!mTextView.getText().toString().endsWith(mSuffix)){ mTextView.setText(String.format("%s%s", mTextView.getText(), mSuffix)); } } }
4,103
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferenceControlFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/screens/LauncherPreferenceControlFragment.java
package net.kdt.pojavlaunch.prefs.screens; import android.content.Context; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Bundle; import androidx.preference.PreferenceCategory; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.prefs.CustomSeekBarPreference; import net.kdt.pojavlaunch.prefs.LauncherPreferences; public class LauncherPreferenceControlFragment extends LauncherPreferenceFragment { private boolean mGyroAvailable = false; @Override public void onCreatePreferences(Bundle b, String str) { // Get values int longPressTrigger = LauncherPreferences.PREF_LONGPRESS_TRIGGER; int prefButtonSize = (int) LauncherPreferences.PREF_BUTTONSIZE; int mouseScale = (int) LauncherPreferences.PREF_MOUSESCALE; int gyroSampleRate = LauncherPreferences.PREF_GYRO_SAMPLE_RATE; float mouseSpeed = LauncherPreferences.PREF_MOUSESPEED; float gyroSpeed = LauncherPreferences.PREF_GYRO_SENSITIVITY; float joystickDeadzone = LauncherPreferences.PREF_DEADZONE_SCALE; //Triggers a write for some reason which resets the value addPreferencesFromResource(R.xml.pref_control); CustomSeekBarPreference seek2 = requirePreference("timeLongPressTrigger", CustomSeekBarPreference.class); seek2.setRange(100, 1000); seek2.setValue(longPressTrigger); seek2.setSuffix(" ms"); CustomSeekBarPreference seek3 = requirePreference("buttonscale", CustomSeekBarPreference.class); seek3.setRange(80, 250); seek3.setValue(prefButtonSize); seek3.setSuffix(" %"); CustomSeekBarPreference seek4 = requirePreference("mousescale", CustomSeekBarPreference.class); seek4.setRange(25, 300); seek4.setValue(mouseScale); seek4.setSuffix(" %"); CustomSeekBarPreference seek6 = requirePreference("mousespeed", CustomSeekBarPreference.class); seek6.setRange(25, 300); seek6.setValue((int)(mouseSpeed *100f)); seek6.setSuffix(" %"); CustomSeekBarPreference deadzoneSeek = requirePreference("gamepad_deadzone_scale", CustomSeekBarPreference.class); deadzoneSeek.setRange(50, 200); deadzoneSeek.setValue((int) (joystickDeadzone * 100f)); deadzoneSeek.setSuffix(" %"); Context context = getContext(); if(context != null) { mGyroAvailable = ((SensorManager)context.getSystemService(Context.SENSOR_SERVICE)).getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null; } PreferenceCategory gyroCategory = requirePreference("gyroCategory", PreferenceCategory.class); gyroCategory.setVisible(mGyroAvailable); CustomSeekBarPreference gyroSensitivitySeek = requirePreference("gyroSensitivity", CustomSeekBarPreference.class); gyroSensitivitySeek.setRange(25, 300); gyroSensitivitySeek.setValue((int) (gyroSpeed*100f)); gyroSensitivitySeek.setSuffix(" %"); CustomSeekBarPreference gyroSampleRateSeek = requirePreference("gyroSampleRate", CustomSeekBarPreference.class); gyroSampleRateSeek.setRange(5, 50); gyroSampleRateSeek.setValue(gyroSampleRate); gyroSampleRateSeek.setSuffix(" ms"); computeVisibility(); } @Override public void onSharedPreferenceChanged(SharedPreferences p, String s) { super.onSharedPreferenceChanged(p, s); computeVisibility(); } private void computeVisibility(){ requirePreference("timeLongPressTrigger").setVisible(!LauncherPreferences.PREF_DISABLE_GESTURES); requirePreference("gyroSensitivity").setVisible(LauncherPreferences.PREF_ENABLE_GYRO); requirePreference("gyroSampleRate").setVisible(LauncherPreferences.PREF_ENABLE_GYRO); requirePreference("gyroInvertX").setVisible(LauncherPreferences.PREF_ENABLE_GYRO); requirePreference("gyroInvertY").setVisible(LauncherPreferences.PREF_ENABLE_GYRO); requirePreference("gyroSmoothing").setVisible(LauncherPreferences.PREF_ENABLE_GYRO); } }
4,246
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferenceFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/screens/LauncherPreferenceFragment.java
package net.kdt.pojavlaunch.prefs.screens; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.preference.Preference; import androidx.preference.PreferenceFragmentCompat; import net.kdt.pojavlaunch.LauncherActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.prefs.LauncherPreferences; /** * Preference for the main screen, any sub-screen should inherit this class for consistent behavior, * overriding only onCreatePreferences */ public class LauncherPreferenceFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { view.setBackgroundColor(Color.parseColor("#232323")); super.onViewCreated(view, savedInstanceState); } @Override public void onCreatePreferences(Bundle b, String str) { addPreferencesFromResource(R.xml.pref_main); setupNotificationRequestPreference(); } private void setupNotificationRequestPreference() { Preference mRequestNotificationPermissionPreference = requirePreference("notification_permission_request"); Activity activity = getActivity(); if(activity instanceof LauncherActivity) { LauncherActivity launcherActivity = (LauncherActivity)activity; mRequestNotificationPermissionPreference.setVisible(!launcherActivity.checkForNotificationPermission()); mRequestNotificationPermissionPreference.setOnPreferenceClickListener(preference -> { launcherActivity.askForNotificationPermission(()->mRequestNotificationPermissionPreference.setVisible(false)); return true; }); }else{ mRequestNotificationPermissionPreference.setVisible(false); } } @Override public void onResume() { super.onResume(); SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences(); if(sharedPreferences != null) sharedPreferences.registerOnSharedPreferenceChangeListener(this); } @Override public void onPause() { SharedPreferences sharedPreferences = getPreferenceManager().getSharedPreferences(); if(sharedPreferences != null) sharedPreferences.unregisterOnSharedPreferenceChangeListener(this); super.onPause(); } @Override public void onSharedPreferenceChanged(SharedPreferences p, String s) { LauncherPreferences.loadPreferences(getContext()); } protected Preference requirePreference(CharSequence key) { Preference preference = findPreference(key); if(preference != null) return preference; throw new IllegalStateException("Preference "+key+" is null"); } @SuppressWarnings("unchecked") protected <T extends Preference> T requirePreference(CharSequence key, Class<T> preferenceClass) { Preference preference = requirePreference(key); if(preferenceClass.isInstance(preference)) return (T)preference; throw new IllegalStateException("Preference "+key+" is not an instance of "+preferenceClass.getSimpleName()); } }
3,359
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferenceExperimentalFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/screens/LauncherPreferenceExperimentalFragment.java
package net.kdt.pojavlaunch.prefs.screens; import android.os.Bundle; import net.kdt.pojavlaunch.R; public class LauncherPreferenceExperimentalFragment extends LauncherPreferenceFragment { @Override public void onCreatePreferences(Bundle b, String str) { addPreferencesFromResource(R.xml.pref_experimental); } }
335
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferenceMiscellaneousFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/screens/LauncherPreferenceMiscellaneousFragment.java
package net.kdt.pojavlaunch.prefs.screens; import android.os.Bundle; import androidx.preference.Preference; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; public class LauncherPreferenceMiscellaneousFragment extends LauncherPreferenceFragment { @Override public void onCreatePreferences(Bundle b, String str) { addPreferencesFromResource(R.xml.pref_misc); Preference driverPreference = requirePreference("zinkPreferSystemDriver"); if(!Tools.checkVulkanSupport(driverPreference.getContext().getPackageManager())) { driverPreference.setVisible(false); } } }
633
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferenceJavaFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/screens/LauncherPreferenceJavaFragment.java
package net.kdt.pojavlaunch.prefs.screens; import static net.kdt.pojavlaunch.Architecture.is32BitsDevice; import static net.kdt.pojavlaunch.Tools.getTotalDeviceMemory; import android.os.Bundle; import android.widget.TextView; import androidx.activity.result.ActivityResultLauncher; import androidx.preference.EditTextPreference; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.contracts.OpenDocumentWithExtension; import net.kdt.pojavlaunch.multirt.MultiRTConfigDialog; import net.kdt.pojavlaunch.prefs.CustomSeekBarPreference; import net.kdt.pojavlaunch.prefs.LauncherPreferences; public class LauncherPreferenceJavaFragment extends LauncherPreferenceFragment { private MultiRTConfigDialog mDialogScreen; private final ActivityResultLauncher<Object> mVmInstallLauncher = registerForActivityResult(new OpenDocumentWithExtension("xz"), (data)->{ if(data != null) Tools.installRuntimeFromUri(getContext(), data); }); @Override public void onCreatePreferences(Bundle b, String str) { int ramAllocation = LauncherPreferences.PREF_RAM_ALLOCATION; // Triggers a write for some reason addPreferencesFromResource(R.xml.pref_java); CustomSeekBarPreference seek7 = requirePreference("allocation", CustomSeekBarPreference.class); int maxRAM; int deviceRam = getTotalDeviceMemory(seek7.getContext()); if(is32BitsDevice() || deviceRam < 2048) maxRAM = Math.min(1000, deviceRam); else maxRAM = deviceRam - (deviceRam < 3064 ? 800 : 1024); //To have a minimum for the device to breathe seek7.setMin(256); seek7.setMax(maxRAM); seek7.setValue(ramAllocation); seek7.setSuffix(" MB"); EditTextPreference editJVMArgs = findPreference("javaArgs"); if (editJVMArgs != null) { editJVMArgs.setOnBindEditTextListener(TextView::setSingleLine); } requirePreference("install_jre").setOnPreferenceClickListener(preference->{ openMultiRTDialog(); return true; }); } private void openMultiRTDialog() { if (mDialogScreen == null) { mDialogScreen = new MultiRTConfigDialog(); mDialogScreen.prepare(getContext(), mVmInstallLauncher); } mDialogScreen.show(); } }
2,389
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LauncherPreferenceVideoFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/prefs/screens/LauncherPreferenceVideoFragment.java
package net.kdt.pojavlaunch.prefs.screens; import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_NOTCH_SIZE; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import androidx.preference.ListPreference; import androidx.preference.SwitchPreference; import androidx.preference.SwitchPreferenceCompat; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.prefs.CustomSeekBarPreference; import net.kdt.pojavlaunch.prefs.LauncherPreferences; /** * Fragment for any settings video related */ public class LauncherPreferenceVideoFragment extends LauncherPreferenceFragment { @Override public void onCreatePreferences(Bundle b, String str) { addPreferencesFromResource(R.xml.pref_video); //Disable notch checking behavior on android 8.1 and below. requirePreference("ignoreNotch").setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && PREF_NOTCH_SIZE > 0); CustomSeekBarPreference seek5 = requirePreference("resolutionRatio", CustomSeekBarPreference.class); seek5.setMin(25); seek5.setSuffix(" %"); // #724 bug fix if (seek5.getValue() < 25) { seek5.setValue(100); } // Sustained performance is only available since Nougat SwitchPreference sustainedPerfSwitch = requirePreference("sustainedPerformance", SwitchPreference.class); sustainedPerfSwitch.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N); ListPreference rendererListPreference = requirePreference("renderer", ListPreference.class); Tools.RenderersList renderersList = Tools.getCompatibleRenderers(getContext()); rendererListPreference.setEntries(renderersList.rendererDisplayNames); rendererListPreference.setEntryValues(renderersList.rendererIds.toArray(new String[0])); computeVisibility(); } @Override public void onSharedPreferenceChanged(SharedPreferences p, String s) { super.onSharedPreferenceChanged(p, s); computeVisibility(); } private void computeVisibility(){ requirePreference("force_vsync", SwitchPreferenceCompat.class) .setVisible(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE); } }
2,343
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
QuiltInstallFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/QuiltInstallFragment.java
package net.kdt.pojavlaunch.fragments; import net.kdt.pojavlaunch.modloaders.FabriclikeUtils; import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy; public class QuiltInstallFragment extends FabriclikeInstallFragment { public static final String TAG = "QuiltInstallFragment"; private static ModloaderListenerProxy sTaskProxy; public QuiltInstallFragment() { super(FabriclikeUtils.QUILT_UTILS); } @Override protected ModloaderListenerProxy getListenerProxy() { return sTaskProxy; } @Override protected void setListenerProxy(ModloaderListenerProxy listenerProxy) { sTaskProxy = listenerProxy; } }
672
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FabriclikeInstallFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/FabriclikeInstallFragment.java
package net.kdt.pojavlaunch.fragments; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.PojavApplication; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.FabriclikeDownloadTask; import net.kdt.pojavlaunch.modloaders.FabriclikeUtils; import net.kdt.pojavlaunch.modloaders.FabricVersion; import net.kdt.pojavlaunch.modloaders.ModloaderDownloadListener; import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy; import net.kdt.pojavlaunch.modloaders.modpacks.SelfReferencingFuture; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.Future; public abstract class FabriclikeInstallFragment extends Fragment implements ModloaderDownloadListener, CompoundButton.OnCheckedChangeListener { private final FabriclikeUtils mFabriclikeUtils; private Spinner mGameVersionSpinner; private FabricVersion[] mGameVersionArray; private Future<?> mGameVersionFuture; private String mSelectedGameVersion; private Spinner mLoaderVersionSpinner; private FabricVersion[] mLoaderVersionArray; private Future<?> mLoaderVersionFuture; private String mSelectedLoaderVersion; private ProgressBar mProgressBar; private Button mStartButton; private View mRetryView; private CheckBox mOnlyStableCheckbox; protected FabriclikeInstallFragment(FabriclikeUtils mFabriclikeUtils) { super(R.layout.fragment_fabric_install); this.mFabriclikeUtils = mFabriclikeUtils; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mStartButton = view.findViewById(R.id.fabric_installer_start_button); mStartButton.setOnClickListener(this::onClickStart); mGameVersionSpinner = view.findViewById(R.id.fabric_installer_game_ver_spinner); mGameVersionSpinner.setOnItemSelectedListener(new GameVersionSelectedListener()); mLoaderVersionSpinner = view.findViewById(R.id.fabric_installer_loader_ver_spinner); mLoaderVersionSpinner.setOnItemSelectedListener(new LoaderVersionSelectedListener()); mProgressBar = view.findViewById(R.id.fabric_installer_progress_bar); mRetryView = view.findViewById(R.id.fabric_installer_retry_layout); mOnlyStableCheckbox = view.findViewById(R.id.fabric_installer_only_stable_checkbox); mOnlyStableCheckbox.setOnCheckedChangeListener(this); view.findViewById(R.id.fabric_installer_retry_button).setOnClickListener(this::onClickRetry); ((TextView)view.findViewById(R.id.fabric_installer_label_loader_ver)).setText(getString(R.string.fabric_dl_loader_version, mFabriclikeUtils.getName())); ModloaderListenerProxy proxy = getListenerProxy(); if(proxy != null) { mStartButton.setEnabled(false); proxy.attachListener(this); } updateGameVersions(); } @Override public void onStop() { cancelFutureChecked(mGameVersionFuture); cancelFutureChecked(mLoaderVersionFuture); ModloaderListenerProxy proxy = getListenerProxy(); if(proxy != null) { proxy.detachListener(); } super.onStop(); } private void onClickStart(View v) { if(ProgressKeeper.hasOngoingTasks()) { Toast.makeText(v.getContext(), R.string.tasks_ongoing, Toast.LENGTH_LONG).show(); return; } ModloaderListenerProxy proxy = new ModloaderListenerProxy(); FabriclikeDownloadTask fabricDownloadTask = new FabriclikeDownloadTask(proxy, mFabriclikeUtils, mSelectedGameVersion, mSelectedLoaderVersion, true); proxy.attachListener(this); setListenerProxy(proxy); mStartButton.setEnabled(false); new Thread(fabricDownloadTask).start(); } private void onClickRetry(View v) { mStartButton.setEnabled(false); mRetryView.setVisibility(View.GONE); mLoaderVersionSpinner.setAdapter(null); if(mGameVersionArray == null) { mGameVersionSpinner.setAdapter(null); updateGameVersions(); return; } updateLoaderVersions(); } @Override public void onDownloadFinished(File downloadedFile) { Tools.runOnUiThread(()->{ getListenerProxy().detachListener(); setListenerProxy(null); mStartButton.setEnabled(true); // This works because the due to the fact that we have transitioned here // without adding a transaction to the back stack, which caused the previous // transaction to be amended (i guess?? thats how the back stack dump looks like) // we can get back to the main fragment with just one back stack pop. // For some reason that amendment causes the transaction to lose its tag // so we cant use the tag here. getParentFragmentManager().popBackStackImmediate(); }); } @Override public void onDataNotAvailable() { Tools.runOnUiThread(()->{ Context context = requireContext(); getListenerProxy().detachListener(); setListenerProxy(null); mStartButton.setEnabled(true); Tools.dialog(context, context.getString(R.string.global_error), context.getString(R.string.fabric_dl_cant_read_meta, mFabriclikeUtils.getName())); }); } @Override public void onDownloadError(Exception e) { Tools.runOnUiThread(()-> { Context context = requireContext(); getListenerProxy().detachListener(); setListenerProxy(null); mStartButton.setEnabled(true); Tools.showError(context, e); }); } private void cancelFutureChecked(Future<?> future) { if(future != null && !future.isCancelled()) future.cancel(true); } private void startLoading() { mProgressBar.setVisibility(View.VISIBLE); mStartButton.setEnabled(false); } private void stopLoading() { mProgressBar.setVisibility(View.GONE); // The "visibility on" is managed by the spinners } private ArrayAdapter<FabricVersion> createAdapter(FabricVersion[] fabricVersions, boolean onlyStable) { ArrayList<FabricVersion> filteredVersions = new ArrayList<>(fabricVersions.length); for(FabricVersion fabricVersion : fabricVersions) { if(!onlyStable || fabricVersion.stable) filteredVersions.add(fabricVersion); } filteredVersions.trimToSize(); return new ArrayAdapter<>(requireContext(), android.R.layout.simple_spinner_dropdown_item, filteredVersions); } private void onException(Future<?> myFuture, Exception e) { Tools.runOnUiThread(()->{ if(myFuture.isCancelled()) return; stopLoading(); if(e != null) Tools.showError(requireContext(), e); mRetryView.setVisibility(View.VISIBLE); }); } @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { updateGameSpinner(); updateLoaderSpinner(); } class LoaderVersionSelectedListener implements AdapterView.OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { mSelectedLoaderVersion = ((FabricVersion) adapterView.getAdapter().getItem(i)).version; mStartButton.setEnabled(mSelectedGameVersion != null); } @Override public void onNothingSelected(AdapterView<?> adapterView) { mSelectedLoaderVersion = null; mStartButton.setEnabled(false); } } class LoadLoaderVersionsTask implements SelfReferencingFuture.FutureInterface { @Override public void run(Future<?> myFuture) { Log.i("LoadLoaderVersions", "Starting..."); try { mLoaderVersionArray = mFabriclikeUtils.downloadLoaderVersions(mSelectedGameVersion); if(mLoaderVersionArray != null) onFinished(myFuture); else onException(myFuture, null); }catch (IOException e) { onException(myFuture, e); } } private void onFinished(Future<?> myFuture) { Tools.runOnUiThread(()->{ if(myFuture.isCancelled()) return; stopLoading(); updateLoaderSpinner(); }); } } private void updateLoaderVersions() { startLoading(); mLoaderVersionFuture = new SelfReferencingFuture(new LoadLoaderVersionsTask()).startOnExecutor(PojavApplication.sExecutorService); } private void updateLoaderSpinner() { mLoaderVersionSpinner.setAdapter(createAdapter(mLoaderVersionArray, mOnlyStableCheckbox.isChecked())); } class GameVersionSelectedListener implements AdapterView.OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { mSelectedGameVersion = ((FabricVersion) adapterView.getAdapter().getItem(i)).version; cancelFutureChecked(mLoaderVersionFuture); updateLoaderVersions(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { mSelectedGameVersion = null; if(mLoaderVersionFuture != null) mLoaderVersionFuture.cancel(true); adapterView.setAdapter(null); } } class LoadGameVersionsTask implements SelfReferencingFuture.FutureInterface { @Override public void run(Future<?> myFuture) { try { mGameVersionArray = mFabriclikeUtils.downloadGameVersions(); if(mGameVersionArray != null) onFinished(myFuture); else onException(myFuture, null); }catch (IOException e) { onException(myFuture, e); } } private void onFinished(Future<?> myFuture) { Tools.runOnUiThread(()->{ if(myFuture.isCancelled()) return; stopLoading(); updateGameSpinner(); }); } } private void updateGameVersions() { startLoading(); mGameVersionFuture = new SelfReferencingFuture(new LoadGameVersionsTask()).startOnExecutor(PojavApplication.sExecutorService); } private void updateGameSpinner() { mGameVersionSpinner.setAdapter(createAdapter(mGameVersionArray, mOnlyStableCheckbox.isChecked())); } protected abstract ModloaderListenerProxy getListenerProxy(); protected abstract void setListenerProxy(ModloaderListenerProxy listenerProxy); }
11,547
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
LocalLoginFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/LocalLoginFragment.java
package net.kdt.pojavlaunch.fragments; import android.os.Bundle; import android.view.View; import android.widget.EditText; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LocalLoginFragment extends Fragment { public static final String TAG = "LOCAL_LOGIN_FRAGMENT"; private EditText mUsernameEditText; public LocalLoginFragment(){ super(R.layout.fragment_local_login); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mUsernameEditText = view.findViewById(R.id.login_edit_email); view.findViewById(R.id.login_button).setOnClickListener(v -> { if(!checkEditText()) return; ExtraCore.setValue(ExtraConstants.MOJANG_LOGIN_TODO, new String[]{ mUsernameEditText.getText().toString(), "" }); Tools.swapFragment(requireActivity(), MainMenuFragment.class, MainMenuFragment.TAG, null); }); } /** @return Whether the mail (and password) text are eligible to make an auth request */ private boolean checkEditText(){ String text = mUsernameEditText.getText().toString(); Pattern pattern = Pattern.compile("[^a-zA-Z0-9_]"); Matcher matcher = pattern.matcher(text); return !(text.isEmpty() || text.length() < 3 || text.length() > 16 || matcher.find() || new File(Tools.DIR_ACCOUNT_NEW + "/" + text + ".json").exists() ); } }
1,826
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MicrosoftLoginFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/MicrosoftLoginFragment.java
package net.kdt.pojavlaunch.fragments; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.CookieManager; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; public class MicrosoftLoginFragment extends Fragment { public static final String TAG = "MICROSOFT_LOGIN_FRAGMENT"; private WebView mWebview; // Technically the client is blank (or there is none) when the fragment is initialized private boolean mBlankClient = true; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mWebview = (WebView) inflater.inflate(R.layout.fragment_microsoft_login, container, false); setWebViewSettings(); if(savedInstanceState == null) startNewSession(); else restoreWebViewState(savedInstanceState); return mWebview; } // WebView.restoreState() does not restore the WebSettings or the client, so set them there // separately. Note that general state should not be altered here (aka no loading pages, no manipulating back/front lists), // to avoid "undesirable side-effects" @SuppressLint("SetJavaScriptEnabled") private void setWebViewSettings() { WebSettings settings = mWebview.getSettings(); settings.setJavaScriptEnabled(true); mWebview.setWebViewClient(new WebViewTrackClient()); mBlankClient = false; } private void startNewSession() { CookieManager.getInstance().removeAllCookies((b)->{ mWebview.clearHistory(); mWebview.clearCache(true); mWebview.clearFormData(); mWebview.clearHistory(); mWebview.loadUrl("https://login.live.com/oauth20_authorize.srf" + "?client_id=00000000402b5328" + "&response_type=code" + "&scope=service%3A%3Auser.auth.xboxlive.com%3A%3AMBI_SSL" + "&redirect_url=https%3A%2F%2Flogin.live.com%2Foauth20_desktop.srf"); }); } private void restoreWebViewState(Bundle savedInstanceState) { Log.i("MSAuthFragment","Restoring state..."); if(mWebview.restoreState(savedInstanceState) == null) { Log.w("MSAuthFragment", "Failed to restore state, starting afresh"); // if, for some reason, we failed to restore our session, // just start afresh startNewSession(); } } @Override public void onStart() { super.onStart(); // If we have switched to a blank client and haven't fully gone though the lifecycle callbacks to restore it, // restore it here. if(mBlankClient) mWebview.setWebViewClient(new WebViewTrackClient()); } @Override public void onSaveInstanceState(@NonNull Bundle outState) { // Since the value cannot be null, just create a "blank" client. This is done to not let Android // kill us if something happens after the state gets saved, when we can't do fragment transitions mWebview.setWebViewClient(new WebViewClient()); // For some dumb reason state is saved even when Android won't actually destroy the activity. // Let the fragment know that the client is blank so that we can restore it in onStart() // (it was the earliest lifecycle call actually invoked in this case) mBlankClient = true; super.onSaveInstanceState(outState); mWebview.saveState(outState); } /* Expose webview actions to others */ public boolean canGoBack(){ return mWebview.canGoBack();} public void goBack(){ mWebview.goBack();} /** Client to track when to sent the data to the launcher */ class WebViewTrackClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if(url.startsWith("ms-xal-00000000402b5328")) { // Should be captured by the activity to kill the fragment and get ExtraCore.setValue(ExtraConstants.MICROSOFT_LOGIN_TODO, Uri.parse(url)); Toast.makeText(view.getContext(), "Login started !", Toast.LENGTH_SHORT).show(); Tools.backToMainMenu(requireActivity()); return true; } // Sometimes, the user just clicked cancel if(url.contains("res=cancel")){ requireActivity().onBackPressed(); return true; } return super.shouldOverrideUrlLoading(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) {} @Override public void onPageFinished(WebView view, String url) {} } }
5,225
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FabricInstallFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/FabricInstallFragment.java
package net.kdt.pojavlaunch.fragments; import net.kdt.pojavlaunch.modloaders.FabriclikeUtils; import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy; public class FabricInstallFragment extends FabriclikeInstallFragment { public static final String TAG = "FabricInstallFragment"; private static ModloaderListenerProxy sTaskProxy; public FabricInstallFragment() { super(FabriclikeUtils.FABRIC_UTILS); } @Override protected ModloaderListenerProxy getListenerProxy() { return sTaskProxy; } @Override protected void setListenerProxy(ModloaderListenerProxy listenerProxy) { sTaskProxy = listenerProxy; } }
676
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProfileTypeSelectFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/ProfileTypeSelectFragment.java
package net.kdt.pojavlaunch.fragments; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; public class ProfileTypeSelectFragment extends Fragment { public static final String TAG = "ProfileTypeSelectFragment"; public ProfileTypeSelectFragment() { super(R.layout.fragment_profile_type); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); view.findViewById(R.id.vanilla_profile).setOnClickListener(v -> Tools.swapFragment(requireActivity(), ProfileEditorFragment.class, ProfileEditorFragment.TAG, new Bundle(1))); // NOTE: Special care needed! If you wll decide to add these to the back stack, please read // the comment in FabricInstallFragment.onDownloadFinished() and amend the code // in FabricInstallFragment.onDownloadFinished() and ModVersionListFragment.onDownloadFinished() view.findViewById(R.id.optifine_profile).setOnClickListener(v -> Tools.swapFragment(requireActivity(), OptiFineInstallFragment.class, OptiFineInstallFragment.TAG, null)); view.findViewById(R.id.modded_profile_fabric).setOnClickListener((v)-> Tools.swapFragment(requireActivity(), FabricInstallFragment.class, FabricInstallFragment.TAG, null)); view.findViewById(R.id.modded_profile_forge).setOnClickListener((v)-> Tools.swapFragment(requireActivity(), ForgeInstallFragment.class, ForgeInstallFragment.TAG, null)); view.findViewById(R.id.modded_profile_modpack).setOnClickListener((v)-> Tools.swapFragment(requireActivity(), SearchModFragment.class, SearchModFragment.TAG, null)); view.findViewById(R.id.modded_profile_quilt).setOnClickListener((v)-> Tools.swapFragment(requireActivity(), QuiltInstallFragment.class, QuiltInstallFragment.TAG, null)); } }
2,119
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
OptiFineInstallFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/OptiFineInstallFragment.java
package net.kdt.pojavlaunch.fragments; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.widget.ExpandableListAdapter; import net.kdt.pojavlaunch.JavaGUILauncherActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy; import net.kdt.pojavlaunch.modloaders.OptiFineDownloadTask; import net.kdt.pojavlaunch.modloaders.OptiFineUtils; import net.kdt.pojavlaunch.modloaders.OptiFineVersionListAdapter; import java.io.File; import java.io.IOException; public class OptiFineInstallFragment extends ModVersionListFragment<OptiFineUtils.OptiFineVersions> { public static final String TAG = "OptiFineInstallFragment"; private static ModloaderListenerProxy sTaskProxy; @Override public int getTitleText() { return R.string.of_dl_select_version; } @Override public int getNoDataMsg() { return R.string.of_dl_failed_to_scrape; } @Override public ModloaderListenerProxy getTaskProxy() { return sTaskProxy; } @Override public OptiFineUtils.OptiFineVersions loadVersionList() throws IOException { return OptiFineUtils.downloadOptiFineVersions(); } @Override public void setTaskProxy(ModloaderListenerProxy proxy) { sTaskProxy = proxy; } @Override public ExpandableListAdapter createAdapter(OptiFineUtils.OptiFineVersions versionList, LayoutInflater layoutInflater) { return new OptiFineVersionListAdapter(versionList, layoutInflater); } @Override public Runnable createDownloadTask(Object selectedVersion, ModloaderListenerProxy listenerProxy) { return new OptiFineDownloadTask((OptiFineUtils.OptiFineVersion) selectedVersion, listenerProxy); } @Override public void onDownloadFinished(Context context, File downloadedFile) { Intent modInstallerStartIntent = new Intent(context, JavaGUILauncherActivity.class); OptiFineUtils.addAutoInstallArgs(modInstallerStartIntent, downloadedFile); context.startActivity(modInstallerStartIntent); } }
2,160
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
FileSelectorFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/FileSelectorFragment.java
package net.kdt.pojavlaunch.fragments; import android.app.AlertDialog; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.kdt.pickafile.FileListView; import com.kdt.pickafile.FileSelectedListener; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import java.io.File; public class FileSelectorFragment extends Fragment { public static final String TAG = "FileSelectorFragment"; public static final String BUNDLE_SELECT_FOLDER = "select_folder"; public static final String BUNDLE_SHOW_FILE = "show_file"; public static final String BUNDLE_SHOW_FOLDER = "show_folder"; public static final String BUNDLE_ROOT_PATH = "root_path"; private Button mSelectFolderButton, mCreateFolderButton; private FileListView mFileListView; private TextView mFilePathView; private boolean mSelectFolder = true; private boolean mShowFiles = true; private boolean mShowFolders = true; private String mRootPath = Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? Tools.DIR_GAME_NEW : Environment.getExternalStorageDirectory().getAbsolutePath(); public FileSelectorFragment(){ super(R.layout.fragment_file_selector); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { bindViews(view); parseBundle(); if(!mSelectFolder) mSelectFolderButton.setVisibility(View.GONE); else mSelectFolderButton.setVisibility(View.VISIBLE); mFileListView.setShowFiles(mShowFiles); mFileListView.setShowFolders(mShowFolders); mFileListView.lockPathAt(new File(mRootPath)); mFileListView.setDialogTitleListener((title)->mFilePathView.setText(removeLockPath(title))); mFileListView.refreshPath(); mCreateFolderButton.setOnClickListener(v -> { final EditText editText = new EditText(getContext()); new AlertDialog.Builder(getContext()) .setTitle(R.string.folder_dialog_insert_name) .setView(editText) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(R.string.folder_dialog_create, (dialog, which) -> { File folder = new File(mFileListView.getFullPath(), editText.getText().toString()); boolean success = folder.mkdir(); if(success){ mFileListView.listFileAt(new File(mFileListView.getFullPath(),editText.getText().toString())); }else{ mFileListView.refreshPath(); } }).show(); }); mSelectFolderButton.setOnClickListener(v -> { ExtraCore.setValue(ExtraConstants.FILE_SELECTOR, removeLockPath(mFileListView.getFullPath().getAbsolutePath())); Tools.removeCurrentFragment(requireActivity()); }); mFileListView.setFileSelectedListener(new FileSelectedListener() { @Override public void onFileSelected(File file, String path) { ExtraCore.setValue(ExtraConstants.FILE_SELECTOR, removeLockPath(path)); Tools.removeCurrentFragment(requireActivity()); } }); } private String removeLockPath(String path){ return path.replace(mRootPath, "."); } private void parseBundle(){ Bundle bundle = getArguments(); if(bundle == null) return; mSelectFolder = bundle.getBoolean(BUNDLE_SELECT_FOLDER, mSelectFolder); mShowFiles = bundle.getBoolean(BUNDLE_SHOW_FILE, mShowFiles); mShowFolders = bundle.getBoolean(BUNDLE_SHOW_FOLDER, mShowFolders); mRootPath = bundle.getString(BUNDLE_ROOT_PATH, mRootPath); } private void bindViews(@NonNull View view){ mSelectFolderButton = view.findViewById(R.id.file_selector_select_folder); mCreateFolderButton = view.findViewById(R.id.file_selector_create_folder); mFileListView = view.findViewById(R.id.file_selector); mFilePathView = view.findViewById(R.id.file_selector_current_path); } }
4,539
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
MainMenuFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/MainMenuFragment.java
package net.kdt.pojavlaunch.fragments; import static net.kdt.pojavlaunch.Tools.shareLog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.kdt.mcgui.mcVersionSpinner; import net.kdt.pojavlaunch.CustomControlsActivity; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; public class MainMenuFragment extends Fragment { public static final String TAG = "MainMenuFragment"; private mcVersionSpinner mVersionSpinner; public MainMenuFragment(){ super(R.layout.fragment_launcher); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { Button mNewsButton = view.findViewById(R.id.news_button); Button mCustomControlButton = view.findViewById(R.id.custom_control_button); Button mInstallJarButton = view.findViewById(R.id.install_jar_button); Button mShareLogsButton = view.findViewById(R.id.share_logs_button); ImageButton mEditProfileButton = view.findViewById(R.id.edit_profile_button); Button mPlayButton = view.findViewById(R.id.play_button); mVersionSpinner = view.findViewById(R.id.mc_version_spinner); mNewsButton.setOnClickListener(v -> Tools.openURL(requireActivity(), Tools.URL_HOME)); mCustomControlButton.setOnClickListener(v -> startActivity(new Intent(requireContext(), CustomControlsActivity.class))); mInstallJarButton.setOnClickListener(v -> runInstallerWithConfirmation(false)); mInstallJarButton.setOnLongClickListener(v->{ runInstallerWithConfirmation(true); return true; }); mEditProfileButton.setOnClickListener(v -> mVersionSpinner.openProfileEditor(requireActivity())); mPlayButton.setOnClickListener(v -> ExtraCore.setValue(ExtraConstants.LAUNCH_GAME, true)); mShareLogsButton.setOnClickListener((v) -> shareLog(requireContext())); mNewsButton.setOnLongClickListener((v)->{ Tools.swapFragment(requireActivity(), SearchModFragment.class, SearchModFragment.TAG, null); return true; }); } @Override public void onResume() { super.onResume(); mVersionSpinner.reloadProfiles(); } private void runInstallerWithConfirmation(boolean isCustomArgs) { if (ProgressKeeper.getTaskCount() == 0) Tools.installMod(requireActivity(), isCustomArgs); else Toast.makeText(requireContext(), R.string.tasks_ongoing, Toast.LENGTH_LONG).show(); } }
2,912
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
SelectAuthFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/SelectAuthFragment.java
package net.kdt.pojavlaunch.fragments; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; public class SelectAuthFragment extends Fragment { public static final String TAG = "AUTH_SELECT_FRAGMENT"; public SelectAuthFragment(){ super(R.layout.fragment_select_auth_method); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { Button mMicrosoftButton = view.findViewById(R.id.button_microsoft_authentication); Button mLocalButton = view.findViewById(R.id.button_local_authentication); mMicrosoftButton.setOnClickListener(v -> Tools.swapFragment(requireActivity(), MicrosoftLoginFragment.class, MicrosoftLoginFragment.TAG, null)); mLocalButton.setOnClickListener(v -> Tools.swapFragment(requireActivity(), LocalLoginFragment.class, LocalLoginFragment.TAG, null)); } }
1,087
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ModVersionListFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/ModVersionListFragment.java
package net.kdt.pojavlaunch.fragments; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.mirrors.DownloadMirror; import net.kdt.pojavlaunch.modloaders.ModloaderDownloadListener; import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; import java.io.File; import java.io.IOException; public abstract class ModVersionListFragment<T> extends Fragment implements Runnable, View.OnClickListener, ExpandableListView.OnChildClickListener, ModloaderDownloadListener { public static final String TAG = "ForgeInstallFragment"; private ExpandableListView mExpandableListView; private ProgressBar mProgressBar; private LayoutInflater mInflater; private View mRetryView; public ModVersionListFragment() { super(R.layout.fragment_mod_version_list); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); this.mInflater = LayoutInflater.from(context); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ((TextView)view.findViewById(R.id.title_textview)).setText(getTitleText()); mProgressBar = view.findViewById(R.id.mod_dl_list_progress); mExpandableListView = view.findViewById(R.id.mod_dl_expandable_version_list); mExpandableListView.setOnChildClickListener(this); mRetryView = view.findViewById(R.id.mod_dl_retry_layout); view.findViewById(R.id.forge_installer_retry_button).setOnClickListener(this); ModloaderListenerProxy taskProxy = getTaskProxy(); if(taskProxy != null) { mExpandableListView.setEnabled(false); taskProxy.attachListener(this); } new Thread(this).start(); } @Override public void onStop() { ModloaderListenerProxy taskProxy = getTaskProxy(); if(taskProxy != null) taskProxy.detachListener(); super.onStop(); } @Override public void run() { try { T versions = loadVersionList(); Tools.runOnUiThread(()->{ if(versions != null) { mExpandableListView.setAdapter(createAdapter(versions, mInflater)); }else{ mRetryView.setVisibility(View.VISIBLE); } mProgressBar.setVisibility(View.GONE); }); }catch (IOException e) { Tools.runOnUiThread(()-> { if (getContext() != null) { Tools.showError(getContext(), e); mRetryView.setVisibility(View.VISIBLE); mProgressBar.setVisibility(View.GONE); } }); } } @Override public void onClick(View view) { mRetryView.setVisibility(View.GONE); mProgressBar.setVisibility(View.VISIBLE); new Thread(this).start(); } @Override public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) { if(ProgressKeeper.hasOngoingTasks()) { Toast.makeText(expandableListView.getContext(), R.string.tasks_ongoing, Toast.LENGTH_LONG).show(); return true; } Object forgeVersion = expandableListView.getExpandableListAdapter().getChild(i, i1); ModloaderListenerProxy taskProxy = new ModloaderListenerProxy(); Runnable downloadTask = createDownloadTask(forgeVersion, taskProxy); setTaskProxy(taskProxy); taskProxy.attachListener(this); mExpandableListView.setEnabled(false); new Thread(downloadTask).start(); return true; } @Override public void onDownloadFinished(File downloadedFile) { Tools.runOnUiThread(()->{ Context context = requireContext(); getTaskProxy().detachListener(); setTaskProxy(null); mExpandableListView.setEnabled(true); // Read the comment in FabricInstallFragment.onDownloadFinished() to see how this works getParentFragmentManager().popBackStackImmediate(); onDownloadFinished(context, downloadedFile); }); } @Override public void onDataNotAvailable() { Tools.runOnUiThread(()->{ Context context = requireContext(); getTaskProxy().detachListener(); setTaskProxy(null); mExpandableListView.setEnabled(true); Tools.dialog(context, context.getString(R.string.global_error), context.getString(getNoDataMsg())); }); } @Override public void onDownloadError(Exception e) { Tools.runOnUiThread(()->{ Context context = requireContext(); getTaskProxy().detachListener(); setTaskProxy(null); mExpandableListView.setEnabled(true); Tools.showError(context, e); }); } public abstract int getTitleText(); public abstract int getNoDataMsg(); public abstract ModloaderListenerProxy getTaskProxy(); public abstract T loadVersionList() throws IOException; public abstract void setTaskProxy(ModloaderListenerProxy proxy); public abstract ExpandableListAdapter createAdapter(T versionList, LayoutInflater layoutInflater); public abstract Runnable createDownloadTask(Object selectedVersion, ModloaderListenerProxy listenerProxy); public abstract void onDownloadFinished(Context context, File downloadedFile); }
6,055
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
SearchModFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/SearchModFragment.java
package net.kdt.pojavlaunch.fragments; import android.content.Context; import android.content.res.ColorStateList; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.math.MathUtils; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.modloaders.modpacks.ModItemAdapter; import net.kdt.pojavlaunch.modloaders.modpacks.api.CommonApi; import net.kdt.pojavlaunch.modloaders.modpacks.api.ModpackApi; import net.kdt.pojavlaunch.modloaders.modpacks.models.SearchFilters; import net.kdt.pojavlaunch.profiles.VersionSelectorDialog; import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper; public class SearchModFragment extends Fragment implements ModItemAdapter.SearchResultCallback { public static final String TAG = "SearchModFragment"; private View mOverlay; private float mOverlayTopCache; // Padding cache reduce resource lookup private final RecyclerView.OnScrollListener mOverlayPositionListener = new RecyclerView.OnScrollListener() { @Override public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { mOverlay.setY(MathUtils.clamp(mOverlay.getY() - dy, -mOverlay.getHeight(), mOverlayTopCache)); } }; private EditText mSearchEditText; private ImageButton mFilterButton; private RecyclerView mRecyclerview; private ModItemAdapter mModItemAdapter; private ProgressBar mSearchProgressBar; private TextView mStatusTextView; private ColorStateList mDefaultTextColor; private ModpackApi modpackApi; private final SearchFilters mSearchFilters; public SearchModFragment(){ super(R.layout.fragment_mod_search); mSearchFilters = new SearchFilters(); mSearchFilters.isModpack = true; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); modpackApi = new CommonApi(context.getString(R.string.curseforge_api_key)); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // You can only access resources after attaching to current context mModItemAdapter = new ModItemAdapter(getResources(), modpackApi, this); ProgressKeeper.addTaskCountListener(mModItemAdapter); mOverlayTopCache = getResources().getDimension(R.dimen.fragment_padding_medium); mOverlay = view.findViewById(R.id.search_mod_overlay); mSearchEditText = view.findViewById(R.id.search_mod_edittext); mSearchProgressBar = view.findViewById(R.id.search_mod_progressbar); mRecyclerview = view.findViewById(R.id.search_mod_list); mStatusTextView = view.findViewById(R.id.search_mod_status_text); mFilterButton = view.findViewById(R.id.search_mod_filter); mDefaultTextColor = mStatusTextView.getTextColors(); mRecyclerview.setLayoutManager(new LinearLayoutManager(getContext())); mRecyclerview.setAdapter(mModItemAdapter); mRecyclerview.addOnScrollListener(mOverlayPositionListener); mSearchEditText.setOnEditorActionListener((v, actionId, event) -> { mSearchProgressBar.setVisibility(View.VISIBLE); mSearchFilters.name = mSearchEditText.getText().toString(); mModItemAdapter.performSearchQuery(mSearchFilters); return true; }); mOverlay.post(()->{ int overlayHeight = mOverlay.getHeight(); mRecyclerview.setPadding(mRecyclerview.getPaddingLeft(), mRecyclerview.getPaddingTop() + overlayHeight, mRecyclerview.getPaddingRight(), mRecyclerview.getPaddingBottom()); }); mFilterButton.setOnClickListener(v -> displayFilterDialog()); } @Override public void onDestroyView() { super.onDestroyView(); ProgressKeeper.removeTaskCountListener(mModItemAdapter); mRecyclerview.removeOnScrollListener(mOverlayPositionListener); } @Override public void onSearchFinished() { mSearchProgressBar.setVisibility(View.GONE); mStatusTextView.setVisibility(View.GONE); } @Override public void onSearchError(int error) { mSearchProgressBar.setVisibility(View.GONE); mStatusTextView.setVisibility(View.VISIBLE); switch (error) { case ERROR_INTERNAL: mStatusTextView.setTextColor(Color.RED); mStatusTextView.setText(R.string.search_modpack_error); break; case ERROR_NO_RESULTS: mStatusTextView.setTextColor(mDefaultTextColor); mStatusTextView.setText(R.string.search_modpack_no_result); break; } } private void displayFilterDialog() { AlertDialog dialog = new AlertDialog.Builder(requireContext()) .setView(R.layout.dialog_mod_filters) .create(); // setup the view behavior dialog.setOnShowListener(dialogInterface -> { TextView mSelectedVersion = dialog.findViewById(R.id.search_mod_selected_mc_version_textview); Button mSelectVersionButton = dialog.findViewById(R.id.search_mod_mc_version_button); Button mApplyButton = dialog.findViewById(R.id.search_mod_apply_filters); assert mSelectVersionButton != null; assert mSelectedVersion != null; assert mApplyButton != null; // Setup the expendable list behavior mSelectVersionButton.setOnClickListener(v -> VersionSelectorDialog.open(v.getContext(), true, (id, snapshot)-> mSelectedVersion.setText(id))); // Apply visually all the current settings mSelectedVersion.setText(mSearchFilters.mcVersion); // Apply the new settings mApplyButton.setOnClickListener(v -> { mSearchFilters.mcVersion = mSelectedVersion.getText().toString(); dialogInterface.dismiss(); }); }); dialog.show(); } }
6,503
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z
ProfileEditorFragment.java
/FileExtraction/Java_unseen/PojavLauncherTeam_PojavLauncher/app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/fragments/ProfileEditorFragment.java
package net.kdt.pojavlaunch.fragments; import android.content.Context; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.util.Base64; import android.util.Base64OutputStream; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import androidx.activity.result.ActivityResultLauncher; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import net.kdt.pojavlaunch.R; import net.kdt.pojavlaunch.Tools; import net.kdt.pojavlaunch.extra.ExtraConstants; import net.kdt.pojavlaunch.extra.ExtraCore; import net.kdt.pojavlaunch.multirt.MultiRTUtils; import net.kdt.pojavlaunch.multirt.RTSpinnerAdapter; import net.kdt.pojavlaunch.multirt.Runtime; import net.kdt.pojavlaunch.prefs.LauncherPreferences; import net.kdt.pojavlaunch.profiles.ProfileIconCache; import net.kdt.pojavlaunch.profiles.VersionSelectorDialog; import net.kdt.pojavlaunch.utils.CropperUtils; import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles; import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ProfileEditorFragment extends Fragment implements CropperUtils.CropperListener{ public static final String TAG = "ProfileEditorFragment"; public static final String DELETED_PROFILE = "deleted_profile"; private String mProfileKey; private MinecraftProfile mTempProfile = null; private String mValueToConsume = ""; private Button mSaveButton, mDeleteButton, mControlSelectButton, mGameDirButton, mVersionSelectButton; private Spinner mDefaultRuntime, mDefaultRenderer; private EditText mDefaultName, mDefaultJvmArgument; private TextView mDefaultPath, mDefaultVersion, mDefaultControl; private ImageView mProfileIcon; private final ActivityResultLauncher<?> mCropperLauncher = CropperUtils.registerCropper(this, this); private List<String> mRenderNames; public ProfileEditorFragment(){ super(R.layout.fragment_profile_editor); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // Paths, which can be changed String value = (String) ExtraCore.consumeValue(ExtraConstants.FILE_SELECTOR); if(value != null){ if(mValueToConsume.equals(FileSelectorFragment.BUNDLE_SELECT_FOLDER)){ mTempProfile.gameDir = value; }else{ mTempProfile.controlFile = value; } } return super.onCreateView(inflater, container, savedInstanceState); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { bindViews(view); Tools.RenderersList renderersList = Tools.getCompatibleRenderers(view.getContext()); mRenderNames = renderersList.rendererIds; List<String> renderList = new ArrayList<>(renderersList.rendererDisplayNames.length + 1); renderList.addAll(Arrays.asList(renderersList.rendererDisplayNames)); renderList.add(view.getContext().getString(R.string.global_default)); mDefaultRenderer.setAdapter(new ArrayAdapter<>(getContext(), R.layout.item_simple_list_1, renderList)); // Set up behaviors mSaveButton.setOnClickListener(v -> { ProfileIconCache.dropIcon(mProfileKey); save(); Tools.backToMainMenu(requireActivity()); }); mDeleteButton.setOnClickListener(v -> { if(LauncherProfiles.mainProfileJson.profiles.size() > 1){ ProfileIconCache.dropIcon(mProfileKey); LauncherProfiles.mainProfileJson.profiles.remove(mProfileKey); LauncherProfiles.write(); ExtraCore.setValue(ExtraConstants.REFRESH_VERSION_SPINNER, DELETED_PROFILE); } Tools.removeCurrentFragment(requireActivity()); }); mGameDirButton.setOnClickListener(v -> { Bundle bundle = new Bundle(2); bundle.putBoolean(FileSelectorFragment.BUNDLE_SELECT_FOLDER, true); bundle.putString(FileSelectorFragment.BUNDLE_ROOT_PATH, Tools.DIR_GAME_HOME); bundle.putBoolean(FileSelectorFragment.BUNDLE_SHOW_FILE, false); mValueToConsume = FileSelectorFragment.BUNDLE_SELECT_FOLDER; Tools.swapFragment(requireActivity(), FileSelectorFragment.class, FileSelectorFragment.TAG, bundle); }); mControlSelectButton.setOnClickListener(v -> { Bundle bundle = new Bundle(3); bundle.putBoolean(FileSelectorFragment.BUNDLE_SELECT_FOLDER, false); bundle.putString(FileSelectorFragment.BUNDLE_ROOT_PATH, Tools.CTRLMAP_PATH); Tools.swapFragment(requireActivity(), FileSelectorFragment.class, FileSelectorFragment.TAG, bundle); }); // Setup the expendable list behavior mVersionSelectButton.setOnClickListener(v -> VersionSelectorDialog.open(v.getContext(), false, (id, snapshot)->{ mTempProfile.lastVersionId = id; mDefaultVersion.setText(id); })); // Set up the icon change click listener mProfileIcon.setOnClickListener(v -> CropperUtils.startCropper(mCropperLauncher)); loadValues(LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE, ""), view.getContext()); } private void loadValues(@NonNull String profile, @NonNull Context context){ if(mTempProfile == null){ mTempProfile = getProfile(profile); } mProfileIcon.setImageDrawable( ProfileIconCache.fetchIcon(getResources(), mProfileKey, mTempProfile.icon) ); // Runtime spinner List<Runtime> runtimes = MultiRTUtils.getRuntimes(); int jvmIndex = runtimes.indexOf(new Runtime("<Default>")); if (mTempProfile.javaDir != null) { String selectedRuntime = mTempProfile.javaDir.substring(Tools.LAUNCHERPROFILES_RTPREFIX.length()); int nindex = runtimes.indexOf(new Runtime(selectedRuntime)); if (nindex != -1) jvmIndex = nindex; } mDefaultRuntime.setAdapter(new RTSpinnerAdapter(context, runtimes)); if(jvmIndex == -1) jvmIndex = runtimes.size() - 1; mDefaultRuntime.setSelection(jvmIndex); // Renderer spinner int rendererIndex = mDefaultRenderer.getAdapter().getCount() - 1; if(mTempProfile.pojavRendererName != null) { int nindex = mRenderNames.indexOf(mTempProfile.pojavRendererName); if(nindex != -1) rendererIndex = nindex; } mDefaultRenderer.setSelection(rendererIndex); mDefaultVersion.setText(mTempProfile.lastVersionId); mDefaultJvmArgument.setText(mTempProfile.javaArgs == null ? "" : mTempProfile.javaArgs); mDefaultName.setText(mTempProfile.name); mDefaultPath.setText(mTempProfile.gameDir == null ? "" : mTempProfile.gameDir); mDefaultControl.setText(mTempProfile.controlFile == null ? "" : mTempProfile.controlFile); } private MinecraftProfile getProfile(@NonNull String profile){ MinecraftProfile minecraftProfile; if(getArguments() == null) { minecraftProfile = new MinecraftProfile(LauncherProfiles.mainProfileJson.profiles.get(profile)); mProfileKey = profile; }else{ minecraftProfile = MinecraftProfile.createTemplate(); mProfileKey = LauncherProfiles.getFreeProfileKey(); } return minecraftProfile; } private void bindViews(@NonNull View view){ mDefaultControl = view.findViewById(R.id.vprof_editor_ctrl_spinner); mDefaultRuntime = view.findViewById(R.id.vprof_editor_spinner_runtime); mDefaultRenderer = view.findViewById(R.id.vprof_editor_profile_renderer); mDefaultVersion = view.findViewById(R.id.vprof_editor_version_spinner); mDefaultPath = view.findViewById(R.id.vprof_editor_path); mDefaultName = view.findViewById(R.id.vprof_editor_profile_name); mDefaultJvmArgument = view.findViewById(R.id.vprof_editor_jre_args); mSaveButton = view.findViewById(R.id.vprof_editor_save_button); mDeleteButton = view.findViewById(R.id.vprof_editor_delete_button); mControlSelectButton = view.findViewById(R.id.vprof_editor_ctrl_button); mVersionSelectButton = view.findViewById(R.id.vprof_editor_version_button); mGameDirButton = view.findViewById(R.id.vprof_editor_path_button); mProfileIcon = view.findViewById(R.id.vprof_editor_profile_icon); } private void save(){ //First, check for potential issues in the inputs mTempProfile.lastVersionId = mDefaultVersion.getText().toString(); mTempProfile.controlFile = mDefaultControl.getText().toString(); mTempProfile.name = mDefaultName.getText().toString(); mTempProfile.javaArgs = mDefaultJvmArgument.getText().toString(); mTempProfile.gameDir = mDefaultPath.getText().toString(); if(mTempProfile.controlFile.isEmpty()) mTempProfile.controlFile = null; if(mTempProfile.javaArgs.isEmpty()) mTempProfile.javaArgs = null; if(mTempProfile.gameDir.isEmpty()) mTempProfile.gameDir = null; Runtime selectedRuntime = (Runtime) mDefaultRuntime.getSelectedItem(); mTempProfile.javaDir = (selectedRuntime.name.equals("<Default>") || selectedRuntime.versionString == null) ? null : Tools.LAUNCHERPROFILES_RTPREFIX + selectedRuntime.name; if(mDefaultRenderer.getSelectedItemPosition() == mRenderNames.size()) mTempProfile.pojavRendererName = null; else mTempProfile.pojavRendererName = mRenderNames.get(mDefaultRenderer.getSelectedItemPosition()); LauncherProfiles.mainProfileJson.profiles.put(mProfileKey, mTempProfile); LauncherProfiles.write(); ExtraCore.setValue(ExtraConstants.REFRESH_VERSION_SPINNER, mProfileKey); } @Override public void onCropped(Bitmap contentBitmap) { mProfileIcon.setImageBitmap(contentBitmap); Log.i("bitmap", "w="+contentBitmap.getWidth() +" h="+contentBitmap.getHeight()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (Base64OutputStream base64OutputStream = new Base64OutputStream(byteArrayOutputStream, Base64.NO_WRAP)) { contentBitmap.compress( Build.VERSION.SDK_INT < Build.VERSION_CODES.R ? // On Android < 30, there was no distinction between "lossy" and "lossless", // and the type is picked by the quality parameter. We set the quality to 60. // so it should be lossy, Bitmap.CompressFormat.WEBP: // On Android >= 30, we can explicitly specify that we want lossy compression // with the visual quality of 60. Bitmap.CompressFormat.WEBP_LOSSY, 60, base64OutputStream ); base64OutputStream.flush(); byteArrayOutputStream.flush(); }catch (IOException e) { Tools.showErrorRemote(e); return; } String iconLine = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8); mTempProfile.icon = "data:image/webp;base64," + iconLine; } @Override public void onFailed(Exception exception) { Tools.showErrorRemote(exception); } }
12,064
Java
.java
PojavLauncherTeam/PojavLauncher
5,778
1,166
108
2020-03-11T03:22:54Z
2024-05-05T14:27:56Z