Cleanup, part 1

This commit is contained in:
artdeell
2023-04-30 14:42:35 +03:00
parent 401e604763
commit 57b37dfc8c
44 changed files with 197 additions and 435 deletions

View File

@@ -12,13 +12,10 @@ 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 final int MAX_SIZE = 100;
private final double NANOS = 1000000000.0;
private int mWidth, mHeight;
private static final int MAX_SIZE = 100;
private static final double NANOS = 1000000000.0;
private boolean mIsDestroyed = false;
private final TextPaint mFpsPaint;
private boolean mDrawing;
// Temporary count fps https://stackoverflow.com/a/13729241
private final LinkedList<Long> mTimes = new LinkedList<Long>(){{add(System.nanoTime());}};
@@ -43,9 +40,6 @@ public class AWTCanvasView extends TextureView implements TextureView.SurfaceTex
@Override
public void onSurfaceTextureAvailable(SurfaceTexture texture, int w, int h) {
getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT);
mWidth = w;
mHeight = h;
mIsDestroyed = false;
new Thread(this, "AndroidAWTRenderer").start();
}
@@ -59,8 +53,6 @@ public class AWTCanvasView extends TextureView implements TextureView.SurfaceTex
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int w, int h) {
getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT);
mWidth = w;
mHeight = h;
}
@Override
@@ -72,17 +64,18 @@ public class AWTCanvasView extends TextureView implements TextureView.SurfaceTex
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 */);
mDrawing = rgbArray != null;
boolean mDrawing = rgbArray != null;
if (rgbArray != null) {
canvas.save();
canvas.drawBitmap(rgbArray, 0, AWT_CANVAS_WIDTH, 0, 0, AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT, true, null);
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);
@@ -91,6 +84,7 @@ public class AWTCanvasView extends TextureView implements TextureView.SurfaceTex
} catch (Throwable throwable) {
Tools.showError(getContext(), throwable);
}
rgbArrayBitmap.recycle();
surface.release();
}

View File

