Compare commits

..
Author SHA1 Message Date
artdeell 81c6813a6b Fix[nativesextractor]: improve style, address performance/debuggability concerns 2025-02-15 18:33:54 +03:00
artdeell d713fe52ea Feat[mc_downloader]: native library downloading and extraction
Currently implemented only for JNA
2025-02-14 17:56:20 +03:00
artdeell 92bde837fd Feat[mod_fragment]: remove explicit static variable in each mod install fragment 2025-02-10 22:48:17 +03:00
artdeell 1e060d1aa8 Style[bta_adapter]: change return types 2025-02-10 22:48:17 +03:00
artdeell fab0186cbe Style[bta_profile]: add clarifying comments 2025-02-10 22:48:17 +03:00
artdeell 988d3bbcb6 Style[bta_profile]: improve code niceness 2025-02-10 22:48:17 +03:00
artdeell 9e53552a8c Feat[bta_profile]: add the ability to install nightlies 2025-02-10 22:48:17 +03:00
artdeell 740568fafa Fix[bta_profile]: set custom game directory 2025-02-10 22:48:17 +03:00
artdeell 4903cfc8d3 Feat[launcher]: add support for the "Better than Adventure!" mod 2025-02-10 22:48:17 +03:00
Maksim Belov 21cfcdb15e Feat[input]: GLFW direct controller input (#6604) 2025-02-07 18:35:52 +03:00
artdeell ffc74c502a Fix[downloader]: fix size fetching 2025-02-07 18:35:11 +03:00
artdeell 4e1bdd8675 Fix[lwjgl]: update OpenAL to fix issues with soundfilters and other mods
Reference: https://github.com/PojavLauncherTeam/lwjgl3/pull/7
2025-02-05 22:28:56 +03:00
artdeell 0ee0dfecc2 Fix[glfw]: stubs for getMonitorContentScale 2025-02-04 18:47:03 +03:00
Maksim Belov 5a98a43d21 Merge pull request #6599 from PojavLauncherTeam/feat/true_display_create_state
Feat/true display create state
2025-02-04 18:40:07 +03:00
artdeell 3d256a29e4 Fix[workflow]: update upload-artifact to v4 2025-02-03 14:14:25 +03:00
artdeell b0630c298f Feat[lwjglx]: Return actual display creation state instead of always "true"
Fixes RandomPatches
2025-02-03 14:11:44 +03:00
Maksim Belov 32ff194a45 Feat[downloader]: Checksum downloading from libraries (#6545) 2025-01-28 18:22:31 +03:00
Mathias-Boulay 4fd0d0a2a5 tweak(profile-editor): limit path view height 2025-01-27 08:59:42 +01:00
Maksim BelovandDuy Tran Khanh a47f3276ba New Crowdin updates (#6501)
Co-authored-by: Duy Tran Khanh <[email protected]>
2025-01-27 09:27:31 +03:00
Mathias-Boulay 755b397f19 fix(modpack): installs being broken when installing multiple versions 2025-01-26 23:31:40 +03:00
artdeell 40e2eb8c21 Style[pojavexec]: move hooks to separate dirs, use logging macros 2025-01-26 21:45:40 +03:00
artdeell 23cc342c95 Feat[hooks]: add hooks for chmod/fchmod
Allows NIO ZipFs to function on old Android versions
2025-01-26 21:45:40 +03:00
Mathias-Boulay b63255e4cf fix(glsurface): avoid negative size 2025-01-25 22:58:47 +03:00
artdeell 5b99165160 Fix[glinfoutils]: more robust error handling for checks 2025-01-24 12:15:56 +03:00
artdeell a39cd84e08 Freat[misc_settings]: check for Turnip compatibility to hide the driver option 2025-01-20 21:31:26 +03:00
artdeell bff49a7ed6 Feat[egl_bridge]: simplify ZINK_PREFER_SYSTEM_DRIVER handling 2025-01-20 21:31:26 +03:00
artdeell a9815b2ac9 Feat[launcher]: remove duplicate GLES initializations 2025-01-20 21:31:26 +03:00
Mathias Boulay 5de68224c6 fix(preferences): memory allocation by increments of 8MB (#6511) 2025-01-20 20:32:49 +03:00
Maksim Belov 55e53ea02c Fix[pojavexec]: fix incorrect JNIEnv usage in some cases (#6510)
* Fix[pojavexec]: remove central JNIEnv variables

These caused some irreliability, as pojavexec isn't guaranteed to be loaded on the same thread as the call to glfwInit

This fixes:
- 1.3-1.5.2 setting their window size to 0,0 (and thus not working correctly)
- Forge for <1.13 not resizing its window

* Fix[egl_bridge]: remove attachEnvs()

* Whoops[input_bridge]: remove unnecessary prints
2025-01-20 12:46:59 +03:00
artdeell c04e3af70d Fix[locale]: improve some default strings 2025-01-18 21:51:59 +03:00
Mathias Boulay 8b6ec53bd1 fix(side dialog): crash when deflating twice in quick succession (#6502) 2025-01-18 21:49:25 +03:00
artdeell 51bc3cfb0a Merge recent translations (#6501) 2025-01-18 21:15:53 +03:00
Mathias Boulay 315352a979 hotfix(fullscreen handling): Fix animations not refreshing (#6500) 2025-01-18 20:08:03 +03:00
Maksim Belov a470792ed1 Feat[controls]: implement control layout sanitizer (#6499) 2025-01-18 19:49:38 +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
Jordan 80e0a6aac8 Update GPLAY_PRIVACY_POLICY (#6174)
Update GPLAY_PRIVACY_POLICY to be more clear, and remove the news entry as the news in Pojav no longer exists.
2025-01-03 00:00:03 +03:00
artdeell dd15d8a469 Style[gestures]: rename method to getGestureDelay 2025-01-02 21:50:40 +03:00
artdeell 93924b429b Fix[gestures]: rename method and improve documentation 2025-01-02 21:50:40 +03:00
movte a77271df03 Fix the issue where the long-press trigger delay does not refresh properly. 2025-01-02 21:50:40 +03:00
Maksim Belov 5d80d9baec Feat[downloader]: downloader improvements (#6428)
- Add download size queries through a HEAD request
- Use the file size for progress instead of file count when all file size are available
- Add download speed meter
2024-12-30 20:31:59 +03:00
Mathias-Boulay 99c8ea2bfd cleanup(tools): remove unused code 2024-12-27 12:31:27 +03:00
Mathias-Boulay 9a7fb2ae69 cleanup(tools): remove unused code related to fullscreen 2024-12-27 12:31:27 +03:00
Mathias-Boulay f2e95b6e65 refactor(seekbars):migrate range values into xml files 2024-12-27 12:31:27 +03:00
Mathias-Boulay 8cc5cca99f Fix(quick-setting): improper placement
This was due to an issue that only happens within older android versions.
2024-12-27 12:31:27 +03:00
Mathias-Boulay dcbb1e010e refactor(customseekbar): implement seekBarIncrement attribute 2024-12-27 12:31:27 +03:00
Mathias-Boulay b3df2645e5 Fix,refactor(profiles): prefer nameless profiles
Also refactored the use of a constant across the code
2024-12-27 12:31:27 +03:00
Mathias-Boulay 38e47687fa Tweak(jvm arg): take control of -XX:ActiveProcessorCount
Setting it ourselves guarantee a better experience by default
2024-12-27 12:31:27 +03:00
Mathias-Boulay 4738e1aa59 Tweak(pref-detection): Verify all cores aren't the same frequency 2024-12-27 12:31:27 +03:00
Mathias-Boulay e0fcb1e67d Qol(settings): use energy saving settings for powerful devices
Less boiling pocket heaters.
May contain a small few refactor
2024-12-27 12:31:27 +03:00
TarikBR 89f0254106 Fix[docs]: Change license to LGPLv3 in readme and fix link (#6389)
Closes #6384
2024-12-16 18:09:44 +03:00
artdeell 011139db38 Feat[folder_provider]: notify the file manager on file changes 2024-12-12 12:32:31 +03:00
Mathias-Boulay e71be1ed64 Fix(folder provider): display pojav version
This allows the sort to be stable when listing pojav versions in the file app.
2024-12-11 22:23:03 +01:00
Mathias Boulay f1cb9e60cf chore(build): update gradle to 8.9 and AGP to 8.7.2 (#6353)
* chore(build): update gradle to 8.9 and AGP to 8.7.2

This may or may not force the generation of all sub projects

* build(actions): update GH Action gradle version

* chore(build): update gradle to 8.11

* fix(build): allow proguard profile to launch

It is still plagued with bugs, but it might stay handy the day we need to push some limits

* Fix: allow CriticalNativeTest in proguard build

* Build: Allow proguard granularity
2024-12-11 19:41:35 +01:00
171 changed files with 5601 additions and 2144 deletions

No files matched your search

+15 -3
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:
@@ -99,13 +111,13 @@ jobs:
md5sum out/app-debug-noruntime.apk > out/app-debug-noruntime.md5
- name: Upload APK
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: app-debug
path: out/app-debug.*
- name: Upload AAB
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: app-release-aab
path: out/app-gplay.aab
@@ -122,7 +134,7 @@ jobs:
inAppUpdatePriority: 5
- name: Upload APK (without runtime)
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: app-debug-noruntime
path: out/app-debug-noruntime.*
+1
View File
@@ -9,3 +9,4 @@ local.properties
app_pojavlauncher/.cxx/
.vs/
/curseforge_key.txt
/app_pojavlauncher/libs/ltw-release.aar
+1 -1
View File
@@ -1,3 +1,3 @@
1. This app (while idle) does NOT collect any sensitive information, and does NOT use network (exception is the "News" page, it uses network to load the launcher news)
1. This app (while idle) does NOT collect any sensitive information, and uses network for downloading Minecraft resources.
2. While running Minecraft, app also does NOT collect any sensitive information about your device. Snooper by Mojang does.
3. Some sensitive data is stored in crash reports after the game crashes, but it's not being shared to anyone except the current user.
+1 -1
View File
@@ -112,7 +112,7 @@ Then, run these commands ~~or build using Android Studio~~.
- Probably more, that's why we have a bug tracker ;)
## License
- PojavLauncher is licensed under [GNU GPLv3](https://github.com/khanhduytran0/PojavLauncher/blob/master/LICENSE).
- PojavLauncher is licensed under [GNU LGPLv3](https://github.com/PojavLauncherTeam/PojavLauncher/blob/v3_openjdk/LICENSE).
## Contributing
Contributions are welcome! We welcome any type of contribution, not only code. For example, you can help the wiki shape up. You can help the [translation](https://crowdin.com/project/pojavlauncher) too!
+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"
@@ -1 +1 @@
1687691695196
1738839797928
@@ -1 +1 @@
1692525087345
1738839797913
@@ -1 +1 @@
1732218529630
1738839797921
@@ -2,9 +2,15 @@ package com.kdt;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.SeekBar;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.R;
/**
* Seekbar with ability to handle ranges and increments
*/
@@ -14,27 +20,67 @@ public class CustomSeekbar extends SeekBar {
private int mIncrement = 1;
private SeekBar.OnSeekBarChangeListener mListener;
/** When using increments, this flag is used to prevent double calls to the listener */
private boolean mInternalChanges = false;
private final OnSeekBarChangeListener mInternalListener = new OnSeekBarChangeListener() {
/** When using increments, this flag is used to prevent double calls to the listener */
private boolean internalChanges = false;
/** Store the previous progress to prevent double calls with increments */
private int previousProgress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (internalChanges) return;
internalChanges = true;
progress += mMin;
progress = applyIncrement(progress);
if (progress != previousProgress) {
if (mListener != null) {
previousProgress = progress;
mListener.onProgressChanged(seekBar, progress, fromUser);
}
}
// Forces the thumb to snap to the increment
setProgress(progress);
internalChanges = false;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (internalChanges) return;
if (mListener != null) {
mListener.onStartTrackingTouch(seekBar);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (internalChanges) return;
internalChanges = true;
setProgress(seekBar.getProgress());
if (mListener != null) {
mListener.onStopTrackingTouch(seekBar);
}
internalChanges = false;
}
};
public CustomSeekbar(Context context) {
super(context);
setup();
setup(null);
}
public CustomSeekbar(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
setup(attrs);
}
public CustomSeekbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setup();
}
public CustomSeekbar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setup();
setup(attrs);
}
public void setIncrement(int increment) {
@@ -63,10 +109,15 @@ public class CustomSeekbar extends SeekBar {
@Override
public synchronized void setMin(int min) {
super.setMin(min);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
super.setMin(0);
}
mMin = min;
//todo perform something to update the progress ?
}
/**
* Wrapper to allow for a listener to be set around the internal listener
*/
@@ -75,52 +126,27 @@ public class CustomSeekbar extends SeekBar {
mListener = l;
}
public void setup() {
super.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
/** Store the previous progress to prevent double calls with increments */
private int previousProgress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mInternalChanges) return;
mInternalChanges = true;
progress += mMin;
progress = applyIncrement(progress);
if (progress != previousProgress) {
if (mListener != null) {
previousProgress = progress;
mListener.onProgressChanged(seekBar, progress, fromUser);
}
}
// Forces the thumb to snap to the increment
setProgress(progress);
mInternalChanges = false;
public void setup(@Nullable AttributeSet attrs) {
try (TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.CustomSeekbar)) {
setIncrement(attributes.getInt(R.styleable.CustomSeekbar_seekBarIncrement, 1));
int min = attributes.getInt(R.styleable.CustomSeekbar_android_min, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
super.setMin(0);
}
setRange(min, super.getMax());
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (mInternalChanges) return;
if (mListener != null) {
mListener.onStartTrackingTouch(seekBar);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mInternalChanges) return;
mInternalChanges = true;
setProgress(seekBar.getProgress());
if (mListener != null) {
mListener.onStopTrackingTouch(seekBar);
}
mInternalChanges = false;
}
});
// Due to issues with negative progress when setting up the seekbar
// We need to set a random progress to force the refresh of the thumb
if(super.getProgress() == 0) {
super.setProgress(super.getProgress() + 1);
post(() -> {
super.setProgress(super.getProgress() - 1);
post(() -> super.setOnSeekBarChangeListener(mInternalListener));
});
} else {
super.setOnSeekBarChangeListener(mInternalListener);
}
}
/**
@@ -132,6 +132,9 @@ public abstract class SideDialogView {
return;
}
mSideDialogAnimator.removeAllUpdateListeners();
mSideDialogAnimator.removeAllListeners();
mParent.removeView(mDialogLayout);
mIsInstantiated = false;
@@ -212,7 +215,6 @@ public abstract class SideDialogView {
mSideDialogAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mSideDialogAnimator.removeListener(this);
deflateLayout();
}
});
@@ -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);
}
@@ -243,8 +243,8 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
@Override
public void onAttachedToWindow() {
// Post to get the correct display dimensions after layout.
LauncherPreferences.computeNotchSize(this);
mControlLayout.post(()->{
LauncherPreferences.computeNotchSize(this);
Tools.getDisplayMetrics(this);
loadControls();
});
@@ -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);
@@ -29,6 +29,8 @@ import androidx.annotation.RequiresApi;
import net.kdt.pojavlaunch.customcontrols.ControlLayout;
import net.kdt.pojavlaunch.customcontrols.gamepad.DefaultDataProvider;
import net.kdt.pojavlaunch.customcontrols.gamepad.Gamepad;
import net.kdt.pojavlaunch.customcontrols.gamepad.direct.DirectGamepad;
import net.kdt.pojavlaunch.customcontrols.gamepad.direct.DirectGamepadEnableHandler;
import net.kdt.pojavlaunch.customcontrols.mouse.AbstractTouchpad;
import net.kdt.pojavlaunch.customcontrols.mouse.AndroidPointerCapture;
import net.kdt.pojavlaunch.customcontrols.mouse.InGUIEventProcessor;
@@ -40,15 +42,16 @@ import net.kdt.pojavlaunch.utils.MCOptionUtils;
import org.lwjgl.glfw.CallbackBridge;
import fr.spse.gamepad_remapper.GamepadHandler;
import fr.spse.gamepad_remapper.RemapperManager;
import fr.spse.gamepad_remapper.RemapperView;
/**
* Class dealing with showing minecraft surface and taking inputs to dispatch them to minecraft
*/
public class MinecraftGLSurface extends View implements GrabListener {
public class MinecraftGLSurface extends View implements GrabListener, DirectGamepadEnableHandler {
/* Gamepad object for gamepad inputs, instantiated on need */
private Gamepad mGamepad = null;
private GamepadHandler mGamepadHandler;
/* The RemapperView.Builder object allows you to set which buttons to remap */
private final RemapperManager mInputManager = new RemapperManager(getContext(), new RemapperView.Builder(null)
.remapA(true)
@@ -88,6 +91,7 @@ public class MinecraftGLSurface extends View implements GrabListener {
public MinecraftGLSurface(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setFocusable(true);
CallbackBridge.setDirectGamepadEnableHandler(this);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@@ -203,7 +207,11 @@ public class MinecraftGLSurface extends View implements GrabListener {
}
private void createGamepad(View contextView, InputDevice inputDevice) {
mGamepad = new Gamepad(contextView, inputDevice, DefaultDataProvider.INSTANCE, true);
if(CallbackBridge.sGamepadDirectInput) {
mGamepadHandler = new DirectGamepad();
}else {
mGamepadHandler = new Gamepad(contextView, inputDevice, DefaultDataProvider.INSTANCE, true);
}
}
/**
@@ -215,9 +223,9 @@ public class MinecraftGLSurface extends View implements GrabListener {
int mouseCursorIndex = -1;
if(Gamepad.isGamepadEvent(event)){
if(mGamepad == null) createGamepad(this, event.getDevice());
if(mGamepadHandler == null) createGamepad(this, event.getDevice());
mInputManager.handleMotionEventInput(getContext(), event, mGamepad);
mInputManager.handleMotionEventInput(getContext(), event, mGamepadHandler);
return true;
}
@@ -239,7 +247,7 @@ public class MinecraftGLSurface extends View implements GrabListener {
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
return true;
case MotionEvent.ACTION_SCROLL:
CallbackBridge.sendScroll((double) event.getAxisValue(MotionEvent.AXIS_HSCROLL), (double) event.getAxisValue(MotionEvent.AXIS_VSCROLL));
CallbackBridge.sendScroll(event.getAxisValue(MotionEvent.AXIS_HSCROLL), event.getAxisValue(MotionEvent.AXIS_VSCROLL));
return true;
case MotionEvent.ACTION_BUTTON_PRESS:
return sendMouseButtonUnconverted(event.getActionButton(),true);
@@ -287,9 +295,9 @@ public class MinecraftGLSurface extends View implements GrabListener {
}
if(Gamepad.isGamepadEvent(event)){
if(mGamepad == null) createGamepad(this, event.getDevice());
if(mGamepadHandler == null) createGamepad(this, event.getDevice());
mInputManager.handleKeyEventInput(getContext(), event, mGamepad);
mInputManager.handleKeyEventInput(getContext(), event, mGamepadHandler);
return true;
}
@@ -338,8 +346,14 @@ public class MinecraftGLSurface extends View implements GrabListener {
// Use the width and height of the View instead of display dimensions to avoid
// getting squiched/stretched due to inconsistencies between the layout and
// screen dimensions.
windowWidth = Tools.getDisplayFriendlyRes(getWidth(), LauncherPreferences.PREF_SCALE_FACTOR);
windowHeight = Tools.getDisplayFriendlyRes(getHeight(), LauncherPreferences.PREF_SCALE_FACTOR);
int newWidth = Tools.getDisplayFriendlyRes(getWidth(), LauncherPreferences.PREF_SCALE_FACTOR);
int newHeight = Tools.getDisplayFriendlyRes(getHeight(), LauncherPreferences.PREF_SCALE_FACTOR);
if (newHeight < 1 || newWidth < 1) {
Log.e("MGLSurface", String.format("Impossible resolution : %dx%d", newWidth, newHeight));
return;
}
windowWidth = newWidth;
windowHeight = newHeight;
if(mSurface == null){
Log.w("MGLSurface", "Attempt to refresh size on null surface");
return;
@@ -405,6 +419,17 @@ public class MinecraftGLSurface extends View implements GrabListener {
}
}
@Override
public void onDirectGamepadEnabled() {
post(()->{
if(mGamepadHandler != null && mGamepadHandler instanceof Gamepad) {
((Gamepad)mGamepadHandler).removeSelf();
}
// Force gamepad recreation on next event
mGamepadHandler = null;
});
}
/** A small interface called when the listener is ready for the first time */
public interface SurfaceReadyListener {
void isReady();
@@ -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);
@@ -40,14 +40,9 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
@@ -66,8 +61,10 @@ import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.DateUtils;
import net.kdt.pojavlaunch.utils.DownloadUtils;
import net.kdt.pojavlaunch.utils.FileUtils;
import net.kdt.pojavlaunch.utils.GLInfoUtils;
import net.kdt.pojavlaunch.utils.JREUtils;
import net.kdt.pojavlaunch.utils.JSONUtils;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import net.kdt.pojavlaunch.utils.OldVersionsUtils;
import net.kdt.pojavlaunch.value.DependentLibrary;
import net.kdt.pojavlaunch.value.MinecraftAccount;
@@ -158,14 +155,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 +200,60 @@ 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.
* This issue is caused by a very severe limit on the amount of GL buffer names that could be allocated
* by the Adreno properietary GLES driver.
* @return whether the GPU is affected by the Large Thin Wrapper render distance issue on vanilla
*/
private static boolean affectedByRenderDistanceIssue() {
GLInfoUtils.GLInfo info = GLInfoUtils.getGlInfo();
return info.isAdreno() && info.glesMajorVersion >= 3;
}
private static boolean checkRenderDistance(File gamedir) {
if(!"opengles3_ltw".equals(Tools.LOCAL_RENDERER)) return false;
if(!affectedByRenderDistanceIssue()) return false;
if(hasSodium(gamedir)) return false;
int renderDistance;
try {
MCOptionUtils.load();
String renderDistanceString = MCOptionUtils.get("renderDistance");
renderDistance = Integer.parseInt(renderDistanceString);
}catch (Exception e) {
Log.e("Tools", "Failed to check render distance", e);
renderDistance = 12; // Assume Minecraft's default render distance
}
// 7 is the render distance "magic number" above which MC creates too many buffers
// for Adreno's OpenGL ES implementation
return renderDistance > 7;
}
public static void launchMinecraft(final AppCompatActivity activity, MinecraftAccount minecraftAccount,
@@ -203,10 +281,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
@@ -230,9 +325,17 @@ public final class Tools {
}
javaArgList.add("-Dlog4j.configurationFile=" + configFile);
}
File versionSpecificNativesDir = new File(Tools.DIR_CACHE, "natives/"+versionId);
if(versionSpecificNativesDir.exists()) {
String dirPath = versionSpecificNativesDir.getAbsolutePath();
javaArgList.add("-Djava.library.path="+dirPath+":"+Tools.NATIVE_LIB_DIR);
javaArgList.add("-Djna.boot.library.path="+dirPath);
}
javaArgList.addAll(Arrays.asList(getMinecraftJVMArgs(versionId, gamedir)));
javaArgList.add("-cp");
javaArgList.add(getLWJGL3ClassPath() + ":" + launchClassPath);
javaArgList.add(launchClassPath + ":" + getLWJGL3ClassPath());
javaArgList.add(versionInfo.mainClass);
javaArgList.addAll(Arrays.asList(launchArgs));
@@ -513,8 +616,7 @@ public final class Tools {
return displayMetrics;
}
@SuppressWarnings("deprecation")
private static void setFullscreenLegacy(Activity activity, boolean fullscreen) {
public static void setFullscreen(Activity activity, boolean fullscreen) {
final View decorView = activity.getWindow().getDecorView();
View.OnSystemUiVisibilityChangeListener visibilityChangeListener = visibility -> {
boolean multiWindowMode = SDK_INT >= 24 && activity.isInMultiWindowMode();
@@ -538,44 +640,6 @@ public final class Tools {
visibilityChangeListener.onSystemUiVisibilityChange(decorView.getSystemUiVisibility()); //call it once since the UI state may not change after the call, so the activity wont become fullscreen
}
@RequiresApi(Build.VERSION_CODES.R)
private static void setFullscreenSdk30(Activity activity, boolean fullscreen) {
WindowInsetsControllerCompat windowInsetsController =
WindowCompat.getInsetsController(activity.getWindow(), activity.getWindow().getDecorView());
if (windowInsetsController == null) {
Log.w(APP_NAME, "WindowInsetsController is null, cannot set fullscreen");
return;
}
// Configure the behavior of the hidden system bars.
windowInsetsController.setSystemBarsBehavior(
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
);
ViewCompat.setOnApplyWindowInsetsListener(
activity.getWindow().getDecorView(),
(view, windowInsets) -> {
if (fullscreen && !activity.isInMultiWindowMode()) {
windowInsetsController.hide(WindowInsetsCompat.Type.systemBars());
activity.getWindow().setDecorFitsSystemWindows(false);
} else {
windowInsetsController.show(WindowInsetsCompat.Type.systemBars());
activity.getWindow().setDecorFitsSystemWindows(true);
}
return ViewCompat.onApplyWindowInsets(view, windowInsets);
});
}
public static void setFullscreen(Activity activity, boolean fullscreen) {
if (SDK_INT >= Build.VERSION_CODES.R) {
setFullscreenSdk30(activity, fullscreen);
}else {
setFullscreenLegacy(activity, fullscreen);
}
}
public static DisplayMetrics currentDisplayMetrics;
public static void updateWindowSize(Activity activity) {
@@ -970,6 +1034,8 @@ public final class Tools {
Logger.appendToLog("Info: API version: " + SDK_INT);
Logger.appendToLog("Info: Selected Minecraft version: " + gameVersion);
Logger.appendToLog("Info: Custom Java arguments: \"" + javaArguments + "\"");
GLInfoUtils.GLInfo info = GLInfoUtils.getGlInfo();
Logger.appendToLog("Info: Graphics device: "+info.vendor+ " "+info.renderer+" (OpenGL ES "+info.glesMajorVersion+")");
}
public interface DownloaderFeedback {
@@ -1300,12 +1366,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;
}
}
@@ -30,4 +30,9 @@ public class DefaultDataProvider implements GamepadDataProvider {
public void attachGrabListener(GrabListener grabListener) {
CallbackBridge.addGrabListener(grabListener);
}
@Override
public void detachGrabListener(GrabListener grabListener) {
CallbackBridge.removeGrabListener(grabListener);
}
}
@@ -26,7 +26,6 @@ import androidx.core.math.MathUtils;
import net.kdt.pojavlaunch.GrabListener;
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import org.lwjgl.glfw.CallbackBridge;
@@ -43,6 +42,7 @@ import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTI
import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.DIRECTION_WEST;
import static net.kdt.pojavlaunch.customcontrols.gamepad.GamepadJoystick.isJoystickEvent;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_DEADZONE_SCALE;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_SCALE_FACTOR;
import static net.kdt.pojavlaunch.utils.MCOptionUtils.getMcScale;
import static org.lwjgl.glfw.CallbackBridge.sendKeyPress;
import static org.lwjgl.glfw.CallbackBridge.sendMouseButton;
@@ -52,9 +52,6 @@ import fr.spse.gamepad_remapper.Settings;
public class Gamepad implements GrabListener, GamepadHandler {
/* Resolution scaler option, allow downsizing a window */
private final float mScaleFactor = LauncherPreferences.DEFAULT_PREF.getInt("resolutionRatio",100)/100f;
/* Sensitivity, adjusted according to screen size */
private final double mSensitivityFactor = (1.4 * (1080f/ currentDisplayMetrics.heightPixels));
@@ -90,6 +87,8 @@ public class Gamepad implements GrabListener, GamepadHandler {
private final GamepadDataProvider mMapProvider;
private boolean mRemoved = false;
public Gamepad(View contextView, InputDevice inputDevice, GamepadDataProvider mapProvider, boolean showCursor){
Settings.setDeadzoneScale(PREF_DEADZONE_SCALE);
@@ -98,7 +97,7 @@ public class Gamepad implements GrabListener, GamepadHandler {
@Override
public void doFrame(long frameTimeNanos) {
tick(frameTimeNanos);
mScreenChoreographer.postFrameCallback(this);
if(!mRemoved) mScreenChoreographer.postFrameCallback(this);
}
};
mScreenChoreographer.postFrameCallback(frameCallback);
@@ -116,7 +115,7 @@ public class Gamepad implements GrabListener, GamepadHandler {
mPointerImageView.setImageDrawable(ResourcesCompat.getDrawable(ctx.getResources(), R.drawable.ic_gamepad_pointer, ctx.getTheme()));
mPointerImageView.getDrawable().setFilterBitmap(false);
int size = (int) ((22 * getMcScale()) / mScaleFactor);
int size = (int) ((22 * getMcScale()) / PREF_SCALE_FACTOR);
mPointerImageView.setLayoutParams(new FrameLayout.LayoutParams(size, size));
mMapProvider = mapProvider;
@@ -155,7 +154,7 @@ public class Gamepad implements GrabListener, GamepadHandler {
public void notifyGUISizeChange(int newSize){
//Change the pointer size to match UI
int size = (int) ((22 * newSize) / mScaleFactor);
int size = (int) ((22 * newSize) / PREF_SCALE_FACTOR);
mPointerImageView.post(() -> mPointerImageView.setLayoutParams(new FrameLayout.LayoutParams(size, size)));
}
@@ -228,7 +227,7 @@ public class Gamepad implements GrabListener, GamepadHandler {
if(!isGrabbing){
CallbackBridge.mouseX = MathUtils.clamp(CallbackBridge.mouseX, 0, CallbackBridge.windowWidth);
CallbackBridge.mouseY = MathUtils.clamp(CallbackBridge.mouseY, 0, CallbackBridge.windowHeight);
placePointerView((int) (CallbackBridge.mouseX / mScaleFactor), (int) (CallbackBridge.mouseY/ mScaleFactor));
placePointerView((int) (CallbackBridge.mouseX / PREF_SCALE_FACTOR), (int) (CallbackBridge.mouseY/ PREF_SCALE_FACTOR));
}
//Send the mouse to the game
@@ -340,7 +339,7 @@ public class Gamepad implements GrabListener, GamepadHandler {
placePointerView(CallbackBridge.physicalWidth/2, CallbackBridge.physicalHeight/2);
mPointerImageView.setVisibility(View.VISIBLE);
// Sensitivity in menu is MC and HARDWARE resolution dependent
mMouseSensitivity = 19 * mScaleFactor / mSensitivityFactor;
mMouseSensitivity = 19 * PREF_SCALE_FACTOR / mSensitivityFactor;
}
@Override
@@ -455,4 +454,15 @@ public class Gamepad implements GrabListener, GamepadHandler {
break;
}
}
/**
* Stops the Gamepad and removes all traces of the Gamepad from the view hierarchy.
* After this call, the Gamepad is not recoverable and a new one must be made.
*/
public void removeSelf() {
mRemoved = true;
mMapProvider.detachGrabListener(this);
ViewGroup viewGroup = (ViewGroup) mPointerImageView.getParent();
if(viewGroup != null) viewGroup.removeView(mPointerImageView);
}
}
@@ -7,4 +7,5 @@ public interface GamepadDataProvider {
GamepadMap getGameMap();
boolean isGrabbing();
void attachGrabListener(GrabListener grabListener);
void detachGrabListener(GrabListener grabListener);
}
@@ -325,6 +325,11 @@ public class GamepadMapperAdapter extends RecyclerView.Adapter<GamepadMapperAdap
grabListener.onGrabState(mGrabState);
}
@Override
public void detachGrabListener(GrabListener grabListener) {
mGamepadGrabListener = null;
}
public void setGrabState(boolean newState) {
mGrabState = newState;
if(mGamepadGrabListener != null) mGamepadGrabListener.onGrabState(newState);
@@ -0,0 +1,78 @@
package net.kdt.pojavlaunch.customcontrols.gamepad.direct;
import static org.lwjgl.glfw.CallbackBridge.sGamepadAxisBuffer;
import static org.lwjgl.glfw.CallbackBridge.sGamepadButtonBuffer;
import android.view.KeyEvent;
import android.view.MotionEvent;
import fr.spse.gamepad_remapper.GamepadHandler;
public class DirectGamepad implements GamepadHandler {
@Override
public void handleGamepadInput(int keycode, float value) {
int gKeycode = -1, gAxis = -1;
switch (keycode) {
case KeyEvent.KEYCODE_BUTTON_A: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_A; break;
case KeyEvent.KEYCODE_BUTTON_B: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_B; break;
case KeyEvent.KEYCODE_BUTTON_X: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_X; break;
case KeyEvent.KEYCODE_BUTTON_Y: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_Y; break;
case KeyEvent.KEYCODE_BUTTON_L1: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_LEFT_BUMPER; break;
case KeyEvent.KEYCODE_BUTTON_R1: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER; break;
case KeyEvent.KEYCODE_BUTTON_L2:
case MotionEvent.AXIS_LTRIGGER:
gAxis = GamepadKeycodes.GLFW_GAMEPAD_AXIS_LEFT_TRIGGER;
break;
case KeyEvent.KEYCODE_BUTTON_R2:
case MotionEvent.AXIS_RTRIGGER:
gAxis = GamepadKeycodes.GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER;
break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_LEFT_THUMB; break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_RIGHT_THUMB; break;
case KeyEvent.KEYCODE_BUTTON_START: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_START; break;
case KeyEvent.KEYCODE_BUTTON_SELECT: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_BACK; break;
case KeyEvent.KEYCODE_DPAD_UP: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_UP; break;
case KeyEvent.KEYCODE_DPAD_DOWN: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_DOWN; break;
case KeyEvent.KEYCODE_DPAD_LEFT: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_LEFT; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: gKeycode = GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_RIGHT; break;
case KeyEvent.KEYCODE_DPAD_CENTER:
// Behave the same way as the Gamepad here, as GLFW doesn't have a keycode
// for the dpad center.
sGamepadButtonBuffer.put(GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_UP, GamepadKeycodes.GLFW_RELEASE);
sGamepadButtonBuffer.put(GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_DOWN, GamepadKeycodes.GLFW_RELEASE);
sGamepadButtonBuffer.put(GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_LEFT, GamepadKeycodes.GLFW_RELEASE);
sGamepadButtonBuffer.put(GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_RIGHT, GamepadKeycodes.GLFW_RELEASE);
return;
case MotionEvent.AXIS_X: gAxis = GamepadKeycodes.GLFW_GAMEPAD_AXIS_LEFT_X; break;
case MotionEvent.AXIS_Y: gAxis = GamepadKeycodes.GLFW_GAMEPAD_AXIS_LEFT_Y; break;
case MotionEvent.AXIS_Z: gAxis = GamepadKeycodes.GLFW_GAMEPAD_AXIS_RIGHT_X; break;
case MotionEvent.AXIS_RZ: gAxis = GamepadKeycodes.GLFW_GAMEPAD_AXIS_RIGHT_Y; break;
case MotionEvent.AXIS_HAT_X:
sGamepadButtonBuffer.put(
GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_LEFT,
value < -0.85 ? GamepadKeycodes.GLFW_PRESS : GamepadKeycodes.GLFW_RELEASE
);
sGamepadButtonBuffer.put(
GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_RIGHT,
value > 0.85 ? GamepadKeycodes.GLFW_PRESS : GamepadKeycodes.GLFW_RELEASE
);
return;
case MotionEvent.AXIS_HAT_Y:
sGamepadButtonBuffer.put(
GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_UP,
value < -0.85 ? GamepadKeycodes.GLFW_PRESS : GamepadKeycodes.GLFW_RELEASE
);
sGamepadButtonBuffer.put(
GamepadKeycodes.GLFW_GAMEPAD_BUTTON_DPAD_DOWN,
value > 0.85 ? GamepadKeycodes.GLFW_PRESS : GamepadKeycodes.GLFW_RELEASE
);
return;
}
if(gKeycode != -1) {
sGamepadButtonBuffer.put(gKeycode, value > 0.85 ? GamepadKeycodes.GLFW_PRESS : GamepadKeycodes.GLFW_RELEASE);
}
if(gAxis != -1) {
sGamepadAxisBuffer.put(gAxis, value);
}
}
}
@@ -0,0 +1,17 @@
package net.kdt.pojavlaunch.customcontrols.gamepad.direct;
/**
* Interface that is called once when the GLFW implementation requests to switch from
* the default gamepad implementation to the direct one. The implementor of this interface
* must take the necessary steps to disable the default gamepad implementation and replace
* it with an instance of DirectGamepad.
* This is useful for switching from default to direct input after the user has already
* interacted with the gamepad.
*/
public interface DirectGamepadEnableHandler {
/**
* Called once when GLFW requests switching the gamepad mode from default to direct.
*/
void onDirectGamepadEnabled();
}
@@ -0,0 +1,31 @@
package net.kdt.pojavlaunch.customcontrols.gamepad.direct;
public class GamepadKeycodes {
public static final byte GLFW_RELEASE = 0;
public static final byte GLFW_PRESS = 1;
public static final short GLFW_GAMEPAD_BUTTON_A = 0;
public static final short GLFW_GAMEPAD_BUTTON_B = 1;
public static final short GLFW_GAMEPAD_BUTTON_X = 2;
public static final short GLFW_GAMEPAD_BUTTON_Y = 3;
public static final short GLFW_GAMEPAD_BUTTON_LEFT_BUMPER = 4;
public static final short GLFW_GAMEPAD_BUTTON_RIGHT_BUMPER = 5;
public static final short GLFW_GAMEPAD_BUTTON_BACK = 6;
public static final short GLFW_GAMEPAD_BUTTON_START = 7;
// Home button, unused because Android takes the home button events
// for itself
public static final short GLFW_GAMEPAD_BUTTON_GUIDE = 8;
public static final short GLFW_GAMEPAD_BUTTON_LEFT_THUMB = 9;
public static final short GLFW_GAMEPAD_BUTTON_RIGHT_THUMB = 10;
public static final short GLFW_GAMEPAD_BUTTON_DPAD_UP = 11;
public static final short GLFW_GAMEPAD_BUTTON_DPAD_RIGHT = 12;
public static final short GLFW_GAMEPAD_BUTTON_DPAD_DOWN = 13;
public static final short GLFW_GAMEPAD_BUTTON_DPAD_LEFT = 14;
public static final short GLFW_GAMEPAD_AXIS_LEFT_X = 0;
public static final short GLFW_GAMEPAD_AXIS_LEFT_Y = 1;
public static final short GLFW_GAMEPAD_AXIS_RIGHT_X = 2;
public static final short GLFW_GAMEPAD_AXIS_RIGHT_Y = 3;
public static final short GLFW_GAMEPAD_AXIS_LEFT_TRIGGER = 4;
public static final short GLFW_GAMEPAD_AXIS_RIGHT_TRIGGER = 5;
}
@@ -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,7 +17,7 @@ public class LeftClickGesture extends ValidatorGesture {
private boolean mMouseActivated;
public LeftClickGesture(Handler handler) {
super(handler, LauncherPreferences.PREF_LONGPRESS_TRIGGER);
super(handler);
}
public final void inputEvent() {
@@ -27,6 +27,11 @@ public class LeftClickGesture extends ValidatorGesture {
}
}
@Override
protected int getGestureDelay() {
return LauncherPreferences.PREF_LONGPRESS_TRIGGER;
}
@Override
public boolean checkAndTrigger() {
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, mGestureEndX, mGestureEndY, FINGER_STILL_THRESHOLD);
@@ -6,29 +6,35 @@ import net.kdt.pojavlaunch.LwjglGlfwKeycode;
import org.lwjgl.glfw.CallbackBridge;
public class RightClickGesture extends ValidatorGesture{
public class RightClickGesture extends ValidatorGesture {
private boolean mGestureEnabled = true;
private boolean mGestureValid = true;
private float mGestureStartX, mGestureStartY, mGestureEndX, mGestureEndY;
public RightClickGesture(Handler mHandler) {
super(mHandler, 150);
super(mHandler);
}
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;
}
@Override
protected int getGestureDelay() {
return 150;
}
@Override
public boolean checkAndTrigger() {
// If the validate() method was called, it means that the user held on for too long. The cancellation should be ignored.
@@ -44,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);
@@ -9,16 +9,13 @@ import android.os.Handler;
public abstract class ValidatorGesture implements Runnable{
private final Handler mHandler;
private boolean mGestureActive;
private final int mRequiredDuration;
/**
* @param mHandler the Handler that will be used for calling back the checkAndTrigger() method.
* This Handler should run on the same thread as the callee of submit()/cancel()
* @param mRequiredDuration the duration after which the class will call checkAndTrigger().
*/
public ValidatorGesture(Handler mHandler, int mRequiredDuration) {
public ValidatorGesture(Handler mHandler) {
this.mHandler = mHandler;
this.mRequiredDuration = mRequiredDuration;
}
/**
@@ -28,7 +25,7 @@ public abstract class ValidatorGesture implements Runnable{
*/
public final boolean submit() {
if(mGestureActive) return false;
mHandler.postDelayed(this, mRequiredDuration);
mHandler.postDelayed(this, getGestureDelay());
mGestureActive = true;
return true;
}
@@ -55,7 +52,13 @@ public abstract class ValidatorGesture implements Runnable{
}
/**
* This method will be called after mRequiredDuration milliseconds, if the gesture was not cancelled.
* This method will be called during gesture submission to determine the gesture check duration.
* @return the required gesture check duration in milliseconds
*/
protected abstract int getGestureDelay();
/**
* This method will be called after getGestureDelay() milliseconds, if the gesture was not cancelled.
* @return false if you want to mark this gesture as "inactive"
* true otherwise
*/
@@ -0,0 +1,52 @@
package net.kdt.pojavlaunch.fragments;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.ExpandableListAdapter;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.modloaders.BTADownloadTask;
import net.kdt.pojavlaunch.modloaders.BTAUtils;
import net.kdt.pojavlaunch.modloaders.BTAVersionListAdapter;
import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy;
import java.io.File;
import java.io.IOException;
public class BTAInstallFragment extends ModVersionListFragment<BTAUtils.BTAVersionList> {
public static final String TAG = "BTAInstallFragment";
public BTAInstallFragment() {
super(TAG);
}
@Override
public int getTitleText() {
return R.string.select_bta_version;
}
@Override
public int getNoDataMsg() {
return R.string.modloader_dl_failed_to_load_list;
}
@Override
public BTAUtils.BTAVersionList loadVersionList() throws IOException {
return BTAUtils.downloadVersionList();
}
@Override
public ExpandableListAdapter createAdapter(BTAUtils.BTAVersionList versionList, LayoutInflater layoutInflater) {
return new BTAVersionListAdapter(versionList, layoutInflater);
}
@Override
public Runnable createDownloadTask(Object selectedVersion, ModloaderListenerProxy listenerProxy) {
return new BTADownloadTask(listenerProxy, (BTAUtils.BTAVersion) selectedVersion);
}
@Override
public void onDownloadFinished(Context context, File downloadedFile) {
// We don't have to do anything after the BTADownloadTask ends, so this is a stub
}
}
@@ -6,19 +6,8 @@ import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy;
public class FabricInstallFragment extends FabriclikeInstallFragment {
public static final String TAG = "FabricInstallFragment";
private static ModloaderListenerProxy sTaskProxy;
public FabricInstallFragment() {
super(FabriclikeUtils.FABRIC_UTILS);
}
@Override
protected ModloaderListenerProxy getListenerProxy() {
return sTaskProxy;
}
@Override
protected void setListenerProxy(ModloaderListenerProxy listenerProxy) {
sTaskProxy = listenerProxy;
super(FabriclikeUtils.FABRIC_UTILS, TAG);
}
}
@@ -21,6 +21,7 @@ import androidx.fragment.app.Fragment;
import net.kdt.pojavlaunch.PojavApplication;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.modloaders.FabriclikeDownloadTask;
import net.kdt.pojavlaunch.modloaders.FabriclikeUtils;
import net.kdt.pojavlaunch.modloaders.FabricVersion;
@@ -36,6 +37,7 @@ import java.util.concurrent.Future;
public abstract class FabriclikeInstallFragment extends Fragment implements ModloaderDownloadListener, CompoundButton.OnCheckedChangeListener {
private final FabriclikeUtils mFabriclikeUtils;
private final String mExtraTag;
private Spinner mGameVersionSpinner;
private FabricVersion[] mGameVersionArray;
private Future<?> mGameVersionFuture;
@@ -48,9 +50,10 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
private Button mStartButton;
private View mRetryView;
private CheckBox mOnlyStableCheckbox;
protected FabriclikeInstallFragment(FabriclikeUtils mFabriclikeUtils) {
protected FabriclikeInstallFragment(FabriclikeUtils mFabriclikeUtils, String mFragmentTag) {
super(R.layout.fragment_fabric_install);
this.mFabriclikeUtils = mFabriclikeUtils;
this.mExtraTag = mFragmentTag + "_proxy";
}
@Override
@@ -239,6 +242,7 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
}
private void updateLoaderSpinner() {
if(mLoaderVersionArray == null) return;
mLoaderVersionSpinner.setAdapter(createAdapter(mLoaderVersionArray, mOnlyStableCheckbox.isChecked()));
}
@@ -285,9 +289,14 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
}
private void updateGameSpinner() {
if(mGameVersionArray == null) return;
mGameVersionSpinner.setAdapter(createAdapter(mGameVersionArray, mOnlyStableCheckbox.isChecked()));
}
protected abstract ModloaderListenerProxy getListenerProxy();
protected abstract void setListenerProxy(ModloaderListenerProxy listenerProxy);
private ModloaderListenerProxy getListenerProxy() {
return (ModloaderListenerProxy) ExtraCore.getValue(mExtraTag);
}
private void setListenerProxy(ModloaderListenerProxy listenerProxy) {
ExtraCore.setValue(mExtraTag, listenerProxy);
}
}
@@ -21,7 +21,9 @@ import java.util.List;
public class ForgeInstallFragment extends ModVersionListFragment<List<String>> {
public static final String TAG = "ForgeInstallFragment";
private static ModloaderListenerProxy sTaskProxy;
public ForgeInstallFragment() {
super(TAG);
}
@Override
public void onAttach(@NonNull Context context) {
@@ -38,15 +40,6 @@ public class ForgeInstallFragment extends ModVersionListFragment<List<String>> {
return R.string.forge_dl_no_installer;
}
@Override
public ModloaderListenerProxy getTaskProxy() {
return sTaskProxy;
}
@Override
public void setTaskProxy(ModloaderListenerProxy proxy) {
sTaskProxy = proxy;
}
@Override
public List<String> loadVersionList() throws IOException {
return ForgeUtils.downloadForgeVersions();
@@ -16,6 +16,7 @@ import androidx.fragment.app.Fragment;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.mirrors.DownloadMirror;
import net.kdt.pojavlaunch.modloaders.ModloaderDownloadListener;
import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy;
@@ -25,14 +26,15 @@ import java.io.File;
import java.io.IOException;
public abstract class ModVersionListFragment<T> extends Fragment implements Runnable, View.OnClickListener, ExpandableListView.OnChildClickListener, ModloaderDownloadListener {
public static final String TAG = "ForgeInstallFragment";
private final String mExtraTag;
private ExpandableListView mExpandableListView;
private ProgressBar mProgressBar;
private LayoutInflater mInflater;
private View mRetryView;
public ModVersionListFragment() {
public ModVersionListFragment(String mFragmentTag) {
super(R.layout.fragment_mod_version_list);
this.mExtraTag = mFragmentTag + "_proxy";
}
@Override
@@ -148,11 +150,19 @@ public abstract class ModVersionListFragment<T> extends Fragment implements Runn
});
}
private void setTaskProxy(ModloaderListenerProxy proxy) {
ExtraCore.setValue(mExtraTag, proxy);
}
private ModloaderListenerProxy getTaskProxy() {
return (ModloaderListenerProxy) ExtraCore.getValue(mExtraTag);
}
public abstract int getTitleText();
public abstract int getNoDataMsg();
public abstract ModloaderListenerProxy getTaskProxy();
public abstract T loadVersionList() throws IOException;
public abstract void setTaskProxy(ModloaderListenerProxy proxy);
public abstract ExpandableListAdapter createAdapter(T versionList, LayoutInflater layoutInflater);
public abstract Runnable createDownloadTask(Object selectedVersion, ModloaderListenerProxy listenerProxy);
public abstract void onDownloadFinished(Context context, File downloadedFile);
@@ -7,7 +7,6 @@ import android.widget.ExpandableListAdapter;
import net.kdt.pojavlaunch.JavaGUILauncherActivity;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.modloaders.ModloaderListenerProxy;
import net.kdt.pojavlaunch.modloaders.OptiFineDownloadTask;
import net.kdt.pojavlaunch.modloaders.OptiFineUtils;
@@ -18,7 +17,9 @@ import java.io.IOException;
public class OptiFineInstallFragment extends ModVersionListFragment<OptiFineUtils.OptiFineVersions> {
public static final String TAG = "OptiFineInstallFragment";
private static ModloaderListenerProxy sTaskProxy;
public OptiFineInstallFragment() {
super(TAG);
}
@Override
public int getTitleText() {
return R.string.of_dl_select_version;
@@ -28,22 +29,11 @@ public class OptiFineInstallFragment extends ModVersionListFragment<OptiFineUtil
public int getNoDataMsg() {
return R.string.of_dl_failed_to_scrape;
}
@Override
public ModloaderListenerProxy getTaskProxy() {
return sTaskProxy;
}
@Override
public OptiFineUtils.OptiFineVersions loadVersionList() throws IOException {
return OptiFineUtils.downloadOptiFineVersions();
}
@Override
public void setTaskProxy(ModloaderListenerProxy proxy) {
sTaskProxy = proxy;
}
@Override
public ExpandableListAdapter createAdapter(OptiFineUtils.OptiFineVersions versionList, LayoutInflater layoutInflater) {
return new OptiFineVersionListAdapter(versionList, layoutInflater);
@@ -35,5 +35,7 @@ public class ProfileTypeSelectFragment extends Fragment {
Tools.swapFragment(requireActivity(), SearchModFragment.class, SearchModFragment.TAG, null));
view.findViewById(R.id.modded_profile_quilt).setOnClickListener((v)->
Tools.swapFragment(requireActivity(), QuiltInstallFragment.class, QuiltInstallFragment.TAG, null));
view.findViewById(R.id.modded_profile_bta).setOnClickListener((v)->
Tools.swapFragment(requireActivity(), BTAInstallFragment.class, BTAInstallFragment.TAG, null));
}
}
@@ -9,16 +9,6 @@ public class QuiltInstallFragment extends FabriclikeInstallFragment {
private static ModloaderListenerProxy sTaskProxy;
public QuiltInstallFragment() {
super(FabriclikeUtils.QUILT_UTILS);
}
@Override
protected ModloaderListenerProxy getListenerProxy() {
return sTaskProxy;
}
@Override
protected void setListenerProxy(ModloaderListenerProxy listenerProxy) {
sTaskProxy = listenerProxy;
super(FabriclikeUtils.QUILT_UTILS, TAG);
}
}
@@ -43,7 +43,7 @@ public class DownloadMirror {
return;
}catch (FileNotFoundException e) {
Log.w("DownloadMirror", "Cannot find the file on the mirror", e);
Log.i("DownloadMirror", "Failling back to default source");
Log.i("DownloadMirror", "Falling back to default source");
}
DownloadUtils.downloadFileMonitored(urlInput, outputFile, buffer, monitor);
}
@@ -63,11 +63,53 @@ public class DownloadMirror {
return;
}catch (FileNotFoundException e) {
Log.w("DownloadMirror", "Cannot find the file on the mirror", e);
Log.i("DownloadMirror", "Failling back to default source");
Log.i("DownloadMirror", "Falling back to default source");
}
DownloadUtils.downloadFile(urlInput, outputFile);
}
/**
* Get the content length of a file on the current mirror. If the file is missing on the mirror,
* or the mirror does not give out the length, request the length from the original source
* @param downloadClass Class of the download. Can either be DOWNLOAD_CLASS_LIBRARIES,
* DOWNLOAD_CLASS_METADATA or DOWNLOAD_CLASS_ASSETS
* @param urlInput The original (Mojang) URL for the download
* @return the length of the file denoted by the URL in bytes, or -1 if not available
*/
public static long getContentLengthMirrored(int downloadClass, String urlInput) throws IOException {
long length = DownloadUtils.getContentLength(getMirrorMapping(downloadClass, urlInput));
if(length < 1) {
Log.w("DownloadMirror", "Unable to get content length from mirror");
Log.i("DownloadMirror", "Falling back to default source");
return DownloadUtils.getContentLength(urlInput);
}else {
return length;
}
}
/**
* Download a file as a string from the current mirror. If the file does not exist on the mirror
* or the mirror returns an invalid string, request the file from the original source
* @param downloadClass Class of the download. Can either be DOWNLOAD_CLASS_LIBRARIES,
* DOWNLOAD_CLASS_METADATA or DOWNLOAD_CLASS_ASSETS
* @param urlInput The original (Mojang) URL for the download
* @return the contents of the downloaded file as a String.
*/
public static String downloadStringMirrored(int downloadClass, String urlInput) throws IOException{
String resultString = null;
try {
resultString = DownloadUtils.downloadString(getMirrorMapping(downloadClass,urlInput));
}catch (FileNotFoundException e) {
Log.w("DownloadMirror", "Failed to download string from mirror", e);
}
if(Tools.isValidString(resultString)) {
return resultString;
}else {
Log.w("DownloadMirror", "Downloaded string is invalid, falling back to default");
}
return DownloadUtils.downloadString(urlInput);
}
/**
* Check if the current download source is a mirror and not an official source.
* @return true if the source is a mirror, false otherwise
@@ -0,0 +1,99 @@
package net.kdt.pojavlaunch.modloaders;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;
import com.kdt.mcgui.ProgressLayout;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
import net.kdt.pojavlaunch.utils.DownloadUtils;
import net.kdt.pojavlaunch.utils.FileUtils;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class BTADownloadTask implements Runnable {
private static final String BASE_JSON = "{\"inheritsFrom\":\"b1.7.3\",\"mainClass\":\"net.minecraft.client.Minecraft\",\"libraries\":[{\"name\":\"bta-client:bta-client:%1$s\",\"downloads\":{\"artifact\":{\"path\":\"bta-client/bta-client-%1$s.jar\",\"url\":\"%2$s\"}}}],\"id\":\"%3$s\"}";
private final ModloaderDownloadListener mListener;
private final BTAUtils.BTAVersion mBtaVersion;
public BTADownloadTask(ModloaderDownloadListener mListener, BTAUtils.BTAVersion mBtaVersion) {
this.mListener = mListener;
this.mBtaVersion = mBtaVersion;
}
@Override
public void run() {
ProgressKeeper.submitProgress(ProgressLayout.INSTALL_MODPACK, 0, R.string.fabric_dl_progress, "BTA");
try {
runCatching() ;
mListener.onDownloadFinished(null);
}catch (IOException e) {
mListener.onDownloadError(e);
}
ProgressLayout.clearProgress(ProgressLayout.INSTALL_MODPACK);
}
private String tryDownloadIcon() {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (Base64OutputStream base64OutputStream = new Base64OutputStream(byteArrayOutputStream, Base64.DEFAULT)){
// Instead of appending and wasting memory with a StringBuilder, just write the prefix
// to the stream before the base64 icon data.
byteArrayOutputStream.write("data:image/png;base64,".getBytes(StandardCharsets.US_ASCII));
DownloadUtils.download(mBtaVersion.iconUrl, base64OutputStream);
return new String(byteArrayOutputStream.toByteArray(), StandardCharsets.US_ASCII);
}catch (IOException e) {
Log.w("BTADownloadTask", "Failed to download base64 icon", e);
}finally {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
Log.wtf("BTADownloadTask", "Failed to close a byte array stream??", e);
}
}
return null;
}
private void createJson(String btaVersionId) throws IOException {
String btaJson = String.format(BASE_JSON, mBtaVersion.versionName, mBtaVersion.downloadUrl, btaVersionId);
File jsonDir = new File(Tools.DIR_HOME_VERSION, btaVersionId);
File jsonFile = new File(jsonDir, btaVersionId+".json");
FileUtils.ensureDirectory(jsonDir);
Tools.write(jsonFile.getAbsolutePath(), btaJson);
}
// BTA doesn't have SHA1 checksums in its repositories, so the user may try to reinstall it
// if it didn't work due to a broken download. So, for reinstalls like that to work,
// we need to delete the old client jar to force the download of a new one.
private void removeOldClient() throws IOException{
File btaClientPath = new File(Tools.DIR_HOME_LIBRARY, String.format("bta-client/bta-client-%1$s.jar", mBtaVersion.versionName));
if(btaClientPath.exists() && !btaClientPath.delete())
throw new IOException("Failed to delete old client jar");
}
private void createProfile(String btaVersionId) throws IOException {
LauncherProfiles.load();
MinecraftProfile btaProfile = new MinecraftProfile();
btaProfile.lastVersionId = btaVersionId;
btaProfile.name = "Better than Adventure!";
// Allows for smooth upgrades
btaProfile.gameDir = "./custom_instances/better_than_adventure";
btaProfile.icon = tryDownloadIcon();
LauncherProfiles.insertMinecraftProfile(btaProfile);
LauncherProfiles.write();
}
public void runCatching() throws IOException {
removeOldClient();
String btaVersionId = "bta-"+mBtaVersion.versionName;
createJson(btaVersionId);
createProfile(btaVersionId);
}
}
@@ -0,0 +1,142 @@
package net.kdt.pojavlaunch.modloaders;
import android.util.Log;
import androidx.annotation.Keep;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.SerializedName;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.utils.DownloadUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class BTAUtils {
private static final String BASE_DOWNLOADS_URL = "https://downloads.betterthanadventure.net/bta-client/";
private static final String CLIENT_JAR_URL = BASE_DOWNLOADS_URL + "%s/%s/client.jar";
private static final String ICON_URL = BASE_DOWNLOADS_URL + "%s/%s/auto/%s.png";
private static final String MANIFEST_URL = BASE_DOWNLOADS_URL + "%s/versions.json";
private static final String BUILD_TYPE_RELEASE = "release";
private static final String BUILD_TYPE_NIGHTLY = "nightly";
private static final List<String> BTA_TESTED_VERSIONS = new ArrayList<>();
static {
BTA_TESTED_VERSIONS.add("v7.3");
BTA_TESTED_VERSIONS.add("v7.2_01");
BTA_TESTED_VERSIONS.add("v7.2");
BTA_TESTED_VERSIONS.add("v7.1_01");
BTA_TESTED_VERSIONS.add("v7.1");
}
private static String getIconUrl(String version, String buildType) {
String iconName = version.replace('.','_');
if(buildType.equals("nightly")) iconName = "v"+iconName;
return String.format(ICON_URL, buildType, version, iconName);
}
private static String getClientJarUrl(String version, String buildType) {
return String.format(CLIENT_JAR_URL, buildType, version);
}
private static String getManifestUrl(String buildType) {
return String.format(MANIFEST_URL, buildType);
}
private static <T> T getManifest(String buildType, DownloadUtils.ParseCallback<T> parser)
throws DownloadUtils.ParseException, IOException {
String manifestUrl = getManifestUrl(buildType);
return DownloadUtils.downloadStringCached(manifestUrl,"bta_"+manifestUrl, parser);
}
private static List<BTAVersion> createVersionList(List<String> versionStrings, String buildType) {
ListIterator<String> iterator = versionStrings.listIterator(versionStrings.size());
ArrayList<BTAVersion> btaVersions = new ArrayList<>(versionStrings.size());
// The original list is guaranteed to be in ascending order - the earliest versions
// are at the top, but for user convenience we need to put the newest versions at the top,
// so the BTAVersion list is made from the reverse of the string list.
while(iterator.hasPrevious()) {
String version = iterator.previous();
if(version == null) continue;
btaVersions.add(new BTAVersion(
version,
getClientJarUrl(version, buildType),
getIconUrl(version, buildType)
));
}
btaVersions.trimToSize();
return btaVersions;
}
private static List<BTAVersion> processNightliesJson(String nightliesInfo) throws JsonParseException {
BTAVersionsManifest manifest = Tools.GLOBAL_GSON.fromJson(nightliesInfo, BTAVersionsManifest.class);
return createVersionList(manifest.versions, BUILD_TYPE_NIGHTLY);
}
private static BTAVersionList processReleasesJson(String releasesInfo) throws JsonParseException {
BTAVersionsManifest manifest = Tools.GLOBAL_GSON.fromJson(releasesInfo, BTAVersionsManifest.class);
List<String> stringVersions = manifest.versions;
List<String> testedVersions = new ArrayList<>();
List<String> untestedVersions = new ArrayList<>();
for(String version : stringVersions) {
if(version == null) break;
// Checking for presence in testing array here to avoid accidentally adding nonexistent
// versions if some of them end up getting removed.
if(BTA_TESTED_VERSIONS.contains(version)) {
testedVersions.add(version);
}else {
untestedVersions.add(version);
}
}
return new BTAVersionList(
createVersionList(testedVersions, BUILD_TYPE_RELEASE),
createVersionList(untestedVersions, BUILD_TYPE_RELEASE),
null
);
}
public static BTAVersionList downloadVersionList() throws IOException {
try {
BTAVersionList releases = getManifest(BUILD_TYPE_RELEASE, BTAUtils::processReleasesJson);
List<BTAVersion> nightlies = getManifest(BUILD_TYPE_NIGHTLY, BTAUtils::processNightliesJson);
return new BTAVersionList(releases.testedVersions, releases.untestedVersions, nightlies);
}catch (DownloadUtils.ParseException e) {
Log.e("BTAUtils", "Failed to process json", e);
return null;
}
}
private static class BTAVersionsManifest {
@Keep
public List<String> versions;
@Keep
@SerializedName("default")
public String defaultVersion;
}
public static class BTAVersion {
public final String versionName;
public final String downloadUrl;
public final String iconUrl;
public BTAVersion(String versionName, String downloadUrl, String iconUrl) {
this.versionName = versionName;
this.downloadUrl = downloadUrl;
this.iconUrl = iconUrl;
}
}
public static class BTAVersionList {
public final List<BTAVersion> testedVersions;
public final List<BTAVersion> untestedVersions;
public final List<BTAVersion> nightlyVersions;
public BTAVersionList(List<BTAVersion> mTestedVersions, List<BTAVersion> mUntestedVersions, List<BTAVersion> nightlyVersions) {
this.testedVersions = mTestedVersions;
this.untestedVersions = mUntestedVersions;
this.nightlyVersions = nightlyVersions;
}
}
}
@@ -0,0 +1,99 @@
package net.kdt.pojavlaunch.modloaders;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.TextView;
import net.kdt.pojavlaunch.R;
import java.util.ArrayList;
import java.util.List;
public class BTAVersionListAdapter extends BaseExpandableListAdapter implements ExpandableListAdapter{
private final LayoutInflater mLayoutInflater;
private final ArrayList<String> mGroupNames;
private final ArrayList<List<BTAUtils.BTAVersion>> mGroups;
public BTAVersionListAdapter(BTAUtils.BTAVersionList versionList, LayoutInflater mLayoutInflater) {
this.mLayoutInflater = mLayoutInflater;
Context context = mLayoutInflater.getContext();
mGroupNames = new ArrayList<>(2);
mGroups = new ArrayList<>(2);
if(!versionList.testedVersions.isEmpty()) {
mGroupNames.add(context.getString(R.string.bta_installer_available_versions));
mGroups.add(versionList.testedVersions);
}
if(!versionList.untestedVersions.isEmpty()) {
mGroupNames.add(context.getString(R.string.bta_installer_untested_versions));
mGroups.add(versionList.untestedVersions);
}
if(!versionList.nightlyVersions.isEmpty()) {
mGroupNames.add(context.getString(R.string.bta_installer_nightly_versions));
mGroups.add(versionList.nightlyVersions);
}
mGroupNames.trimToSize();
mGroups.trimToSize();
}
@Override
public int getGroupCount() {
return mGroups.size();
}
@Override
public int getChildrenCount(int i) {
return mGroups.get(i).size();
}
@Override
public Object getGroup(int i) {
return mGroupNames.get(i);
}
@Override
public BTAUtils.BTAVersion getChild(int i, int i1) {
return mGroups.get(i).get(i1);
}
@Override
public long getGroupId(int i) {
return i;
}
@Override
public long getChildId(int i, int i1) {
return i1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int i, boolean b, View convertView, ViewGroup viewGroup) {
if(convertView == null)
convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, viewGroup, false);
((TextView) convertView).setText((String)getGroup(i));
return convertView;
}
@Override
public View getChildView(int i, int i1, boolean b, View convertView, ViewGroup viewGroup) {
if(convertView == null)
convertView = mLayoutInflater.inflate(android.R.layout.simple_expandable_list_item_1, viewGroup, false);
((TextView) convertView).setText(getChild(i,i1).versionName);
return convertView;
}
@Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
}
@@ -21,7 +21,14 @@ public class ModpackInstaller {
public static ModLoader installModpack(ModDetail modDetail, int selectedVersion, InstallFunction installFunction) throws IOException {
String versionUrl = modDetail.versionUrls[selectedVersion];
String versionHash = modDetail.versionHashes[selectedVersion];
String modpackName = modDetail.title.toLowerCase(Locale.ROOT).trim().replace(" ", "_" );
String modpackName = (modDetail.title.toLowerCase(Locale.ROOT) + " " + modDetail.versionNames[selectedVersion])
.trim().replaceAll("[\\\\/:*?\"<>| \\t\\n]", "_" );
if (versionHash != null) {
modpackName += "_" + versionHash;
}
if (modpackName.length() > 255){
modpackName = modpackName.substring(0,255);
}
// Build a new minecraft instance, folder first
@@ -5,15 +5,21 @@ import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import java.io.File;
public class FFmpegPlugin {
public static boolean isAvailable = false;
public static String libraryPath;
public static String executablePath;
public static void discover(Context context) {
PackageManager manager = context.getPackageManager();
try {
PackageInfo ffmpegPluginInfo = manager.getPackageInfo("net.kdt.pojavlaunch.ffmpeg", PackageManager.GET_SHARED_LIBRARY_FILES);
libraryPath = ffmpegPluginInfo.applicationInfo.nativeLibraryDir;
isAvailable = true;
File ffmpegExecutable = new File(libraryPath, "libffmpeg.so");
executablePath = ffmpegExecutable.getAbsolutePath();
// Older plugin versions still have the old executable location
isAvailable = ffmpegExecutable.exists();
}catch (Exception e) {
Log.i("FFmpegPlugin", "Failed to discover plugin", e);
}
@@ -23,15 +23,18 @@ public class CustomSeekBarPreference extends SeekBarPreference {
private int mMin;
/** The textview associated by default to the preference */
private TextView mTextView;
/** Seekbar increment in case the max gets set */
private final int mIncrement;
@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);
mIncrement = a.getInt(R.styleable.SeekBarPreference_seekBarIncrement, 0);
}
}
public CustomSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
@@ -111,7 +114,12 @@ public class CustomSeekBarPreference extends SeekBarPreference {
*/
public void setRange(int min, int max){
setMin(min);
setMax(max);
setMaxKeepIncrement(max);
}
public void setMaxKeepIncrement(int max) {
super.setMax(max);
setSeekBarIncrement(mIncrement);
}
@@ -10,17 +10,15 @@ import android.content.*;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import androidx.core.view.DisplayCutoutCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.utils.JREUtils;
import java.io.IOException;
public class LauncherPreferences {
public static final String PREF_KEY_CURRENT_PROFILE = "currentProfile";
public static final String PREF_KEY_SKIP_NOTIFICATION_CHECK = "skipNotificationPermissionCheck";
@@ -28,11 +26,6 @@ public class LauncherPreferences {
public static SharedPreferences DEFAULT_PREF;
public static String PREF_RENDERER = "opengles2";
public static boolean PREF_VERTYPE_RELEASE = true;
public static boolean PREF_VERTYPE_SNAPSHOT = false;
public static boolean PREF_VERTYPE_OLDALPHA = false;
public static boolean PREF_VERTYPE_OLDBETA = false;
public static boolean PREF_HIDE_SIDEBAR = false;
public static boolean PREF_IGNORE_NOTCH = false;
public static int PREF_NOTCH_SIZE = 0;
public static float PREF_BUTTONSIZE = 100f;
@@ -54,14 +47,14 @@ public class LauncherPreferences {
public static boolean PREF_USE_ALTERNATE_SURFACE = true;
public static boolean PREF_JAVA_SANDBOX = true;
public static float PREF_SCALE_FACTOR = 1f;
public static boolean PREF_ENABLE_GYRO = false;
public static float PREF_GYRO_SENSITIVITY = 1f;
public static int PREF_GYRO_SAMPLE_RATE = 16;
public static boolean PREF_GYRO_SMOOTHING = true;
public static boolean PREF_GYRO_INVERT_X = false;
public static boolean PREF_GYRO_INVERT_Y = false;
public static boolean PREF_FORCE_VSYNC = false;
public static boolean PREF_BUTTON_ALL_CAPS = true;
@@ -77,19 +70,15 @@ 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");
PREF_BUTTONSIZE = DEFAULT_PREF.getInt("buttonscale", 100);
PREF_MOUSESCALE = DEFAULT_PREF.getInt("mousescale", 100)/100f;
PREF_MOUSESPEED = ((float)DEFAULT_PREF.getInt("mousespeed",100))/100f;
PREF_HIDE_SIDEBAR = DEFAULT_PREF.getBoolean("hideSidebar", false);
PREF_IGNORE_NOTCH = DEFAULT_PREF.getBoolean("ignoreNotch", false);
PREF_VERTYPE_RELEASE = DEFAULT_PREF.getBoolean("vertype_release", true);
PREF_VERTYPE_SNAPSHOT = DEFAULT_PREF.getBoolean("vertype_snapshot", false);
PREF_VERTYPE_OLDALPHA = DEFAULT_PREF.getBoolean("vertype_oldalpha", false);
PREF_VERTYPE_OLDBETA = DEFAULT_PREF.getBoolean("vertype_oldbeta", false);
PREF_MOUSESPEED = ((float)DEFAULT_PREF.getInt("mousespeed",100))/100f;
PREF_IGNORE_NOTCH = DEFAULT_PREF.getBoolean("ignoreNotch", false);
PREF_LONGPRESS_TRIGGER = DEFAULT_PREF.getInt("timeLongPressTrigger", 300);
PREF_DEFAULTCTRL_PATH = DEFAULT_PREF.getString("defaultCtrl", Tools.CTRLDEF_FILE);
PREF_FORCE_ENGLISH = DEFAULT_PREF.getBoolean("force_english", false);
@@ -98,19 +87,19 @@ public class LauncherPreferences {
PREF_DISABLE_SWAP_HAND = DEFAULT_PREF.getBoolean("disableDoubleTap", false);
PREF_RAM_ALLOCATION = DEFAULT_PREF.getInt("allocation", findBestRAMAllocation(ctx));
PREF_CUSTOM_JAVA_ARGS = DEFAULT_PREF.getString("javaArgs", "");
PREF_SUSTAINED_PERFORMANCE = DEFAULT_PREF.getBoolean("sustainedPerformance", false);
PREF_SUSTAINED_PERFORMANCE = DEFAULT_PREF.getBoolean("sustainedPerformance", isDevicePowerful);
PREF_VIRTUAL_MOUSE_START = DEFAULT_PREF.getBoolean("mouse_start", false);
PREF_ARC_CAPES = DEFAULT_PREF.getBoolean("arc_capes",false);
PREF_USE_ALTERNATE_SURFACE = DEFAULT_PREF.getBoolean("alternate_surface", false);
PREF_USE_ALTERNATE_SURFACE = DEFAULT_PREF.getBoolean("alternate_surface", isDevicePowerful);
PREF_JAVA_SANDBOX = DEFAULT_PREF.getBoolean("java_sandbox", true);
PREF_SCALE_FACTOR = DEFAULT_PREF.getInt("resolutionRatio", 100)/100f;
PREF_SCALE_FACTOR = DEFAULT_PREF.getInt("resolutionRatio", findBestResolution(ctx, isDevicePowerful))/100f;
PREF_ENABLE_GYRO = DEFAULT_PREF.getBoolean("enableGyro", false);
PREF_GYRO_SENSITIVITY = ((float)DEFAULT_PREF.getInt("gyroSensitivity", 100))/100f;
PREF_GYRO_SAMPLE_RATE = DEFAULT_PREF.getInt("gyroSampleRate", 16);
PREF_GYRO_SMOOTHING = DEFAULT_PREF.getBoolean("gyroSmoothing", true);
PREF_GYRO_INVERT_X = DEFAULT_PREF.getBoolean("gyroInvertX", false);
PREF_GYRO_INVERT_Y = DEFAULT_PREF.getBoolean("gyroInvertY", false);
PREF_FORCE_VSYNC = DEFAULT_PREF.getBoolean("force_vsync", false);
PREF_FORCE_VSYNC = DEFAULT_PREF.getBoolean("force_vsync", isDevicePowerful);
PREF_BUTTON_ALL_CAPS = DEFAULT_PREF.getBoolean("buttonAllCaps", true);
PREF_DUMP_SHADERS = DEFAULT_PREF.getBoolean("dump_shaders", false);
PREF_DEADZONE_SCALE = ((float) DEFAULT_PREF.getInt("gamepad_deadzone_scale", 100))/100f;
@@ -132,7 +121,7 @@ public class LauncherPreferences {
if(DEFAULT_PREF.contains("defaultRuntime")) {
PREF_DEFAULT_RUNTIME = DEFAULT_PREF.getString("defaultRuntime","");
}else{
if(MultiRTUtils.getRuntimes().size() < 1) {
if(MultiRTUtils.getRuntimes().isEmpty()) {
PREF_DEFAULT_RUNTIME = "";
return;
}
@@ -152,18 +141,58 @@ public class LauncherPreferences {
*/
private static int findBestRAMAllocation(Context ctx){
int deviceRam = Tools.getTotalDeviceMemory(ctx);
if (deviceRam < 1024) return 300;
if (deviceRam < 1536) return 450;
if (deviceRam < 2048) return 600;
if (deviceRam < 1024) return 296;
if (deviceRam < 1536) return 448;
if (deviceRam < 2048) return 656;
// Limit the max for 32 bits devices more harshly
if (is32BitsDevice()) return 700;
if (is32BitsDevice()) return 696;
if (deviceRam < 3064) return 936;
if (deviceRam < 4096) return 1148;
if (deviceRam < 4096) return 1144;
if (deviceRam < 6144) return 1536;
return 2048; //Default RAM allocation for 64 bits
}
/// Find a correct resolution for the device
///
/// Some devices are shipped with a ridiculously high resolution, which can cause performance issues
/// This function will try to find a resolution that is good enough for the device
private static int findBestResolution(Context context, boolean isDevicePowerful) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int minSide = Math.min(metrics.widthPixels, metrics.heightPixels);
int targetSide = isDevicePowerful ? 1080 : 720;
if (minSide <= targetSide) return 100; // No need to scale down
float ratio = (100f * targetSide / minSide);
// The value must match the seekbar values
int increment = context.getResources().getInteger(R.integer.resolution_seekbar_increment);
return (int) (Math.ceil(ratio / increment) * increment);
}
/// Check if the device is considered powerful.
/// Powerful devices will have some energy saving tweaks enabled by default
private static boolean isDevicePowerful(Context context) {
if (SDK_INT < Build.VERSION_CODES.Q) return false;
if (Tools.getTotalDeviceMemory(context) <= 4096) return false;
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
if (Math.min(metrics.widthPixels, metrics.heightPixels) < 1080) return false;
if (Runtime.getRuntime().availableProcessors() <= 4) return false;
if (hasAllCoreSameFreq()) return false;
return true;
}
private static boolean hasAllCoreSameFreq() {
int coreCount = Runtime.getRuntime().availableProcessors();
try {
String freq0 = Tools.read("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq");
String freqX = Tools.read("/sys/devices/system/cpu/cpu" + (coreCount - 1) + "/cpufreq/cpuinfo_max_freq");
if(freq0.equals(freqX)) return true;
} catch (IOException e) {
Log.e("LauncherPreferences", "Failed to read CPU frequencies", e);
}
return false;
}
/** Compute the notch size to avoid being out of bounds */
public static void computeNotchSize(Activity activity) {
if (Build.VERSION.SDK_INT < P) return;
@@ -122,8 +122,6 @@ public abstract class QuickSettingSideDialog extends com.kdt.SideDialogView {
mEditor.putBoolean("disableGestures", isChecked);
});
mGyroSensitivityBar.setRange(25, 300);
mGyroSensitivityBar.setIncrement(5);
mGyroSensitivityBar.setOnSeekBarChangeListener((SimpleSeekBarListener) (seekBar, progress, fromUser) -> {
PREF_GYRO_SENSITIVITY = progress / 100f;
mEditor.putInt("gyroSensitivity", progress);
@@ -132,8 +130,6 @@ public abstract class QuickSettingSideDialog extends com.kdt.SideDialogView {
mGyroSensitivityBar.setProgress((int) (mOriginalGyroSensitivity * 100f));
setSeekTextPercent(mGyroSensitivityText, mGyroSensitivityBar.getProgress());
mMouseSpeedBar.setRange(25, 300);
mMouseSpeedBar.setIncrement(5);
mMouseSpeedBar.setOnSeekBarChangeListener((SimpleSeekBarListener) (seekBar, progress, fromUser) -> {
PREF_MOUSESPEED = progress / 100f;
mEditor.putInt("mousespeed", progress);
@@ -142,8 +138,6 @@ public abstract class QuickSettingSideDialog extends com.kdt.SideDialogView {
mMouseSpeedBar.setProgress((int) (mOriginalMouseSpeed * 100f));
setSeekTextPercent(mMouseSpeedText, mMouseSpeedBar.getProgress());
mGestureDelayBar.setRange(100, 1000);
mGestureDelayBar.setIncrement(10);
mGestureDelayBar.setOnSeekBarChangeListener((SimpleSeekBarListener) (seekBar, progress, fromUser) -> {
PREF_LONGPRESS_TRIGGER = progress;
mEditor.putInt("timeLongPressTrigger", progress);
@@ -152,8 +146,6 @@ public abstract class QuickSettingSideDialog extends com.kdt.SideDialogView {
mGestureDelayBar.setProgress(mOriginalGestureDelay);
setSeekTextMillisecond(mGestureDelayText, mGestureDelayBar.getProgress());
mResolutionBar.setRange(25, 100);
mResolutionBar.setIncrement(5);
mResolutionBar.setOnSeekBarChangeListener((SimpleSeekBarListener) (seekBar, progress, fromUser) -> {
PREF_SCALE_FACTOR = progress/100f;
mEditor.putInt("resolutionRatio", progress);
@@ -2,8 +2,6 @@ package net.kdt.pojavlaunch.prefs.screens;
import android.content.Context;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import androidx.preference.PreferenceCategory;
@@ -32,31 +30,26 @@ public class LauncherPreferenceControlFragment extends LauncherPreferenceFragmen
CustomSeekBarPreference seek2 = requirePreference("timeLongPressTrigger",
CustomSeekBarPreference.class);
seek2.setRange(100, 1000);
seek2.setValue(longPressTrigger);
seek2.setSuffix(" ms");
CustomSeekBarPreference seek3 = requirePreference("buttonscale",
CustomSeekBarPreference.class);
seek3.setRange(80, 250);
seek3.setValue(prefButtonSize);
seek3.setSuffix(" %");
CustomSeekBarPreference seek4 = requirePreference("mousescale",
CustomSeekBarPreference.class);
seek4.setRange(25, 300);
seek4.setValue(mouseScale);
seek4.setSuffix(" %");
CustomSeekBarPreference seek6 = requirePreference("mousespeed",
CustomSeekBarPreference.class);
seek6.setRange(25, 300);
seek6.setValue((int)(mouseSpeed *100f));
seek6.setSuffix(" %");
CustomSeekBarPreference deadzoneSeek = requirePreference("gamepad_deadzone_scale",
CustomSeekBarPreference.class);
deadzoneSeek.setRange(50, 200);
deadzoneSeek.setValue((int) (joystickDeadzone * 100f));
deadzoneSeek.setSuffix(" %");
@@ -71,13 +64,11 @@ public class LauncherPreferenceControlFragment extends LauncherPreferenceFragmen
CustomSeekBarPreference gyroSensitivitySeek = requirePreference("gyroSensitivity",
CustomSeekBarPreference.class);
gyroSensitivitySeek.setRange(25, 300);
gyroSensitivitySeek.setValue((int) (gyroSpeed*100f));
gyroSensitivitySeek.setSuffix(" %");
CustomSeekBarPreference gyroSampleRateSeek = requirePreference("gyroSampleRate",
CustomSeekBarPreference.class);
gyroSampleRateSeek.setRange(5, 50);
gyroSampleRateSeek.setValue(gyroSampleRate);
gyroSampleRateSeek.setSuffix(" ms");
computeVisibility();
@@ -29,19 +29,18 @@ public class LauncherPreferenceJavaFragment extends LauncherPreferenceFragment {
// Triggers a write for some reason
addPreferencesFromResource(R.xml.pref_java);
CustomSeekBarPreference seek7 = requirePreference("allocation",
CustomSeekBarPreference memorySeekbar = requirePreference("allocation",
CustomSeekBarPreference.class);
int maxRAM;
int deviceRam = getTotalDeviceMemory(seek7.getContext());
int deviceRam = getTotalDeviceMemory(memorySeekbar.getContext());
if(is32BitsDevice() || deviceRam < 2048) maxRAM = Math.min(1024, deviceRam);
else maxRAM = deviceRam - (deviceRam < 3064 ? 800 : 1024); //To have a minimum for the device to breathe
seek7.setMin(256);
seek7.setMax(maxRAM);
seek7.setValue(ramAllocation);
seek7.setSuffix(" MB");
memorySeekbar.setMaxKeepIncrement(maxRAM);
memorySeekbar.setValue(ramAllocation);
memorySeekbar.setSuffix(" MB");
EditTextPreference editJVMArgs = findPreference("javaArgs");
if (editJVMArgs != null) {
@@ -1,19 +1,21 @@
package net.kdt.pojavlaunch.prefs.screens;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.preference.Preference;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.utils.GLInfoUtils;
public class LauncherPreferenceMiscellaneousFragment extends LauncherPreferenceFragment {
@Override
public void onCreatePreferences(Bundle b, String str) {
addPreferencesFromResource(R.xml.pref_misc);
Preference driverPreference = requirePreference("zinkPreferSystemDriver");
if(!Tools.checkVulkanSupport(driverPreference.getContext().getPackageManager())) {
driverPreference.setVisible(false);
}
PackageManager packageManager = driverPreference.getContext().getPackageManager();
boolean supportsTurnip = Tools.checkVulkanSupport(packageManager) && GLInfoUtils.getGlInfo().isAdreno();
driverPreference.setVisible(supportsTurnip);
}
}
@@ -1,7 +1,5 @@
package net.kdt.pojavlaunch.prefs.screens;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_NOTCH_SIZE;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
@@ -22,24 +20,30 @@ public class LauncherPreferenceVideoFragment extends LauncherPreferenceFragment
@Override
public void onCreatePreferences(Bundle b, String str) {
addPreferencesFromResource(R.xml.pref_video);
int resolution = (int) (LauncherPreferences.PREF_SCALE_FACTOR * 100);
//Disable notch checking behavior on android 8.1 and below.
requirePreference("ignoreNotch").setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && PREF_NOTCH_SIZE > 0);
requirePreference("ignoreNotch").setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && LauncherPreferences.PREF_NOTCH_SIZE > 0);
CustomSeekBarPreference seek5 = requirePreference("resolutionRatio",
CustomSeekBarPreference resolutionSeekbar = requirePreference("resolutionRatio",
CustomSeekBarPreference.class);
seek5.setMin(25);
seek5.setSuffix(" %");
resolutionSeekbar.setSuffix(" %");
// #724 bug fix
if (seek5.getValue() < 25) {
seek5.setValue(100);
if (resolution < 25) {
resolutionSeekbar.setValue(100);
} else {
resolutionSeekbar.setValue(resolution);
}
// Sustained performance is only available since Nougat
SwitchPreference sustainedPerfSwitch = requirePreference("sustainedPerformance",
SwitchPreference.class);
sustainedPerfSwitch.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N);
sustainedPerfSwitch.setChecked(LauncherPreferences.PREF_SUSTAINED_PERFORMANCE);
requirePreference("alternate_surface", SwitchPreferenceCompat.class).setChecked(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE);
requirePreference("force_vsync", SwitchPreferenceCompat.class).setChecked(LauncherPreferences.PREF_FORCE_VSYNC);
ListPreference rendererListPreference = requirePreference("renderer",
ListPreference.class);
@@ -95,21 +95,21 @@ public class ProfileAdapter extends BaseAdapter {
Drawable cachedIcon = ProfileIconCache.fetchIcon(v.getResources(), nm, minecraftProfile.icon);
extendedTextView.setCompoundDrawablesRelative(cachedIcon, null, extendedTextView.getCompoundsDrawables()[2], null);
if(Tools.isValidString(minecraftProfile.name))
extendedTextView.setText(minecraftProfile.name);
else
extendedTextView.setText(R.string.unnamed);
// Historically, the profile name "New" was hardcoded as the default profile name
// We consider "New" the same as putting no name at all
String profileName = (Tools.isValidString(minecraftProfile.name) && !"New".equalsIgnoreCase(minecraftProfile.name)) ? minecraftProfile.name : null;
String versionName = minecraftProfile.lastVersionId;
if(minecraftProfile.lastVersionId != null){
if(minecraftProfile.lastVersionId.equalsIgnoreCase("latest-release")){
extendedTextView.setText( String.format("%s - %s", extendedTextView.getText(), v.getContext().getText(R.string.profiles_latest_release)));
} else if(minecraftProfile.lastVersionId.equalsIgnoreCase("latest-snapshot")){
extendedTextView.setText( String.format("%s - %s", extendedTextView.getText(), v.getContext().getText(R.string.profiles_latest_snapshot)));
} else {
extendedTextView.setText( String.format("%s - %s", extendedTextView.getText(), minecraftProfile.lastVersionId));
}
if (MinecraftProfile.LATEST_RELEASE.equalsIgnoreCase(versionName))
versionName = v.getContext().getString(R.string.profiles_latest_release);
else if (MinecraftProfile.LATEST_SNAPSHOT.equalsIgnoreCase(versionName))
versionName = v.getContext().getString(R.string.profiles_latest_snapshot);
} else extendedTextView.setText(extendedTextView.getText());
if (versionName == null && profileName != null)
extendedTextView.setText(profileName);
else if (versionName != null && profileName == null)
extendedTextView.setText(versionName);
else extendedTextView.setText(String.format("%s - %s", profileName, versionName));
// Set selected background if needed
if(displaySelection){
@@ -1,10 +1,12 @@
package net.kdt.pojavlaunch.scoped;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Point;
import android.net.Uri;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract;
@@ -16,6 +18,7 @@ import android.webkit.MimeTypeMap;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.BuildConfig;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
@@ -44,8 +47,11 @@ 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;
private String mStorageProviderAuthortiy;
// The default columns to return information about a root if no specific
// columns are requested in a query.
@@ -76,10 +82,15 @@ public class FolderProvider extends DocumentsProvider {
final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_ROOT_PROJECTION);
final String applicationName = getContext().getString(R.string.app_short_name);
String summary = BuildConfig.VERSION_NAME;
if (BuildConfig.DEBUG) {
summary = "(" + getContext().getString(R.string.generic_debug) + ") " + summary;
}
final MatrixCursor.RowBuilder row = result.newRow();
row.add(Root.COLUMN_ROOT_ID, getDocIdForFile(BASE_DIR));
row.add(Root.COLUMN_DOCUMENT_ID, getDocIdForFile(BASE_DIR));
row.add(Root.COLUMN_SUMMARY, null);
row.add(Root.COLUMN_SUMMARY, summary);
row.add(Root.COLUMN_FLAGS, Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_SEARCH | Root.FLAG_SUPPORTS_IS_CHILD);
row.add(Root.COLUMN_TITLE, applicationName);
row.add(Root.COLUMN_MIME_TYPES, ALL_MIME_TYPES);
@@ -91,6 +102,8 @@ public class FolderProvider extends DocumentsProvider {
@Override
public Cursor queryDocument(String documentId, String[] projection) throws FileNotFoundException {
final MatrixCursor result = new MatrixCursor(projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION);
// Future-proofing in case if we implement realtime file watching
result.setNotificationUri(mContentResolver, createUriForDocId(documentId));
includeFile(result, documentId, null);
return result;
}
@@ -104,6 +117,8 @@ public class FolderProvider extends DocumentsProvider {
for (File file : children) {
includeFile(result, null, file);
}
// Set the notification URI as that's what the "Files" app will be listening to in case of file deletion
result.setNotificationUri(mContentResolver, createUriForDocId(parentDocumentId));
return result;
}
@@ -123,6 +138,14 @@ 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;
}
@@ -146,6 +169,8 @@ public class FolderProvider extends DocumentsProvider {
} catch (IOException e) {
throw new FileNotFoundException("Failed to create document with id " + newFile.getPath());
}
// Notify the file manager that the parent directory has changed
notifyChange(createUriForDocId(parentDocumentId));
return newFile.getPath();
}
@@ -190,6 +215,8 @@ public class FolderProvider extends DocumentsProvider {
throw new FileNotFoundException("Failed to delete document with id " + documentId);
}
}
// Notify the file manager that the parent directory has changed
notifyChange(createUriForFile(file.getParentFile()));
}
@Override
@@ -332,4 +359,16 @@ public class FolderProvider extends DocumentsProvider {
Log.i("FolderProvider", pathIds.toString());
return new DocumentsContract.Path(getDocIdForFile(source), pathIds);
}
private Uri createUriForDocId(String documentId) throws FileNotFoundException {
return createUriForFile(getFileForDocId(documentId));
}
private Uri createUriForFile(File file) {
return DocumentsContract.buildDocumentUri(mStorageProviderAuthortiy, file.getAbsolutePath());
}
private void notifyChange(Uri uri) {
mContentResolver.notifyChange(uri, null);
}
}
@@ -3,13 +3,14 @@ package net.kdt.pojavlaunch.tasks;
import net.kdt.pojavlaunch.JMinecraftVersionList;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
public class AsyncMinecraftDownloader {
public static String normalizeVersionId(String versionString) {
JMinecraftVersionList versionList = (JMinecraftVersionList) ExtraCore.getValue(ExtraConstants.RELEASE_TABLE);
if(versionList == null || versionList.versions == null) return versionString;
if("latest-release".equals(versionString)) versionString = versionList.latest.get("release");
if("latest-snapshot".equals(versionString)) versionString = versionList.latest.get("snapshot");
if(MinecraftProfile.LATEST_RELEASE.equals(versionString)) versionString = versionList.latest.get("release");
if(MinecraftProfile.LATEST_SNAPSHOT.equals(versionString)) versionString = versionList.latest.get("snapshot");
return versionString;
}
@@ -37,14 +37,20 @@ import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
public class MinecraftDownloader {
private static final double ONE_MEGABYTE = (1024d * 1024d);
public static final String MINECRAFT_RES = "https://resources.download.minecraft.net/";
private static final String MAVEN_CENTRAL_REPO1 = "https://repo1.maven.org/maven2/";
private AtomicReference<Exception> mDownloaderThreadException;
private ArrayList<DownloaderTask> mScheduledDownloadTasks;
private AtomicLong mDownloadFileCounter;
private AtomicLong mDownloadSizeCounter;
private long mDownloadFileCount;
private ArrayList<File> mDeclaredNatives;
private AtomicLong mProcessedFileCounter;
private AtomicLong mProcessedSizeCounter; // Total bytes of processed files (passed SHA1 or downloaded)
private AtomicLong mInternetUsageCounter; // How many bytes downloaded over Internet
private long mTotalFileCount;
private long mTotalSize;
private File mSourceJarFile; // The source client JAR picked during the inheritance process
private File mTargetJarFile; // The destination client JAR to which the source will be copied to.
private boolean mUseFileCounter; // Whether a file counter or a size counter should be used for progress
private static final ThreadLocal<byte[]> sThreadLocalDownloadBuffer = new ThreadLocal<>();
@@ -80,12 +86,16 @@ public class MinecraftDownloader {
// Put up a dummy progress line, for the activity to start the service and do all the other necessary
// work to keep the launcher alive. We will replace this line when we will start downloading stuff.
ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, 0, R.string.newdl_starting);
SpeedCalculator speedCalculator = new SpeedCalculator();
mTargetJarFile = createGameJarPath(versionName);
mScheduledDownloadTasks = new ArrayList<>();
mDownloadFileCounter = new AtomicLong(0);
mDownloadSizeCounter = new AtomicLong(0);
mDeclaredNatives = new ArrayList<>();
mProcessedFileCounter = new AtomicLong(0);
mProcessedSizeCounter = new AtomicLong(0);
mInternetUsageCounter = new AtomicLong(0);
mDownloaderThreadException = new AtomicReference<>(null);
mUseFileCounter = false;
if(!downloadAndProcessMetadata(activity, verInfo, versionName)) {
throw new RuntimeException(activity.getString(R.string.exception_failed_to_unpack_jre17));
@@ -104,17 +114,16 @@ public class MinecraftDownloader {
try {
while (mDownloaderThreadException.get() == null &&
!downloaderPool.awaitTermination(33, TimeUnit.MILLISECONDS)) {
long dlFileCounter = mDownloadFileCounter.get();
int progress = (int)((dlFileCounter * 100L) / mDownloadFileCount);
ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, progress,
R.string.newdl_downloading_game_files, dlFileCounter,
mDownloadFileCount, (double)mDownloadSizeCounter.get() / (1024d * 1024d));
double speed = speedCalculator.feed(mInternetUsageCounter.get()) / ONE_MEGABYTE;
if(mUseFileCounter) reportProgressFileCounter(speed);
else reportProgressSizeCounter(speed);
}
Exception thrownException = mDownloaderThreadException.get();
if(thrownException != null) {
throw thrownException;
} else {
ensureJarFileCopy();
extractNatives(versionName);
}
}catch (InterruptedException e) {
// Interrupted while waiting, which means that the download was cancelled.
@@ -123,6 +132,23 @@ public class MinecraftDownloader {
}
}
private void reportProgressFileCounter(double speed) {
long dlFileCounter = mProcessedFileCounter.get();
int progress = (int)((dlFileCounter * 100L) / mTotalFileCount);
ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, progress,
R.string.newdl_downloading_game_files, dlFileCounter,
mTotalFileCount, speed);
}
private void reportProgressSizeCounter(double speed) {
long dlFileSize = mProcessedSizeCounter.get();
double dlSizeMegabytes = (double) dlFileSize / ONE_MEGABYTE;
double dlTotalMegabytes = (double) mTotalSize / ONE_MEGABYTE;
int progress = (int)((dlFileSize * 100L) / mTotalSize);
ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, progress,
R.string.newdl_downloading_game_files_size, dlSizeMegabytes, dlTotalMegabytes, speed);
}
private File createGameJsonPath(String versionId) {
return new File(Tools.DIR_HOME_VERSION, versionId + File.separator + versionId + ".json");
}
@@ -145,6 +171,25 @@ public class MinecraftDownloader {
org.apache.commons.io.FileUtils.copyFile(mSourceJarFile, mTargetJarFile, false);
}
private void extractNatives(String versionName) throws IOException {
if(mDeclaredNatives.isEmpty()) return;
int totalCount = mDeclaredNatives.size();
ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, 0,
R.string.newdl_extracting_native_libraries, 0, totalCount);
File targetDirectory = new File(Tools.DIR_CACHE, "natives/"+versionName);
FileUtils.ensureDirectory(targetDirectory);
NativesExtractor nativesExtractor = new NativesExtractor(targetDirectory);
int extractedCount = 0;
for(File source : mDeclaredNatives) {
nativesExtractor.extractFromAar(source);
extractedCount++;
ProgressLayout.setProgress(ProgressLayout.DOWNLOAD_MINECRAFT, extractedCount * 100 / totalCount,
R.string.newdl_extracting_native_libraries, extractedCount, totalCount);
}
}
private File downloadGameJson(JMinecraftVersionList.Version verInfo) throws IOException, MirrorTamperedException {
File targetFile = createGameJsonPath(verInfo.id);
if(verInfo.sha1 == null && targetFile.canRead() && targetFile.isFile())
@@ -233,19 +278,50 @@ public class MinecraftDownloader {
private void scheduleDownload(File targetFile, int downloadClass, String url, String sha1,
long size, boolean skipIfFailed) throws IOException {
FileUtils.ensureParentDirectory(targetFile);
mDownloadFileCount++;
mTotalFileCount++;
// Only attempt to check size if we still use the size counter and didn't switch to file counter.
if(size <= 0 && !mUseFileCounter) {
size = DownloadMirror.getContentLengthMirrored(downloadClass, url);
}
if(size < 0) {
// If we were unable to get the content length ourselves, we automatically fall back
// to tracking the progress using the file counter.
size = 0;
mUseFileCounter = true;
Log.i("MinecraftDownloader", "Failed to determine size of "+targetFile.getName()+", switching to file counter");
}else {
mTotalSize += size;
}
mScheduledDownloadTasks.add(
new DownloaderTask(targetFile, downloadClass, url, sha1, size, skipIfFailed)
);
}
/**
* Schedule the download of an AAR library containing the required natives, for later extraction
* and adding to the library path.
* @param baseRepository the source Maven repository to download from.
* @param dependentLibrary the DependentLibrary to get the path from
* @throws IOException in case if download scheduling fails.
*/
private void scheduleNativeLibraryDownload(String baseRepository, DependentLibrary dependentLibrary) throws IOException {
String path = FileUtils.removeExtension(Tools.artifactToPath(dependentLibrary)) + ".aar";
String downloadUrl = baseRepository + path;
File targetPath = new File(Tools.DIR_HOME_LIBRARY, path);
mDeclaredNatives.add(targetPath);
scheduleDownload(targetPath, DownloadMirror.DOWNLOAD_CLASS_LIBRARIES, downloadUrl, null, 0, true);
}
private void scheduleLibraryDownloads(DependentLibrary[] dependentLibraries) throws IOException {
Tools.preProcessLibraries(dependentLibraries);
growDownloadList(dependentLibraries.length);
for(DependentLibrary dependentLibrary : dependentLibraries) {
// Don't download lwjgl, we have our own bundled in.
if(dependentLibrary.name.startsWith("org.lwjgl")) continue;
// Special handling for JNA Android natives
if(dependentLibrary.name.startsWith("net.java.dev.jna:jna:")) {
scheduleNativeLibraryDownload(MAVEN_CENTRAL_REPO1, dependentLibrary);
}
String libArtifactPath = Tools.artifactToPath(dependentLibrary);
String sha1 = null, url = null;
long size = 0;
@@ -361,6 +437,40 @@ public class MinecraftDownloader {
this.mSkipIfFailed = skipIfFailed;
}
private String downloadSha1() throws IOException {
String downloadedHash = DownloadMirror.downloadStringMirrored(
mDownloadClass, mTargetUrl + ".sha1"
);
if(!Tools.isValidString(downloadedHash)) return null;
// Ensure that we don't have leading/trailing whitespaces before checking hash length
downloadedHash = downloadedHash.trim();
// SHA1 is made up of 20 bytes, which means 40 hexadecimal digits, which means 40 chars
if(downloadedHash.length() != 40) return null;
return downloadedHash;
}
/*
* Maven repositories usually have the hash of a library near it, like:
* .../libraryName-1.0.jar
* .../libraryName.1.0.jar.sha1
* Since Minecraft libraries are stored in maven repositories, try to use
* this when downloading libraries without hashes in the json.
*/
private void tryGetLibrarySha1() {
String resultHash = null;
try {
resultHash = downloadSha1();
// The hash is a 40-byte download.
mInternetUsageCounter.getAndAdd(40);
}catch (IOException e) {
Log.i("MinecraftDownloader", "Failed to download hash", e);
}
if(resultHash != null) {
Log.i("MinecraftDownloader", "Got hash: "+resultHash+ " for "+FileUtils.getFileName(mTargetUrl));
mTargetSha1 = resultHash;
}
}
@Override
public void run() {
try {
@@ -371,6 +481,10 @@ public class MinecraftDownloader {
}
private void runCatching() throws Exception {
if(mDownloadClass == DownloadMirror.DOWNLOAD_CLASS_LIBRARIES && !Tools.isValidString(mTargetSha1)) {
// If we're downloading a library, try to get sha1 since it might be available as a file
tryGetLibrarySha1();
}
if(Tools.isValidString(mTargetSha1)) {
verifyFileSha1();
}else {
@@ -401,18 +515,20 @@ public class MinecraftDownloader {
}catch (Exception e) {
if(!mSkipIfFailed) throw e;
}
mDownloadFileCounter.incrementAndGet();
mProcessedFileCounter.incrementAndGet();
}
private void finishWithoutDownloading() {
mDownloadFileCounter.incrementAndGet();
mDownloadSizeCounter.addAndGet(mDownloadSize);
mProcessedFileCounter.incrementAndGet();
mProcessedSizeCounter.addAndGet(mDownloadSize);
}
@Override
public void updateProgress(int curr, int max) {
mDownloadSizeCounter.addAndGet(curr - mLastCurr);
mLastCurr = curr;
int delta = curr - mLastCurr;
mProcessedSizeCounter.addAndGet(delta);
mInternetUsageCounter.addAndGet(delta);
mLastCurr = curr;
}
}
}
@@ -0,0 +1,116 @@
package net.kdt.pojavlaunch.tasks;
import net.kdt.pojavlaunch.Architecture;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.utils.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class NativesExtractor {
private static final ArrayList<String> LIBRARY_BLACKLIST = createLibraryBlacklist();
private final File mDestinationDir;
private final String mLibraryLocation;
public NativesExtractor(File mDestinationDir) {
this.mDestinationDir = mDestinationDir;
this.mLibraryLocation = "jni/"+getAarArchitectureName()+"/";
}
/**
* Create a library blacklist so that downloaded natives are not able to
* override built-in libraries.
* @return the resulting blacklist of library file names
*/
private static ArrayList<String> createLibraryBlacklist() {
String[] includedLibraryNames = new File(Tools.NATIVE_LIB_DIR).list();
ArrayList<String> blacklist = new ArrayList<>(includedLibraryNames.length);
for(String libraryName : includedLibraryNames) {
// allow overriding jnidispatch (as the integrated version may be too old)
if(libraryName.equals("libjnidispatch.so")) continue;
blacklist.add(libraryName);
}
blacklist.trimToSize();
return blacklist;
}
private static String getAarArchitectureName() {
int architecture = Architecture.getDeviceArchitecture();
switch (architecture) {
case Architecture.ARCH_ARM:
return "armeabi-v7a";
case Architecture.ARCH_ARM64:
return "arm64-v8a";
case Architecture.ARCH_X86:
return "x86";
case Architecture.ARCH_X86_64:
return "x86_64";
}
throw new RuntimeException("Unknown CPU architecture: "+architecture);
}
public void extractFromAar(File source) throws IOException {
byte[] buffer = new byte[8192];
try (FileInputStream fileInputStream = new FileInputStream(source);
ZipInputStream zipInputStream = new ZipInputStream(fileInputStream)) {
// Wrap the ZIP input stream into a non-closeable stream to
// avoid it being closed by processEntry()
NonCloseableInputStream entryCopyStream = new NonCloseableInputStream(zipInputStream);
ZipEntry entry;
while((entry = zipInputStream.getNextEntry()) != null) {
String entryName = entry.getName();
if(!entryName.startsWith(mLibraryLocation) || entry.isDirectory()) continue;
// Entry name is actually the full path, so we need to strip the path before extraction
entryName = FileUtils.getFileName(entryName);
// getFileName may make the file name null, avoid that case.
if(entryName == null || LIBRARY_BLACKLIST.contains(entryName)) continue;
processEntry(entryCopyStream, entry, new File(mDestinationDir, entryName), buffer);
}
}
}
private static long fileCrc32(File target, byte[] buffer) throws IOException {
try(FileInputStream fileInputStream = new FileInputStream(target)) {
CRC32 crc32 = new CRC32();
int len;
while((len = fileInputStream.read(buffer)) != -1) {
crc32.update(buffer, 0, len);
}
return crc32.getValue();
}
}
private void processEntry(InputStream sourceStream, ZipEntry zipEntry, File entryDestination, byte[] buffer) throws IOException {
if(entryDestination.exists()) {
long expectedSize = zipEntry.getSize();
long expectedCrc32 = zipEntry.getCrc();
long realSize = entryDestination.length();
long realCrc32 = fileCrc32(entryDestination, buffer);
// File in archive is the same as the local one, don't extract
if(realSize == expectedSize && realCrc32 == expectedCrc32) return;
}
// copyInputStreamToFile copies the stream to a file and then closes it.
org.apache.commons.io.FileUtils.copyInputStreamToFile(sourceStream, entryDestination);
}
private static class NonCloseableInputStream extends FilterInputStream {
protected NonCloseableInputStream(InputStream in) {
super(in);
}
@Override
public void close() {
// Do nothing (the point of this class)
}
}
}
@@ -0,0 +1,44 @@
package net.kdt.pojavlaunch.tasks;
/**
* A simple class to calculate the average Internet speed using a simple moving average.
*/
public class SpeedCalculator {
private long mLastMillis;
private long mLastBytes;
private int mIndex;
private final double[] mPreviousInputs;
private double mSum;
public SpeedCalculator() {
this(64);
}
public SpeedCalculator(int averageDepth) {
mPreviousInputs = new double[averageDepth];
}
private double addToAverage(double speed) {
mSum -= mPreviousInputs[mIndex];
mSum += speed;
mPreviousInputs[mIndex] = speed;
if(++mIndex == mPreviousInputs.length) mIndex = 0;
double dLength = mPreviousInputs.length;
return (mSum + (dLength / 2d)) / dLength;
}
/**
* Update the current amount of bytes downloaded.
* @param bytes the new amount of bytes downloaded
* @return the current download speed in bytes per second
*/
public double feed(long bytes) {
long millis = System.currentTimeMillis();
long deltaBytes = bytes - mLastBytes;
long deltaMillis = millis - mLastMillis;
mLastBytes = bytes;
mLastMillis = millis;
double speed = (double)deltaBytes / ((double)deltaMillis / 1000d);
return addToAverage(speed);
}
}
@@ -155,6 +155,23 @@ public class DownloadUtils {
return result;
}
/**
* Get the content length for a given URL.
* @param url the URL to get the length for
* @return the length in bytes or -1 if not available
* @throws IOException if an I/O error occurs.
*/
public static long getContentLength(String url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("HEAD");
urlConnection.setDoInput(false);
urlConnection.setDoOutput(false);
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
if(responseCode >= 200 && responseCode <= 299) return urlConnection.getContentLength();
return -1;
}
public interface ParseCallback<T> {
T process(String input) throws ParseException;
}
@@ -24,6 +24,17 @@ public class FileUtils {
return pathOrUrl.substring(lastSlashIndex);
}
/**
* Remove the extension (all text after the last dot) from a path/URL string.
* @param pathOrUrl the path or the URL of the file
* @return the input with the extension removed
*/
public static String removeExtension(String pathOrUrl) {
int lastDotIndex = pathOrUrl.lastIndexOf('.');
if(lastDotIndex == -1) return pathOrUrl;
return pathOrUrl.substring(0, lastDotIndex);
}
/**
* Ensure that a directory exists, is a directory and is writable.
* @param targetFile the directory to check
@@ -0,0 +1,167 @@
package net.kdt.pojavlaunch.utils;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.EGLSurface;
import android.opengl.GLES20;
import android.opengl.GLES30;
import android.util.Log;
public class GLInfoUtils {
public static String GLES_VERSION_PREFIX = "OpenGL ES ";
private static GLInfo info;
private static int getMajorGLVersion(String versionString) {
if(versionString.startsWith(GLES_VERSION_PREFIX)) {
versionString = versionString.substring(GLES_VERSION_PREFIX.length());
}
int firstDot = versionString.indexOf('.');
String majorVersion = versionString.substring(0, firstDot).trim();
return Integer.parseInt(majorVersion);
}
private static GLInfo queryInfo(int contextGLVersion) {
String vendor = GLES20.glGetString(GLES20.GL_VENDOR);
String renderer = GLES20.glGetString(GLES20.GL_RENDERER);
String versionString = GLES20.glGetString(GLES30.GL_VERSION);
int version = 2;
try {
version = getMajorGLVersion(versionString);
}catch (NumberFormatException e) {
Log.w("GLInfoUtils","Failed to parse GL version number, falling back to 2", e);
}
// LTW depends on the ability to create a context with a major version of 3,
// and even if the string parse returns 3 while EGL can only create 2,
// it's still a noncompilant implementation
version = Math.min(version, contextGLVersion);
return new GLInfo(vendor, renderer, version);
}
private static void initDummyInfo() {
Log.e("GLInfoUtils", "An error happened during info query. Will use dummy info. This should be investigated.");
info = new GLInfo("<Unknown>", "<Unknown>", 2);
}
private static EGLContext tryCreateContext(EGLDisplay eglDisplay, EGLConfig config, int majorVersion) {
int[] egl_context_attributes = new int[] { EGL14.EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL14.EGL_NONE };
EGLContext context = EGL14.eglCreateContext(eglDisplay, config, EGL14.EGL_NO_CONTEXT, egl_context_attributes, 0);
if(context == EGL14.EGL_NO_CONTEXT || context == null) {
Log.e("GLInfoUtils", "Failed to create a context with major version "+majorVersion);
return null;
}
return context;
}
private static EGLContext tryMakeCurrent(EGLDisplay eglDisplay, EGLConfig config, EGLSurface surface, int majorVersion) {
EGLContext context = tryCreateContext(eglDisplay, config, majorVersion);
if(context == null) return null;
// Old Mali drivers are broken, and will actually let us create a context with GLES 3
// But won't let us make it current, which will break the check anyway...
boolean makeCurrentResult = EGL14.eglMakeCurrent(eglDisplay, surface, surface, context);
if(!makeCurrentResult) {
Log.i("GLInfoUtils", "Failed to make context GL version "+majorVersion +" current");
EGL14.eglDestroyContext(eglDisplay, context);
return null;
}
return context;
}
private static boolean initAndQueryInfo() {
// This is here just to satisfy Android M which incorrectly null-checks it
int[] egl_version = new int[2];
EGLDisplay eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY);
if(eglDisplay == EGL14.EGL_NO_DISPLAY || !EGL14.eglInitialize(eglDisplay, egl_version, 0 , egl_version, 1)) 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("GLInfoUtils", "Failed to choose an EGL config");
return false;
}
// Create PBuffer surface as some devices might actually not support surfaceless.
int[] pbuffer_attributes = new int[] {
EGL14.EGL_WIDTH, 16,
EGL14.EGL_HEIGHT, 16,
EGL14.EGL_NONE
};
EGLSurface surface = EGL14.eglCreatePbufferSurface(eglDisplay, config[0], pbuffer_attributes, 0);
if(surface == null || surface == EGL14.EGL_NO_SURFACE) {
Log.e("GLInfoUtils", "Failed to create pbuffer surface");
EGL14.eglTerminate(eglDisplay);
return false;
}
int contextGLVersion = 3;
EGLContext context = tryMakeCurrent(eglDisplay, config[0], surface, contextGLVersion);
if(context == null) {
contextGLVersion = 2;
context = tryMakeCurrent(eglDisplay, config[0], surface, contextGLVersion);
}
// Creation/currenting failed in both cases
if(context == null) {
Log.e("GLInfoUtils", "Failed to create and make context current");
EGL14.eglDestroySurface(eglDisplay, surface);
EGL14.eglTerminate(eglDisplay);
return false;
}
info = queryInfo(contextGLVersion);
EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT);
EGL14.eglDestroyContext(eglDisplay, context);
EGL14.eglTerminate(eglDisplay);
return true;
}
/**
* Get the information about the current OpenGL ES device, which consists of the vendor,
* the renderer and the major GLES version
* @return the info
*/
public static GLInfo getGlInfo() {
if(info != null) return info;
Log.i("GLInfoUtils", "Querying graphics device info...");
boolean infoQueryResult = false;
try {
infoQueryResult = initAndQueryInfo();
}catch (Throwable e) {
Log.e("GLInfoUtils", "Throwable when trying to initialize GL info", e);
}
if(!infoQueryResult) initDummyInfo();
return info;
}
public static class GLInfo {
public final String vendor;
public final String renderer;
public final int glesMajorVersion;
protected GLInfo(String vendor, String renderer, int glesMajorVersion) {
this.vendor = vendor;
this.renderer = renderer;
this.glesMajorVersion = glesMajorVersion;
}
/**
* Check if this GLInfo belongs to a Qualcomm Adreno graphics adapter
* @return
*/
public boolean isAdreno() {
return renderer.contains("Adreno") && vendor.equals("Qualcomm");
}
}
}
@@ -32,11 +32,6 @@ import net.kdt.pojavlaunch.plugins.FFmpegPlugin;
import net.kdt.pojavlaunch.prefs.*;
import org.lwjgl.glfw.*;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
public class JREUtils {
private JREUtils() {}
@@ -109,7 +104,8 @@ public class JREUtils {
public void run() {
try {
if (logcatPb == null) {
logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog:I", "LIBGL:I", "NativeInput").redirectErrorStream(true);
// No filtering by tag anymore as that relied on incorrect log levels set in log.h
logcatPb = new ProcessBuilder().command("logcat", /* "-G", "1mb", */ "-v", "brief", "-s", "jrelog", "LIBGL", "NativeInput").redirectErrorStream(true);
}
Log.i("jrelog-logcat","Clearing logcat");
@@ -192,8 +188,6 @@ public class JREUtils {
if(PREF_DUMP_SHADERS)
envMap.put("LIBGL_VGPU_DUMP", "1");
if(PREF_ZINK_PREFER_SYSTEM_DRIVER)
envMap.put("POJAV_ZINK_PREFER_SYSTEM_DRIVER", "1");
if(PREF_VSYNC_IN_ZINK)
envMap.put("POJAV_VSYNC_IN_ZINK", "1");
if(Tools.deviceHasHangingLinker())
@@ -215,14 +209,14 @@ public class JREUtils {
envMap.put("LD_LIBRARY_PATH", LD_LIBRARY_PATH);
envMap.put("PATH", jreHome + "/bin:" + Os.getenv("PATH"));
if(FFmpegPlugin.isAvailable) {
envMap.put("PATH", FFmpegPlugin.libraryPath+":"+envMap.get("PATH"));
envMap.put("POJAV_FFMPEG_PATH", FFmpegPlugin.executablePath);
}
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");
@@ -240,8 +234,10 @@ public class JREUtils {
}
reader.close();
}
GLInfoUtils.GLInfo info = GLInfoUtils.getGlInfo();
if(!envMap.containsKey("LIBGL_ES") && LOCAL_RENDERER != null) {
int glesMajor = getDetectedVersion();
int glesMajor = info.glesMajorVersion;
Log.i("glesDetect","GLES version detected: "+glesMajor);
if (glesMajor < 3) {
@@ -255,6 +251,11 @@ public class JREUtils {
envMap.put("LIBGL_ES", "3");
}
}
if(info.isAdreno() && !PREF_ZINK_PREFER_SYSTEM_DRIVER) {
envMap.put("POJAV_LOAD_TURNIP", "1");
}
for (Map.Entry<String, String> env : envMap.entrySet()) {
Logger.appendToLog("Added custom env: " + env.getKey() + "=" + env.getValue());
try {
@@ -295,6 +296,8 @@ public class JREUtils {
purgeArg(userArgs, "-Dorg.lwjgl.opengl.libname");
// Don't let the user specify a custom Freetype library (as the user is unlikely to specify a version compiled for Android)
purgeArg(userArgs, "-Dorg.lwjgl.freetype.libname");
// Overridden by us to specify the exact number of cores that the android system has
purgeArg(userArgs, "-XX:ActiveProcessorCount");
//Add automatically generated args
userArgs.add("-Xms" + LauncherPreferences.PREF_RAM_ALLOCATION + "M");
@@ -305,12 +308,16 @@ public class JREUtils {
// that we ship with Java (since it may be older than what's needed)
userArgs.add("-Dorg.lwjgl.freetype.libname="+ NATIVE_LIB_DIR+"/libfreetype.so");
// Some phones are not using the right number of cores, fix that
userArgs.add("-XX:ActiveProcessorCount=" + java.lang.Runtime.getRuntime().availableProcessors());
userArgs.addAll(JVMArgs);
activity.runOnUiThread(() -> Toast.makeText(activity, activity.getString(R.string.autoram_info_msg,LauncherPreferences.PREF_RAM_ALLOCATION), Toast.LENGTH_SHORT).show());
System.out.println(JVMArgs);
initJavaRuntime(runtimeHome);
setupExitTrap(activity.getApplication());
JREUtils.setupExitMethod(activity.getApplication());
JREUtils.initializeHooks();
chdir(gameDirectory == null ? Tools.DIR_GAME_NEW : gameDirectory.getAbsolutePath());
userArgs.add(0,"java"); //argv[0] is the program name according to C standard.
@@ -363,7 +370,8 @@ public class JREUtils {
"-Dnet.minecraft.clientmodname=" + Tools.APP_NAME,
"-Dfml.earlyprogresswindow=false", //Forge 1.14+ workaround
"-Dloader.disable_forked_guis=true"
"-Dloader.disable_forked_guis=true",
"-Djdk.lang.Process.launchMechanism=FORK" // Default is POSIX_SPAWN which requires starting jspawnhelper, which doesn't work on Android
));
if(LauncherPreferences.PREF_ARC_CAPES) {
overridableArguments.add("-javaagent:"+new File(Tools.DIR_DATA,"arc_dns_injector/arc_dns_injector.jar").getAbsolutePath()+"=23.95.137.176");
@@ -458,7 +466,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";
@@ -505,71 +513,19 @@ public class JREUtils {
}
public static int getDetectedVersion() {
/*
* Get all the device configurations and check the EGL_RENDERABLE_TYPE attribute
* to determine the highest ES version supported by any config. The
* EGL_KHR_create_context extension is required to check for ES3 support; if the
* extension is not present this test will fail to detect ES3 support. This
* effectively makes the extension mandatory for ES3-capable devices.
*/
EGL10 egl = (EGL10) EGLContext.getEGL();
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] numConfigs = new int[1];
if (egl.eglInitialize(display, null)) {
try {
boolean checkES3 = hasExtension(egl.eglQueryString(display, EGL10.EGL_EXTENSIONS),
"EGL_KHR_create_context");
if (egl.eglGetConfigs(display, null, 0, numConfigs)) {
EGLConfig[] configs = new EGLConfig[numConfigs[0]];
if (egl.eglGetConfigs(display, configs, numConfigs[0], numConfigs)) {
int highestEsVersion = 0;
int[] value = new int[1];
for (int i = 0; i < numConfigs[0]; i++) {
if (egl.eglGetConfigAttrib(display, configs[i],
EGL10.EGL_RENDERABLE_TYPE, value)) {
if (checkES3 && ((value[0] & EGL_OPENGL_ES3_BIT_KHR) ==
EGL_OPENGL_ES3_BIT_KHR)) {
if (highestEsVersion < 3) highestEsVersion = 3;
} else if ((value[0] & EGL_OPENGL_ES2_BIT) == EGL_OPENGL_ES2_BIT) {
if (highestEsVersion < 2) highestEsVersion = 2;
} else if ((value[0] & EGL_OPENGL_ES_BIT) == EGL_OPENGL_ES_BIT) {
if (highestEsVersion < 1) highestEsVersion = 1;
}
} else {
Log.w("glesDetect", "Getting config attribute with "
+ "EGL10#eglGetConfigAttrib failed "
+ "(" + i + "/" + numConfigs[0] + "): "
+ egl.eglGetError());
}
}
return highestEsVersion;
} else {
Log.e("glesDetect", "Getting configs with EGL10#eglGetConfigs failed: "
+ egl.eglGetError());
return -1;
}
} else {
Log.e("glesDetect", "Getting number of configs with EGL10#eglGetConfigs failed: "
+ egl.eglGetError());
return -2;
}
} finally {
egl.eglTerminate(display);
}
} else {
Log.e("glesDetect", "Couldn't initialize EGL.");
return -3;
}
return GLInfoUtils.getGlInfo().glesMajorVersion;
}
public static native int chdir(String path);
public static native boolean dlopen(String libPath);
public static native void setLdLibraryPath(String ldLibraryPath);
public static native void setupBridgeWindow(Object surface);
public static native void releaseBridgeWindow();
public static native void setupExitTrap(Context context);
public static native void initializeHooks();
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");
}
@@ -2,6 +2,7 @@ package net.kdt.pojavlaunch.utils;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_FORCE_ENGLISH;
import android.content.*;
import android.content.res.*;
@@ -10,7 +11,6 @@ import android.os.LocaleList;
import androidx.preference.*;
import java.util.*;
import net.kdt.pojavlaunch.prefs.*;
public class LocaleUtils extends ContextWrapper {
@@ -21,10 +21,13 @@ 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(DEFAULT_PREF.getBoolean("force_english", false)){
if(PREF_FORCE_ENGLISH){
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
@@ -5,6 +5,9 @@ import androidx.annotation.Keep;
@Keep
public class MinecraftProfile {
public static String LATEST_RELEASE = "latest-release";
public static String LATEST_SNAPSHOT= "latest-snapshot";
public String name;
public String type;
public String created;
@@ -23,8 +26,8 @@ public class MinecraftProfile {
public static MinecraftProfile createTemplate(){
MinecraftProfile TEMPLATE = new MinecraftProfile();
TEMPLATE.name = "New";
TEMPLATE.lastVersionId = "latest-release";
TEMPLATE.name = "";
TEMPLATE.lastVersionId = LATEST_RELEASE;
return TEMPLATE;
}
@@ -1,6 +1,8 @@
package org.lwjgl.glfw;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.customcontrols.gamepad.direct.DirectGamepadEnableHandler;
import android.content.*;
import android.util.Log;
import android.view.Choreographer;
@@ -8,6 +10,10 @@ import android.view.Choreographer;
import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import dalvik.annotation.optimization.CriticalNative;
@@ -16,6 +22,8 @@ public class CallbackBridge {
public static final Choreographer sChoreographer = Choreographer.getInstance();
private static boolean isGrabbing = false;
private static final ArrayList<GrabListener> grabListeners = new ArrayList<>();
// Use a weak reference here to avoid possibly statically referencing a Context.
private static @Nullable WeakReference<DirectGamepadEnableHandler> sDirectGamepadEnableHandler;
public static final int CLIPBOARD_COPY = 2000;
public static final int CLIPBOARD_PASTE = 2001;
@@ -27,6 +35,10 @@ public class CallbackBridge {
public volatile static boolean holdingAlt, holdingCapslock, holdingCtrl,
holdingNumlock, holdingShift;
public static final ByteBuffer sGamepadButtonBuffer;
public static final FloatBuffer sGamepadAxisBuffer;
public static boolean sGamepadDirectInput = false;
public static void putMouseEventWithCoords(int button, float x, float y) {
putMouseEventWithCoords(button, true, x, y);
sChoreographer.postFrameCallbackDelayed(l -> putMouseEventWithCoords(button, false, x, y), 33);
@@ -165,6 +177,16 @@ public class CallbackBridge {
}
}
//Called from JRE side
@SuppressWarnings("unused")
@Keep
private static void onDirectInputEnable() {
Log.i("CallbackBridge", "onDirectInputEnable()");
DirectGamepadEnableHandler enableHandler = Tools.getWeakReference(sDirectGamepadEnableHandler);
if(enableHandler != null) enableHandler.onDirectGamepadEnabled();
sGamepadDirectInput = true;
}
//Called from JRE side
@SuppressWarnings("unused")
@Keep
@@ -194,6 +216,16 @@ public class CallbackBridge {
}
}
public static FloatBuffer createGamepadAxisBuffer() {
ByteBuffer axisByteBuffer = nativeCreateGamepadAxisBuffer();
// NOTE: hardcoded order (also in jre_lwjgl3glfw CallbackBridge)
return axisByteBuffer.order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
}
public static void setDirectGamepadEnableHandler(DirectGamepadEnableHandler h) {
sDirectGamepadEnableHandler = new WeakReference<>(h);
}
@Keep @CriticalNative public static native void nativeSetUseInputStackQueue(boolean useInputStackQueue);
@Keep @CriticalNative private static native boolean nativeSendChar(char codepoint);
@@ -206,8 +238,12 @@ public class CallbackBridge {
@Keep @CriticalNative private static native void nativeSendScroll(double xoffset, double yoffset);
@Keep @CriticalNative private static native void nativeSendScreenSize(int width, int height);
public static native void nativeSetWindowAttrib(int attrib, int value);
private static native ByteBuffer nativeCreateGamepadButtonBuffer();
private static native ByteBuffer nativeCreateGamepadAxisBuffer();
static {
System.loadLibrary("pojavexec");
sGamepadButtonBuffer = nativeCreateGamepadButtonBuffer();
sGamepadAxisBuffer = createGamepadAxisBuffer();
}
}
+12 -14
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 := \
@@ -41,6 +28,9 @@ LOCAL_SRC_FILES := \
ctxbridges/osmesa_loader.c \
ctxbridges/swap_interval_no_egl.c \
environ/environ.c \
jvm_hooks/emui_iterator_fix_hook.c \
jvm_hooks/java_exec_hooks.c \
jvm_hooks/lwjgl_dlopen_hook.c \
input_bridge_v3.c \
jre_launcher.c \
utils.c \
@@ -49,10 +39,18 @@ LOCAL_SRC_FILES := \
ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
LOCAL_CFLAGS += -DADRENO_POSSIBLE
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 := \
native_hooks/exit_hook.c \
native_hooks/chmod_hook.c
include $(BUILD_SHARED_LIBRARY)
#ifeq ($(TARGET_ARCH_ABI),arm64-v8a)
include $(CLEAR_VARS)
LOCAL_MODULE := linkerhook
@@ -1,5 +1,4 @@
#include <EGL/egl.h>
#include <android/log.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <string.h>
@@ -11,11 +10,13 @@
#include "gl_bridge.h"
#include "egl_loader.h"
#define TAG __FILE_NAME__
#include <log.h>
//
// Created by maks on 17.09.2022.
//
static const char* g_LogTag = "GLBridge";
static __thread gl_render_window_t* currentBundle;
static EGLDisplay g_EglDisplay;
@@ -23,13 +24,11 @@ bool gl_init() {
if(!dlsym_EGL()) return false;
g_EglDisplay = eglGetDisplay_p(EGL_DEFAULT_DISPLAY);
if (g_EglDisplay == EGL_NO_DISPLAY) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s",
"eglGetDisplay_p(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY");
LOGE("%s", "eglGetDisplay_p(EGL_DEFAULT_DISPLAY) returned EGL_NO_DISPLAY");
return false;
}
if (eglInitialize_p(g_EglDisplay, 0, 0) != EGL_TRUE) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "eglInitialize_p() failed: %04x",
eglGetError_p());
LOGE("eglInitialize_p() failed: %04x", eglGetError_p());
return false;
}
return true;
@@ -55,25 +54,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));
@@ -81,14 +61,12 @@ gl_render_window_t* gl_init_context(gl_render_window_t *share) {
EGLint num_configs = 0;
if (eglChooseConfig_p(g_EglDisplay, egl_attributes, NULL, 0, &num_configs) != EGL_TRUE) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "eglChooseConfig_p() failed: %04x",
eglGetError_p());
LOGE("eglChooseConfig_p() failed: %04x", eglGetError_p());
free(bundle);
return NULL;
}
if (num_configs == 0) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "%s",
"eglChooseConfig_p() found no matching config");
LOGE("%s", "eglChooseConfig_p() found no matching config");
free(bundle);
return NULL;
}
@@ -115,8 +93,7 @@ gl_render_window_t* gl_init_context(gl_render_window_t *share) {
bundle->context = eglCreateContext_p(g_EglDisplay, bundle->config, share == NULL ? EGL_NO_CONTEXT : share->context, egl_context_attributes);
if (bundle->context == EGL_NO_CONTEXT) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "eglCreateContext_p() finished with error: %04x",
eglGetError_p());
LOGE("eglCreateContext_p() finished with error: %04x", eglGetError_p());
free(bundle);
return NULL;
}
@@ -129,14 +106,14 @@ void gl_swap_surface(gl_render_window_t* bundle) {
}
if(bundle->surface != NULL) eglDestroySurface_p(g_EglDisplay, bundle->surface);
if(bundle->newNativeSurface != NULL) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "Switching to new native surface");
LOGI("Switching to new native surface");
bundle->nativeSurface = bundle->newNativeSurface;
bundle->newNativeSurface = NULL;
ANativeWindow_acquire(bundle->nativeSurface);
ANativeWindow_setBuffersGeometry(bundle->nativeSurface, 0, 0, bundle->format);
bundle->surface = eglCreateWindowSurface_p(g_EglDisplay, bundle->config, bundle->nativeSurface, NULL);
}else{
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "No new native surface, switching to 1x1 pbuffer");
LOGI("No new native surface, switching to 1x1 pbuffer");
bundle->nativeSurface = NULL;
const EGLint pbuffer_attrs[] = {EGL_WIDTH, 1 , EGL_HEIGHT, 1, EGL_NONE};
bundle->surface = eglCreatePbufferSurface_p(g_EglDisplay, bundle->config, pbuffer_attrs);
@@ -145,10 +122,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)) {
@@ -159,11 +132,11 @@ void gl_make_current(gl_render_window_t* bundle) {
bool hasSetMainWindow = false;
if(pojav_environ->mainWindowBundle == NULL) {
pojav_environ->mainWindowBundle = (basic_render_window_t*)bundle;
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "Main window bundle is now %p", pojav_environ->mainWindowBundle);
LOGI("Main window bundle is now %p", pojav_environ->mainWindowBundle);
pojav_environ->mainWindowBundle->newNativeSurface = pojav_environ->pojavWindow;
hasSetMainWindow = true;
}
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "Making current, surface=%p, nativeSurface=%p, newNativeSurface=%p", bundle->surface, bundle->nativeSurface, bundle->newNativeSurface);
LOGI("Making current, surface=%p, nativeSurface=%p, newNativeSurface=%p", bundle->surface, bundle->nativeSurface, bundle->newNativeSurface);
if(bundle->surface == NULL) { //it likely will be on the first run
gl_swap_surface(bundle);
}
@@ -175,7 +148,7 @@ void gl_make_current(gl_render_window_t* bundle) {
gl_swap_surface((gl_render_window_t*)pojav_environ->mainWindowBundle);
pojav_environ->mainWindowBundle = NULL;
}
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "eglMakeCurrent returned with error: %04x", eglGetError_p());
LOGE("eglMakeCurrent returned with error: %04x", eglGetError_p());
}
}
@@ -193,14 +166,14 @@ void gl_swap_buffers() {
currentBundle->newNativeSurface = NULL;
gl_swap_surface(currentBundle);
eglMakeCurrent_p(g_EglDisplay, currentBundle->surface, currentBundle->surface, currentBundle->context);
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "The window has died, awaiting window change");
LOGI("The window has died, awaiting window change");
}
}
void gl_setup_window() {
if(pojav_environ->mainWindowBundle != NULL) {
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "Main window bundle is not NULL, changing state");
LOGI("Main window bundle is not NULL, changing state");
pojav_environ->mainWindowBundle->state = STATE_RENDERER_NEW_WINDOW;
pojav_environ->mainWindowBundle->newNativeSurface = pojav_environ->pojavWindow;
}
@@ -211,3 +184,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) {
LOGI("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) {
LOGI("GL4ES internals initialized dimension callback");
set_getmainfbsize(gl4esi_get_display_dimensions);
}
#undef GETSYM
}
@@ -4,10 +4,10 @@
#include <malloc.h>
#include <string.h>
#include <environ/environ.h>
#include <android/log.h>
#include "osm_bridge.h"
#define TAG __FILE_NAME__
#include <log.h>
static const char* g_LogTag = "GLBridge";
static __thread osm_render_window_t* currentBundle;
// a tiny buffer for rendering when there's nowhere t render
static char no_render_buffer[4];
@@ -49,13 +49,13 @@ void osm_set_no_render_buffer(ANativeWindow_Buffer* buffer) {
void osm_swap_surfaces(osm_render_window_t* bundle) {
if(bundle->nativeSurface != NULL && bundle->newNativeSurface != bundle->nativeSurface) {
if(!bundle->disable_rendering) {
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "Unlocking for cleanup...");
LOGI("Unlocking for cleanup...");
ANativeWindow_unlockAndPost(bundle->nativeSurface);
}
ANativeWindow_release(bundle->nativeSurface);
}
if(bundle->newNativeSurface != NULL) {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag, "Switching to new native surface");
LOGI("Switching to new native surface");
bundle->nativeSurface = bundle->newNativeSurface;
bundle->newNativeSurface = NULL;
ANativeWindow_acquire(bundle->nativeSurface);
@@ -63,8 +63,7 @@ void osm_swap_surfaces(osm_render_window_t* bundle) {
bundle->disable_rendering = false;
return;
}else {
__android_log_print(ANDROID_LOG_ERROR, g_LogTag,
"No new native surface, switching to dummy framebuffer");
LOGI("No new native surface, switching to dummy framebuffer");
bundle->nativeSurface = NULL;
osm_set_no_render_buffer(&bundle->buffer);
bundle->disable_rendering = true;
@@ -96,7 +95,7 @@ void osm_make_current(osm_render_window_t* bundle) {
currentBundle = bundle;
if(pojav_environ->mainWindowBundle == NULL) {
pojav_environ->mainWindowBundle = (basic_render_window_t*) bundle;
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "Main window bundle is now %p", pojav_environ->mainWindowBundle);
LOGI("Main window bundle is now %p", pojav_environ->mainWindowBundle);
pojav_environ->mainWindowBundle->newNativeSurface = pojav_environ->pojavWindow;
hasSetMainWindow = true;
}
@@ -130,7 +129,7 @@ void osm_swap_buffers() {
void osm_setup_window() {
if(pojav_environ->mainWindowBundle != NULL) {
__android_log_print(ANDROID_LOG_INFO, g_LogTag, "Main window bundle is not NULL, changing state");
LOGI("Main window bundle is not NULL, changing state");
pojav_environ->mainWindowBundle->state = STATE_RENDERER_NEW_WINDOW;
pojav_environ->mainWindowBundle->newNativeSurface = pojav_environ->pojavWindow;
}
@@ -5,9 +5,11 @@
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <android/log.h>
#include <android/native_window.h>
#define TAG __FILE_NAME__
#include <log.h>
// Taken from https://android.googlesource.com/platform/frameworks/native/+/41abd67/include/ui/egl/android_natives.h
// Might be outdated, if you can find a more recent version please add it there
// region android_native_base_t definition
@@ -227,17 +229,17 @@ void setNativeWindowSwapInterval(struct ANativeWindow* nativeWindow, int swapInt
}
struct ANativeWindow_real* nativeWindowReal = (struct ANativeWindow_real*) nativeWindow;
if(nativeWindowReal->common.magic != ANDROID_NATIVE_WINDOW_MAGIC) {
__android_log_print(ANDROID_LOG_WARN, "SwapIntervalNoEGL", "ANativeWindow magic does not match. Expected %i, got %i",
LOGW("ANativeWindow magic does not match. Expected %i, got %i",
ANDROID_NATIVE_WINDOW_MAGIC, nativeWindowReal->common.magic);
return;
}
if(nativeWindowReal->common.version != sizeof(struct ANativeWindow_real)) {
__android_log_print(ANDROID_LOG_WARN, "SwapIntervalNoEGL", "ANativeWindow version does not match. Expected %i, got %i",
LOGW("ANativeWindow version does not match. Expected %i, got %i",
sizeof(struct ANativeWindow_real), nativeWindowReal->common.version);
return;
}
int error;
if((error = nativeWindowReal->setSwapInterval(nativeWindow, swapInterval)) != 0) {
__android_log_print(ANDROID_LOG_WARN, "SwapIntervalNoEGL", "Failed to set swap interval: %s", strerror(-error));
LOGW("Failed to set swap interval: %s", strerror(-error));
}
}
@@ -82,7 +82,6 @@ bool linker_ns_load(const char* lib_search_path) {
// load the two functions we need
android_create_namespace = dlsym(ld_android_handle, "__loader_android_create_namespace");
ld_android_link_namespaces_t android_link_namespaces = dlsym(ld_android_handle, "__loader_android_link_namespaces");
__android_log_print(ANDROID_LOG_INFO, "nsbypass", "found functions at %p %p", android_create_namespace, android_link_namespaces);
if(android_create_namespace == NULL || android_link_namespaces == NULL) {
dlclose(ld_android_handle);
return false;
+16 -41
View File
@@ -99,41 +99,8 @@ EXTERNAL_API void* pojavGetCurrentContext() {
//#define ADRENO_POSSIBLE
#ifdef ADRENO_POSSIBLE
//Checks if your graphics are Adreno. Returns true if your graphics are Adreno, false otherwise or if there was an error
bool checkAdrenoGraphics() {
EGLDisplay eglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if(eglDisplay == EGL_NO_DISPLAY || eglInitialize(eglDisplay, NULL, NULL) != EGL_TRUE) return false;
EGLint egl_attributes[] = { EGL_BLUE_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_RED_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 24, EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_NONE };
EGLint num_configs = 0;
if(eglChooseConfig(eglDisplay, egl_attributes, NULL, 0, &num_configs) != EGL_TRUE || num_configs == 0) {
eglTerminate(eglDisplay);
return false;
}
EGLConfig eglConfig;
eglChooseConfig(eglDisplay, egl_attributes, &eglConfig, 1, &num_configs);
const EGLint egl_context_attributes[] = { EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE };
EGLContext context = eglCreateContext(eglDisplay, eglConfig, EGL_NO_CONTEXT, egl_context_attributes);
if(context == EGL_NO_CONTEXT) {
eglTerminate(eglDisplay);
return false;
}
if(eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, context) != EGL_TRUE) {
eglDestroyContext(eglDisplay, context);
eglTerminate(eglDisplay);
}
const char* vendor = glGetString(GL_VENDOR);
const char* renderer = glGetString(GL_RENDERER);
bool is_adreno = false;
if(strcmp(vendor, "Qualcomm") == 0 && strstr(renderer, "Adreno") != NULL) {
is_adreno = true; // TODO: check for Turnip support
}
eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglDestroyContext(eglDisplay, context);
eglTerminate(eglDisplay);
return is_adreno;
}
void* load_turnip_vulkan() {
if(!checkAdrenoGraphics()) return NULL;
if(getenv("POJAV_LOAD_TURNIP") == NULL) return NULL;
const char* native_dir = getenv("POJAV_NATIVEDIR");
const char* cache_dir = getenv("TMPDIR");
if(!linker_ns_load(native_dir)) return NULL;
@@ -172,8 +139,7 @@ static void set_vulkan_ptr(void* ptr) {
}
void load_vulkan() {
if(getenv("POJAV_ZINK_PREFER_SYSTEM_DRIVER") == NULL &&
android_get_device_api_level() >= 28) { // the loader does not support below that
if(android_get_device_api_level() >= 28) { // the loader does not support below that
#ifdef ADRENO_POSSIBLE
void* result = load_turnip_vulkan();
if(result != NULL) {
@@ -215,6 +181,11 @@ int pojavInitOpenGL() {
extern void updateMonitorSize(int width, int height);
EXTERNAL_API int pojavInit() {
pojav_environ->glfwThreadVmEnv = get_attached_env(pojav_environ->runtimeJavaVMPtr);
if(pojav_environ->glfwThreadVmEnv == NULL) {
printf("Failed to attach Java-side JNIEnv to GLFW thread\n");
return 0;
}
ANativeWindow_acquire(pojav_environ->pojavWindow);
pojav_environ->savedWidth = ANativeWindow_getWidth(pojav_environ->pojavWindow);
pojav_environ->savedHeight = ANativeWindow_getHeight(pojav_environ->pojavWindow);
@@ -258,14 +229,18 @@ EXTERNAL_API void* pojavCreateContext(void* contextSrc) {
return br_init_context((basic_render_window_t*)contextSrc);
}
EXTERNAL_API JNIEXPORT jlong JNICALL
Java_org_lwjgl_vulkan_VK_getVulkanDriverHandle(ABI_COMPAT JNIEnv *env, ABI_COMPAT jclass thiz) {
printf("EGLBridge: LWJGL-side Vulkan loader requested the Vulkan handle\n");
// The code below still uses the env var because
void* maybe_load_vulkan() {
// We use the env var because
// 1. it's easier to do that
// 2. it won't break if something will try to load vulkan and osmesa simultaneously
if(getenv("VULKAN_PTR") == NULL) load_vulkan();
return strtoul(getenv("VULKAN_PTR"), NULL, 0x10);
return (void*) strtoul(getenv("VULKAN_PTR"), NULL, 0x10);
}
EXTERNAL_API JNIEXPORT jlong JNICALL
Java_org_lwjgl_vulkan_VK_getVulkanDriverHandle(ABI_COMPAT JNIEnv *env, ABI_COMPAT jclass thiz) {
printf("EGLBridge: LWJGL-side Vulkan loader requested the Vulkan handle\n");
return (jlong) maybe_load_vulkan();
}
EXTERNAL_API void pojavSwapInterval(int interval) {
@@ -7,11 +7,14 @@
#include <assert.h>
#include <string.h>
#include "environ.h"
#define TAG __FILE_NAME__
#include <log.h>
struct pojav_environ_s *pojav_environ;
__attribute__((constructor)) void env_init() {
char* strptr_env = getenv("POJAV_ENVIRON");
if(strptr_env == NULL) {
__android_log_print(ANDROID_LOG_INFO, "Environ", "No environ found, creating...");
LOGI("No environ found, creating...");
pojav_environ = malloc(sizeof(struct pojav_environ_s));
assert(pojav_environ);
memset(pojav_environ, 0 , sizeof(struct pojav_environ_s));
@@ -19,8 +22,8 @@ __attribute__((constructor)) void env_init() {
setenv("POJAV_ENVIRON", strptr_env, 1);
free(strptr_env);
}else{
__android_log_print(ANDROID_LOG_INFO, "Environ", "Found existing environ: %s", strptr_env);
LOGI("Found existing environ: %s", strptr_env);
pojav_environ = (void*) strtoul(strptr_env, NULL, 0x10);
}
__android_log_print(ANDROID_LOG_INFO, "Environ", "%p", pojav_environ);
LOGI("%p", pojav_environ);
}
@@ -28,6 +28,11 @@ typedef void GLFW_invoke_Key_func(void* window, int key, int scancode, int actio
typedef void GLFW_invoke_MouseButton_func(void* window, int button, int action, int mods);
typedef void GLFW_invoke_Scroll_func(void* window, double xoffset, double yoffset);
typedef struct {
unsigned char buttons [15];
float axes[6];
} GLFWgamepadstate;
struct pojav_environ_s {
struct ANativeWindow* pojavWindow;
basic_render_window_t* mainWindowBundle;
@@ -42,6 +47,7 @@ struct pojav_environ_s {
double cursorX, cursorY, cLastX, cLastY;
jmethodID method_accessAndroidClipboard;
jmethodID method_onGrabStateChanged;
jmethodID method_onDirectInputEnable;
jmethodID method_glftSetWindowAttrib;
jmethodID method_internalWindowSizeChanged;
jmethodID method_internalChangeMonitorSize;
@@ -51,13 +57,13 @@ struct pojav_environ_s {
jbyte* keyDownBuffer;
jbyte* mouseDownBuffer;
JavaVM* runtimeJavaVMPtr;
JNIEnv* runtimeJNIEnvPtr_JRE;
JNIEnv* glfwThreadVmEnv;
JavaVM* dalvikJavaVMPtr;
JNIEnv* dalvikJNIEnvPtr_ANDROID;
long showingWindow;
bool isInputReady, isCursorEntered, isUseStackQueueCall, shouldUpdateMouse;
bool shouldUpdateMonitorSize, monitorSizeConsumed;
int savedWidth, savedHeight;
GLFWgamepadstate gamepadState;
#define ADD_CALLBACK_WWIN(NAME) \
GLFW_invoke_##NAME##_func* GLFW_invoke_##NAME;
ADD_CALLBACK_WWIN(Char);
+65 -155
View File
@@ -19,9 +19,11 @@
#include <stdatomic.h>
#include <math.h>
#define TAG __FILE_NAME__
#include "log.h"
#include "utils.h"
#include "environ/environ.h"
#include "jvm_hooks/jvm_hooks.h"
#define EVENT_TYPE_CHAR 1000
#define EVENT_TYPE_CHAR_MODS 1001
@@ -30,37 +32,47 @@
#define EVENT_TYPE_MOUSE_BUTTON 1006
#define EVENT_TYPE_SCROLL 1007
jint (*orig_ProcessImpl_forkAndExec)(JNIEnv *env, jobject process, jint mode, jbyteArray helperpath, jbyteArray prog, jbyteArray argBlock, jint argc, jbyteArray envBlock, jint envc, jbyteArray dir, jintArray std_fds, jboolean redirectErrorStream);
#define TRY_ATTACH_ENV(env_name, vm, error_message, then) JNIEnv* env_name;\
do { \
env_name = get_attached_env(vm); \
if(env_name == NULL) { \
printf(error_message); \
then \
} \
} while(0)
static void registerFunctions(JNIEnv *env);
jint JNI_OnLoad(JavaVM* vm, __attribute__((unused)) void* reserved) {
if (pojav_environ->dalvikJavaVMPtr == NULL) {
__android_log_print(ANDROID_LOG_INFO, "Native", "Saving DVM environ...");
LOGI("Saving DVM environ...");
//Save dalvik global JavaVM pointer
pojav_environ->dalvikJavaVMPtr = vm;
(*vm)->GetEnv(vm, (void**) &pojav_environ->dalvikJNIEnvPtr_ANDROID, JNI_VERSION_1_4);
pojav_environ->bridgeClazz = (*pojav_environ->dalvikJNIEnvPtr_ANDROID)->NewGlobalRef(pojav_environ->dalvikJNIEnvPtr_ANDROID,(*pojav_environ->dalvikJNIEnvPtr_ANDROID) ->FindClass(pojav_environ->dalvikJNIEnvPtr_ANDROID,"org/lwjgl/glfw/CallbackBridge"));
pojav_environ->method_accessAndroidClipboard = (*pojav_environ->dalvikJNIEnvPtr_ANDROID)->GetStaticMethodID(pojav_environ->dalvikJNIEnvPtr_ANDROID, pojav_environ->bridgeClazz, "accessAndroidClipboard", "(ILjava/lang/String;)Ljava/lang/String;");
pojav_environ->method_onGrabStateChanged = (*pojav_environ->dalvikJNIEnvPtr_ANDROID)->GetStaticMethodID(pojav_environ->dalvikJNIEnvPtr_ANDROID, pojav_environ->bridgeClazz, "onGrabStateChanged", "(Z)V");
JNIEnv *dvEnv;
(*vm)->GetEnv(vm, (void**) &dvEnv, JNI_VERSION_1_4);
pojav_environ->bridgeClazz = (*dvEnv)->NewGlobalRef(dvEnv,(*dvEnv) ->FindClass(dvEnv,"org/lwjgl/glfw/CallbackBridge"));
pojav_environ->method_accessAndroidClipboard = (*dvEnv)->GetStaticMethodID(dvEnv, pojav_environ->bridgeClazz, "accessAndroidClipboard", "(ILjava/lang/String;)Ljava/lang/String;");
pojav_environ->method_onGrabStateChanged = (*dvEnv)->GetStaticMethodID(dvEnv, pojav_environ->bridgeClazz, "onGrabStateChanged", "(Z)V");
pojav_environ->method_onDirectInputEnable = (*dvEnv)->GetStaticMethodID(dvEnv, pojav_environ->bridgeClazz, "onDirectInputEnable", "()V");
pojav_environ->isUseStackQueueCall = JNI_FALSE;
} else if (pojav_environ->dalvikJavaVMPtr != vm) {
__android_log_print(ANDROID_LOG_INFO, "Native", "Saving JVM environ...");
LOGI("Saving JVM environ...");
pojav_environ->runtimeJavaVMPtr = vm;
(*vm)->GetEnv(vm, (void**) &pojav_environ->runtimeJNIEnvPtr_JRE, JNI_VERSION_1_4);
pojav_environ->vmGlfwClass = (*pojav_environ->runtimeJNIEnvPtr_JRE)->NewGlobalRef(pojav_environ->runtimeJNIEnvPtr_JRE, (*pojav_environ->runtimeJNIEnvPtr_JRE)->FindClass(pojav_environ->runtimeJNIEnvPtr_JRE, "org/lwjgl/glfw/GLFW"));
pojav_environ->method_glftSetWindowAttrib = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticMethodID(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, "glfwSetWindowAttrib", "(JII)V");
pojav_environ->method_internalWindowSizeChanged = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticMethodID(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, "internalWindowSizeChanged", "(J)V");
pojav_environ->method_internalChangeMonitorSize = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticMethodID(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, "internalChangeMonitorSize", "(II)V");
jfieldID field_keyDownBuffer = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticFieldID(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, "keyDownBuffer", "Ljava/nio/ByteBuffer;");
jobject keyDownBufferJ = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticObjectField(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, field_keyDownBuffer);
pojav_environ->keyDownBuffer = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetDirectBufferAddress(pojav_environ->runtimeJNIEnvPtr_JRE, keyDownBufferJ);
jfieldID field_mouseDownBuffer = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticFieldID(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, "mouseDownBuffer", "Ljava/nio/ByteBuffer;");
jobject mouseDownBufferJ = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetStaticObjectField(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, field_mouseDownBuffer);
pojav_environ->mouseDownBuffer = (*pojav_environ->runtimeJNIEnvPtr_JRE)->GetDirectBufferAddress(pojav_environ->runtimeJNIEnvPtr_JRE, mouseDownBufferJ);
hookExec();
installLinkerBugMitigation();
installEMUIIteratorMititgation();
JNIEnv *vmEnv;
(*vm)->GetEnv(vm, (void**) &vmEnv, JNI_VERSION_1_4);
pojav_environ->vmGlfwClass = (*vmEnv)->NewGlobalRef(vmEnv, (*vmEnv)->FindClass(vmEnv, "org/lwjgl/glfw/GLFW"));
pojav_environ->method_glftSetWindowAttrib = (*vmEnv)->GetStaticMethodID(vmEnv, pojav_environ->vmGlfwClass, "glfwSetWindowAttrib", "(JII)V");
pojav_environ->method_internalWindowSizeChanged = (*vmEnv)->GetStaticMethodID(vmEnv, pojav_environ->vmGlfwClass, "internalWindowSizeChanged", "(J)V");
pojav_environ->method_internalChangeMonitorSize = (*vmEnv)->GetStaticMethodID(vmEnv, pojav_environ->vmGlfwClass, "internalChangeMonitorSize", "(II)V");
jfieldID field_keyDownBuffer = (*vmEnv)->GetStaticFieldID(vmEnv, pojav_environ->vmGlfwClass, "keyDownBuffer", "Ljava/nio/ByteBuffer;");
jobject keyDownBufferJ = (*vmEnv)->GetStaticObjectField(vmEnv, pojav_environ->vmGlfwClass, field_keyDownBuffer);
pojav_environ->keyDownBuffer = (*vmEnv)->GetDirectBufferAddress(vmEnv, keyDownBufferJ);
jfieldID field_mouseDownBuffer = (*vmEnv)->GetStaticFieldID(vmEnv, pojav_environ->vmGlfwClass, "mouseDownBuffer", "Ljava/nio/ByteBuffer;");
jobject mouseDownBufferJ = (*vmEnv)->GetStaticObjectField(vmEnv, pojav_environ->vmGlfwClass, field_mouseDownBuffer);
pojav_environ->mouseDownBuffer = (*vmEnv)->GetDirectBufferAddress(vmEnv, mouseDownBufferJ);
hookExec(vmEnv);
installLwjglDlopenHook(vmEnv);
installEMUIIteratorMititgation(vmEnv);
}
if(pojav_environ->dalvikJavaVMPtr == vm) {
@@ -92,10 +104,10 @@ ADD_CALLBACK_WWIN(Scroll)
#undef ADD_CALLBACK_WWIN
void updateMonitorSize(int width, int height) {
(*pojav_environ->runtimeJNIEnvPtr_JRE)->CallStaticVoidMethod(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, pojav_environ->method_internalChangeMonitorSize, width, height);
(*pojav_environ->glfwThreadVmEnv)->CallStaticVoidMethod(pojav_environ->glfwThreadVmEnv, pojav_environ->vmGlfwClass, pojav_environ->method_internalChangeMonitorSize, width, height);
}
void updateWindowSize(void* window) {
(*pojav_environ->runtimeJNIEnvPtr_JRE)->CallStaticVoidMethod(pojav_environ->runtimeJNIEnvPtr_JRE, pojav_environ->vmGlfwClass, pojav_environ->method_internalWindowSizeChanged, (jlong)window);
(*pojav_environ->glfwThreadVmEnv)->CallStaticVoidMethod(pojav_environ->glfwThreadVmEnv, pojav_environ->vmGlfwClass, pojav_environ->method_internalWindowSizeChanged, (jlong)window);
}
void pojavPumpEvents(void* window) {
@@ -230,119 +242,6 @@ void sendData(int type, int i1, int i2, int i3, int i4) {
atomic_fetch_add_explicit(&pojav_environ->eventCounter, 1, memory_order_acquire);
}
/**
* Hooked version of java.lang.UNIXProcess.forkAndExec()
* which is used to handle the "open" command.
*/
jint
hooked_ProcessImpl_forkAndExec(JNIEnv *env, jobject process, jint mode, jbyteArray helperpath, jbyteArray prog, jbyteArray argBlock, jint argc, jbyteArray envBlock, jint envc, jbyteArray dir, jintArray std_fds, jboolean redirectErrorStream) {
char *pProg = (char *)((*env)->GetByteArrayElements(env, prog, NULL));
// Here we only handle the "xdg-open" command
if (strcmp(basename(pProg), "xdg-open") != 0) {
(*env)->ReleaseByteArrayElements(env, prog, (jbyte *)pProg, 0);
return orig_ProcessImpl_forkAndExec(env, process, mode, helperpath, prog, argBlock, argc, envBlock, envc, dir, std_fds, redirectErrorStream);
}
(*env)->ReleaseByteArrayElements(env, prog, (jbyte *)pProg, 0);
Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(env, NULL, /* CLIPBOARD_OPEN */ 2002, argBlock);
return 0;
}
void hookExec() {
jclass cls;
orig_ProcessImpl_forkAndExec = dlsym(RTLD_DEFAULT, "Java_java_lang_UNIXProcess_forkAndExec");
if (!orig_ProcessImpl_forkAndExec) {
orig_ProcessImpl_forkAndExec = dlsym(RTLD_DEFAULT, "Java_java_lang_ProcessImpl_forkAndExec");
cls = (*pojav_environ->runtimeJNIEnvPtr_JRE)->FindClass(pojav_environ->runtimeJNIEnvPtr_JRE, "java/lang/ProcessImpl");
} else {
cls = (*pojav_environ->runtimeJNIEnvPtr_JRE)->FindClass(pojav_environ->runtimeJNIEnvPtr_JRE, "java/lang/UNIXProcess");
}
JNINativeMethod methods[] = {
{"forkAndExec", "(I[B[B[BI[BI[B[IZ)I", (void *)&hooked_ProcessImpl_forkAndExec}
};
(*pojav_environ->runtimeJNIEnvPtr_JRE)->RegisterNatives(pojav_environ->runtimeJNIEnvPtr_JRE, cls, methods, 1);
printf("Registered forkAndExec\n");
}
/**
* Basically a verbatim implementation of ndlopen(), found at
* https://github.com/PojavLauncherTeam/lwjgl3/blob/3.3.1/modules/lwjgl/core/src/generated/c/linux/org_lwjgl_system_linux_DynamicLinkLoader.c#L11
* The idea is that since, on Android 10 and earlier, the linker doesn't really do namespace nesting.
* It is not a problem as most of the libraries are in the launcher path, but when you try to run
* VulkanMod which loads shaderc outside of the default jni libs directory through this method,
* it can't load it because the path is not in the allowed paths for the anonymous namesapce.
* This method fixes the issue by being in libpojavexec, and thus being in the classloader namespace
*/
jlong ndlopen_bugfix(__attribute__((unused)) JNIEnv *env,
__attribute__((unused)) jclass class,
jlong filename_ptr,
jint jmode) {
const char* filename = (const char*) filename_ptr;
int mode = (int)jmode;
return (jlong) dlopen(filename, mode);
}
/**
* Install the linker bug mitigation for Android 10 and lower. Fixes VulkanMod crashing on these
* Android versions due to missing namespace nesting.
*/
void installLinkerBugMitigation() {
if(android_get_device_api_level() >= 30) return;
__android_log_print(ANDROID_LOG_INFO, "Api29LinkerFix", "API < 30 detected, installing linker bug mitigation");
JNIEnv* env = pojav_environ->runtimeJNIEnvPtr_JRE;
jclass dynamicLinkLoader = (*env)->FindClass(env, "org/lwjgl/system/linux/DynamicLinkLoader");
if(dynamicLinkLoader == NULL) {
__android_log_print(ANDROID_LOG_ERROR, "Api29LinkerFix", "Failed to find the target class");
(*env)->ExceptionClear(env);
return;
}
JNINativeMethod ndlopenMethod[] = {
{"ndlopen", "(JI)J", &ndlopen_bugfix}
};
if((*env)->RegisterNatives(env, dynamicLinkLoader, ndlopenMethod, 1) != 0) {
__android_log_print(ANDROID_LOG_ERROR, "Api29LinkerFix", "Failed to register the bugfix method");
(*env)->ExceptionClear(env);
}
}
/**
* This function is meant as a substitute for SharedLibraryUtil.getLibraryPath() that just returns 0
* (thus making the parent Java function return null). This is done to avoid using the LWJGL's default function,
* which will hang the crappy EMUI linker by dlopen()ing inside of dl_iterate_phdr().
* @return 0, to make the parent Java function return null immediately.
* For reference: https://github.com/PojavLauncherTeam/lwjgl3/blob/fix_huawei_hang/modules/lwjgl/core/src/main/java/org/lwjgl/system/SharedLibraryUtil.java
*/
jint getLibraryPath_fix(__attribute__((unused)) JNIEnv *env,
__attribute__((unused)) jclass class,
__attribute__((unused)) jlong pLibAddress,
__attribute__((unused)) jlong sOutAddress,
__attribute__((unused)) jint bufSize){
return 0;
}
/**
* Install the linker hang mitigation that is meant to prevent linker hangs on old EMUI firmware.
*/
void installEMUIIteratorMititgation() {
if(getenv("POJAV_EMUI_ITERATOR_MITIGATE") == NULL) return;
__android_log_print(ANDROID_LOG_INFO, "EMUIIteratorFix", "Installing...");
JNIEnv* env = pojav_environ->runtimeJNIEnvPtr_JRE;
jclass sharedLibraryUtil = (*env)->FindClass(env, "org/lwjgl/system/SharedLibraryUtil");
if(sharedLibraryUtil == NULL) {
__android_log_print(ANDROID_LOG_ERROR, "EMUIIteratorFix", "Failed to find the target class");
(*env)->ExceptionClear(env);
return;
}
JNINativeMethod getLibraryPathMethod[] = {
{"getLibraryPath", "(JJI)I", &getLibraryPath_fix}
};
if((*env)->RegisterNatives(env, sharedLibraryUtil, getLibraryPathMethod, 1) != 0) {
__android_log_print(ANDROID_LOG_ERROR, "EMUIIteratorFix", "Failed to register the mitigation method");
(*env)->ExceptionClear(env);
}
}
void critical_set_stackqueue(jboolean use_input_stack_queue) {
pojav_environ->isUseStackQueueCall = (int) use_input_stack_queue;
}
@@ -360,7 +259,7 @@ JNIEXPORT jstring JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(JNI
(*pojav_environ->dalvikJavaVMPtr)->AttachCurrentThread(pojav_environ->dalvikJavaVMPtr, &dalvikEnv, NULL);
assert(dalvikEnv != NULL);
assert(pojav_environ->bridgeClazz != NULL);
LOGD("Clipboard: Converting string\n");
char *copySrcC;
jstring copyDst = NULL;
@@ -373,7 +272,7 @@ JNIEXPORT jstring JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(JNI
jstring pasteDst = convertStringJVM(dalvikEnv, env, (jstring) (*dalvikEnv)->CallStaticObjectMethod(dalvikEnv, pojav_environ->bridgeClazz, pojav_environ->method_accessAndroidClipboard, action, copyDst));
if (copySrc) {
(*dalvikEnv)->DeleteLocalRef(dalvikEnv, copyDst);
(*dalvikEnv)->DeleteLocalRef(dalvikEnv, copyDst);
(*env)->ReleaseByteArrayElements(env, copySrc, (jbyte *)copySrcC, 0);
}
(*pojav_environ->dalvikJavaVMPtr)->DetachCurrentThread(pojav_environ->dalvikJavaVMPtr);
@@ -384,7 +283,7 @@ JNIEXPORT jboolean JNICALL JavaCritical_org_lwjgl_glfw_CallbackBridge_nativeSetI
#ifdef DEBUG
LOGD("Debug: Changing input state, isReady=%d, pojav_environ->isUseStackQueueCall=%d\n", inputReady, pojav_environ->isUseStackQueueCall);
#endif
__android_log_print(ANDROID_LOG_INFO, "NativeInput", "Input ready: %i", inputReady);
LOGI("Input ready: %i", inputReady);
pojav_environ->isInputReady = inputReady;
return pojav_environ->isUseStackQueueCall;
}
@@ -394,13 +293,18 @@ JNIEXPORT jboolean JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeSetInputRead
}
JNIEXPORT void JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeSetGrabbing(__attribute__((unused)) JNIEnv* env, __attribute__((unused)) jclass clazz, jboolean grabbing) {
JNIEnv *dalvikEnv;
(*pojav_environ->dalvikJavaVMPtr)->AttachCurrentThread(pojav_environ->dalvikJavaVMPtr, &dalvikEnv, NULL);
(*dalvikEnv)->CallStaticVoidMethod(dalvikEnv, pojav_environ->bridgeClazz, pojav_environ->method_onGrabStateChanged, grabbing);
(*pojav_environ->dalvikJavaVMPtr)->DetachCurrentThread(pojav_environ->dalvikJavaVMPtr);
TRY_ATTACH_ENV(dvm_env, pojav_environ->dalvikJavaVMPtr, "nativeSetGrabbing failed!\n", return;);
(*dvm_env)->CallStaticVoidMethod(dvm_env, pojav_environ->bridgeClazz, pojav_environ->method_onGrabStateChanged, grabbing);
pojav_environ->isGrabbing = grabbing;
}
JNIEXPORT jboolean JNICALL
Java_org_lwjgl_glfw_CallbackBridge_nativeEnableGamepadDirectInput(__attribute__((unused)) JNIEnv *env, __attribute__((unused)) jclass clazz) {
TRY_ATTACH_ENV(dvm_env, pojav_environ->dalvikJavaVMPtr, "nativeEnableGamepadDirectInput failed!\n", return JNI_FALSE;);
(*dvm_env)->CallStaticVoidMethod(dvm_env, pojav_environ->bridgeClazz, pojav_environ->method_onDirectInputEnable);
return JNI_TRUE;
}
jboolean critical_send_char(jchar codepoint) {
if (pojav_environ->GLFW_invoke_Char && pojav_environ->isInputReady) {
if (pojav_environ->isUseStackQueueCall) {
@@ -560,16 +464,7 @@ JNIEXPORT void JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeSetWindowAttrib(
// in environ for the Android UI thread but this is the only place that uses it
// (very rarely, only in lifecycle callbacks) so i dont care
JavaVM* jvm = pojav_environ->runtimeJavaVMPtr;
JNIEnv *jvm_env = NULL;
jint env_result = (*jvm)->GetEnv(jvm, (void**)&jvm_env, JNI_VERSION_1_4);
if(env_result == JNI_EDETACHED) {
env_result = (*jvm)->AttachCurrentThread(jvm, &jvm_env, NULL);
}
if(env_result != JNI_OK) {
printf("input_bridge nativeSetWindowAttrib() JNI call failed: %i\n", env_result);
return;
}
TRY_ATTACH_ENV(jvm_env, pojav_environ->runtimeJavaVMPtr, "nativeSetWindowAttrib failed: %i", return;);
(*jvm_env)->CallStaticVoidMethod(
jvm_env, pojav_environ->vmGlfwClass,
@@ -635,12 +530,27 @@ static void registerFunctions(JNIEnv *env) {
bool use_critical_cc = tryCriticalNative(env);
jclass bridge_class = (*env)->FindClass(env, "org/lwjgl/glfw/CallbackBridge");
if(use_critical_cc) {
__android_log_print(ANDROID_LOG_INFO, "pojavexec", "CriticalNative is available. Enjoy the 4.6x times faster input!");
LOGI("CriticalNative is available. Enjoy the 4.6x times faster input!");
}else{
__android_log_print(ANDROID_LOG_INFO, "pojavexec", "CriticalNative is not available. Upgrade, maybe?");
LOGI("CriticalNative is not available. Upgrade, maybe?");
}
(*env)->RegisterNatives(env,
bridge_class,
use_critical_cc ? critical_fcns : noncritical_fcns,
sizeof(critical_fcns)/sizeof(critical_fcns[0]));
}
JNIEXPORT jlong JNICALL
Java_org_lwjgl_glfw_GLFW_internalGetGamepadDataPointer(JNIEnv *env, jclass clazz) {
return (jlong) &pojav_environ->gamepadState;
}
JNIEXPORT jobject JNICALL
Java_org_lwjgl_glfw_CallbackBridge_nativeCreateGamepadButtonBuffer(JNIEnv *env, jclass clazz) {
return (*env)->NewDirectByteBuffer(env, &pojav_environ->gamepadState.buttons, sizeof(pojav_environ->gamepadState.buttons));
}
JNIEXPORT jobject JNICALL
Java_org_lwjgl_glfw_CallbackBridge_nativeCreateGamepadAxisBuffer(JNIEnv *env, jclass clazz) {
return (*env)->NewDirectByteBuffer(env, &pojav_environ->gamepadState.axes, sizeof(pojav_environ->gamepadState.axes));
}
@@ -185,9 +185,6 @@ JNIEXPORT jint JNICALL Java_com_oracle_dalvik_VMLauncher_launchJVM(JNIEnv *env,
jint res = 0;
// Save dalvik JNIEnv pointer for JVM launch thread
pojav_environ->dalvikJNIEnvPtr_ANDROID = env;
if (argsArray == NULL) {
LOGE("Args array null, returning");
//handle error
@@ -0,0 +1,45 @@
//
// Created by maks on 23.01.2025.
//
#include "jvm_hooks.h"
#include <stdlib.h>
#define TAG __FILE_NAME__
#include <log.h>
/**
* This function is meant as a substitute for SharedLibraryUtil.getLibraryPath() that just returns 0
* (thus making the parent Java function return null). This is done to avoid using the LWJGL's default function,
* which will hang the crappy EMUI linker by dlopen()ing inside of dl_iterate_phdr().
* @return 0, to make the parent Java function return null immediately.
* For reference: https://github.com/PojavLauncherTeam/lwjgl3/blob/fix_huawei_hang/modules/lwjgl/core/src/main/java/org/lwjgl/system/SharedLibraryUtil.java
*/
jint getLibraryPath_fix(__attribute__((unused)) JNIEnv *env,
__attribute__((unused)) jclass class,
__attribute__((unused)) jlong pLibAddress,
__attribute__((unused)) jlong sOutAddress,
__attribute__((unused)) jint bufSize){
return 0;
}
/**
* Install the linker hang mitigation that is meant to prevent linker hangs on old EMUI firmware.
*/
void installEMUIIteratorMititgation(JNIEnv *env) {
if(getenv("POJAV_EMUI_ITERATOR_MITIGATE") == NULL) return;
LOGI("Installing...");
jclass sharedLibraryUtil = (*env)->FindClass(env, "org/lwjgl/system/SharedLibraryUtil");
if(sharedLibraryUtil == NULL) {
LOGE("Failed to find target class");
(*env)->ExceptionClear(env);
return;
}
JNINativeMethod getLibraryPathMethod[] = {
{"getLibraryPath", "(JJI)I", &getLibraryPath_fix}
};
if((*env)->RegisterNatives(env, sharedLibraryUtil, getLibraryPathMethod, 1) != 0) {
LOGE("Failed to register the mitigation method");
(*env)->ExceptionClear(env);
}
}
@@ -0,0 +1,88 @@
//
// Created by maks on 05.01.2025.
//
#include "jvm_hooks.h"
#include <libgen.h>
#include <string.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "environ/environ.h"
#include "utils.h"
static jint (*orig_ProcessImpl_forkAndExec)(JNIEnv *env, jobject process, jint mode, jbyteArray helperpath, jbyteArray prog, jbyteArray argBlock, jint argc, jbyteArray envBlock, jint envc, jbyteArray dir, jintArray std_fds, jboolean redirectErrorStream);
// Turn a C-style string into a Java byte array
static jbyteArray stringToBytes(JNIEnv *env, const char* string) {
const jsize string_data_len = (jsize)(strlen(string) + 1);
jbyteArray result = (*env)->NewByteArray(env, (jsize)string_data_len);
(*env)->SetByteArrayRegion(env, result, 0, (jsize)string_data_len, (const jbyte*) string);
return result;
}
// Replace the env block with the one that has the desired LD_LIBRARY_PATH/PATH.
// (Due to my laziness this ignores the current contents of the block)
static void replaceLibPathInEnvBlock(JNIEnv *env, jbyteArray* envBlock, jint* envc, const char* directory) {
static bool env_block_replacement_warning = false;
if(*envBlock != NULL && !env_block_replacement_warning) {
printf("exec_hooks WARN: replaceLibPathInEnvBlock does not preserve original env. Please notify PojavLauncherTeam if you need that feature\n");
env_block_replacement_warning = true;
}
char envStr[1024];
jsize new_envl = snprintf(envStr, sizeof(envStr) / sizeof(char), "LD_LIBRARY_PATH=%s%cPATH=%s", directory, 0 ,directory) + 1;
jbyteArray newBlock = (*env)->NewByteArray(env, new_envl);
(*env)->SetByteArrayRegion(env, newBlock, 0, new_envl, (jbyte*) envStr);
*envBlock = newBlock;
*envc = 2;
}
/**
* Hooked version of java.lang.UNIXProcess.forkAndExec()
* which is used to handle the "open" command and "ffmpeg" invocations
*/
static jint hooked_ProcessImpl_forkAndExec(JNIEnv *env, jobject process, jint mode, jbyteArray helperpath, jbyteArray prog, jbyteArray argBlock, jint argc, jbyteArray envBlock, jint envc, jbyteArray dir, jintArray std_fds, jboolean redirectErrorStream) {
const char *pProg = (char *)((*env)->GetByteArrayElements(env, prog, NULL));
const char* pProgBaseName = basename(pProg);
const size_t basename_len = strlen(pProgBaseName);
char prog_basename[basename_len];
memcpy(&prog_basename, pProgBaseName, basename_len + 1);
(*env)->ReleaseByteArrayElements(env, prog, (jbyte *)pProg, 0);
if(strcmp(prog_basename, "xdg-open") == 0) {
// When invoking xdg-open, send the open URL into Android
Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(env, NULL, CLIPBOARD_OPEN, argBlock);
return 0;
}else if(strcmp(prog_basename, "ffmpeg") == 0) {
// When invoking ffmpeg, always replace the program path with the path to ffmpeg from the plugin.
// This allows us to replace the executable name, which is needed because android doesn't allow
// us to put files that don't start with "lib" and end with ".so" into folders that we can execute
// from
// Also add LD_LIBRARY_PATH and PATH for the lib in order to override the ones from the launcher, since
// they may interfere with ffmpeg dependencies.
const char* ffmpeg_path = getenv("POJAV_FFMPEG_PATH");
if(ffmpeg_path != NULL) {
replaceLibPathInEnvBlock(env, &envBlock, &envc, dirname(ffmpeg_path));
prog = stringToBytes(env, ffmpeg_path);
}
}
return orig_ProcessImpl_forkAndExec(env, process, mode, helperpath, prog, argBlock, argc, envBlock, envc, dir, std_fds, redirectErrorStream);
}
// Hook the forkAndExec method in the Java runtime for custom executable overriding.
void hookExec(JNIEnv *env) {
jclass hookClass;
orig_ProcessImpl_forkAndExec = dlsym(RTLD_DEFAULT, "Java_java_lang_UNIXProcess_forkAndExec");
if (!orig_ProcessImpl_forkAndExec) {
orig_ProcessImpl_forkAndExec = dlsym(RTLD_DEFAULT, "Java_java_lang_ProcessImpl_forkAndExec");
hookClass = (*env)->FindClass(env, "java/lang/ProcessImpl");
} else {
hookClass = (*env)->FindClass(env, "java/lang/UNIXProcess");
}
JNINativeMethod methods[] = {
{"forkAndExec", "(I[B[B[BI[BI[B[IZ)I", (void *)&hooked_ProcessImpl_forkAndExec}
};
(*env)->RegisterNatives(env, hookClass, methods, 1);
printf("Registered forkAndExec\n");
}
@@ -0,0 +1,14 @@
//
// Created by maks on 23.01.2025.
//
#ifndef POJAVLAUNCHER_JVM_HOOKS_H
#define POJAVLAUNCHER_JVM_HOOKS_H
#include <jni.h>
void installEMUIIteratorMititgation(JNIEnv *env);
void installLwjglDlopenHook(JNIEnv *env);
void hookExec(JNIEnv *env);
#endif //POJAVLAUNCHER_JVM_HOOKS_H
@@ -0,0 +1,66 @@
//
// Created by maks on 06.01.2025.
//
#include "jvm_hooks.h"
#include <android/api-level.h>
#include "environ/environ.h"
#include <dlfcn.h>
#include <string.h>
#include <stdlib.h>
#define TAG __FILE_NAME__
#include <log.h>
extern void* maybe_load_vulkan();
/**
* Basically a verbatim implementation of ndlopen(), found at
* https://github.com/PojavLauncherTeam/lwjgl3/blob/3.3.1/modules/lwjgl/core/src/generated/c/linux/org_lwjgl_system_linux_DynamicLinkLoader.c#L11
* but with our own additions for stuff like vulkanmod.
*/
static jlong ndlopen_bugfix(__attribute__((unused)) JNIEnv *env,
__attribute__((unused)) jclass class,
jlong filename_ptr,
jint jmode) {
const char* filename = (const char*) filename_ptr;
// Oveeride vulkan loading to let us load vulkan ourselves
if(strstr(filename, "libvulkan.so") == filename) {
printf("LWJGL linkerhook: replacing load for libvulkan.so with custom driver\n");
return (jlong) maybe_load_vulkan();
}
// This hook also serves the task of mitigating a bug: the idea is that since, on Android 10 and
// earlier, the linker doesn't really do namespace nesting.
// It is not a problem as most of the libraries are in the launcher path, but when you try to run
// VulkanMod which loads shaderc outside of the default jni libs directory through this method,
// it can't load it because the path is not in the allowed paths for the anonymous namesapce.
// This method fixes the issue by being in libpojavexec, and thus being in the classloader namespace
int mode = (int)jmode;
return (jlong) dlopen(filename, mode);
}
/**
* Install the LWJGL dlopen hook. This allows us to mitigate linker bugs and add custom library overrides.
*/
void installLwjglDlopenHook(JNIEnv *env) {
LOGI("Installing LWJGL dlopen() hook");
jclass dynamicLinkLoader = (*env)->FindClass(env, "org/lwjgl/system/linux/DynamicLinkLoader");
if(dynamicLinkLoader == NULL) {
LOGE("Failed to find the target class");
(*env)->ExceptionClear(env);
return;
}
JNINativeMethod ndlopenMethod[] = {
{"ndlopen", "(JI)J", &ndlopen_bugfix}
};
if((*env)->RegisterNatives(env, dynamicLinkLoader, ndlopenMethod, 1) != 0) {
LOGE("Failed to register the hooked method");
(*env)->ExceptionClear(env);
}
}
+10 -5
View File
@@ -1,6 +1,9 @@
#ifdef __ANDROID__
#ifndef POJAVLAUNCHER_LOG_H
#define POJAVLAUNCHER_LOG_H
#include <android/log.h>
#ifndef TAG
#define TAG "jrelog"
#endif
@@ -8,12 +11,14 @@
extern "C" {
#endif
#define LOGE(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_SILENT, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_SILENT, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, TAG, __VA_ARGS__)
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,33 @@
//
// Created by maks on 23.01.2025.
//
#include "native_hooks.h"
#include <unistd.h>
#include <errno.h>
#define TAG __FILE_NAME__
#include <log.h>
// Hooks for chmod and fchmod that always return success.
// This allows older Android versions to work with Java NIO zipfs inside of the Pojav folder.
typedef int (*chmod_func)(const char*, mode_t);
typedef int (*fchmod_func)(int, mode_t);
#define TEMPLATE_HOOK(X, Y, Z, W) static int X(Y, mode_t mode) { \
int result = BYTEHOOK_CALL_PREV(X, Z, W, mode); \
if(result != 0) errno = 0; \
BYTEHOOK_POP_STACK(); \
return 0; \
} \
TEMPLATE_HOOK(custom_chmod, const char* filename, chmod_func, filename)
TEMPLATE_HOOK(custom_fchmod, int fd, fchmod_func, fd)
#undef TEMPLATE_HOOK
void create_chmod_hooks(bytehook_hook_all_t bytehook_hook_all_p) {
bytehook_stub_t stub_chmod = bytehook_hook_all_p(NULL, "chmod", &custom_chmod, NULL, NULL);
bytehook_stub_t stub_fchmod = bytehook_hook_all_p(NULL, "fchmod", &custom_fchmod, NULL, NULL);
LOGI("Successfully initialized chmod hooks, stubs: %p %p", stub_chmod, stub_fchmod);
}
@@ -0,0 +1,86 @@
//
// Created by maks on 15.01.2025.
//
#include "native_hooks.h"
#include <jni.h>
#include <stdbool.h>
#include <bytehook.h>
#include <dlfcn.h>
#include <stdlib.h>
#include "stdio_is.h"
#define TAG __FILE_NAME__
#include <log.h>
static _Atomic bool exit_tripped = false;
static int exit_code = 0;
typedef void (*exit_func)(int);
// Use the exit hook *only* to store the exit code.
static void custom_exit(int code) {
exit_code = code;
BYTEHOOK_CALL_PREV(custom_exit, exit_func, code);
BYTEHOOK_POP_STACK();
}
static void custom_atexit() {
if(exit_tripped) {
return;
}
exit_tripped = true;
nominal_exit(exit_code, false);
}
static void create_hooks(bytehook_hook_all_t bytehook_hook_all_p) {
bytehook_stub_t stub_exit = bytehook_hook_all_p(NULL, "exit", &custom_exit, NULL, NULL);
LOGI("Successfully initialized exit hook, stub: %p", stub_exit);
// Only apply chmod hooks on devices where the game directory is in games/PojavLauncher
// which is below API 29
if(android_get_device_api_level() < 29) {
create_chmod_hooks(bytehook_hook_all_p);
}
}
static bool init_hooks() {
void* bytehook_handle = dlopen("libbytehook.so", RTLD_NOW);
if(bytehook_handle == NULL) {
goto dlerror;
}
bytehook_hook_all_t bytehook_hook_all_p;
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) {
create_hooks(bytehook_hook_all_p);
return true;
} else {
LOGE("bytehook_init failed (%i)", bhook_status);
dlclose(bytehook_handle);
return false;
}
dlerror:
if(bytehook_handle != NULL) dlclose(bytehook_handle);
LOGE("Failed to load hook library: %s", dlerror());
return false;
}
JNIEXPORT void JNICALL
Java_net_kdt_pojavlaunch_utils_JREUtils_initializeHooks(JNIEnv *env, jclass clazz) {
bool hooks_ready = init_hooks();
if(!hooks_ready) {
LOGE("Failed to initialize native hooks!");
}
// Always register atexit, because that's what we will call our exit from.
// We only use the hook to capture the exit code.
atexit(custom_atexit);
}
@@ -0,0 +1,15 @@
//
// Created by maks on 23.01.2025.
//
#ifndef POJAVLAUNCHER_NATIVE_HOOKS_H
#define POJAVLAUNCHER_NATIVE_HOOKS_H
#include <bytehook.h>
typedef bytehook_stub_t (*bytehook_hook_all_t)(const char *callee_path_name, const char *sym_name, void *new_func,
bytehook_hooked_t hooked, void *hooked_arg);
void create_chmod_hooks(bytehook_hook_all_t bytehook_hook_all_p);
#endif //POJAVLAUNCHER_NATIVE_HOOKS_H
+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_
+13
View File
@@ -157,6 +157,19 @@ JNIEXPORT jint JNICALL Java_net_kdt_pojavlaunch_utils_JREUtils_executeBinary(JNI
return result;
}
JNIEnv* get_attached_env(JavaVM* jvm) {
JNIEnv *jvm_env = NULL;
jint env_result = (*jvm)->GetEnv(jvm, (void**)&jvm_env, JNI_VERSION_1_4);
if(env_result == JNI_EDETACHED) {
env_result = (*jvm)->AttachCurrentThread(jvm, &jvm_env, NULL);
}
if(env_result != JNI_OK) {
printf("get_attached_env failed: %i\n", env_result);
return NULL;
}
return jvm_env;
}
// METHOD 2
/*
JNIEXPORT jint JNICALL Java_net_kdt_pojavlaunch_utils_JREUtils_executeForkedBinary(JNIEnv *env, jclass clazz, jobjectArray cmdArgs) {
+4 -4
View File
@@ -2,15 +2,15 @@
#include <stdbool.h>
#define CLIPBOARD_COPY 2000
#define CLIPBOARD_PASTE 2001
#define CLIPBOARD_OPEN 2002
char** convert_to_char_array(JNIEnv *env, jobjectArray jstringArray);
jobjectArray convert_from_char_array(JNIEnv *env, char **charArray, int num_rows);
void free_char_array(JNIEnv *env, jobjectArray jstringArray, const char **charArray);
jstring convertStringJVM(JNIEnv* srcEnv, JNIEnv* dstEnv, jstring srcStr);
void hookExec();
void installLinkerBugMitigation();
void installEMUIIteratorMititgation();
JNIEnv* get_attached_env(JavaVM* jvm);
JNIEXPORT jstring JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(JNIEnv* env, jclass clazz, jint action, jbyteArray copySrc);
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff. Show more