Compare commits

..
Author SHA1 Message Date
artdeell d120354e73 Feat[controls]: implement control layout sanitizer 2025-01-18 19:29:50 +03:00
artdeell 6b0ff501cc Chore[build]: next codename 2025-01-17 08:36:45 +03:00
artdeell 5d8cf0d2dc Feat[touch_char_input]: directly modify the Editable instead of relying on the internal TextView methods. 2025-01-17 08:28:11 +03:00
artdeell 2a44e8da69 Fix[file_provider]: check for storage before initializing 2025-01-17 08:28:11 +03:00
artdeell 097282507b Fix[fabriclike_install]: ensure array readiness before creating adapter 2025-01-17 08:28:11 +03:00
artdeell 2f34549f65 Fix[storage]: fix previous commit not starting the game 2025-01-17 08:28:11 +03:00
artdeell 9c83fc677b Fix[storage]: better ensure mounted storage
Avoids several crashes caused by Pojav running on devices without always-mounted external storage.
2025-01-17 08:28:11 +03:00
artdeell b8e5f08719 Fix[exit_hook]: move exit hook into a separate library
Fixes an issue on some devices where namespacing issues caused libbytehook to not be found when pojavexec was loaded by LWJGL.
2025-01-17 08:28:11 +03:00
artdeell 3e42bfd21f Fix[touch_char_input]: use TextWatcher instead of onTextChanged override
Avoids a bug on some devices caused by setText called by the framework early
2025-01-17 08:28:11 +03:00
Maksim Belov b28fc4a1f4 Feat[renderer]: Add LTW renderer (#6477)
* Feat[launcher]: start introducing the Tinywrapper renderer

* Feat[launcher]: add renderer, add compatibility checks

* Chore[ltw]: update to latest

* Style[code]: code cosmetic changes

* Legal[ltw]: make LTW optional

* Fix[ltw]: fix actions, add forgotten file

* Workflow[ltw]: disallow forks, allow building on error
2025-01-14 00:23:49 +03:00
Mathias-Boulay ed89b44d3b tweak(ui): make the keyboard shift the input
For some reason, when entering the settings fragment, it would have this behavior.
2025-01-13 10:54:38 +03:00
Mathias-Boulay 3c616b9d90 tweak(ui): inline the delete profile button
Makes the main ui slightly cleaner
2025-01-13 10:54:38 +03:00
Maksim Belov 208b92be83 Style[exec_hooks]: change function name, log lines, add clipboard constants 2025-01-08 16:29:40 +03:00
Maksim Belov ebe5314f28 Feat[lwjgl]: add vulkan to lwjgl dlopen hook, move hook to new file 2025-01-08 16:29:40 +03:00
Maksim Belov aadb91dc98 Whoops[exec_hooks]: do not null program unconditionally 2025-01-08 16:29:40 +03:00
Maksim Belov 6d39ab2d49 Fix[ffmpeg_plugin]: replace LD_LIBRARY_PATH/PATH for ffmpeg, switch default exec mode 2025-01-08 16:29:40 +03:00
artdeell 041838725b Fix[ffmpeg_plugin]: better FFmpeg plugin insertion
NOTE: requires a different version of the FFmpeg plugin which I haven't made yet
2025-01-08 16:29:40 +03:00
Mathias-Boulay a72451c9e7 fix(gesture): Right click not working
Turns out if you were perfectly still, it would fail. For a quick tap, it was fairly easy to create.
2025-01-07 20:21:59 +01:00
Maksim Belov 2e596cd07f Fix[renderer]: move GL4ES initialization code (#6447) 2025-01-04 02:41:02 +03:00
43 changed files with 578 additions and 673 deletions

No files matched your search

+12
View File
@@ -26,6 +26,18 @@ jobs:
distribution: 'temurin'
java-version: '8'
- name: Get LTW
uses: dawidd6/action-download-artifact@v2
continue-on-error: true
with:
github_token: ${{secrets.LTW_CLONER_SECRET}}
repo: PojavLauncherTeam/BigTinyWrapper
workflow: android.yml
workflow_conclusion: success
name: output-aar
path: app_pojavlauncher/libs
allow_forks: false
- name: Get JRE 8
uses: dawidd6/action-download-artifact@v2
with:
+2 -2
View File
@@ -51,7 +51,7 @@ def getVersionName = {
return ("LOCAL-" + "${getDate()}")
}else {
// Used by github actions
TAG_STRING = 'foxglove-' + "${getDate()}" + "-" + TAG_PART_COMMIT.toString().trim()
TAG_STRING = 'gladiolus-' + "${getDate()}" + "-" + TAG_PART_COMMIT.toString().trim()
}
}
@@ -227,5 +227,5 @@ dependencies {
// implementation 'net.sourceforge.streamsupport:streamsupport-cfuture:1.7.0'
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
}
@@ -55,7 +55,8 @@
</activity>
<activity
android:name=".LauncherActivity"
android:label="@string/app_short_name" />
android:label="@string/app_short_name"
android:windowSoftInputMode="adjustResize"/>
<activity
android:name=".ImportControlActivity"
android:configChanges="keyboard|keyboardHidden"
@@ -18,12 +18,13 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.content.res.ResourcesCompat;
@@ -188,7 +189,10 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
}
public void removeCurrentAccount(){
int position = getSelectedItemPosition();
removeAccount(getSelectedItemPosition());
}
private void removeAccount(int position) {
if(position == 0) return;
File accountFile = new File(Tools.DIR_ACCOUNT_NEW, mAccountList.get(position)+".json");
if(accountFile.exists()) accountFile.delete();
@@ -321,8 +325,9 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
BitmapDrawable oldBitmapDrawable = mHeadDrawable;
if(mSelectecAccount != null){
ExtendedTextView view = ((ExtendedTextView) getSelectedView());
if(view != null){
View layout = getSelectedView();
if(layout != null){
ExtendedTextView view = layout.findViewById(R.id.account_item);
Bitmap bitmap = mSelectecAccount.getSkinFace();
if(bitmap != null) {
mHeadDrawable = new BitmapDrawable(getResources(), bitmap);
@@ -339,8 +344,7 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
}
}
private static class AccountAdapter extends ArrayAdapter<String> {
private class AccountAdapter extends ArrayAdapter<String> {
private final HashMap<String, Drawable> mImageCache = new HashMap<>();
public AccountAdapter(@NonNull Context context, int resource, @NonNull String[] objects) {
@@ -349,20 +353,19 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return getView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_minecraft_account, parent, false);
}
ExtendedTextView textview = (ExtendedTextView) convertView;
ExtendedTextView textview = convertView.findViewById(R.id.account_item);
ImageView deleteButton = convertView.findViewById(R.id.delete_account_button);
textview.setText(super.getItem(position));
// Handle the "Add account section"
if(position == 0) textview.setCompoundDrawables(ResourcesCompat.getDrawable(parent.getResources(), R.drawable.ic_add, null), null, null, null);
if(position == 0) {
textview.setCompoundDrawables(ResourcesCompat.getDrawable(parent.getResources(), R.drawable.ic_add, null), null, null, null);
deleteButton.setVisibility(View.GONE);
}
else {
String username = super.getItem(position);
Drawable accountHead = mImageCache.get(username);
@@ -371,9 +374,37 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
mImageCache.put(username, accountHead);
}
textview.setCompoundDrawables(accountHead, null, null, null);
deleteButton.setVisibility(View.VISIBLE);
deleteButton.setOnClickListener(v -> {
showDeleteDialog(getContext(), position);
});
}
return convertView;
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View view = getDropDownView(position, convertView, parent);
view.findViewById(R.id.delete_account_button).setVisibility(View.GONE);
return view;
}
private void showDeleteDialog(Context context, int position) {
new AlertDialog.Builder(context)
.setMessage(R.string.warning_remove_account)
.setPositiveButton(android.R.string.cancel, null)
.setNeutralButton(R.string.global_delete, (dialog, which) -> {
onDetachedFromWindow();
removeAccount(position);
})
.show();
}
}
}
@@ -37,10 +37,7 @@ public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void onResume() {
super.onResume();
if(!Tools.checkStorageRoot(this)) {
startActivity(new Intent(this, MissingStorageActivity.class));
finish();
}
Tools.checkStorageInteractive(this);
}
@Override
@@ -39,7 +39,12 @@ public class ImportControlActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tools.initContextConstants(getApplicationContext());
if(Tools.checkStorageInteractive(this)) {
Tools.initStorageConstants(getApplicationContext());
}else {
// Return early, no initialization needed.
return;
}
setContentView(R.layout.activity_import_control);
mEditText = findViewById(R.id.editText_import_control_file_name);
@@ -61,6 +66,12 @@ public class ImportControlActivity extends Activity {
@Override
protected void onPostResume() {
super.onPostResume();
if(!Tools.checkStorageInteractive(this)) {
// Don't try to read the file as when this check fails, external storage paths
// are no longer valid (likely unmounted).
// checkStorageInteractive() will finish this activity for us.
return;
}
if(!mHasIntentChanged) return;
mIsFileVerified = false;
getUriData();
@@ -59,7 +59,7 @@ public class LauncherActivity extends BaseActivity {
private mcAccountSpinner mAccountSpinner;
private FragmentContainerView mFragmentView;
private ImageButton mSettingsButton, mDeleteAccountButton;
private ImageButton mSettingsButton;
private ProgressLayout mProgressLayout;
private ProgressServiceKeeper mProgressServiceKeeper;
private ModloaderInstallTracker mInstallTracker;
@@ -101,13 +101,6 @@ public class LauncherActivity extends BaseActivity {
}
};
/* 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();
@@ -200,7 +193,6 @@ public class LauncherActivity extends BaseActivity {
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);
@@ -343,7 +335,6 @@ public class LauncherActivity extends BaseActivity {
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);
}
@@ -334,6 +334,9 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
// Reload PREF_DEFAULTCTRL_PATH
// If the storage root got unmounted/unreadable we won't be able to load the file anyway,
// and MissingStorageActivity will be started.
if(!Tools.checkStorageRoot(this)) return;
LauncherPreferences.loadPreferences(getApplicationContext());
try {
mControlLayout.loadLayout(LauncherPreferences.PREF_DEFAULTCTRL_PATH);
@@ -19,6 +19,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
import net.kdt.pojavlaunch.utils.*;
import net.kdt.pojavlaunch.utils.FileUtils;
@@ -57,10 +58,15 @@ public class PojavApplication extends Application {
try {
super.onCreate();
Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent();
Tools.DIR_CACHE = getCacheDir();
Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts";
if(Tools.checkStorageRoot(this)){
// Implicitly initializes early constants and storage constants.
// Required to run the main activity properly.
LauncherPreferences.loadPreferences(this);
} else {
// In other cases, only initialize enough for the basicmost basics to work
// and not explode.
Tools.initEarlyConstants(this);
}
Tools.DEVICE_ARCHITECTURE = Architecture.getDeviceArchitecture();
//Force x86 lib directory for Asus x86 based zenfones
if(Architecture.isx86Device() && Architecture.is32BitsDevice()){
@@ -14,6 +14,7 @@ import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
public class TestStorageActivity extends Activity {
@@ -60,7 +61,8 @@ public class TestStorageActivity extends Activity {
startActivity(new Intent(this, MissingStorageActivity.class));
return;
}
//Only run them once we get a definitive green light to use storage
//Initialize constants (implicitly) and preferences after we confirm that we have storage.
LauncherPreferences.loadPreferences(this);
AsyncAssetManager.unpackComponents(this);
AsyncAssetManager.unpackSingleFiles(this);
@@ -22,12 +22,16 @@ import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.GLES30;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.provider.DocumentsContract;
import android.provider.OpenableColumns;
import android.util.ArrayMap;
@@ -68,6 +72,7 @@ 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.MCOptionUtils;
import net.kdt.pojavlaunch.utils.OldVersionsUtils;
import net.kdt.pojavlaunch.value.DependentLibrary;
import net.kdt.pojavlaunch.value.MinecraftAccount;
@@ -158,14 +163,42 @@ public final class Tools {
}
/**
* 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.
* Checks if the Pojav's storage root is accessible and read-writable. If it's not, starts
* the MissingStorageActivity and finishes the supplied activity.
* @param context the Activity that checks for storage availability
* @return whether the storage is available or not.
*/
public static void initContextConstants(Context ctx){
public static boolean checkStorageInteractive(Activity context) {
if(!Tools.checkStorageRoot(context)) {
context.startActivity(new Intent(context, MissingStorageActivity.class));
context.finish();
return false;
}
return true;
}
/**
* Initialize context constants most necessary for launcher's early startup phase
* that are not dependent on user storage.
* All values that depend on DIR_DATA and are not dependent on DIR_GAME_HOME must
* be initialized here.
* @param ctx the context for initialization.
*/
public static void initEarlyConstants(Context ctx) {
DIR_CACHE = ctx.getCacheDir();
DIR_DATA = ctx.getFilesDir().getParent();
MULTIRT_HOME = DIR_DATA+"/runtimes";
MULTIRT_HOME = DIR_DATA + "/runtimes";
DIR_ACCOUNT_NEW = DIR_DATA + "/accounts";
NATIVE_LIB_DIR = ctx.getApplicationInfo().nativeLibraryDir;
}
/**
* Initialize context constants that depend on user storage.
* Any value (in)directly dependent on DIR_GAME_HOME should be set only here.
* You ABSOLUTELY MUST check for storage presence using checkStorageRoot() before calling this.
*/
public static void initStorageConstants(Context ctx){
initEarlyConstants(ctx);
DIR_GAME_HOME = getPojavStorageRoot(ctx).getAbsolutePath();
DIR_GAME_NEW = DIR_GAME_HOME + "/.minecraft";
DIR_HOME_VERSION = DIR_GAME_NEW + "/versions";
@@ -175,7 +208,97 @@ public final class Tools {
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;
}
/**
* Optimization mods based on Sodium can mitigate the render distance issue. Check if Sodium
* or its derivative is currently installed to skip the render distance check.
* @param gameDir current game directory
* @return whether sodium or a sodium-based mod is installed
*/
private static boolean hasSodium(File gameDir) {
File modsDir = new File(gameDir, "mods");
File[] mods = modsDir.listFiles(file -> file.isFile() && file.getName().endsWith(".jar"));
if(mods == null) return false;
for(File file : mods) {
String name = file.getName();
if(name.contains("sodium") ||
name.contains("embeddium") ||
name.contains("rubidium")) return true;
}
return false;
}
/**
* Initialize OpenGL and do checks to see if the GPU of the device is affected by the render
* distance issue.
* Currently only checks whether the user has an Adreno GPU capable of OpenGL ES 3
* and surfaceless rendering installed.
* This issue is caused by a very severe limit on the amount of GL buffer names that could be allocated
* by the Adreno properietary GLES driver.
* @return whether the GPU is affected by the Large Thin Wrapper render distance issue on vanilla
*/
private static boolean affectedByRenderDistanceIssue() {
EGLDisplay eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
if(eglDisplay == EGL14.EGL_NO_DISPLAY || !EGL14.eglInitialize(eglDisplay, null, 0, null, 0)) return false;
int[] egl_attributes = new int[] {
EGL14.EGL_BLUE_SIZE, 8,
EGL14.EGL_GREEN_SIZE, 8,
EGL14.EGL_RED_SIZE, 8,
EGL14.EGL_ALPHA_SIZE, 8,
EGL14.EGL_DEPTH_SIZE, 24,
EGL14.EGL_SURFACE_TYPE, EGL14.EGL_PBUFFER_BIT,
EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
EGL14.EGL_NONE
};
EGLConfig[] config = new EGLConfig[1];
int[] num_configs = new int[]{0};
if(!EGL14.eglChooseConfig(eglDisplay, egl_attributes, 0, config, 0, 1, num_configs, 0) || num_configs[0] == 0) {
EGL14.eglTerminate(eglDisplay);
Log.e("CheckVendor", "Failed to choose an EGL config");
return false;
}
int[] egl_context_attributes = new int[] { EGL14.EGL_CONTEXT_CLIENT_VERSION, 3, EGL14.EGL_NONE };
EGLContext context = EGL14.eglCreateContext(eglDisplay, config[0], EGL14.EGL_NO_CONTEXT, egl_context_attributes, 0);
if(context == EGL14.EGL_NO_CONTEXT) {
Log.e("CheckVendor", "Failed to create a context");
EGL14.eglTerminate(eglDisplay);
return false;
}
if(!EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, context)) {
Log.e("CheckVendor", "Failed to make context current");
EGL14.eglDestroyContext(eglDisplay, context);
EGL14.eglTerminate(eglDisplay);
}
boolean is_adreno = GLES30.glGetString(GLES30.GL_VENDOR).equals("Qualcomm") &&
GLES30.glGetString(GLES30.GL_RENDERER).contains("Adreno");
Log.e("CheckVendor", "Running Adreno graphics: "+is_adreno);
EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT);
EGL14.eglDestroyContext(eglDisplay, context);
EGL14.eglTerminate(eglDisplay);
return is_adreno;
}
private static boolean checkRenderDistance(File gamedir) {
if(!"opengles3_ltw".equals(Tools.LOCAL_RENDERER)) return false;
if(!affectedByRenderDistanceIssue()) return false;
if(hasSodium(gamedir)) return false;
int renderDistance;
try {
MCOptionUtils.load();
String renderDistanceString = MCOptionUtils.get("renderDistance");
renderDistance = Integer.parseInt(renderDistanceString);
}catch (Exception e) {
Log.e("Tools", "Failed to check render distance", e);
renderDistance = 12; // Assume Minecraft's default render distance
}
// 7 is the render distance "magic number" above which MC creates too many buffers
// for Adreno's OpenGL ES implementation
return renderDistance > 7;
}
public static void launchMinecraft(final AppCompatActivity activity, MinecraftAccount minecraftAccount,
@@ -203,10 +326,27 @@ public final class Tools {
// 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);
if(checkRenderDistance(gamedir)) {
LifecycleAwareAlertDialog.DialogCreator dialogCreator = ((alertDialog, dialogBuilder) ->
dialogBuilder.setMessage(activity.getString(R.string.ltw_render_distance_warning_msg))
.setPositiveButton(android.R.string.ok, (d, w)->{}));
if(LifecycleAwareAlertDialog.haltOnDialog(activity.getLifecycle(), activity, dialogCreator)) {
return;
}
// If the code goes here, it means that the user clicked "OK". Fix the render distance.
try {
MCOptionUtils.set("renderDistance", "7");
MCOptionUtils.save();
}catch (Exception e) {
Log.e("Tools", "Failed to fix render distance setting", e);
}
}
Runtime runtime = MultiRTUtils.forceReread(Tools.pickRuntime(minecraftProfile, versionJavaRequirement));
JMinecraftVersionList.Version versionInfo = Tools.getVersionInfo(versionId);
// Pre-process specific files
@@ -1271,12 +1411,16 @@ public final class Tools {
boolean deviceHasVulkan = checkVulkanSupport(context.getPackageManager());
// Currently, only 32-bit x86 does not have the Zink binary
boolean deviceHasZinkBinary = !(Architecture.is32BitsDevice() && Architecture.isx86Device());
boolean deviceHasOpenGLES3 = JREUtils.getDetectedVersion() >= 3;
// LTW is an optional proprietary dependency
boolean appHasLtw = new File(Tools.NATIVE_LIB_DIR, "libltw.so").exists();
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;
if(rendererId.contains("ltw") && (!deviceHasOpenGLES3 || !appHasLtw)) continue;
rendererIds.add(rendererId);
rendererNames.add(defaultRendererNames[i]);
}
@@ -80,6 +80,10 @@ public class ControlLayout extends FrameLayout {
}
public void loadLayout(CustomControls controlLayout) {
boolean sanitizedModified = false;
if(controlLayout != null) {
sanitizedModified = LayoutSanitizer.sanitizeLayout(controlLayout);
}
if(mActionRow == null){
mActionRow = new ActionRow(getContext());
addView(mActionRow);
@@ -118,7 +122,7 @@ public class ControlLayout extends FrameLayout {
mLayout.scaledAt = LauncherPreferences.PREF_BUTTONSIZE;
setModified(false);
setModified(sanitizedModified);
mButtons = null;
getButtonChildren(); // Force refresh
} // loadLayout
@@ -0,0 +1,52 @@
package net.kdt.pojavlaunch.customcontrols;
import java.util.Iterator;
import java.util.List;
public class LayoutSanitizer {
// Maybe add more conditions here later?
private static boolean isInvalidFormula(String formula) {
return formula.contains("Infinity");
}
private static boolean isSaneData(ControlData controlData) {
if(controlData.getWidth() == 0 || controlData.getHeight() == 0) return false;
if(isInvalidFormula(controlData.dynamicX) || isInvalidFormula(controlData.dynamicY)) return false;
return true;
}
private static ControlData getControlData(Object dataEntry) {
if(dataEntry instanceof ControlData) {
return (ControlData) dataEntry;
}else if(dataEntry instanceof ControlDrawerData) {
return ((ControlDrawerData) dataEntry).properties;
}else throw new RuntimeException("Encountered wrong type during ControlData sanitization");
}
private static boolean sanitizeList(List<?> controlDataList) {
boolean madeChanges = false;
Iterator<?> iterator = controlDataList.iterator();
while(iterator.hasNext()) {
ControlData controlData = getControlData(iterator.next());
if(!isSaneData(controlData)) {
madeChanges = true;
iterator.remove();
}
}
return madeChanges;
}
/**
* Check all buttons in a control layout and ensure they're sane (contain values valid enough
* to be displayed properly). Removes any buttons deemed not sane.
* @param controls the original control layout.
* @return whether the sanitization process made any changes to the layout
*/
public static boolean sanitizeLayout(CustomControls controls) {
boolean madeChanges = sanitizeList(controls.mControlDataList);
if(sanitizeList(controls.mDrawerDataList)) madeChanges = true;
if(sanitizeList(controls.mJoystickDataList)) madeChanges = true;
return madeChanges;
}
}
@@ -3,8 +3,9 @@ package net.kdt.pojavlaunch.customcontrols.keyboard;
import static android.content.Context.INPUT_METHOD_SERVICE;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.Selection;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
@@ -34,31 +35,6 @@ public class TouchCharInput extends androidx.appcompat.widget.AppCompatEditText
private boolean mIsDoingInternalChanges = false;
private CharacterSenderStrategy mCharacterSender;
/**
* We take the new chars, and send them to the game.
* If less chars are present, remove some.
* The text is always cleaned up.
*/
@Override
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
super.onTextChanged(text, start, lengthBefore, lengthAfter);
if(mIsDoingInternalChanges)return;
if(mCharacterSender != null){
for(int i=0; i < lengthBefore; ++i){
mCharacterSender.sendBackspace();
}
for(int i=start, count = 0; count < lengthAfter; ++i){
mCharacterSender.sendChar(text.charAt(i));
++count;
}
}
//Reset the keyboard state
if(text.length() < 1) clear();
}
/**
* When we change from app to app, the keyboard gets disabled.
* So, we disable the object
@@ -102,13 +78,15 @@ public class TouchCharInput extends androidx.appcompat.widget.AppCompatEditText
* Clear the EditText from any leftover inputs
* It does not affect the in-game input
*/
@SuppressLint("SetTextI18n")
public void clear(){
mIsDoingInternalChanges = true;
// Edit the Editable directly as it doesn't affect the state
// of the TextView.
Editable editable = getEditableText();
editable.clear();
//Braille space, doesn't trigger keyboard auto-complete
//replacing directly the text without though setText avoids notifying changes
setText(TEXT_FILLER);
setSelection(TEXT_FILLER.length());
editable.append(TEXT_FILLER);
Selection.setSelection(editable, TEXT_FILLER.length());
mIsDoingInternalChanges = false;
}
@@ -142,6 +120,9 @@ public class TouchCharInput extends androidx.appcompat.widget.AppCompatEditText
/** This function deals with anything that has to be executed when the constructor is called */
private void setup(){
// Using TextWatcher instead of overriding onTextChanged because some Huawei firmware
// calls setText in constructor, causing havoc for our listener
addTextChangedListener(new InputTextWatcher());
setOnEditorActionListener((textView, i, keyEvent) -> {
sendEnter();
clear();
@@ -151,5 +132,38 @@ public class TouchCharInput extends androidx.appcompat.widget.AppCompatEditText
clear();
disable();
}
private class InputTextWatcher implements android.text.TextWatcher {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
/**
* We take the new chars, and send them to the game.
* If less chars are present, remove some.
* The text is always cleaned up.
*/
@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
if(mIsDoingInternalChanges) return;
if(mCharacterSender != null){
for(int i=0; i < lengthBefore; ++i){
mCharacterSender.sendBackspace();
}
for(int i=start, count = 0; count < lengthAfter; ++i){
mCharacterSender.sendChar(text.charAt(i));
++count;
}
}
}
@Override
public void afterTextChanged(Editable editable) {
if(mIsDoingInternalChanges) return;
// Moved from onTextChanged because "It is an error to attempt to make changes to s from this callback."
// reference: https://developer.android.com/reference/android/text/TextWatcher#onTextChanged(java.lang.CharSequence,%20int,%20int,%20int)
if(editable.length() < 1) clear();
}
}
}
@@ -17,14 +17,15 @@ public class RightClickGesture extends ValidatorGesture {
public final void inputEvent() {
if(!mGestureEnabled) return;
if(submit()) {
mGestureStartX = CallbackBridge.mouseX;
mGestureStartY = CallbackBridge.mouseY;
mGestureStartX = mGestureEndX = CallbackBridge.mouseX;
mGestureStartY = mGestureEndY = CallbackBridge.mouseY;
mGestureEnabled = false;
mGestureValid = true;
}
}
public void setMotion(float deltaX, float deltaY) {
System.out.println("set motion called");
mGestureEndX += deltaX;
mGestureEndY += deltaY;
}
@@ -49,6 +50,7 @@ public class RightClickGesture extends ValidatorGesture {
mGestureEnabled = true;
if(!mGestureValid || isSwitching) return;
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, mGestureEndX, mGestureEndY, LeftClickGesture.FINGER_STILL_THRESHOLD);
System.out.println("Right click: " + fingerStill);
if(!fingerStill) return;
CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, true);
CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, false);
@@ -239,6 +239,7 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
}
private void updateLoaderSpinner() {
if(mLoaderVersionArray == null) return;
mLoaderVersionSpinner.setAdapter(createAdapter(mLoaderVersionArray, mOnlyStableCheckbox.isChecked()));
}
@@ -285,6 +286,7 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
}
private void updateGameSpinner() {
if(mGameVersionArray == null) return;
mGameVersionSpinner.setAdapter(createAdapter(mGameVersionArray, mOnlyStableCheckbox.isChecked()));
}
@@ -70,8 +70,8 @@ public class LauncherPreferences {
public static void loadPreferences(Context ctx) {
//Required for the data folder.
Tools.initContextConstants(ctx);
//Required for CTRLDEF_FILE and MultiRT
Tools.initStorageConstants(ctx);
boolean isDevicePowerful = isDevicePowerful(ctx);
PREF_RENDERER = DEFAULT_PREF.getString("renderer", "opengles2");
@@ -47,7 +47,7 @@ public class FolderProvider extends DocumentsProvider {
private static final String ALL_MIME_TYPES = "*/*";
private static final File BASE_DIR = new File(Tools.DIR_GAME_HOME);
private File BASE_DIR;
private ContentResolver mContentResolver;
@@ -138,6 +138,12 @@ public class FolderProvider extends DocumentsProvider {
@Override
public boolean onCreate() {
if(Tools.checkStorageRoot(getContext())) {
Tools.initStorageConstants(getContext());
}else {
return false;
}
BASE_DIR = new File(Tools.DIR_GAME_HOME);
mContentResolver = getContext().getContentResolver();
mStorageProviderAuthortiy = getContext().getString(R.string.storageProviderAuthorities);
return true;
@@ -220,9 +220,9 @@ public class JREUtils {
if(LOCAL_RENDERER != null) {
envMap.put("POJAV_RENDERER", LOCAL_RENDERER);
if(LOCAL_RENDERER.equals("opengles3_desktopgl_angle_vulkan")) {
if(LOCAL_RENDERER.equals("opengles3_ltw")) {
envMap.put("LIBGL_ES", "3");
envMap.put("POJAVEXEC_EGL","libEGL_angle.so"); // Use ANGLE EGL
envMap.put("POJAVEXEC_EGL","libltw.so"); // Use ANGLE EGL
}
}
if(LauncherPreferences.PREF_BIG_CORE_AFFINITY) envMap.put("POJAV_BIG_CORE_AFFINITY", "1");
@@ -315,7 +315,8 @@ public class JREUtils {
System.out.println(JVMArgs);
initJavaRuntime(runtimeHome);
setupExitTrap(activity.getApplication());
JREUtils.setupExitMethod(activity.getApplication());
JREUtils.initializeGameExitHook();
chdir(gameDirectory == null ? Tools.DIR_GAME_NEW : gameDirectory.getAbsolutePath());
userArgs.add(0,"java"); //argv[0] is the program name according to C standard.
@@ -464,7 +465,7 @@ public class JREUtils {
case "opengles3":
renderLibrary = "libgl4es_114.so"; break;
case "vulkan_zink": renderLibrary = "libOSMesa.so"; break;
case "opengles3_desktopgl_angle_vulkan" : renderLibrary = "libtinywrapper.so"; break;
case "opengles3_ltw" : renderLibrary = "libltw.so"; break;
default:
Log.w("RENDER_LIBRARY", "No renderer selected, defaulting to opengles2");
renderLibrary = "libgl4es_114.so";
@@ -572,10 +573,12 @@ public class JREUtils {
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);
public static native void initializeGameExitHook();
public static native void setupExitMethod(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("exithook");
System.loadLibrary("pojavexec");
System.loadLibrary("pojavexec_awt");
}
@@ -11,7 +11,6 @@ import android.os.LocaleList;
import androidx.preference.*;
import java.util.*;
import net.kdt.pojavlaunch.prefs.*;
public class LocaleUtils extends ContextWrapper {
@@ -22,7 +21,10 @@ public class LocaleUtils extends ContextWrapper {
public static ContextWrapper setLocale(Context context) {
if (DEFAULT_PREF == null) {
DEFAULT_PREF = PreferenceManager.getDefaultSharedPreferences(context);
LauncherPreferences.loadPreferences(context);
// Too early to initialize all prefs here, as this is called by PojavApplication
// before storage checks are done and before the storage paths are initialized.
// So only initialize PREF_FORCE_ENGLISH for the check below.
PREF_FORCE_ENGLISH = DEFAULT_PREF.getBoolean("force_english", false);
}
if(PREF_FORCE_ENGLISH){
+7 -13
View File
@@ -8,18 +8,6 @@ HERE_PATH := $(LOCAL_PATH)
LOCAL_PATH := $(HERE_PATH)
include $(CLEAR_VARS)
LOCAL_MODULE := angle_gles2
LOCAL_SRC_FILES := tinywrapper/angle-gles/$(TARGET_ARCH_ABI)/libGLESv2_angle.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := tinywrapper
LOCAL_SHARED_LIBRARIES := angle_gles2
LOCAL_SRC_FILES := tinywrapper/main.c tinywrapper/string_utils.c
LOCAL_C_INCLUDES := $(LOCAL_PATH)/tinywrapper
include $(BUILD_SHARED_LIBRARY)
$(call import-module,prefab/bytehook)
LOCAL_PATH := $(HERE_PATH)
@@ -28,7 +16,6 @@ include $(CLEAR_VARS)
LOCAL_LDLIBS := -ldl -llog -landroid
# -lGLESv2
LOCAL_MODULE := pojavexec
LOCAL_SHARED_LIBRARIES := bytehook
# LOCAL_CFLAGS += -DDEBUG
# -DGLES_TEST
LOCAL_SRC_FILES := \
@@ -55,6 +42,13 @@ LOCAL_LDLIBS += -lEGL -lGLESv2
endif
include $(BUILD_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := exithook
LOCAL_LDLIBS := -ldl -llog
LOCAL_SHARED_LIBRARIES := bytehook pojavexec
LOCAL_SRC_FILES := exit_hook.c
include $(BUILD_SHARED_LIBRARY)
#ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
include $(CLEAR_VARS)
LOCAL_MODULE := linkerhook
@@ -55,25 +55,6 @@ static void gl4esi_get_display_dimensions(int* width, int* height) {
*height = 0;
}
static bool already_initialized = false;
static void gl_init_gl4es_internals() {
if(already_initialized) return;
already_initialized = true;
void* gl4es = dlopen("libgl4es_114.so", RTLD_NOLOAD);
if(gl4es == NULL) return;
void (*set_getmainfbsize)(void (*new_getMainFBSize)(int* width, int* height));
set_getmainfbsize = dlsym(gl4es, "set_getmainfbsize");
if(set_getmainfbsize == NULL) goto warn;
set_getmainfbsize(gl4esi_get_display_dimensions);
goto cleanup;
warn:
printf("gl4esinternals warning: gl4es was found but internals not initialized. expect rendering issues.\n");
cleanup:
// dlclose just decreases a ref counter, so this is fine
dlclose(gl4es);
}
gl_render_window_t* gl_init_context(gl_render_window_t *share) {
gl_render_window_t* bundle = malloc(sizeof(gl_render_window_t));
memset(bundle, 0, sizeof(gl_render_window_t));
@@ -145,10 +126,6 @@ void gl_swap_surface(gl_render_window_t* bundle) {
}
void gl_make_current(gl_render_window_t* bundle) {
// Perform initialization here as the renderer may not be loaded when gl_init or gl_init_context is called.
// Yes, even though it is dlopened on MC startup by Pojav, due to linker namespacing weirdness
// on API 29/MIUI it may not be loaded at the point of the gl_init call in the current namespace.
gl_init_gl4es_internals();
if(bundle == NULL) {
if(eglMakeCurrent_p(g_EglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) {
@@ -211,3 +188,20 @@ void gl_swap_interval(int swapInterval) {
eglSwapInterval_p(g_EglDisplay, swapInterval);
}
JNIEXPORT void JNICALL
Java_org_lwjgl_opengl_PojavRendererInit_nativeInitGl4esInternals(JNIEnv *env, jclass clazz,
jobject function_provider) {
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "GL4ES internals initializing...");
jclass funcProviderClass = (*env)->GetObjectClass(env, function_provider);
jmethodID method_getFunctionAddress = (*env)->GetMethodID(env, funcProviderClass, "getFunctionAddress", "(Ljava/lang/CharSequence;)J");
#define GETSYM(N) ((*env)->CallLongMethod(env, function_provider, method_getFunctionAddress, (*env)->NewStringUTF(env, N)));
void (*set_getmainfbsize)(void (*new_getMainFBSize)(int* width, int* height)) = (void*)GETSYM("set_getmainfbsize");
if(set_getmainfbsize != NULL) {
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "GL4ES internals initialized dimension callback");
set_getmainfbsize(gl4esi_get_display_dimensions);
}
#undef GETSYM
}
@@ -0,0 +1,82 @@
//
// Created by maks on 15.01.2025.
//
#include <jni.h>
#include <unistd.h>
#include <stdbool.h>
#include <bytehook.h>
#include <dlfcn.h>
#include <android/log.h>
#include <stdlib.h>
#include "stdio_is.h"
static _Atomic bool exit_tripped = false;
typedef void (*exit_func)(int);
static void custom_exit(int code) {
// If the exit was already done (meaning it is recursive or from a different thread), pass the call through
if(exit_tripped) {
BYTEHOOK_CALL_PREV(custom_exit, exit_func, code);
BYTEHOOK_POP_STACK();
return;
}
exit_tripped = true;
// Perform a nominal exit, as we expect.
nominal_exit(code, false);
BYTEHOOK_POP_STACK();
}
static void custom_atexit() {
// Same as custom_exit, but without the code or the exit passthrough.
if(exit_tripped) {
return;
}
exit_tripped = true;
nominal_exit(0, false);
}
static bool init_exit_hook() {
void* bytehook_handle = dlopen("libbytehook.so", RTLD_NOW);
if(bytehook_handle == NULL) {
goto dlerror;
}
bytehook_stub_t (*bytehook_hook_all_p)(const char *callee_path_name, const char *sym_name, void *new_func,
bytehook_hooked_t hooked, void *hooked_arg);
int (*bytehook_init_p)(int mode, bool debug);
bytehook_hook_all_p = dlsym(bytehook_handle, "bytehook_hook_all");
bytehook_init_p = dlsym(bytehook_handle, "bytehook_init");
if(bytehook_hook_all_p == NULL || bytehook_init_p == NULL) {
goto dlerror;
}
int bhook_status = bytehook_init_p(BYTEHOOK_MODE_AUTOMATIC, false);
if(bhook_status == BYTEHOOK_STATUS_CODE_OK) {
bytehook_stub_t stub = bytehook_hook_all_p(NULL, "exit", &custom_exit, NULL, NULL);
__android_log_print(ANDROID_LOG_INFO, "exit_hook", "Successfully initialized exit hook, stub=%p", stub);
return true;
} else {
__android_log_print(ANDROID_LOG_INFO, "exit_hook", "bytehook_init failed (%i)", bhook_status);
dlclose(bytehook_handle);
return false;
}
dlerror:
if(bytehook_handle != NULL) dlclose(bytehook_handle);
__android_log_print(ANDROID_LOG_ERROR, "exit_hook", "Failed to load hook library: %s", dlerror());
return false;
}
JNIEXPORT void JNICALL
Java_net_kdt_pojavlaunch_utils_JREUtils_initializeGameExitHook(JNIEnv *env, jclass clazz) {
bool hookReady = init_exit_hook();
if(!hookReady){
// If we can't hook, register atexit(). This won't report a proper error code,
// but it will prevent a SIGSEGV or a SIGABRT from the depths of Dalvik that happens
// on exit().
atexit(custom_atexit);
}
}
+12 -49
View File
@@ -8,9 +8,10 @@
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <bytehook.h>
#include <environ/environ.h>
#include "stdio_is.h"
//
// Created by maks on 17.02.21.
//
@@ -25,7 +26,6 @@ static pthread_t logger;
static jmethodID logger_onEventLogged;
static volatile jobject logListener = NULL;
static int latestlog_fd = -1;
static _Atomic bool exit_tripped = false;
static bool recordBuffer(char* buf, ssize_t len) {
@@ -100,11 +100,6 @@ Java_net_kdt_pojavlaunch_Logger_begin(JNIEnv *env, __attribute((unused)) jclass
pthread_detach(logger);
}
typedef void (*exit_func)(int);
_Noreturn void nominal_exit(int code, bool is_signal) {
JNIEnv *env;
jint errorCode = (*exitTrap_jvm)->GetEnv(exitTrap_jvm, (void**)&env, JNI_VERSION_1_6);
@@ -142,48 +137,6 @@ _Noreturn void nominal_exit(int code, bool is_signal) {
while(1) {}
}
static void custom_exit(int code) {
// If the exit was already done (meaning it is recursive or from a different thread), pass the call through
if(exit_tripped) {
BYTEHOOK_CALL_PREV(custom_exit, exit_func, code);
BYTEHOOK_POP_STACK();
return;
}
exit_tripped = true;
// Perform a nominal exit, as we expect.
nominal_exit(code, false);
BYTEHOOK_POP_STACK();
}
static void custom_atexit() {
// Same as custom_exit, but without the code or the exit passthrough.
if(exit_tripped) {
return;
}
exit_tripped = true;
nominal_exit(0, false);
}
JNIEXPORT void JNICALL Java_net_kdt_pojavlaunch_utils_JREUtils_setupExitTrap(JNIEnv *env, __attribute((unused)) jclass clazz, jobject context) {
exitTrap_ctx = (*env)->NewGlobalRef(env,context);
(*env)->GetJavaVM(env,&exitTrap_jvm);
exitTrap_exitClass = (*env)->NewGlobalRef(env,(*env)->FindClass(env,"net/kdt/pojavlaunch/ExitActivity"));
exitTrap_staticMethod = (*env)->GetStaticMethodID(env,exitTrap_exitClass,"showExitMessage","(Landroid/content/Context;IZ)V");
if(bytehook_init(BYTEHOOK_MODE_AUTOMATIC, false) == BYTEHOOK_STATUS_CODE_OK) {
bytehook_hook_all(NULL,
"exit",
&custom_exit,
NULL,
NULL);
}else {
// If we can't hook, register atexit(). This won't report a proper error code,
// but it will prevent a SIGSEGV or a SIGABRT from the depths of Dalvik that happens
// on exit().
atexit(custom_atexit);
}
}
JNIEXPORT void JNICALL Java_net_kdt_pojavlaunch_Logger_appendToLog(JNIEnv *env, __attribute((unused)) jclass clazz, jstring text) {
jsize appendStringLength = (*env)->GetStringUTFLength(env, text);
char newChars[appendStringLength+2];
@@ -205,3 +158,13 @@ Java_net_kdt_pojavlaunch_Logger_setLogListener(JNIEnv *env, __attribute((unused)
}
if(logListenerLocal != NULL) (*env)->DeleteGlobalRef(env, logListenerLocal);
}
JNIEXPORT void JNICALL
Java_net_kdt_pojavlaunch_utils_JREUtils_setupExitMethod(JNIEnv *env, jclass clazz,
jobject context) {
exitTrap_ctx = (*env)->NewGlobalRef(env,context);
(*env)->GetJavaVM(env,&exitTrap_jvm);
exitTrap_exitClass = (*env)->NewGlobalRef(env,(*env)->FindClass(env,"net/kdt/pojavlaunch/ExitActivity"));
exitTrap_staticMethod = (*env)->GetStaticMethodID(env,exitTrap_exitClass,"showExitMessage","(Landroid/content/Context;IZ)V");
}
+12
View File
@@ -0,0 +1,12 @@
//
// Created by maks on 15.01.2025.
//
#ifndef POJAVLAUNCHER_STDIO_IS_H
#define POJAVLAUNCHER_STDIO_IS_H
#include <stdbool.h>
_Noreturn void nominal_exit(int code, bool is_signal);
#endif //POJAVLAUNCHER_STDIO_IS_H
@@ -1,201 +0,0 @@
//#import <Foundation/Foundation.h>
#include <stdio.h>
#include <dlfcn.h>
#include "GL/gl.h"
#include "GLES3/gl32.h"
#include "string_utils.h"
#define LOOKUP_FUNC(func) \
if (!gles_##func) { \
gles_##func = dlsym(RTLD_NEXT, #func); \
} if (!gles_##func) { \
gles_##func = dlsym(RTLD_DEFAULT, #func); \
}
int proxy_width, proxy_height, proxy_intformat, maxTextureSize;
void glBindFragDataLocationEXT(GLuint program, GLuint colorNumber, const char * name);
void(*gles_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params);
void(*gles_glShaderSource)(GLuint shader, GLsizei count, const GLchar * const *string, const GLint *length);
void(*gles_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data);
void glBindFragDataLocation(GLuint program, GLuint colorNumber, const char * name) {
glBindFragDataLocationEXT(program, colorNumber, name);
}
void glClearDepth(GLdouble depth) {
glClearDepthf(depth);
}
void *glMapBuffer(GLenum target, GLenum access) {
// Use: GL_EXT_map_buffer_range
GLenum access_range;
GLint length;
switch (target) {
// GL 4.2
case GL_ATOMIC_COUNTER_BUFFER:
// GL 4.3
case GL_DISPATCH_INDIRECT_BUFFER:
case GL_SHADER_STORAGE_BUFFER :
// GL 4.4
case GL_QUERY_BUFFER:
printf("ERROR: glMapBuffer unsupported target=0x%x", target);
break; // not supported for now
case GL_DRAW_INDIRECT_BUFFER:
case GL_TEXTURE_BUFFER:
printf("ERROR: glMapBuffer unimplemented target=0x%x", target);
break;
}
switch (access) {
case GL_READ_ONLY:
access_range = GL_MAP_READ_BIT;
break;
case GL_WRITE_ONLY:
access_range = GL_MAP_WRITE_BIT;
break;
case GL_READ_WRITE:
access_range = GL_MAP_READ_BIT | GL_MAP_WRITE_BIT;
break;
}
glGetBufferParameteriv(target, GL_BUFFER_SIZE, &length);
return glMapBufferRange(target, 0, length, access_range);
}
void glShaderSource(GLuint shader, GLsizei count, const GLchar * const *string, const GLint *length) {
LOOKUP_FUNC(glShaderSource)
// DBG(printf("glShaderSource(%d, %d, %p, %p)\n", shader, count, string, length);)
char *source = NULL;
char *converted;
// get the size of the shader sources and than concatenate in a single string
int l = 0;
for (int i=0; i<count; i++) l+=(length && length[i] >= 0)?length[i]:strlen(string[i]);
if (source) free(source);
source = calloc(1, l+1);
if(length) {
for (int i=0; i<count; i++) {
if(length[i] >= 0)
strncat(source, string[i], length[i]);
else
strcat(source, string[i]);
}
} else {
for (int i=0; i<count; i++)
strcat(source, string[i]);
}
char *source2 = strchr(source, '#');
if (!source2) {
source2 = source;
}
// are there #version?
if (!strncmp(source2, "#version ", 9)) {
converted = strdup(source2);
if (converted[9] == '1') {
if (converted[10] - '0' < 2) {
// 100, 110 -> 120
converted[10] = '2';
} else if (converted[10] - '0' < 6) {
// 130, 140, 150 -> 330
converted[9] = converted[10] = '3';
}
}
// remove "core", is it safe?
if (!strncmp(&converted[13], "core", 4)) {
strncpy(&converted[13], "\n//c", 4);
}
} else {
converted = calloc(1, strlen(source) + 13);
strcpy(converted, "#version 120\n");
strcpy(&converted[13], strdup(source));
}
int convertedLen = strlen(converted);
#ifdef __APPLE__
// patch OptiFine 1.17.x
if (FindString(converted, "\nuniform mat4 textureMatrix = mat4(1.0);")) {
InplaceReplace(converted, &convertedLen, "\nuniform mat4 textureMatrix = mat4(1.0);", "\n#define textureMatrix mat4(1.0)");
}
#endif
// some needed exts
const char* extensions =
"#extension GL_EXT_blend_func_extended : enable\n"
// For OptiFine (see patch above)
"#extension GL_EXT_shader_non_constant_global_initializers : enable\n";
converted = InplaceInsert(GetLine(converted, 1), extensions, converted, &convertedLen);
gles_glShaderSource(shader, 1, (const GLchar * const*)((converted)?(&converted):(&source)), NULL);
free(source);
free(converted);
}
int isProxyTexture(GLenum target) {
switch (target) {
case GL_PROXY_TEXTURE_1D:
case GL_PROXY_TEXTURE_2D:
case GL_PROXY_TEXTURE_3D:
case GL_PROXY_TEXTURE_RECTANGLE_ARB:
return 1;
}
return 0;
}
static int inline nlevel(int size, int level) {
if(size) {
size>>=level;
if(!size) size=1;
}
return size;
}
void glGetTexLevelParameteriv(GLenum target, GLint level, GLenum pname, GLint *params) {
LOOKUP_FUNC(glGetTexLevelParameteriv)
// NSLog("glGetTexLevelParameteriv(%x, %d, %x, %p)", target, level, pname, params);
if (isProxyTexture(target)) {
switch (pname) {
case GL_TEXTURE_WIDTH:
(*params) = nlevel(proxy_width,level);
break;
case GL_TEXTURE_HEIGHT:
(*params) = nlevel(proxy_height,level);
break;
case GL_TEXTURE_INTERNAL_FORMAT:
(*params) = proxy_intformat;
break;
}
} else {
gles_glGetTexLevelParameteriv(target, level, pname, params);
}
}
void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data) {
LOOKUP_FUNC(glTexImage2D)
if (isProxyTexture(target)) {
if (!maxTextureSize) {
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
// maxTextureSize = 16384;
// NSLog(@"Maximum texture size: %d", maxTextureSize);
}
proxy_width = ((width<<level)>maxTextureSize)?0:width;
proxy_height = ((height<<level)>maxTextureSize)?0:height;
proxy_intformat = internalformat;
// swizzle_internalformat((GLenum *) &internalformat, format, type);
} else {
gles_glTexImage2D(target, level, internalformat, width, height, border, format, type, data);
}
}
@@ -1,234 +0,0 @@
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "string_utils.h"
const char* AllSeparators = " \t\n\r.,;()[]{}-<>+*/%&\\\"'^$=!:?";
char* ResizeIfNeeded(char* pBuffer, int *size, int addsize);
char* InplaceReplace(char* pBuffer, int* size, const char* S, const char* D)
{
int lS = strlen(S), lD = strlen(D);
pBuffer = ResizeIfNeeded(pBuffer, size, (lD-lS)*CountString(pBuffer, S));
char* p = pBuffer;
while((p = strstr(p, S)))
{
// found an occurence of S
// check if good to replace, strchr also found '\0' :)
if(strchr(AllSeparators, p[lS])!=NULL && (p==pBuffer || strchr(AllSeparators, p[-1])!=NULL)) {
// move out rest of string
memmove(p+lD, p+lS, strlen(p)-lS+1);
// replace
memcpy(p, D, strlen(D));
// next
p+=lD;
} else p+=lS;
}
return pBuffer;
}
char* InplaceInsert(char* pBuffer, const char* S, char* master, int* size)
{
char* m = ResizeIfNeeded(master, size, strlen(S));
if(m!=master) {
pBuffer += (m-master);
master = m;
}
char* p = pBuffer;
int lS = strlen(S), ll = strlen(pBuffer);
memmove(p+lS, p, ll+1);
memcpy(p, S, lS);
return master;
}
char* GetLine(char* pBuffer, int num)
{
char *p = pBuffer;
while(num-- && (p=strstr(p, "\n"))) p+=strlen("\n");
return (p)?p:pBuffer;
}
int CountLine(const char* pBuffer)
{
int n=0;
const char* p = pBuffer;
while((p=strstr(p, "\n"))) {
p+=strlen("\n");
n++;
}
return n;
}
int GetLineFor(const char* pBuffer, const char* S)
{
int n=0;
const char* p = pBuffer;
const char* end = FindString(pBuffer, S);
if(!end)
return 0;
while((p=strstr(p, "\n"))) {
p+=strlen("\n");
n++;
if(p>=end)
return n;
}
return n;
}
int CountString(const char* pBuffer, const char* S)
{
const char* p = pBuffer;
int lS = strlen(S);
int n = 0;
while((p = strstr(p, S)))
{
// found an occurence of S
// check if good to count, strchr also found '\0' :)
if(strchr(AllSeparators, p[lS])!=NULL && (p==pBuffer || strchr(AllSeparators, p[-1])!=NULL))
n++;
p+=lS;
}
return n;
}
const char* FindString(const char* pBuffer, const char* S)
{
const char* p = pBuffer;
int lS = strlen(S);
while((p = strstr(p, S)))
{
// found an occurence of S
// check if good to count, strchr also found '\0' :)
if(strchr(AllSeparators, p[lS])!=NULL && (p==pBuffer || strchr(AllSeparators, p[-1])!=NULL))
return p;
p+=lS;
}
return NULL;
}
char* FindStringNC(char* pBuffer, const char* S)
{
char* p = pBuffer;
int lS = strlen(S);
while((p = strstr(p, S)))
{
// found an occurence of S
// check if good to count, strchr also found '\0' :)
if(strchr(AllSeparators, p[lS])!=NULL && (p==pBuffer || strchr(AllSeparators, p[-1])!=NULL))
return p;
p+=lS;
}
return NULL;
}
char* ResizeIfNeeded(char* pBuffer, int *size, int addsize) {
char* p = pBuffer;
int newsize = strlen(pBuffer)+addsize+1;
if (newsize>*size) {
newsize += 100;
p = (char*)realloc(pBuffer, newsize);
*size=newsize;
}
return p;
}
char* Append(char* pBuffer, int* size, const char* S) {
char* p =pBuffer;
p = ResizeIfNeeded(pBuffer, size, strlen(S));
strcat(p, S);
return p;
}
int isBlank(char c) {
switch(c) {
case ' ':
case '\t':
case '\n':
case '\r':
case ':':
case ',':
case ';':
case '/':
return 1;
default:
return 0;
}
}
char* StrNext(char *pBuffer, const char* S) {
if(!pBuffer) return NULL;
char *p = strstr(pBuffer, S);
return (p)?p:(p+strlen(S));
}
char* NextStr(char* pBuffer) {
if(!pBuffer) return NULL;
while(isBlank(*pBuffer))
++pBuffer;
return pBuffer;
}
char* NextBlank(char* pBuffer) {
if(!pBuffer) return NULL;
while(!isBlank(*pBuffer))
++pBuffer;
return pBuffer;
}
char* NextLine(char* pBuffer) {
if(!pBuffer) return NULL;
while(*pBuffer && *pBuffer!='\n')
++pBuffer;
return pBuffer;
}
const char* GetNextStr(char* pBuffer) {
static char buff[100] = {0};
buff[0] = '\0';
if(!pBuffer) return NULL;
char* p1 = NextStr(pBuffer);
if(!p1) return buff;
char* p2 = NextBlank(p1);
if(!p2) return buff;
int i=0;
while(p1!=p2 && i<99)
buff[i++] = *(p1++);
buff[i] = '\0';
return buff;
}
int CountStringSimple(char* pBuffer, const char* S)
{
char* p = pBuffer;
int lS = strlen(S);
int n = 0;
while((p = strstr(p, S)))
{
// found an occurence of S
n++;
p+=lS;
}
return n;
}
char* InplaceReplaceSimple(char* pBuffer, int* size, const char* S, const char* D)
{
int lS = strlen(S), lD = strlen(D);
pBuffer = ResizeIfNeeded(pBuffer, size, (lD-lS)*CountStringSimple(pBuffer, S));
char* p = pBuffer;
while((p = strstr(p, S)))
{
// found an occurence of S
// move out rest of string
memmove(p+lD, p+lS, strlen(p)-lS+1);
// replace
memcpy(p, D, strlen(D));
// next
p+=lD;
}
return pBuffer;
}
@@ -1,29 +0,0 @@
#ifndef _GL4ES_STRING_UTILS_H_
#define _GL4ES_STRING_UTILS_H_
extern const char* AllSeparators;
const char* FindString(const char* pBuffer, const char* S);
char* FindStringNC(char* pBuffer, const char* S);
int CountString(const char* pBuffer, const char* S);
char* ResizeIfNeeded(char* pBuffer, int *size, int addsize);
char* InplaceReplace(char* pBuffer, int* size, const char* S, const char* D);
char* Append(char* pBuffer, int* size, const char* S);
char* InplaceInsert(char* pBuffer, const char* S, char* master, int* size);
char* GetLine(char* pBuffer, int num);
int CountLine(const char* pBuffer);
int GetLineFor(const char* pBuffer, const char* S); // get the line number for 1st occurent of S in pBuffer
char* StrNext(char *pBuffer, const char* S); // mostly as strstr, but go after the substring if found
//"blank" (space, tab, cr, lf,":", ",", ";", ".", "/")
char* NextStr(char* pBuffer); // go to next non "blank"
char* NextBlank(char* pBuffer); // go to next "blank"
char* NextLine(char* pBuffer); // go to next new line (crlf not included)
const char* GetNextStr(char* pBuffer); // get a (static) copy of next str (until next separator), can be a simple number or separator also
// those function don't try to be smart with separators...
int CountStringSimple(char* pBuffer, const char* S);
char* InplaceReplaceSimple(char* pBuffer, int* size, const char* S, const char* D);
#endif // _GL4ES_STRING_UTILS_H_
@@ -28,18 +28,8 @@
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/delete_account_button"
android:layout_width="@dimen/_52sdp"
android:layout_height="@dimen/_42sdp"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_menu_delete_forever"
android:scaleType="fitCenter"
app:layout_constraintEnd_toStartOf="@id/setting_button"
app:layout_constraintTop_toTopOf="parent" />
<!-- Holding most of the dynamic content -->
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container_fragment"
@@ -28,19 +28,6 @@
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/delete_account_button"
android:layout_width="@dimen/_52sdp"
android:layout_height="@dimen/_52sdp"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_menu_delete_forever"
android:scaleType="fitCenter"
android:paddingVertical="@dimen/_8sdp"
app:layout_constraintEnd_toStartOf="@id/setting_button"
app:layout_constraintTop_toTopOf="parent" />
<!-- Holding most of the dynamic content -->
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container_fragment"
@@ -1,17 +1,39 @@
<fr.spse.extended_view.ExtendedTextView
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="@dimen/_52sdp"
android:layout_width="match_parent"
android:textSize="@dimen/_16ssp"
android:gravity="center_vertical"
android:drawablePadding="@dimen/_6sdp"
android:paddingStart="@dimen/_8sdp"
app:drawableStartSize="@dimen/_30sdp"
android:orientation="horizontal">
tools:text="HELLO THERE"
tools:drawableStart="@mipmap/ic_launcher"
<fr.spse.extended_view.ExtendedTextView
android:id="@+id/account_item"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:ignore="RtlSymmetry" />
android:textSize="@dimen/_16ssp"
android:gravity="center_vertical"
android:drawablePadding="@dimen/_6sdp"
android:paddingStart="@dimen/_8sdp"
app:drawableStartSize="@dimen/_30sdp"
tools:text="HELLO THERE"
tools:drawableStart="@mipmap/ic_launcher"
tools:ignore="RtlSymmetry" />
<!-- Fun fact, if I put an Image button, the spinner fails to put an onclick listener on the extended view -->
<ImageView
android:id="@+id/delete_account_button"
android:layout_width="@dimen/_52sdp"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_menu_delete_forever"
android:padding="@dimen/padding_moderate"
/>
</LinearLayout>
@@ -3,7 +3,7 @@
<string-array name="renderer">
<item name="1">@string/mcl_setting_renderer_gles2_4</item>
<item name="2">@string/mcl_setting_renderer_vulkan_zink</item>
<item name="3">@string/mcl_setting_renderer_angle</item>
<item name="3">@string/mcl_setting_renderer_ltw</item>
</string-array>
<string-array name="menu_customcontrol">
@@ -36,7 +36,7 @@
<string-array name="renderer_values">
<item>opengles2</item> <!-- gl4es_extra 1.1.4 with OpenGL ES 2/"3" -->
<item>vulkan_zink</item> <!-- virglrenderer with OpenGL ES 3 -->
<item>opengles3_desktopgl_angle_vulkan</item>
<item>opengles3_ltw</item>
</string-array>
<string-array name="download_source_names">
<item>@string/global_default</item>
@@ -66,7 +66,7 @@
<string name="mcl_setting_category_renderer">Renderer</string>
<string name="mcl_setting_renderer_gles2_4">Holy GL4ES - (all versions, fast)</string>
<string name="mcl_setting_renderer_vulkan_zink">Zink (Vulkan) - (all versions, mid)</string>
<string name="mcl_setting_renderer_angle">ANGLE (Vulkan) - (1.17+ only, mid)</string>
<string name="mcl_setting_renderer_ltw">LTW (OpenGL ES 3) - 1.17+ only</string>
<string name="mcl_setting_veroption_release">Release</string>
<string name="mcl_setting_veroption_snapshot">Snapshot</string>
<string name="mcl_setting_veroption_oldalpha">Old-alpha</string>
@@ -418,6 +418,7 @@
<string name="preference_remap_controller_title">Change controller key bindings</string>
<string name="preference_remap_controller_description">Allows you to modify the keyboard keys bound to each controller button</string>
<string name="mcl_button_discord">Discord</string>
<string name="ltw_render_distance_warning_msg">Your GPU is not capable of rendering above 7 render distance without Sodium or other similar mods. The render distance will be automatically reduced when you click "OK".</string>
<string name="mcl_button_open_directory">Open game directory</string>
<string name="discord_invite" translatable="false">https://discord.com/invite/aenk3EUvER</string>
<string name="local_login_bad_username_title">Unsuitable username</string>
@@ -4792,6 +4792,8 @@ public final class GLCapabilities {
GLCapabilities(FunctionProvider provider, Set<String> ext, boolean fc, IntFunction<PointerBuffer> bufferFactory) {
forwardCompatible = fc;
PojavRendererInit.onCreateCapabilities(provider);
PointerBuffer caps = bufferFactory.apply(ADDRESS_BUFFER_SIZE);
OpenGL11 = check_GL11(provider, caps, ext, fc);
@@ -0,0 +1,39 @@
package org.lwjgl.opengl;
import org.lwjgl.system.FunctionProvider;
import org.lwjgl.system.SharedLibrary;
import javax.annotation.Nullable;
/**
* Class for initializing renderer-specific callbacks. Allows to reliably initialize
* any callbacks needed for renderers by using the same FunctionProvider as used for loading
* GL symbols.
* */
public class PojavRendererInit {
public static void onCreateCapabilities(FunctionProvider functionProvider) {
String rendererName = null;
if(functionProvider instanceof SharedLibrary) {
SharedLibrary rendererLibrary = (SharedLibrary) functionProvider;
rendererName = rendererLibrary.getName();
}
if(!isValidString(rendererName)) {
rendererName = System.getProperty("org.lwjgl.opengl.libname");
}
if(!isValidString(rendererName)) {
System.out.println("PojavRendererInit: Failed to find Pojav renderer name! " +
"Renderer-specific initialization may not work properly");
}
// NOTE: hardcoded gl4es libname
if(rendererName.endsWith("libgl4es_114.so")) {
nativeInitGl4esInternals(functionProvider);
}
}
private static boolean isValidString(@Nullable String s) {
return s != null && !s.isEmpty();
}
public static native void nativeInitGl4esInternals(FunctionProvider functionProvider);
}