@@ -2,14 +2,9 @@ package net.kdt.pojavlaunch;
public class AWTInputBridge {
public static final int EVENT_TYPE_CHAR = 1000;
// public static final int EVENT_TYPE_CHAR_MODS = 1001;
// public static final int EVENT_TYPE_CURSOR_ENTER = 1002;
public static final int EVENT_TYPE_CURSOR_POS = 1003;
// public static final int EVENT_TYPE_FRAMEBUFFER_SIZE = 1004;
public static final int EVENT_TYPE_KEY = 1005;
public static final int EVENT_TYPE_MOUSE_BUTTON = 1006;
public static final int EVENT_TYPE_SCROLL = 1007;
// public static final int EVENT_TYPE_WINDOW_SIZE = 1008;
public static void sendKey(char keychar, int keycode) {
// TODO: Android -> AWT keycode mapping
@@ -38,6 +33,6 @@ public class AWTInputBridge {
}
public static native void nativeSendData(int type, int i1, int i2, int i3, int i4);
public static native void nativePutClipboard(String data);
@SuppressWarnings("unused") public static native void nativePutClipboard(String data); //TODO: feed the AWT clipboard
public static native void nativeMoveWindow(int xoff, int yoff);
}

View File

@@ -24,13 +24,14 @@ package net.kdt.pojavlaunch;
* 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 << 0;
public static final int SHIFT_MASK = 1; //first bit
/**
* This flag indicates that the Control key was down when the event

View File

@@ -2,8 +2,6 @@ package net.kdt.pojavlaunch;
import android.os.Build;
import java.util.Locale;
/**
* This class aims at providing a simple and easy way to deal with the device architecture.
*/

View File

@@ -1,26 +1,33 @@
package net.kdt.pojavlaunch;
import static androidx.core.content.FileProvider.getUriForFile;
import android.app.Activity;
import android.content.*;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.*;
import androidx.appcompat.app.*;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.*;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.gson.JsonSyntaxException;
import com.kdt.pickafile.*;
import java.io.*;
import com.kdt.pickafile.FileListView;
import com.kdt.pickafile.FileSelectedListener;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.customcontrols.*;
import net.kdt.pojavlaunch.customcontrols.ControlData;
import net.kdt.pojavlaunch.customcontrols.ControlDrawerData;
import net.kdt.pojavlaunch.customcontrols.ControlLayout;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import java.io.File;
import java.io.IOException;
public class CustomControlsActivity extends BaseActivity {
@@ -74,31 +81,6 @@ public class CustomControlsActivity extends BaseActivity {
}
mDrawerLayout.closeDrawers();
});
/*mDrawerNavigationView.setNavigationItemSelectedListener(
menuItem -> {
switch (menuItem.getItemId()) {
case R.id.menu_ctrl_load:
load(mControlLayout);
break;
case R.id.menu_ctrl_add:
mControlLayout.addControlButton(new ControlData("New"));
break;
case R.id.menu_ctrl_add_drawer:
mControlLayout.addDrawer(new ControlDrawerData());
break;
case R.id.menu_ctrl_selectdefault:
dialogSelectDefaultCtrl(mControlLayout);
break;
case R.id.menu_ctrl_save:
save(false, mControlLayout);
break;
}
//Toast.makeText(MainActivity.this, menuItem.getTitle() + ":" + menuItem.getItemId(), Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawers();
return true;
});
*/
mControlLayout.setActivity(this);
mControlLayout.setModifiable(true);
@@ -149,18 +131,13 @@ public class CustomControlsActivity extends BaseActivity {
builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, null);
if (exit) {
builder.setNeutralButton(R.string.mcn_exit_call, new AlertDialog.OnClickListener(){
@Override
public void onClick(DialogInterface p1, int p2) {
layout.setModifiable(false);
if(ctx instanceof MainActivity) {
((MainActivity) ctx).leaveCustomControls();
}else{
((CustomControlsActivity) ctx).isModified = false;
((Activity)ctx).onBackPressed();
}
// setResult(Activity.RESULT_OK, new Intent());
// CustomControlsActivity.super.onBackPressed();
builder.setNeutralButton(R.string.mcn_exit_call, (p1, p2) -> {
layout.setModifiable(false);
if(ctx instanceof MainActivity) {
((MainActivity) ctx).leaveCustomControls();
}else{
((CustomControlsActivity) ctx).isModified = false;
((Activity)ctx).onBackPressed();
}
});
}

View File

@@ -160,8 +160,8 @@ public class EfficientAndroidLWJGLKeycode {
}
public static boolean containsKey(int keycode){
return getIndexByKey(keycode) >= 0;
public static boolean containsIndex(int index){
return index >= 0;
}
public static String[] generateKeyName() {
@@ -174,10 +174,6 @@ public class EfficientAndroidLWJGLKeycode {
return androidKeyNameArray;
}
public static void execKey(KeyEvent keyEvent) {
execKey(keyEvent, getIndexByKey(keyEvent.getKeyCode()));
}
public static void execKey(KeyEvent keyEvent, int valueIndex) {
//valueIndex points to where the value is stored in the array.
CallbackBridge.holdingAlt = keyEvent.isAltPressed();
@@ -209,10 +205,6 @@ public class EfficientAndroidLWJGLKeycode {
return Arrays.binarySearch(sAndroidKeycodes, key);
}
public static short getValue(int key){
return sLwjglKeycodes[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

View File

@@ -1,7 +1,7 @@
package net.kdt.pojavlaunch;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
@@ -13,6 +13,7 @@ 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);

View File

@@ -36,12 +36,12 @@ public class FatalErrorActivity extends AppCompatActivity {
}
public static void showError(Context ctx, String savePath, boolean storageAllow, Throwable th) {
Intent ferrorIntent = new Intent(ctx, FatalErrorActivity.class);
ferrorIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
ferrorIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ferrorIntent.putExtra("throwable", th);
ferrorIntent.putExtra("savePath", savePath);
ferrorIntent.putExtra("storageAllow", storageAllow);
ctx.startActivity(ferrorIntent);
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);
}
}

View File

@@ -2,12 +2,10 @@ package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.OpenableColumns;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

View File

@@ -5,11 +5,8 @@ import java.util.*;
import net.kdt.pojavlaunch.value.*;
@Keep
@SuppressWarnings("unused") // all unused fields here are parts of JSON structures
public class JMinecraftVersionList {
public static final String TYPE_OLD_ALPHA = "old_alpha";
public static final String TYPE_OLD_BETA = "old_beta";
public static final String TYPE_RELEASE = "release";
public static final String TYPE_SNAPSHOT = "snapshot";
public Map<String, String> latest;
public Version[] versions;

View File

@@ -1,10 +1,8 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Architecture.archAsString;
import static net.kdt.pojavlaunch.Tools.NATIVE_LIB_DIR;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

View File

@@ -19,6 +19,7 @@ import java.util.zip.ZipFile;
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.*;
import net.kdt.pojavlaunch.utils.*;
import org.lwjgl.glfw.*;
@@ -281,8 +282,7 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
List<String> javaArgList = new ArrayList<String>();
// Enable Caciocavallo
JREUtils.jreReleaseList = JREUtils.readJREReleaseProperties(LauncherPreferences.PREF_DEFAULT_RUNTIME);
Tools.getCacioJavaArgs(javaArgList,JREUtils.jreReleaseList.get("JAVA_VERSION").startsWith("1.8.0"));
Tools.getCacioJavaArgs(javaArgList,MultiRTUtils.getSelectedRuntime().javaVersion == 8);
if (javaArgs != null) {
javaArgList.addAll(Arrays.asList(javaArgs.split(" ")));
@@ -302,7 +302,7 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
Logger.getInstance().appendToLog("Info: Java arguments: " + Arrays.toString(javaArgList.toArray(new String[0])));
return JREUtils.launchJavaVM(this, null,javaArgList);
return JREUtils.launchJavaVM(this, null,javaArgList, LauncherPreferences.PREF_CUSTOM_JAVA_ARGS);
} catch (Throwable th) {
Tools.showError(this, th, true);
return -1;

View File

@@ -165,9 +165,7 @@ public class LauncherActivity extends BaseActivity {
ExtraCore.addExtraListener(ExtraConstants.LAUNCH_GAME, mLaunchGameListener);
new AsyncVersionList().getVersionList(versions -> {
ExtraCore.setValue(ExtraConstants.RELEASE_TABLE, versions);
});
new AsyncVersionList().getVersionList(versions -> ExtraCore.setValue(ExtraConstants.RELEASE_TABLE, versions));
mProgressLayout.observe(ProgressLayout.DOWNLOAD_MINECRAFT);
mProgressLayout.observe(ProgressLayout.UNPACK_RUNTIME);
@@ -216,8 +214,8 @@ public class LauncherActivity extends BaseActivity {
/** Custom implementation to feel more natural when a backstack isn't present */
@Override
public void onBackPressed() {
if(isFragmentVisible(MicrosoftLoginFragment.TAG)){
MicrosoftLoginFragment fragment = (MicrosoftLoginFragment) getSupportFragmentManager().findFragmentByTag(MicrosoftLoginFragment.TAG);
MicrosoftLoginFragment fragment = (MicrosoftLoginFragment) getVisibleFragment(MicrosoftLoginFragment.TAG);
if(fragment != null){
if(fragment.canGoBack()){
fragment.goBack();
return;
@@ -232,14 +230,20 @@ public class LauncherActivity extends BaseActivity {
LauncherPreferences.computeNotchSize(this);
}
private boolean isFragmentVisible(String tag){
private Fragment getVisibleFragment(String tag){
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
return fragment != null && fragment.isVisible();
if(fragment != null && fragment.isVisible()) {
return fragment;
}
return null;
}
private boolean isFragmentVisible(int id){
private Fragment getVisibleFragment(int id){
Fragment fragment = getSupportFragmentManager().findFragmentById(id);
return fragment != null && fragment.isVisible();
if(fragment != null && fragment.isVisible()) {
return fragment;
}
return null;
}
private void askForStoragePermission(){

View File

@@ -27,9 +27,8 @@ public class Logger {
private Logger(String fileName){
mLogFile = new File(Tools.DIR_GAME_HOME, fileName);
// Make a new instance of the log file
mLogFile.delete();
// Default PrintStream constructor will overwrite the file for us
try {
mLogFile.createNewFile();
mLogStream = new PrintStream(mLogFile.getAbsolutePath());
}catch (IOException e){e.printStackTrace();}
@@ -62,8 +61,7 @@ public class Logger {
/** Reset the log file, effectively erasing any previous logs */
public void reset(){
try{
mLogFile.delete();
mLogFile.createNewFile();
//Refer to line 30
mLogStream = new PrintStream(mLogFile.getAbsolutePath());
}catch (IOException e){ e.printStackTrace();}
}
@@ -80,8 +78,7 @@ public class Logger {
* @return Whether the log should be censored
*/
private static boolean shouldCensorLog(String text){
if(text.contains("Session ID is")) return true;
return false;
return text.contains("Session ID is");
}
/** Small listener for anything listening to the log */

View File

@@ -1,6 +1,6 @@
// 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
*------------------------------------------------------------------------
@@ -30,6 +30,7 @@
package net.kdt.pojavlaunch;
@SuppressWarnings("unused")
public class LwjglGlfwKeycode {
/** The unknown key. */
public static final short GLFW_KEY_UNKNOWN = 0; // should be -1

View File

@@ -29,7 +29,6 @@ import androidx.drawerlayout.widget.*;
import com.kdt.LoggerView;
import java.io.*;
import java.util.*;
import net.kdt.pojavlaunch.customcontrols.*;
import net.kdt.pojavlaunch.customcontrols.keyboard.LwjglCharSender;
@@ -53,7 +52,6 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
volatile public static boolean isInputStackCall;
public float scaleFactor = 1;
private boolean mIsResuming = false;
public static TouchCharInput touchCharInput;
private MinecraftGLSurface minecraftGLView;
@@ -243,7 +241,6 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
@Override
public void onResume() {
super.onResume();
mIsResuming = true;
if(mGyroControl != null) mGyroControl.enable();
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 1);
}
@@ -255,7 +252,6 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ESCAPE);
}
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 0);
mIsResuming = false;
super.onPause();
}
@@ -322,38 +318,23 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
Tools.LOCAL_RENDERER = LauncherPreferences.PREF_RENDERER;
}
Logger.getInstance().appendToLog("--------- beginning with launcher debug");
Logger.getInstance().appendToLog("Info: Launcher version: " + BuildConfig.VERSION_NAME);
printLauncherInfo();
if (Tools.LOCAL_RENDERER.equals("vulkan_zink")) {
checkVulkanZinkIsSupported();
}
checkLWJGL3Installed();
JREUtils.jreReleaseList = JREUtils.readJREReleaseProperties();
Logger.getInstance().appendToLog("Architecture: " + Architecture.archAsString(Tools.DEVICE_ARCHITECTURE));
checkJavaArgsIsLaunchable(JREUtils.jreReleaseList.get("JAVA_VERSION"));
// appendlnToLog("Info: Custom Java arguments: \"" + LauncherPreferences.PREF_CUSTOM_JAVA_ARGS + "\"");
Logger.getInstance().appendToLog("Info: Selected Minecraft version: " + mVersionId);
JREUtils.redirectAndPrintJRELog();
LauncherProfiles.update();
Tools.launchMinecraft(this, mProfile, minecraftProfile, mVersionId);
}
private void checkJavaArgsIsLaunchable(String jreVersion) throws Throwable {
Logger.getInstance().appendToLog("Info: Custom Java arguments: \"" + LauncherPreferences.PREF_CUSTOM_JAVA_ARGS + "\"");
}
private void checkLWJGL3Installed() {
File lwjgl3dir = new File(Tools.DIR_GAME_HOME, "lwjgl3");
if (!lwjgl3dir.exists() || lwjgl3dir.isFile() || lwjgl3dir.list().length == 0) {
Logger.getInstance().appendToLog("Error: LWJGL3 was not installed!");
throw new RuntimeException(getString(R.string.mcn_check_fail_lwjgl));
} else {
Logger.getInstance().appendToLog("Info: LWJGL3 directory: " + Arrays.toString(lwjgl3dir.list()));
}
private void printLauncherInfo() {
Logger logger = Logger.getInstance();
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: " + mVersionId);
logger.appendToLog("Info: Custom Java arguments: \"" + LauncherPreferences.PREF_CUSTOM_JAVA_ARGS + "\"");
}
private void checkVulkanZinkIsSupported() {
@@ -366,26 +347,6 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
}
}
public void printStream(InputStream stream) {
try {
BufferedReader buffStream = new BufferedReader(new InputStreamReader(stream));
String line = null;
while ((line = buffStream.readLine()) != null) {
Logger.getInstance().appendToLog(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String fromArray(List<String> arr) {
StringBuilder s = new StringBuilder();
for (String exec : arr) {
s.append(" ").append(exec);
}
return s.toString();
}
private void dialogSendCustomKey() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.control_customkey);
@@ -424,16 +385,6 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
}
private void openLogOutput() {
loggerView.setVisibility(View.VISIBLE);
mIsResuming = false;
}
public void closeLogOutput(View view) {
loggerView.setVisibility(View.GONE);
mIsResuming = true;
}
public void toggleMenu(View v) {
drawerLayout.openDrawer(Gravity.RIGHT);
}
public static void toggleMouse(Context ctx) {
@@ -486,12 +437,12 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
sb.setMax(275);
tmpMouseSpeed = (int) ((LauncherPreferences.PREF_MOUSESPEED*100));
sb.setProgress(tmpMouseSpeed-25);
tv.setText(tmpMouseSpeed +" %");
tv.setText(getString(R.string.percent_format, tmpGyroSensitivity));
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
tmpMouseSpeed = i+25;
tv.setText(tmpMouseSpeed +" %");
tv.setText(getString(R.string.percent_format, tmpGyroSensitivity));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@@ -501,7 +452,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
b.setView(v);
b.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> {
LauncherPreferences.PREF_MOUSESPEED = ((float)tmpMouseSpeed)/100f;
LauncherPreferences.DEFAULT_PREF.edit().putInt("mousespeed",tmpMouseSpeed).commit();
LauncherPreferences.DEFAULT_PREF.edit().putInt("mousespeed",tmpMouseSpeed).apply();
dialogInterface.dismiss();
System.gc();
});
@@ -526,12 +477,12 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
sb.setMax(275);
tmpGyroSensitivity = (int) ((LauncherPreferences.PREF_GYRO_SENSITIVITY*100));
sb.setProgress(tmpGyroSensitivity -25);
tv.setText(tmpGyroSensitivity +" %");
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(tmpGyroSensitivity +" %");
tv.setText(getString(R.string.percent_format, tmpGyroSensitivity));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@@ -541,7 +492,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
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).commit();
LauncherPreferences.DEFAULT_PREF.edit().putInt("gyroSensitivity", tmpGyroSensitivity).apply();
dialogInterface.dismiss();
System.gc();
});
@@ -589,6 +540,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
}
});
}
@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(() -> {

View File

@@ -26,18 +26,16 @@ import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import net.kdt.pojavlaunch.customcontrols.ControlLayout;
import net.kdt.pojavlaunch.utils.MathUtils;
import net.kdt.pojavlaunch.customcontrols.gamepad.Gamepad;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.JREUtils;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import net.kdt.pojavlaunch.utils.MathUtils;
import org.lwjgl.glfw.CallbackBridge;
@@ -59,6 +57,7 @@ public class MinecraftGLSurface extends View implements GrabListener{
private final MCOptionUtils.MCOptionListener mGuiScaleListener = () -> mGuiScale = getMcScale();
/* 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;
@@ -108,9 +107,7 @@ public class MinecraftGLSurface extends View implements GrabListener{
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q);
mHandler.sendEmptyMessageDelayed(MSG_DROP_ITEM_BUTTON_CHECK, 600);
}
return;
}
}
};
@@ -202,6 +199,7 @@ public class MinecraftGLSurface extends View implements GrabListener{
* 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;
@@ -420,7 +418,6 @@ public class MinecraftGLSurface extends View implements GrabListener{
}
//TODO MOVE THIS SOMEWHERE ELSE
private boolean debugErrored = false;
/** The input event for mouse with a captured pointer */
@RequiresApi(26)
@Override
@@ -486,23 +483,13 @@ public class MinecraftGLSurface extends View implements GrabListener{
}
int index = EfficientAndroidLWJGLKeycode.getIndexByKey(eventKeycode);
if(index >= 0) {
//Toast.makeText(this,"THIS IS A KEYBOARD EVENT !", Toast.LENGTH_SHORT).show();
if(EfficientAndroidLWJGLKeycode.containsIndex(index)) {
EfficientAndroidLWJGLKeycode.execKey(event, index);
return true;
}
// Some events will be generated an infinite number of times when no consumed
if((event.getFlags() & KeyEvent.FLAG_FALLBACK) == KeyEvent.FLAG_FALLBACK) return true;
return false;
}
/** Get the mouse direction as a string */
private String getMoving(float pos, boolean xOrY) {
if (pos == 0) return "STOPPED";
if (pos > 0) return xOrY ? "RIGHT" : "DOWN";
return xOrY ? "LEFT" : "UP";
return (event.getFlags() & KeyEvent.FLAG_FALLBACK) == KeyEvent.FLAG_FALLBACK;
}
/** Convert the mouse button, then send it
@@ -569,9 +556,6 @@ public class MinecraftGLSurface extends View implements GrabListener{
}
CallbackBridge.sendUpdateWindowSize(windowWidth, windowHeight);
//getMcScale();
//Toast.makeText(getContext(), "width: " + width, Toast.LENGTH_SHORT).show();
//Toast.makeText(getContext(), "height: " + height, Toast.LENGTH_SHORT).show();
}
@@ -591,8 +575,8 @@ public class MinecraftGLSurface extends View implements GrabListener{
new Thread(() -> {
try {
// Wait until the listener is attached
while (mSurfaceReadyListener == null){
Thread.sleep(100);
synchronized(mSurfaceReadyListenerLock) {
if(mSurfaceReadyListener == null) mSurfaceReadyListenerLock.wait();
}
mSurfaceReadyListener.isReady();
@@ -631,7 +615,9 @@ public class MinecraftGLSurface extends View implements GrabListener{
}
public void setSurfaceReadyListener(SurfaceReadyListener listener){
mSurfaceReadyListener = listener;
synchronized (mSurfaceReadyListenerLock) {
mSurfaceReadyListener = listener;
mSurfaceReadyListenerLock.notifyAll();
}
}
}

View File

@@ -33,13 +33,13 @@ public class PojavApplication extends Application {
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
crashFile.getParentFile().mkdirs();
crashFile.createNewFile();
File crashHome = crashFile.getParentFile();
if(crashHome != null) crashHome.mkdirs();
PrintStream crashStream = new PrintStream(crashFile);
crashStream.append("PojavLauncher crash report\n");
crashStream.append(" - Time: " + DateFormat.getDateTimeInstance().format(new Date()) + "\n");
crashStream.append(" - Device: " + Build.PRODUCT + " " + Build.MODEL + "\n");
crashStream.append(" - Android version: " + Build.VERSION.RELEASE + "\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));
@@ -62,7 +62,7 @@ public class PojavApplication extends Application {
Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent();
//Tools.DIR_HOME_JRE = Tools.DIR_DATA + "/jre_runtime".replace("/data/user/0", "/data/data");
Tools.DIR_ACCOUNT_OLD = Tools.DIR_DATA + "/Users";
Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts";
Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts";
// Tools.FILE_ACCOUNT_JSON = getFilesDir().getAbsolutePath() + "/account_profiles.json";

View File

@@ -1,25 +1,16 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.JsonSyntaxException;
import java.io.File;
import java.io.IOException;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
public class PojavProfile {
private static final String PROFILE_PREF = "pojav_profile";
private static final String PROFILE_PREF_FILE = "file";
public static String PROFILE_PREF_TEMP_CONTENT = "tempContent";
public static SharedPreferences getPrefs(Context ctx) {
return ctx.getSharedPreferences(PROFILE_PREF, Context.MODE_PRIVATE);
@@ -29,34 +20,6 @@ public class PojavProfile {
return MinecraftAccount.load(profileName == null ? getCurrentProfileName(ctx) : profileName);
}
public static MinecraftAccount getTempProfileContent() {
try {
MinecraftAccount account = MinecraftAccount.parse(Tools.read(Tools.DIR_DATA+"/cache/tempacc.json"));
if (account.accessToken == null) {
account.accessToken = "0";
}
if (account.clientToken == null) {
account.clientToken = "0";
}
if (account.profileId == null) {
account.profileId = "00000000-0000-0000-0000-000000000000";
}
if (account.username == null) {
account.username = "0";
}
if (account.selectedVersion == null) {
account.selectedVersion = "1.7.10";
}
if (account.msaRefreshToken == null) {
account.msaRefreshToken = "0";
}
return account;
}catch (IOException e) {
Log.e(MinecraftAccount.class.getName(), "Caught an exception while loading the temporary profile",e);
return null;
}
}
public static String getCurrentProfileName(Context ctx) {
String name = getPrefs(ctx).getString(PROFILE_PREF_FILE, "");
// A dirty fix
@@ -67,7 +30,7 @@ public class PojavProfile {
return name;
}
public static boolean setCurrentProfile(@NonNull Context ctx, @Nullable Object obj) {
public static void setCurrentProfile(@NonNull Context ctx, @Nullable Object obj) {
SharedPreferences.Editor pref = getPrefs(ctx).edit();
try { if (obj instanceof String) {
@@ -80,12 +43,7 @@ public class PojavProfile {
throw new IllegalArgumentException("Profile must be String.class or null");
}
} finally {
return pref.commit();
pref.apply();
}
}
public static boolean isFileType(Context ctx) {
return new File(Tools.DIR_ACCOUNT_NEW + "/" + PojavProfile.getCurrentProfileName(ctx) + ".json").exists();
}
}

View File

@@ -149,8 +149,6 @@ public final class Tools {
LauncherProfiles.update();
String gamedirPath = Tools.getGameDirPath(minecraftProfile);
if(minecraftProfile.javaArgs != null && !minecraftProfile.javaArgs.isEmpty())
LauncherPreferences.PREF_CUSTOM_JAVA_ARGS = minecraftProfile.javaArgs;
// Pre-process specific files
disableSplash(gamedirPath);
@@ -164,7 +162,7 @@ public final class Tools {
List<String> javaArgList = new ArrayList<String>();
getCacioJavaArgs(javaArgList, JREUtils.jreReleaseList.get("JAVA_VERSION").startsWith("1.8.0"));
getCacioJavaArgs(javaArgList, MultiRTUtils.getSelectedRuntime().javaVersion == 8);
if (versionInfo.logging != null) {
String configFile = Tools.DIR_DATA + "/security/" + versionInfo.logging.client.file.id.replace("client", "log4j-rce-patch");
@@ -181,7 +179,9 @@ public final class Tools {
javaArgList.addAll(Arrays.asList(launchArgs));
// ctx.appendlnToLog("full args: "+javaArgList.toString());
FFmpegPlugin.discover(activity);
JREUtils.launchJavaVM(activity, gamedirPath, javaArgList);
String args = LauncherPreferences.PREF_CUSTOM_JAVA_ARGS;
if(Tools.isValidString(minecraftProfile.javaArgs)) args = minecraftProfile.javaArgs;
JREUtils.launchJavaVM(activity, gamedirPath, javaArgList, args);
}
public static String getGameDirPath(@NonNull MinecraftProfile minecraftProfile){
@@ -976,4 +976,8 @@ public final class Tools {
if(terminatorIndex == -1) return null;
return input.substring(whatForStart, terminatorIndex);
}
public static boolean isValidString(String string) {
return string != null && !string.isEmpty();
}
}

View File

@@ -6,7 +6,6 @@ import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
@@ -52,6 +51,7 @@ public class Touchpad extends FrameLayout implements GrabListener{
init();
}
@SuppressWarnings("accessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent reports input details from the touch screen
@@ -130,7 +130,7 @@ public class Touchpad extends FrameLayout implements GrabListener{
/** Enable the touchpad */
public void enable(){
setVisibility(VISIBLE);
placeMouseAt(currentDisplayMetrics.widthPixels / 2, currentDisplayMetrics.heightPixels / 2);
placeMouseAt(currentDisplayMetrics.widthPixels / 2f, currentDisplayMetrics.heightPixels / 2f);
}
/** Disable the touchpad and hides the mouse */

View File

@@ -5,16 +5,12 @@ import com.google.gson.JsonSyntaxException;
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
import net.kdt.pojavlaunch.Tools;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.lwjgl.glfw.CallbackBridge;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class LayoutConverter {
@@ -49,12 +45,12 @@ public class LayoutConverter {
for(int i = 0; i < layoutMainArray.length(); i++) {
JSONObject button = layoutMainArray.getJSONObject(i);
ControlData n_button = Tools.GLOBAL_GSON.fromJson(button.toString(), ControlData.class);
if((n_button.dynamicX == null || n_button.dynamicX.isEmpty())&&button.has("x")) {
if(!Tools.isValidString(n_button.dynamicX) && button.has("x")) {
double buttonC = button.getDouble("x");
double ratio = buttonC/CallbackBridge.physicalWidth;
n_button.dynamicX = ratio + " * ${screen_width}";
}
if((n_button.dynamicY == null || n_button.dynamicY.isEmpty())&&button.has("y")) {
if(!Tools.isValidString(n_button.dynamicY) && button.has("y")) {
double buttonC = button.getDouble("y");
double ratio = buttonC/CallbackBridge.physicalHeight;
n_button.dynamicY = ratio + " * ${screen_height}";
@@ -67,12 +63,12 @@ public class LayoutConverter {
JSONObject button = layoutDrawerArray.getJSONObject(i);
JSONObject buttonProperties = button.getJSONObject("properties");
ControlDrawerData n_button = Tools.GLOBAL_GSON.fromJson(button.toString(), ControlDrawerData.class);
if((n_button.properties.dynamicX == null || n_button.properties.dynamicX.isEmpty())&&buttonProperties.has("x")) {
if(!Tools.isValidString(n_button.properties.dynamicX) && buttonProperties.has("x")) {
double buttonC = buttonProperties.getDouble("x");
double ratio = buttonC/CallbackBridge.physicalWidth;
n_button.properties.dynamicX = ratio + " * ${screen_width}";
}
if((n_button.properties.dynamicY == null || n_button.properties.dynamicY.isEmpty())&&buttonProperties.has("y")) {
if(!Tools.isValidString(n_button.properties.dynamicY) && buttonProperties.has("y")) {
double buttonC = buttonProperties.getDouble("y");
double ratio = buttonC/CallbackBridge.physicalHeight;
n_button.properties.dynamicY = ratio + " * ${screen_height}";
@@ -95,12 +91,12 @@ public class LayoutConverter {
n_button.isDynamicBtn = button.getBoolean("isDynamicBtn");
n_button.dynamicX = button.getString("dynamicX");
n_button.dynamicY = button.getString("dynamicY");
if((n_button.dynamicX == null || n_button.dynamicX.isEmpty())&&button.has("x")) {
if(!Tools.isValidString(n_button.dynamicX) && button.has("x")) {
double buttonC = button.getDouble("x");
double ratio = buttonC/CallbackBridge.physicalWidth;
n_button.dynamicX = ratio + " * ${screen_width}";
}
if((n_button.dynamicY == null || n_button.dynamicY.isEmpty())&&button.has("y")) {
if(!Tools.isValidString(n_button.dynamicY) && button.has("y")) {
double buttonC = button.getDouble("y");
double ratio = buttonC/CallbackBridge.physicalHeight;
n_button.dynamicY = ratio + " * ${screen_height}";

View File

@@ -1,5 +1,6 @@
package net.kdt.pojavlaunch.multirt;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
@@ -14,7 +15,6 @@ import net.kdt.pojavlaunch.R;
public class MultiRTConfigDialog {
public static final int MULTIRT_PICK_RUNTIME = 2048;
public static final int MULTIRT_PICK_RUNTIME_STARTUP = 2049;
private AlertDialog mDialog;
private RecyclerView mDialogView;
@@ -24,9 +24,10 @@ public class MultiRTConfigDialog {
mDialog.show();
}
@SuppressLint("NotifyDataSetChanged") //only used to completely refresh the list, it is necessary
public void refresh() {
RecyclerView.Adapter adapter = mDialogView.getAdapter();
if(adapter != null) mDialogView.getAdapter().notifyDataSetChanged();
RecyclerView.Adapter<?> adapter = mDialogView.getAdapter();
if(adapter != null) adapter.notifyDataSetChanged();
}
/** Build the dialog behavior and style */

View File

@@ -1,6 +1,7 @@
package net.kdt.pojavlaunch.multirt;
import static net.kdt.pojavlaunch.Tools.NATIVE_LIB_DIR;
import static net.kdt.pojavlaunch.Tools.getMinecraftClientArgs;
import static org.apache.commons.io.FileUtils.listFiles;
import android.content.Context;
@@ -37,6 +38,7 @@ public class MultiRTUtils {
private static final File RUNTIME_FOLDER = new File(Tools.MULTIRT_HOME);
private static final String JAVA_VERSION_STR = "JAVA_VERSION=\"";
private static final String OS_ARCH_STR = "OS_ARCH=\"";
private static String sSelectedRuntimeName;
public static List<Runtime> getRuntimes() {
if(!RUNTIME_FOLDER.exists()) RUNTIME_FOLDER.mkdirs();
@@ -150,17 +152,23 @@ public class MultiRTUtils {
File dest = new File(RUNTIME_FOLDER,"/"+name);
if((!dest.exists()) || MultiRTUtils.forceReread(name).versionString == null) throw new RuntimeException("Selected runtime is broken!");
Tools.DIR_HOME_JRE = dest.getAbsolutePath();
sSelectedRuntimeName = name;
JREUtils.relocateLibPath();
}
public static Runtime getSelectedRuntime() {
if(sSelectedRuntimeName == null) throw new RuntimeException("getSelectedRuntime() called before a runtime was selected");
return read(sSelectedRuntimeName);
}
public static Runtime forceReread(String name) {
sCache.remove(name);
return read(name);
}
public static Runtime read(String name) {
if(sCache.containsKey(name)) return sCache.get(name);
Runtime returnRuntime;
Runtime returnRuntime = sCache.get(name);
if(returnRuntime != null) return returnRuntime;
File release = new File(RUNTIME_FOLDER,name+"/release");
if(!release.exists()) {
return new Runtime(name);

View File

@@ -2,7 +2,7 @@ package net.kdt.pojavlaunch.multirt;
import static net.kdt.pojavlaunch.PojavApplication.sExecutorService;
import android.app.ProgressDialog;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
@@ -53,6 +53,7 @@ public class RTRecyclerViewAdapter extends RecyclerView.Adapter<RTRecyclerViewAd
return LauncherPreferences.PREF_DEFAULT_RUNTIME.equals(rt.name);
}
@SuppressLint("NotifyDataSetChanged") //not a problem, given the typical size of the list
public void setDefault(Runtime rt){
LauncherPreferences.PREF_DEFAULT_RUNTIME = rt.name;
LauncherPreferences.DEFAULT_PREF.edit().putString("defaultRuntime",LauncherPreferences.PREF_DEFAULT_RUNTIME).apply();

View File

@@ -5,12 +5,6 @@ import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import net.kdt.pojavlaunch.Tools;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FFmpegPlugin {
public static boolean isAvailable = false;
public static String libraryPath;

View File

@@ -15,7 +15,7 @@ public class BackButtonPreference extends Preference {
init();
}
public BackButtonPreference(Context context) {
@SuppressWarnings("unused") public BackButtonPreference(Context context) {
this(context, null);
}

View File

@@ -1,5 +1,6 @@
package net.kdt.pojavlaunch.prefs;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
@@ -23,12 +24,13 @@ public class CustomSeekBarPreference extends SeekBarPreference {
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();
try(TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference, defStyleAttr, defStyleRes)) {
mMin = a.getInt(R.styleable.SeekBarPreference_min, 0);
}
}
public CustomSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
@@ -39,7 +41,7 @@ public class CustomSeekBarPreference extends SeekBarPreference {
this(context, attrs, R.attr.seekBarPreferenceStyle);
}
public CustomSeekBarPreference(Context context) {
@SuppressWarnings("unused") public CustomSeekBarPreference(Context context) {
this(context, null);
}

View File

@@ -97,40 +97,12 @@ public class LauncherPreferences {
PREF_BUTTON_ALL_CAPS = DEFAULT_PREF.getBoolean("buttonAllCaps", true);
PREF_DUMP_SHADERS = DEFAULT_PREF.getBoolean("dump_shaders", false);
/*
if (PREF_CUSTOM_JAVA_ARGS.isEmpty()) {
String DEFAULT_JAVA_ARGS = "";
"-Xms" + (androidHeap > 800 ? 800 : androidHeap) + "m " +
// (32bit) More than 800mb may make JVM not allocateable and crash
"-Xmx" + (doubleAndroidHeap > 800 ? 800 : doubleAndroidHeap) + "m" +
"-XX:+UseG1GC " +
"-XX:+ParallelRefProcEnabled " +
"-XX:MaxGCPauseMillis=200 " +
"-XX:+UnlockExperimentalVMOptions " +
"-XX:+AlwaysPreTouch " +
"-XX:G1NewSizePercent=30 " +
"-XX:G1MaxNewSizePercent=40 " +
"-XX:G1HeapRegionSize=8M " +
"-XX:G1ReservePercent=20 " +
"-XX:G1HeapWastePercent=5 " +
"-XX:G1MixedGCCountTarget=4 " +
"-XX:InitiatingHeapOccupancyPercent=15 " +
"-XX:G1MixedGCLiveThresholdPercent=90 " +
"-XX:G1RSetUpdatingPauseTimePercent=5 " +
"-XX:SurvivorRatio=32 " +
"-XX:+PerfDisableSharedMem " +
"-XX:MaxTenuringThreshold=1";
PREF_CUSTOM_JAVA_ARGS = DEFAULT_JAVA_ARGS;
DEFAULT_PREF.edit().putString("javaArgs", DEFAULT_JAVA_ARGS).commit();
}
*/
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, "")).commit();
PREF_CUSTOM_JAVA_ARGS.replace(arg, "")).apply();
}
}
if(DEFAULT_PREF.contains("defaultRuntime")) {

View File

@@ -12,7 +12,7 @@ import net.kdt.pojavlaunch.multirt.MultiRTConfigDialog;
public class RuntimeManagerPreference extends Preference{
private MultiRTConfigDialog mDialogScreen;
public RuntimeManagerPreference(Context ctx) {
@SuppressWarnings("unused") public RuntimeManagerPreference(Context ctx) {
this(ctx, null);
}

View File

@@ -8,6 +8,7 @@ import android.view.ViewGroup;
import android.widget.BaseAdapter;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
@@ -71,10 +72,6 @@ public class ProfileAdapter extends BaseAdapter {
return mProfileList.indexOf(name);
}
public void fireProfileEdit() {
notifyDataSetChanged();
}
@Override
public long getItemId(int position) {
return position;
@@ -109,7 +106,7 @@ public class ProfileAdapter extends BaseAdapter {
}
extendedTextView.setCompoundDrawablesRelative(cachedIcon, null, extendedTextView.getCompoundsDrawables()[2], null);
if(minecraftProfile.name != null && !minecraftProfile.name.isEmpty())
if(Tools.isValidString(minecraftProfile.name))
extendedTextView.setText(minecraftProfile.name);
else
extendedTextView.setText(R.string.unnamed);

View File

@@ -38,7 +38,7 @@ import java.util.List;
* "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."
* - http://developer.android.com/guide/topics/providers/document-provider.html#43
* - <a href="http://developer.android.com/guide/topics/providers/document-provider.html#43">...</a>
*/
public class FolderProvider extends DocumentsProvider {
@@ -99,7 +99,9 @@ public class FolderProvider extends DocumentsProvider {
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);
for (File file : parent.listFiles()) {
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;
@@ -150,7 +152,9 @@ public class FolderProvider extends DocumentsProvider {
@Override
public String renameDocument(String documentId, String displayName) throws FileNotFoundException {
File sourceFile = getFileForDocId(documentId);
File targetFile = new File(getDocIdForFile(sourceFile.getParentFile()) + "/" + displayName);
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);
}
@@ -220,7 +224,8 @@ public class FolderProvider extends DocumentsProvider {
}
if (isInsideHome) {
if (file.isDirectory()) {
Collections.addAll(pending, file.listFiles());
File[] listing = file.listFiles();
if(listing != null) Collections.addAll(pending, listing);
} else {
if (file.getName().toLowerCase().contains(query)) {
includeFile(result, null, file);
@@ -292,7 +297,10 @@ public class FolderProvider extends DocumentsProvider {
} else if (file.canWrite()) {
flags |= Document.FLAG_SUPPORTS_WRITE;
}
if (file.getParentFile().canWrite()) flags |= Document.FLAG_SUPPORTS_DELETE;
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);

View File

@@ -24,12 +24,6 @@ public class GameService extends Service {
ContextCompat.startForegroundService(context, intent);
}
public static void stopService() {
Service gameService = sGameService.get();
if(gameService != null)
gameService.stopSelf();
}
@Override
public void onCreate() {
Tools.buildNotificationChannel(getApplicationContext());

View File

@@ -1,5 +1,6 @@
package net.kdt.pojavlaunch.services;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
@@ -16,8 +17,6 @@ import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.kdt.mcgui.ProgressLayout;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
@@ -54,6 +53,7 @@ public class ProgressService extends Service implements TaskCountListener {
.setNotificationSilent();
}
@SuppressLint("StringFormatInvalid")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null) {

View File

@@ -6,7 +6,7 @@ import android.util.Log;
import net.kdt.pojavlaunch.progresskeeper.TaskCountListener;
public class ProgressServiceKeeper implements TaskCountListener {
private Context context;
private final Context context;
public ProgressServiceKeeper(Context ctx) {
this.context = ctx;
}

View File

@@ -28,9 +28,8 @@ public class AsyncAssetManager {
* Attempt to install the java 8 runtime, if necessary
* @param am App context
* @param otherRuntimesAvailable Whether other runtimes have been detected
* @return False if no runtime, true if there is one present/
*/
public static boolean unpackRuntime(AssetManager am, boolean otherRuntimesAvailable) {
public static void unpackRuntime(AssetManager am, boolean otherRuntimesAvailable) {
/* Check if JRE is included */
String rt_version = null;
String current_rt_version = MultiRTUtils.__internal__readBinpackVersion("Internal");
@@ -40,9 +39,9 @@ public class AsyncAssetManager {
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 true; //Assume user maintains his own runtime
if(rt_version == null) return otherRuntimesAvailable; // On noruntime builds, skip if there is at least 1 runtime installed (no matter if it is 8 or not)
if(rt_version.equals(current_rt_version)) return true; //If we already have an integrated one installed, check if it's up-to-date
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;
@@ -58,8 +57,6 @@ public class AsyncAssetManager {
Log.e("JREAuto", "Internal JRE unpack failed", e);
}
});
return true; // we have at least one runtime, and it's compatible, good to go
}
/** Unpack single files, with no regard to version tracking */
@@ -97,7 +94,7 @@ public class AsyncAssetManager {
});
}
private static boolean unpackComponent(Context ctx, String component, boolean privateDirectory) throws IOException {
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;
@@ -130,12 +127,7 @@ public class AsyncAssetManager {
}
} else {
Log.i("UnpackPrep", component + ": Pack is up-to-date with the launcher, continuing...");
return false;
}
}
return true;
}
}

View File

@@ -70,7 +70,7 @@ public class AsyncMinecraftDownloader {
downloadVersionJson(versionName, verJsonDir, verInfo);
}
JMinecraftVersionList.Version originalVersion = Tools.getVersionInfo(versionName, true);
if(originalVersion.inheritsFrom != null && !originalVersion.inheritsFrom.isEmpty()) {
if(Tools.isValidString(originalVersion.inheritsFrom)) {
Log.i("Downloader", "probe: inheritsFrom="+originalVersion.inheritsFrom);
String version = originalVersion.inheritsFrom;
String downName = Tools.DIR_HOME_VERSION+"/"+version+"/"+version+".json";

View File

@@ -8,22 +8,16 @@ import android.util.Log;
import androidx.annotation.Nullable;
import com.google.gson.stream.JsonReader;
import com.kdt.mcgui.ProgressLayout;
import net.kdt.pojavlaunch.JMinecraftVersionList;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
/** Class getting the version list, and that's all really */
public class AsyncVersionList {

View File

@@ -1,7 +1,5 @@
package net.kdt.pojavlaunch.utils;
import android.util.*;
import androidx.annotation.Nullable;
import java.io.*;
@@ -12,7 +10,6 @@ import org.apache.commons.io.*;
public class DownloadUtils {
public static final String USER_AGENT = Tools.APP_NAME;
public static final Charset utf8 = Charset.forName("UTF-8");
public static void download(String url, OutputStream os) throws IOException {
download(new URL(url), os);
@@ -34,7 +31,7 @@ public class DownloadUtils {
is = conn.getInputStream();
IOUtils.copy(is, os);
} catch (IOException e) {
throw new IOException("Unable to download from " + url.toString(), e);
throw new IOException("Unable to download from " + url, e);
} finally {
if (is != null) {
try {
@@ -50,7 +47,7 @@ public class DownloadUtils {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
download(url, bos);
bos.close();
return new String(bos.toByteArray(), utf8);
return new String(bos.toByteArray(), StandardCharsets.UTF_8);
}
public static void downloadFile(String url, File out) throws IOException {

View File

@@ -21,33 +21,11 @@ public class FilteredSubList<E> extends AbstractList<E> implements List<E> {
private final ArrayList<E> mArrayList;
public FilteredSubList(Iterable<E> motherList, BasicPredicate<E> filter){
mArrayList = new ArrayList<>();
refresh(motherList, filter);
}
public FilteredSubList(E[] motherList, BasicPredicate<E> filter){
mArrayList = new ArrayList<>();
refresh(motherList, filter);
}
/**
* Rebuild the view from scratch
* @param motherList The motherlist
* @param filter The filtering "predicate"
*/
public void refresh(Iterable<E> motherList, BasicPredicate<E> filter){
if(!mArrayList.isEmpty()) mArrayList.clear();
for(E item : motherList){
if(filter.test(item)){
mArrayList.add(item);
}
}
// Should we trim ?
mArrayList.trimToSize();
}
public void refresh(E[] motherArray, BasicPredicate<E> filter){
if(!mArrayList.isEmpty()) mArrayList.clear();

View File

@@ -20,6 +20,7 @@ import java.util.*;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.plugins.FFmpegPlugin;
import net.kdt.pojavlaunch.prefs.*;
import org.lwjgl.glfw.*;
@@ -33,7 +34,6 @@ public class JREUtils {
private JREUtils() {}
public static String LD_LIBRARY_PATH;
public static Map<String, String> jreReleaseList;
public static String jvmLibraryPath;
public static String findInLdLibPath(String libName) {
@@ -92,27 +92,6 @@ public class JREUtils {
dlopen(NATIVE_LIB_DIR + "/libopenal.so");
}
public static Map<String, String> readJREReleaseProperties() throws IOException {
return readJREReleaseProperties(Tools.DIR_HOME_JRE);
}
public static Map<String, String> readJREReleaseProperties(String name) throws IOException {
Map<String, String> jreReleaseMap = new ArrayMap<>();
if (!name.contains("/")) {
name = Tools.MULTIRT_HOME + "/" + name;
}
BufferedReader jreReleaseReader = new BufferedReader(new FileReader(name + "/release"));
String currLine;
while ((currLine = jreReleaseReader.readLine()) != null) {
if (!currLine.isEmpty() || currLine.contains("=")) {
String[] keyValue = currLine.split("=");
jreReleaseMap.put(keyValue[0], keyValue[1].replace("\"", ""));
}
}
jreReleaseReader.close();
return jreReleaseMap;
}
public static void redirectAndPrintJRELog() {
Log.v("jrelog","Log starts here");
@@ -148,7 +127,6 @@ public class JREUtils {
} else {
Logger.getInstance().appendToLog("ERROR: Unable to get more log.");
}
return;
}
} catch (Throwable e) {
Log.e("jrelog-logcat", "Exception on logging thread", e);
@@ -160,8 +138,8 @@ public class JREUtils {
}
public static void relocateLibPath() throws IOException {
String JRE_ARCHITECTURE = readJREReleaseProperties().get("OS_ARCH");
public static void relocateLibPath() {
String JRE_ARCHITECTURE = MultiRTUtils.getSelectedRuntime().arch;
if (Architecture.archAsInt(JRE_ARCHITECTURE) == ARCH_X86){
JRE_ARCHITECTURE = "i386/i486/i586";
}
@@ -176,18 +154,16 @@ public class JREUtils {
String libName = is64BitsDevice() ? "lib64" : "lib";
StringBuilder ldLibraryPath = new StringBuilder();
if(FFmpegPlugin.isAvailable) {
ldLibraryPath.append(FFmpegPlugin.libraryPath+":");
ldLibraryPath.append(FFmpegPlugin.libraryPath).append(":");
}
ldLibraryPath.append(
Tools.DIR_HOME_JRE + "/" + Tools.DIRNAME_HOME_JRE + "/jli:" +
Tools.DIR_HOME_JRE + "/" + Tools.DIRNAME_HOME_JRE + ":"
);
ldLibraryPath.append(
"/system/" + libName + ":" +
"/vendor/" + libName + ":" +
"/vendor/" + libName + "/hw:" +
NATIVE_LIB_DIR
);
ldLibraryPath.append(Tools.DIR_HOME_JRE)
.append("/").append(Tools.DIRNAME_HOME_JRE)
.append("/jli:").append(Tools.DIR_HOME_JRE).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();
}
@@ -288,7 +264,7 @@ public class JREUtils {
// return ldLibraryPath;
}
public static int launchJavaVM(final Activity activity, String gameDirectory, final List<String> JVMArgs) throws Throwable {
public static int launchJavaVM(final Activity activity, String gameDirectory, final List<String> JVMArgs, final String userArgsString) throws Throwable {
JREUtils.relocateLibPath();
// For debugging only!
/*
@@ -302,7 +278,7 @@ public class JREUtils {
setJavaEnvironment(activity);
final String graphicsLib = loadGraphicsLibrary();
List<String> userArgs = getJavaArgs(activity);
List<String> userArgs = getJavaArgs(activity, userArgsString);
//Remove arguments that can interfere with the good working of the launcher
purgeArg(userArgs,"-Xms");
@@ -346,8 +322,8 @@ public class JREUtils {
* @param ctx The application context
* @return A list filled with args.
*/
public static List<String> getJavaArgs(Context ctx) {
List<String> userArguments = parseJavaArguments(LauncherPreferences.PREF_CUSTOM_JAVA_ARGS);
public static List<String> getJavaArgs(Context ctx, String userArgumentsString) {
List<String> userArguments = parseJavaArguments(userArgumentsString);
String resolvFile;
resolvFile = new File(Tools.DIR_DATA,"resolv.conf").getAbsolutePath();

View File

@@ -8,7 +8,6 @@ import android.content.res.*;
import android.os.Build;
import android.os.LocaleList;
import androidx.core.os.ConfigurationCompat;
import androidx.preference.*;
import java.util.*;
import net.kdt.pojavlaunch.prefs.*;
@@ -19,10 +18,6 @@ public class LocaleUtils extends ContextWrapper {
super(base);
}
public static Locale getLocale(){
return Locale.getDefault();
}
public static ContextWrapper setLocale(Context context) {
if (DEFAULT_PREF == null) {
DEFAULT_PREF = PreferenceManager.getDefaultSharedPreferences(context);

View File

@@ -3,13 +3,14 @@ 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 net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
/** Class here to help with various stuff to help run lower versions smoothly */
@@ -20,7 +21,7 @@ public class OldVersionsUtils {
public static void selectOpenGlVersion(JMinecraftVersionList.Version version){
// 1309989600 is 2011-07-07 2011-07-07T22:00:00+00:00
String creationDate = version.time;
if(creationDate == null || creationDate.isEmpty()){
if(!Tools.isValidString(creationDate)){
ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, "2");
return;
}
@@ -34,7 +35,9 @@ public class OldVersionsUtils {
ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, "2");
return;
}
String openGlVersion = creationDateObj.before(new Date(2011-1900, 6, 8)) ? "1" : "2";
String openGlVersion = creationDateObj.before(new Date(new GregorianCalendar(2011, 6, 8).getTimeInMillis())) ? "1" : "2";
Log.i("GL_SELECT", openGlVersion);
ExtraCore.setValue(ExtraConstants.OPEN_GL_VERSION, openGlVersion);
}catch (ParseException exception){
Log.e("GL_SELECT", exception.toString());

View File

@@ -356,4 +356,5 @@
<string name="create_profile">Create new profile</string>
<string name="preference_shader_dump_title">Enable shader dumping</string>
<string name="preference_shader_dump_description">Log converted shaders into the log file</string>
<string name="percent_format">%d%%</string>
</resources>