Compare commits

..
Author SHA1 Message Date
artdeell 5b50eed2d4 Style[pojavexec]: move hooks to separate dirs, use logging macros 2025-01-24 10:33:50 +03:00
artdeell 38b963aaf7 Feat[hooks]: add hooks for chmod/fchmod
Allows NIO ZipFs to function on old Android versions
2025-01-20 18:37:27 +03:00
artdeell 2f853cfcb6 Feat[egl_bridge]: simplify ZINK_PREFER_SYSTEM_DRIVER handling 2025-01-20 16:49:12 +03:00
artdeell 949d3faf02 Feat[launcher]: remove duplicate GLES initializations 2025-01-20 16:38:14 +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
Mathias Boulay 1af64382eb QoL update (#6350)
* QoL(notification): click to go back into the current game

* Fix(system bars): fix colors for navigation bars

* Tweak(control editor): make snapping less aggressive

* Fix(system bars): properly remove colors in full screen
2024-12-06 21:04:17 +01:00
Mathias-Boulay bc7dfeacfd Fix(control-editors): make sure the layout is instantiated before using it 2024-12-03 21:04:09 +01:00
Maksim Belov fd6bea9b39 Merge pull request #6338 from PojavLauncherTeam/fix/QoL_stuff
QoL update
2024-12-02 13:07:37 +03:00
Mathias-Boulay fc81b87e7f Fix(controls): non square joystick, set size via text 2024-12-01 23:29:16 +01:00
Mathias-Boulay c6fe3c3de5 QoL(gesture): decouple gyroscope from long press gesture 2024-11-29 21:17:29 +01:00
Mathias-Boulay 68fa25cafc Fix(hotbar): first touch on 0 index not being taken into account 2024-11-29 21:14:16 +01:00
Mathias-Boulay fae327978e QoL(profile editor): make the text react like a button
This increases the space you can use, better for left handed people or large hands
2024-11-29 18:57:24 +01:00
Mathias-Boulay 29605ed6b7 QoL: make the settings button easier to click
Bigger hitbox, but not visually
2024-11-29 18:22:39 +01:00
Maksim Belov d5fd73c9e9 Feat[launcher]: Add a quick settings menu (#6303) 2024-11-26 21:05:47 +03:00
157 changed files with 4149 additions and 2106 deletions

No files matched your search

+14 -2
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:
@@ -56,9 +68,9 @@ jobs:
branch: buildjre17-21
name: jre21-pojav
- uses: gradle/gradle-build-action@v2
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: 7.6.1
gradle-version: "8.11"
- name: Build JRE JAR files
run: |
+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!
+15 -5
View File
@@ -1,5 +1,5 @@
plugins {
id 'com.android.application' version '7.4.2'
id 'com.android.application' version '8.7.2'
}
static def getDate() { return new Date().format('yyyyMMdd') }
@@ -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()
}
}
@@ -137,6 +137,10 @@ android {
minifyEnabled true
shrinkResources true
}
proguardNoDebug {
initWith proguard
debuggable false
}
release {
// Don't set to true or java.awt will be a.a or something similar.
@@ -182,9 +186,15 @@ android {
buildFeatures {
prefab true
buildConfig true
}
buildToolsVersion = '33.0.2'
buildToolsVersion = '34.0.0'
}
afterEvaluate {
// Explicit dependencies for which the apk relies on
tasks.mergeDebugAssets.dependsOn(":forge_installer:jar", ":arc_dns_injector:jar", ":jre_lwjgl3glfw:jar")
}
dependencies {
@@ -204,7 +214,7 @@ dependencies {
implementation 'com.github.PojavLauncherTeam:portrait-ssp:6c02fd739b'
implementation 'com.github.Mathias-Boulay:ExtendedView:1.0.0'
implementation 'com.github.Mathias-Boulay:android_gamepad_remapper:2.0.3'
implementation 'com.github.Mathias-Boulay:virtual-joystick-android:2e7aa25e50'
implementation 'com.github.Mathias-Boulay:virtual-joystick-android:1.14'
// implementation 'com.intuit.sdp:sdp-android:1.0.5'
// implementation 'com.intuit.ssp:ssp-android:1.0.5'
@@ -217,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"
@@ -106,7 +107,7 @@
<activity
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|keyboard|navigation|uiMode"
android:launchMode="standard"
android:launchMode="singleTop"
android:process=":game"
android:screenOrientation="sensorLandscape" />
@@ -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;
@@ -186,6 +189,11 @@ public abstract class SideDialogView {
*/
@CallSuper
public final void disappear(boolean destroy) {
if(!mIsInstantiated) {
Log.w("SideDialogView", "Layout not inflated");
return;
}
if (!mDisplaying) {
if(destroy) {
onDisappear();
@@ -207,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
@@ -1,7 +1,10 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
import dalvik.annotation.optimization.CriticalNative;
@Keep
public class CriticalNativeTest {
@CriticalNative
public static native void testCriticalNative(int arg0, int arg1);
@@ -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();
@@ -156,7 +149,12 @@ public class LauncherActivity extends BaseActivity {
@Override
protected boolean shouldIgnoreNotch() {
return getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT || super.shouldIgnoreNotch();
return getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT;
}
@Override
public boolean setFullscreen() {
return false;
}
@Override
@@ -195,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);
@@ -227,11 +224,6 @@ public class LauncherActivity extends BaseActivity {
mInstallTracker.detach();
}
@Override
public boolean setFullscreen() {
return false;
}
@Override
protected void onStart() {
super.onStart();
@@ -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);
}
@@ -15,6 +15,7 @@ public class Logger {
public static native void begin(String logFilePath);
/** Small listener for anything listening to the log */
@Keep
public interface eventLogListener {
void onEventLogged(String text);
}
@@ -36,6 +36,7 @@ import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
@@ -242,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();
});
@@ -333,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);
@@ -442,6 +446,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
if(touchCharInput != null) touchCharInput.switchKeyboardState();
}
@Keep
public static void openLink(String link) {
Context ctx = touchpad.getContext(); // no more better way to obtain a context statically
((Activity)ctx).runOnUiThread(() -> {
@@ -461,6 +466,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
}
});
}
@SuppressWarnings("unused") //TODO: actually use it
public static void openPath(String path) {
Context ctx = touchpad.getContext(); // no more better way to obtain a context statically
@@ -473,6 +479,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
});
}
@Keep
public static void querySystemClipboard() {
Tools.runOnUiThread(()->{
ClipData clipData = GLOBAL_CLIPBOARD.getPrimaryClip();
@@ -491,6 +498,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
});
}
@Keep
public static void putClipboardData(String data, String mimeType) {
Tools.runOnUiThread(()-> {
ClipData clipData = null;
@@ -19,6 +19,7 @@ import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
import net.kdt.pojavlaunch.utils.*;
import net.kdt.pojavlaunch.utils.FileUtils;
@@ -57,10 +58,15 @@ public class PojavApplication extends Application {
try {
super.onCreate();
Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent();
Tools.DIR_CACHE = getCacheDir();
Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts";
if(Tools.checkStorageRoot(this)){
// Implicitly initializes early constants and storage constants.
// Required to run the main activity properly.
LauncherPreferences.loadPreferences(this);
} else {
// In other cases, only initialize enough for the basicmost basics to work
// and not explode.
Tools.initEarlyConstants(this);
}
Tools.DEVICE_ARCHITECTURE = Architecture.getDeviceArchitecture();
//Force x86 lib directory for Asus x86 based zenfones
if(Architecture.isx86Device() && Architecture.is32BitsDevice()){
@@ -14,6 +14,7 @@ import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
public class TestStorageActivity extends Activity {
@@ -60,7 +61,8 @@ public class TestStorageActivity extends Activity {
startActivity(new Intent(this, MissingStorageActivity.class));
return;
}
//Only run them once we get a definitive green light to use storage
//Initialize constants (implicitly) and preferences after we confirm that we have storage.
LauncherPreferences.loadPreferences(this);
AsyncAssetManager.unpackComponents(this);
AsyncAssetManager.unpackSingleFiles(this);
@@ -22,6 +22,11 @@ import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
import android.opengl.GLES30;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
@@ -33,9 +38,6 @@ import android.util.ArrayMap;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
@@ -43,10 +45,13 @@ 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;
@@ -65,8 +70,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;
@@ -157,14 +164,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";
@@ -174,7 +209,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.getInfo();
return info.renderer.contains("Adreno") && info.vendor.equals("Qualcomm") && 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,
@@ -202,10 +290,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
@@ -512,8 +617,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();
@@ -537,47 +641,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) {
final Window window = activity.getWindow();
final View decorView = window.getDecorView();
final int insetControllerFlags = WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars();
final View.OnApplyWindowInsetsListener windowInsetsListener = (view, windowInsets) ->{
WindowInsetsController windowInsetsController = decorView.getWindowInsetsController();
if(windowInsetsController == null) return windowInsets;
boolean multiWindowMode = activity.isInMultiWindowMode();
// Emulate the behaviour of the legacy function using the new flags
if(fullscreen && !multiWindowMode) {
windowInsetsController.hide(insetControllerFlags);
windowInsetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE);
window.setDecorFitsSystemWindows(false);
}else {
windowInsetsController.show(insetControllerFlags);
// Both of the constants below have the exact same numerical value, but
// for some reason the one that works below Android S was removed
// from the acceptable constants for setSystemBarsBehaviour
if (SDK_INT >= Build.VERSION_CODES.S) {
windowInsetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_DEFAULT);
}else {
// noinspection WrongConstant
windowInsetsController.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE);
}
window.setDecorFitsSystemWindows(true);
}
return windowInsets;
};
decorView.setOnApplyWindowInsetsListener(windowInsetsListener);
windowInsetsListener.onApplyWindowInsets(decorView, null);
}
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) {
@@ -972,6 +1035,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.getInfo();
Logger.appendToLog("Info: Graphics device: "+info.vendor+ " "+info.renderer+" (OpenGL ES "+info.glesMajorVersion+")");
}
public interface DownloaderFeedback {
@@ -1302,12 +1367,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]);
}
@@ -7,6 +7,7 @@ import android.util.ArrayMap;
import androidx.annotation.Keep;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.customcontrols.buttons.ControlInterface;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.JSONUtils;
import net.objecthunter.exp4j.ExpressionBuilder;
@@ -240,7 +241,7 @@ public class ControlData {
keyValueMap.put("height", "DUMMY_HEIGHT");
keyValueMap.put("screen_width", "DUMMY_DATA");
keyValueMap.put("screen_height", "DUMMY_DATA");
keyValueMap.put("margin", Integer.toString((int) Tools.dpToPx(2)));
keyValueMap.put("margin", Integer.toString((int) ControlInterface.getMarginDistance()));
keyValueMap.put("preferred_scale", "DUMMY_DATA");
conversionMap = new WeakReference<>(keyValueMap);
@@ -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
@@ -57,13 +57,13 @@ public class CustomControls {
this.mControlDataList.add(new ControlData(ctx, R.string.control_jump, new int[]{LwjglGlfwKeycode.GLFW_KEY_SPACE}, "${right} - ${margin} * 2 - ${width}", "${bottom} - ${margin} * 2 - ${height}", true));
//The default controls are conform to the V3
version = 7;
version = 8;
}
public void save(String path) throws IOException {
//Current version is the V3.1 so the version as to be marked as 7 !
version = 7;
//Current version is the V3.2 so the version as to be marked as 8 !
version = 8;
Tools.write(path, Tools.GLOBAL_GSON.toJson(this));
}
@@ -24,27 +24,56 @@ public class LayoutConverter {
CustomControls layout = LayoutConverter.convertV1Layout(layoutJobj);
layout.save(jsonPath);
return layout;
} else if (layoutJobj.getInt("version") == 2) {
CustomControls layout = LayoutConverter.convertV2Layout(layoutJobj);
layout.save(jsonPath);
return layout;
}else if (layoutJobj.getInt("version") >= 3 && layoutJobj.getInt("version") <= 5) {
return LayoutConverter.convertV3_4Layout(layoutJobj);
} else if (layoutJobj.getInt("version") == 6 || layoutJobj.getInt("version") == 7) {
return Tools.GLOBAL_GSON.fromJson(jsonLayoutData, CustomControls.class);
} else {
return null;
int version = layoutJobj.getInt("version");
if (version == 2) {
CustomControls layout = LayoutConverter.convertV2Layout(layoutJobj);
layout.save(jsonPath);
return layout;
}
if (version == 3 || version == 4 || version == 5) {
return LayoutConverter.convertV3_4Layout(layoutJobj);
}
if (version == 6 || version == 7) {
return convertV6_7Layout(layoutJobj);
}
else if (version == 8) {
return Tools.GLOBAL_GSON.fromJson(jsonLayoutData, CustomControls.class);
}
}
return null;
} catch (JSONException e) {
throw new JsonSyntaxException("Failed to load", e);
}
}
/**
* Normalize the layout to v8 from v6/7. An issue from the joystick height and position has to be fixed.
* @param oldLayoutJson The old layout
* @return The new layout with the fixed joystick height
*/
public static CustomControls convertV6_7Layout(JSONObject oldLayoutJson) {
CustomControls layout = Tools.GLOBAL_GSON.fromJson(oldLayoutJson.toString(), CustomControls.class);
for (ControlJoystickData data : layout.mJoystickDataList) {
if (data.getHeight() > data.getWidth()) {
// Make the size square, adjust the dynamic position related to height
float ratio = data.getHeight() / data.getWidth();
data.dynamicX = data.dynamicX.replace("${height}", "(" + ratio + " * ${height})");
data.dynamicY = data.dynamicY.replace("${height}", "(" + ratio + " * ${height})") + " + (" + (ratio-1) + " * ${height})";
data.setHeight(data.getWidth());
}
}
layout.version = 8;
return layout;
}
/**
* Normalize the layout to v6 from v3/4: The stroke width is no longer dependant on the button size
*/
public static CustomControls convertV3_4Layout(JSONObject oldLayoutJson) {
private static CustomControls convertV3_4Layout(JSONObject oldLayoutJson) {
CustomControls layout = Tools.GLOBAL_GSON.fromJson(oldLayoutJson.toString(), CustomControls.class);
convertStrokeWidth(layout);
layout.version = 6;
@@ -52,7 +81,7 @@ public class LayoutConverter {
}
public static CustomControls convertV2Layout(JSONObject oldLayoutJson) throws JSONException {
private static CustomControls convertV2Layout(JSONObject oldLayoutJson) throws JSONException {
CustomControls layout = Tools.GLOBAL_GSON.fromJson(oldLayoutJson.toString(), CustomControls.class);
JSONArray layoutMainArray = oldLayoutJson.getJSONArray("mControlDataList");
layout.mControlDataList = new ArrayList<>(layoutMainArray.length());
@@ -95,7 +124,7 @@ public class LayoutConverter {
return layout;
}
public static CustomControls convertV1Layout(JSONObject oldLayoutJson) throws JSONException {
private static CustomControls convertV1Layout(JSONObject oldLayoutJson) throws JSONException {
CustomControls empty = new CustomControls();
JSONArray layoutMainArray = oldLayoutJson.getJSONArray("mControlDataList");
for (int i = 0; i < layoutMainArray.length(); i++) {
@@ -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;
}
}
@@ -61,26 +61,27 @@ public class ControlDrawer extends ControlButton {
private void alignButtons(){
if(buttons == null) return;
if(drawerData.orientation == ControlDrawerData.Orientation.FREE) return;
int margin = (int) ControlInterface.getMarginDistance();
for(int i = 0; i < buttons.size(); ++i){
switch (drawerData.orientation){
case RIGHT:
buttons.get(i).setDynamicX(generateDynamicX(getX() + (drawerData.properties.getWidth() + Tools.dpToPx(2))*(i+1) ));
buttons.get(i).setDynamicX(generateDynamicX(getX() + (drawerData.properties.getWidth() + margin)*(i+1) ));
buttons.get(i).setDynamicY(generateDynamicY(getY()));
break;
case LEFT:
buttons.get(i).setDynamicX(generateDynamicX(getX() - (drawerData.properties.getWidth() + Tools.dpToPx(2))*(i+1)));
buttons.get(i).setDynamicX(generateDynamicX(getX() - (drawerData.properties.getWidth() + margin)*(i+1)));
buttons.get(i).setDynamicY(generateDynamicY(getY()));
break;
case UP:
buttons.get(i).setDynamicY(generateDynamicY(getY() - (drawerData.properties.getHeight() + Tools.dpToPx(2))*(i+1)));
buttons.get(i).setDynamicY(generateDynamicY(getY() - (drawerData.properties.getHeight() + margin)*(i+1)));
buttons.get(i).setDynamicX(generateDynamicX(getX()));
break;
case DOWN:
buttons.get(i).setDynamicY(generateDynamicY(getY() + (drawerData.properties.getHeight() + Tools.dpToPx(2))*(i+1)));
buttons.get(i).setDynamicY(generateDynamicY(getY() + (drawerData.properties.getHeight() + margin)*(i+1)));
buttons.get(i).setDynamicX(generateDynamicX(getX()));
break;
}
@@ -30,7 +30,6 @@ import org.lwjgl.glfw.CallbackBridge;
* sending keys has to be implemented by sub classes.
*/
public interface ControlInterface extends View.OnLongClickListener, GrabListener {
View getControlView();
ControlData getProperties();
@@ -214,7 +213,7 @@ public interface ControlInterface extends View.OnLongClickListener, GrabListener
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
default boolean canSnap(ControlInterface button) {
float MIN_DISTANCE = Tools.dpToPx(8);
float MIN_DISTANCE = getSnapDistance();
if (button == this) return false;
return !(net.kdt.pojavlaunch.utils.MathUtils.dist(
@@ -237,7 +236,7 @@ public interface ControlInterface extends View.OnLongClickListener, GrabListener
* @param y Coordinate on the y axis
*/
default void snapAndAlign(float x, float y) {
float MIN_DISTANCE = Tools.dpToPx(8);
final float MIN_DISTANCE = getSnapDistance();
String dynamicX = generateDynamicX(x);
String dynamicY = generateDynamicY(y);
@@ -404,4 +403,12 @@ public interface ControlInterface extends View.OnLongClickListener, GrabListener
return true;
}
static float getSnapDistance() {
return Tools.dpToPx(6);
}
static float getMarginDistance() {
return Tools.dpToPx(2);
}
}
@@ -43,6 +43,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 +53,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));
@@ -116,7 +114,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 +153,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 +226,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 +338,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
@@ -16,23 +16,22 @@ public class DrawerPullButton extends View {
public DrawerPullButton(Context context) {super(context); init();}
public DrawerPullButton(Context context, @Nullable AttributeSet attrs) {super(context, attrs); init();}
private final Paint mPaint = new Paint();
private final Paint mBackgroundPaint = new Paint();
private VectorDrawableCompat mDrawable;
private void init(){
mDrawable = VectorDrawableCompat.create(getContext().getResources(), R.drawable.ic_sharp_settings_24, null);
setAlpha(0.33f);
mBackgroundPaint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
mPaint.setColor(Color.BLACK);
canvas.drawArc(0,-getHeight(),getWidth(), getHeight(), 0, 180, true, mPaint);
canvas.drawArc(getPaddingLeft(),-getHeight() + getPaddingBottom(),getWidth() - getPaddingRight(), getHeight() - getPaddingBottom(), 0, 180, true, mBackgroundPaint);
mPaint.setColor(Color.WHITE);
mDrawable.setBounds(0, 0, getHeight(), getHeight());
mDrawable.setBounds(getPaddingLeft()/2, getPaddingTop()/2, getHeight() - getPaddingRight()/2, getHeight() - getPaddingBottom()/2);
canvas.save();
canvas.translate((getWidth()-getHeight())/2f, 0);
canvas.translate((getWidth()-getHeight())/2f, -getPaddingBottom()/2f);
mDrawable.draw(canvas);
canvas.restore();
}
@@ -332,6 +332,7 @@ public class EditControlSideDialog extends SideDialogView {
/**
* A long function linking all the displayed data on the popup and,
* the currently edited mCurrentlyEditedButton
* @noinspection SuspiciousNameCombination
*/
private void setupRealTimeListeners() {
mNameEditText.addTextChangedListener((SimpleTextWatcher) s -> {
@@ -349,6 +350,10 @@ public class EditControlSideDialog extends SideDialogView {
float width = safeParseFloat(s.toString());
if (width >= 0) {
mCurrentlyEditedButton.getProperties().setWidth(width);
if (mCurrentlyEditedButton.getProperties() instanceof ControlJoystickData) {
// Joysticks are square
mCurrentlyEditedButton.getProperties().setHeight(width);
}
mCurrentlyEditedButton.updateProperties();
}
});
@@ -359,6 +364,10 @@ public class EditControlSideDialog extends SideDialogView {
float height = safeParseFloat(s.toString());
if (height >= 0) {
mCurrentlyEditedButton.getProperties().setHeight(height);
if (mCurrentlyEditedButton.getProperties() instanceof ControlJoystickData) {
// Joysticks are square
mCurrentlyEditedButton.getProperties().setWidth(height);
}
mCurrentlyEditedButton.updateProperties();
}
});
@@ -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();
}
}
}
@@ -11,6 +11,7 @@ import android.view.ViewParent;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.GrabListener;
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
@@ -26,8 +27,16 @@ public class HotbarView extends View implements MCOptionUtils.MCOptionListener,
LwjglGlfwKeycode.GLFW_KEY_4, LwjglGlfwKeycode.GLFW_KEY_5, LwjglGlfwKeycode.GLFW_KEY_6,
LwjglGlfwKeycode.GLFW_KEY_7, LwjglGlfwKeycode.GLFW_KEY_8, LwjglGlfwKeycode.GLFW_KEY_9};
private final DropGesture mDropGesture = new DropGesture(new Handler(Looper.getMainLooper()));
private final GrabListener mGrabListener = new GrabListener() {
@Override
public void onGrabState(boolean isGrabbing) {
mLastIndex = -1;
mDropGesture.cancel();
}
};
private int mWidth;
private int mLastIndex;
private int mLastIndex = -1;
private int mGuiScale;
public HotbarView(Context context) {
@@ -66,6 +75,13 @@ public class HotbarView extends View implements MCOptionUtils.MCOptionListener,
}
mGuiScale = MCOptionUtils.getMcScale();
repositionView();
CallbackBridge.addGrabListener(mGrabListener);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
CallbackBridge.removeGrabListener(mGrabListener);
}
private void repositionView() {
@@ -33,8 +33,12 @@ public class InGameEventProcessor implements TouchEventProcessor {
case MotionEvent.ACTION_MOVE:
mTracker.trackEvent(motionEvent);
float[] motionVector = mTracker.getMotionVector();
CallbackBridge.mouseX += (float) (motionVector[0] * mSensitivity);
CallbackBridge.mouseY += (float) (motionVector[1] * mSensitivity);
float deltaX = (float) (motionVector[0] * mSensitivity);
float deltaY = (float) (motionVector[1] * mSensitivity);
mLeftClickGesture.setMotion(deltaX, deltaY);
mRightClickGesture.setMotion(deltaX, deltaY);
CallbackBridge.mouseX += deltaX;
CallbackBridge.mouseY += deltaY;
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
if(LauncherPreferences.PREF_DISABLE_GESTURES) break;
checkGestures();
@@ -13,23 +13,28 @@ import org.lwjgl.glfw.CallbackBridge;
public class LeftClickGesture extends ValidatorGesture {
public static final int FINGER_STILL_THRESHOLD = (int) Tools.dpToPx(9);
private float mGestureStartX, mGestureStartY;
private float mGestureStartX, mGestureStartY, mGestureEndX, mGestureEndY;
private boolean mMouseActivated;
public LeftClickGesture(Handler handler) {
super(handler, LauncherPreferences.PREF_LONGPRESS_TRIGGER);
super(handler);
}
public final void inputEvent() {
if(submit()) {
mGestureStartX = CallbackBridge.mouseX;
mGestureStartY = CallbackBridge.mouseY;
mGestureStartX = mGestureEndX = CallbackBridge.mouseX;
mGestureStartY = mGestureEndY = CallbackBridge.mouseY;
}
}
@Override
protected int getGestureDelay() {
return LauncherPreferences.PREF_LONGPRESS_TRIGGER;
}
@Override
public boolean checkAndTrigger() {
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, FINGER_STILL_THRESHOLD);
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, mGestureEndX, mGestureEndY, FINGER_STILL_THRESHOLD);
// If the finger is still, fire the gesture.
if(fingerStill) {
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true);
@@ -47,6 +52,11 @@ public class LeftClickGesture extends ValidatorGesture {
}
}
public void setMotion(float deltaX, float deltaY) {
mGestureEndX += deltaX;
mGestureEndY += deltaY;
}
/**
* Check if the finger is still when compared to mouseX/mouseY in CallbackBridge.
* @param startX the starting X of the gesture
@@ -61,4 +71,13 @@ public class LeftClickGesture extends ValidatorGesture {
startY
) <= threshold;
}
public static boolean isFingerStill(float startX, float startY, float endX, float endY, float threshold) {
return MathUtils.dist(
endX,
endY,
startX,
startY
) <= threshold;
}
}
@@ -6,24 +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;
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.
@@ -38,7 +49,8 @@ public class RightClickGesture extends ValidatorGesture{
public void onGestureCancelled(boolean isSwitching) {
mGestureEnabled = true;
if(!mGestureValid || isSwitching) return;
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, LeftClickGesture.FINGER_STILL_THRESHOLD);
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
*/
@@ -239,6 +239,7 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
}
private void updateLoaderSpinner() {
if(mLoaderVersionArray == null) return;
mLoaderVersionSpinner.setAdapter(createAdapter(mLoaderVersionArray, mOnlyStableCheckbox.isChecked()));
}
@@ -285,6 +286,7 @@ public abstract class FabriclikeInstallFragment extends Fragment implements Modl
}
private void updateGameSpinner() {
if(mGameVersionArray == null) return;
mGameVersionSpinner.setAdapter(createAdapter(mGameVersionArray, mOnlyStableCheckbox.isChecked()));
}
@@ -107,7 +107,28 @@ public class ProfileEditorFragment extends Fragment implements CropperUtils.Crop
Tools.removeCurrentFragment(requireActivity());
});
mGameDirButton.setOnClickListener(v -> {
View.OnClickListener gameDirListener = getGameDirListener();
mGameDirButton.setOnClickListener(gameDirListener);
mDefaultPath.setOnClickListener(gameDirListener);
View.OnClickListener controlSelectListener = getControlSelectListener();
mControlSelectButton.setOnClickListener(controlSelectListener);
mDefaultControl.setOnClickListener(controlSelectListener);
// Setup the expendable list behavior
View.OnClickListener versionSelectListener = getVersionSelectListener();
mVersionSelectButton.setOnClickListener(versionSelectListener);
mDefaultVersion.setOnClickListener(versionSelectListener);
// Set up the icon change click listener
mProfileIcon.setOnClickListener(v -> CropperUtils.startCropper(mCropperLauncher));
loadValues(LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE, ""), view.getContext());
}
private View.OnClickListener getGameDirListener() {
return v -> {
Bundle bundle = new Bundle(2);
bundle.putBoolean(FileSelectorFragment.BUNDLE_SELECT_FOLDER, true);
bundle.putString(FileSelectorFragment.BUNDLE_ROOT_PATH, Tools.DIR_GAME_HOME);
@@ -116,9 +137,11 @@ public class ProfileEditorFragment extends Fragment implements CropperUtils.Crop
Tools.swapFragment(requireActivity(),
FileSelectorFragment.class, FileSelectorFragment.TAG, bundle);
});
};
}
mControlSelectButton.setOnClickListener(v -> {
private View.OnClickListener getControlSelectListener() {
return v -> {
Bundle bundle = new Bundle(3);
bundle.putBoolean(FileSelectorFragment.BUNDLE_SELECT_FOLDER, false);
bundle.putString(FileSelectorFragment.BUNDLE_ROOT_PATH, Tools.CTRLMAP_PATH);
@@ -126,20 +149,14 @@ public class ProfileEditorFragment extends Fragment implements CropperUtils.Crop
Tools.swapFragment(requireActivity(),
FileSelectorFragment.class, FileSelectorFragment.TAG, bundle);
});
};
}
// Setup the expendable list behavior
mVersionSelectButton.setOnClickListener(v -> VersionSelectorDialog.open(v.getContext(), false, (id, snapshot)->{
private View.OnClickListener getVersionSelectListener() {
return v -> VersionSelectorDialog.open(v.getContext(), false, (id, snapshot)-> {
mTempProfile.lastVersionId = id;
mDefaultVersion.setText(id);
}));
// Set up the icon change click listener
mProfileIcon.setOnClickListener(v -> CropperUtils.startCropper(mCropperLauncher));
loadValues(LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE, ""), view.getContext());
});
}
@@ -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,30 @@ 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;
}
}
/**
* Check if the current download source is a mirror and not an official source.
* @return true if the source is a mirror, false otherwise
@@ -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);
}
@@ -28,10 +28,10 @@ public class CustomSeekBarPreference extends SeekBarPreference {
@SuppressLint("PrivateResource")
public CustomSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference, defStyleAttr, defStyleRes);
mMin = a.getInt(R.styleable.SeekBarPreference_min, 0);
a.recycle();
try (TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference, defStyleAttr, defStyleRes)) {
mMin = a.getInt(R.styleable.SeekBarPreference_min, 0);
}
}
public CustomSeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
@@ -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;
}
@@ -164,6 +153,46 @@ public class LauncherPreferences {
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);
@@ -32,31 +32,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 +66,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.setMax(maxRAM);
memorySeekbar.setValue(ramAllocation);
memorySeekbar.setSuffix(" MB");
EditTextPreference editJVMArgs = findPreference("javaArgs");
if (editJVMArgs != null) {
@@ -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);
}
}
@@ -13,6 +13,7 @@ import android.os.Process;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import net.kdt.pojavlaunch.MainActivity;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.utils.NotificationUtils;
@@ -39,9 +40,14 @@ public class GameService extends Service {
killIntent.putExtra("kill", true);
PendingIntent pendingKillIntent = PendingIntent.getService(this, NotificationUtils.PENDINGINTENT_CODE_KILL_GAME_SERVICE
, killIntent, Build.VERSION.SDK_INT >=23 ? PendingIntent.FLAG_IMMUTABLE : 0);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "channel_id")
.setContentTitle(getString(R.string.lazy_service_default_title))
.setContentText(getString(R.string.notification_game_runs))
.setContentIntent(contentIntent)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.notification_terminate), pendingKillIntent)
.setSmallIcon(R.drawable.notif_icon)
.setNotificationSilent();
@@ -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,18 @@ 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 AtomicReference<Exception> mDownloaderThreadException;
private ArrayList<DownloaderTask> mScheduledDownloadTasks;
private AtomicLong mDownloadFileCounter;
private AtomicLong mDownloadSizeCounter;
private long mDownloadFileCount;
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 +84,15 @@ 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);
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,11 +111,9 @@ 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) {
@@ -123,6 +128,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");
}
@@ -233,7 +255,19 @@ 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++;
if(size < 0) {
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)
);
@@ -401,18 +435,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,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;
}
@@ -0,0 +1,125 @@
package net.kdt.pojavlaunch.utils;
import android.opengl.EGL14;
import android.opengl.EGLConfig;
import android.opengl.EGLContext;
import android.opengl.EGLDisplay;
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) {
Log.e("GLInfoUtils", "Failed to create a context with major version "+majorVersion);
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_WINDOW_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;
}
int contextGLVersion = 3;
EGLContext context;
context = tryCreateContext(eglDisplay, config[0], 3);
if(context == null) {
contextGLVersion = 2;
context = tryCreateContext(eglDisplay, config[0], 2);
}
if(!EGL14.eglMakeCurrent(eglDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, context)) {
Log.e("GLInfoUtils", "Failed to make context current");
EGL14.eglDestroyContext(eglDisplay, context);
EGL14.eglTerminate(eglDisplay);
}
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;
}
public static GLInfo getInfo() {
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;
}
}
}
@@ -109,7 +109,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 +193,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 +214,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 +239,10 @@ public class JREUtils {
}
reader.close();
}
GLInfoUtils.GLInfo info = GLInfoUtils.getInfo();
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 +256,11 @@ public class JREUtils {
envMap.put("LIBGL_ES", "3");
}
}
if(info.vendor.equals("Qualcomm") && info.renderer.contains("Adreno") && !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 +301,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 +313,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 +375,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 +471,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 +518,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.getInfo().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;
}
@@ -2,8 +2,10 @@ package org.lwjgl.glfw;
import net.kdt.pojavlaunch.*;
import android.content.*;
import android.util.Log;
import android.view.Choreographer;
import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import java.util.ArrayList;
@@ -102,6 +104,7 @@ public class CallbackBridge {
// Called from JRE side
@SuppressWarnings("unused")
@Keep
public static @Nullable String accessAndroidClipboard(int type, String copy) {
switch (type) {
case CLIPBOARD_COPY:
@@ -164,6 +167,7 @@ public class CallbackBridge {
//Called from JRE side
@SuppressWarnings("unused")
@Keep
private static void onGrabStateChanged(final boolean grabbing) {
isGrabbing = grabbing;
sChoreographer.postFrameCallbackDelayed((time) -> {
@@ -190,17 +194,17 @@ public class CallbackBridge {
}
}
@CriticalNative public static native void nativeSetUseInputStackQueue(boolean useInputStackQueue);
@Keep @CriticalNative public static native void nativeSetUseInputStackQueue(boolean useInputStackQueue);
@CriticalNative private static native boolean nativeSendChar(char codepoint);
@Keep @CriticalNative private static native boolean nativeSendChar(char codepoint);
// GLFW: GLFWCharModsCallback deprecated, but is Minecraft still use?
@CriticalNative private static native boolean nativeSendCharMods(char codepoint, int mods);
@CriticalNative private static native void nativeSendKey(int key, int scancode, int action, int mods);
@Keep @CriticalNative private static native boolean nativeSendCharMods(char codepoint, int mods);
@Keep @CriticalNative private static native void nativeSendKey(int key, int scancode, int action, int mods);
// private static native void nativeSendCursorEnter(int entered);
@CriticalNative private static native void nativeSendCursorPos(float x, float y);
@CriticalNative private static native void nativeSendMouseButton(int button, int action, int mods);
@CriticalNative private static native void nativeSendScroll(double xoffset, double yoffset);
@CriticalNative private static native void nativeSendScreenSize(int width, int height);
@Keep @CriticalNative private static native void nativeSendCursorPos(float x, float y);
@Keep @CriticalNative private static native void nativeSendMouseButton(int button, int action, int mods);
@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);
static {
System.loadLibrary("pojavexec");
+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);
}
@@ -51,9 +51,8 @@ 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;
+31 -150
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,37 @@
#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);
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->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 +94,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 +232,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;
}
@@ -384,7 +273,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;
}
@@ -560,16 +449,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;
}
JNIEnv *jvm_env = get_attached_env(pojav_environ->runtimeJavaVMPtr);
(*jvm_env)->CallStaticVoidMethod(
jvm_env, pojav_environ->vmGlfwClass,
@@ -620,6 +500,7 @@ static bool tryCriticalNative(JNIEnv *env) {
};
jclass criticalNativeTest = (*env)->FindClass(env, "net/kdt/pojavlaunch/CriticalNativeTest");
if(criticalNativeTest == NULL) {
LOGD("No CriticalNativeTest class found !");
(*env)->ExceptionClear(env);
return false;
}
@@ -634,9 +515,9 @@ 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,
@@ -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", 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);
@@ -28,18 +28,8 @@
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/delete_account_button"
android:layout_width="@dimen/_52sdp"
android:layout_height="@dimen/_42sdp"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_menu_delete_forever"
android:scaleType="fitCenter"
app:layout_constraintEnd_toStartOf="@id/setting_button"
app:layout_constraintTop_toTopOf="parent" />
<!-- Holding most of the dynamic content -->
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container_fragment"
@@ -51,8 +51,9 @@
<net.kdt.pojavlaunch.customcontrols.handleview.DrawerPullButton
android:id="@+id/drawer_button"
android:layout_width="24dp"
android:layout_height="12dp"
android:layout_width="40dp"
android:layout_height="20dp"
android:padding="8dp"
android:elevation="10dp"
android:layout_gravity="center_horizontal"/>
<net.kdt.pojavlaunch.customcontrols.mouse.HotbarView
@@ -15,8 +15,9 @@
<net.kdt.pojavlaunch.customcontrols.handleview.DrawerPullButton
android:id="@+id/drawer_button"
android:layout_width="32dp"
android:layout_height="16dp"
android:layout_width="40dp"
android:layout_height="20dp"
android:padding="6dp"
android:elevation="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
@@ -28,19 +28,6 @@
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageButton
android:id="@+id/delete_account_button"
android:layout_width="@dimen/_52sdp"
android:layout_height="@dimen/_52sdp"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_menu_delete_forever"
android:scaleType="fitCenter"
android:paddingVertical="@dimen/_8sdp"
app:layout_constraintEnd_toStartOf="@id/setting_button"
app:layout_constraintTop_toTopOf="parent" />
<!-- Holding most of the dynamic content -->
<androidx.fragment.app.FragmentContainerView
android:id="@+id/container_fragment"
@@ -26,6 +26,8 @@
android:id="@+id/editResolution_seekbar"
android:layout_width="0dp"
android:layout_height="@dimen/_36sdp"
android:min="@integer/resolution_seekbar_min"
app:seekBarIncrement="@integer/resolution_seekbar_increment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.538"
@@ -34,9 +36,9 @@
<TextView
android:id="@+id/editResolution_textView_percent"
android:layout_width="50dp"
android:layout_width="150dp"
android:layout_height="0dp"
android:gravity="center"
android:gravity="end"
tools:text="50%"
app:layout_constraintBottom_toBottomOf="@id/editResolution_textView"
@@ -92,6 +94,10 @@
android:layout_width="0dp"
android:layout_height="@dimen/_36sdp"
android:min="@integer/gyro_speed_seekbar_min"
android:max="@integer/gyro_speed_seekbar_max"
app:seekBarIncrement="@integer/gyro_speed_seekbar_increment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.538"
app:layout_constraintStart_toStartOf="parent"
@@ -99,9 +105,9 @@
<TextView
android:id="@+id/editGyro_textView_percent"
android:layout_width="50dp"
android:layout_width="150dp"
android:layout_height="0dp"
android:gravity="center"
android:gravity="end"
tools:text="100%"
app:layout_constraintBottom_toBottomOf="@id/editGyro_textView"
@@ -127,6 +133,10 @@
android:layout_width="0dp"
android:layout_height="@dimen/_36sdp"
android:min="@integer/mouse_speed_seekbar_min"
android:max="@integer/mouse_speed_seekbar_max"
app:seekBarIncrement="@integer/mouse_speed_seekbar_increment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.538"
app:layout_constraintStart_toStartOf="parent"
@@ -134,9 +144,9 @@
<TextView
android:id="@+id/editMouseSpeed_textView_percent"
android:layout_width="50dp"
android:layout_width="150dp"
android:layout_height="0dp"
android:gravity="center"
android:gravity="end"
tools:text="100%"
app:layout_constraintBottom_toBottomOf="@id/editMouseSpeed_textView"
@@ -172,6 +182,10 @@
android:layout_width="0dp"
android:layout_height="@dimen/_36sdp"
android:min="@integer/gesture_delay_seekbar_min"
android:max="@integer/gesture_delay_seekbar_max"
app:seekBarIncrement="@integer/gesture_delay_seekbar_increment"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.538"
app:layout_constraintStart_toStartOf="parent"
@@ -179,10 +193,10 @@
<TextView
android:id="@+id/editGestureDelay_textView_percent"
android:layout_width="50dp"
android:layout_width="150dp"
android:layout_height="0dp"
android:gravity="center"
tools:text="270ms"
android:gravity="end"
tools:text="270 ms"
app:layout_constraintBottom_toBottomOf="@id/editGestureDelay_textView"
app:layout_constraintEnd_toEndOf="parent"
@@ -1,17 +1,39 @@
<fr.spse.extended_view.ExtendedTextView
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="@dimen/_52sdp"
android:layout_width="match_parent"
android:textSize="@dimen/_16ssp"
android:gravity="center_vertical"
android:drawablePadding="@dimen/_6sdp"
android:paddingStart="@dimen/_8sdp"
app:drawableStartSize="@dimen/_30sdp"
android:orientation="horizontal">
tools:text="HELLO THERE"
tools:drawableStart="@mipmap/ic_launcher"
<fr.spse.extended_view.ExtendedTextView
android:id="@+id/account_item"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:ignore="RtlSymmetry" />
android:textSize="@dimen/_16ssp"
android:gravity="center_vertical"
android:drawablePadding="@dimen/_6sdp"
android:paddingStart="@dimen/_8sdp"
app:drawableStartSize="@dimen/_30sdp"
tools:text="HELLO THERE"
tools:drawableStart="@mipmap/ic_launcher"
tools:ignore="RtlSymmetry" />
<!-- Fun fact, if I put an Image button, the spinner fails to put an onclick listener on the extended view -->
<ImageView
android:id="@+id/delete_account_button"
android:layout_width="@dimen/_52sdp"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_menu_delete_forever"
android:padding="@dimen/padding_moderate"
/>
</LinearLayout>
@@ -1,23 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<!-- App name part -->
<string name="app_name"></string>
<string name="app_short_name">PojavLauncher</string>
<!-- Action bar part -->
<!-- Languages list part -->
<!-- Login strings -->
<string name="login_online_login_label">Anmelden</string>
<!-- Hint -->
<!-- Warnings -->
<string name="warning_remove_account">Dieses Konto wird entfernt!</string>
<!-- AlertDialog title -->
<string name="alerttitle_installmod">Wahlweise einen Mod-Installer</string>
<!-- Error messages -->
<string name="error_fatal">PojavLauncher ist unerwartet abgestürzt</string>
<string name="error_no_version">Keine Version!</string>
<string name="error_show_more">Mehr anzeigen</string>
<string name="error_show_less">Weniger anzeigen</string>
<!-- Toast messages -->
<string name="toast_permission_denied">Die Lese/Schreib-Berechtigung für den Speicher ist benötigt!</string>
<string name="toast_optifine_success">Installation erfolgreich</string>
<!--
<string name="toast_3">Exit</string>
-->
<!-- MCLauncherActivity: Tabs -->
<string name="mcl_tab_wiki">Wiki</string>
<!-- MCLauncherActivity: Account status -->
<!-- MCLauncherActivity: Strings -->
<string name="mcl_launch_cleancache">Cache-Dateien bereinigen</string>
<string name="mcl_launch_downloading">Lade %s herunter</string>
<string name="mcl_launch_downloading_progress">"Lade %s herunter (%.2f MB / %.2f MB)"</string>
<string name="mcl_launch_download_assets">Bereite das Herunterladen der Ressourcen vor</string>
<string name="mcl_options">Optionen</string>
<string name="mcl_option_customcontrol">Benutzerdefinierte Steuerung</string>
<string name="mcl_setting_title_use_surface_view">Verwende alternatives Oberflächen-Rendering</string>
<string name="mcl_setting_subtitle_use_surface_view">Könnte die Leistung in GPU abhängigen Szenarien verbessern.</string>
<string name="mcl_setting_title_ignore_notch">Ignoriere die Kameraeinkerbung</string>
<string name="mcl_setting_subtitle_ignore_notch">Ignoriert die Kammeraeinkerbung im Bildschirm und erweitert den Bildschirm unter ihr.\nErmöglicht eine immersiveres Erlebniss.</string>
<string name="mcl_setting_title_resolution_scaler">Auflösungsskalierer</string>
<string name="mcl_setting_subtitle_resolution_scaler">Ermöglicht das Verringern der Spielauflösung. 100% entspricht der vollen Auflösung.</string>
<string name="mcl_setting_title_longpresstrigger">Verzögerung nach langem Drücken des Triggers</string>
<string name="mcl_setting_subtitle_longpresstrigger">Verzögerung für langes drücken des Triggers für das Zerstören von Blöcken oder fallen lassen von Gegenständen ändern.</string>
<string name="mcl_setting_title_buttonscale">Größe der Steuerelemente</string>
<string name="mcl_setting_subtitle_buttonscale">Tasten vergrößern, wenn sie zu klein sind.</string>
<string name="mcl_setting_title_mousescale">Größe der Maus</string>
<string name="mcl_setting_subtitle_mousescale">Größe der virtuellen Maus ändern.</string>
<string name="mcl_setting_title_javaargs">JVM-Startargumente</string>
<string name="mcl_setting_subtitle_javaargs">Achtung! Das Verändern dieser Argumente ohne Fachwissen kann zu Abstürzen führen.</string>
<string name="mcl_setting_category_renderer">Renderer</string>
<string name="mcl_setting_renderer_gles2_4">Holy GL4ES - (alle Versionen, schnell)</string>
<string name="mcl_setting_renderer_vulkan_zink">Zink (Vulkan) - (alle Versionen, mittel)</string>
<string name="mcl_setting_veroption_release">Vollversionen</string>
<string name="mcl_setting_veroption_snapshot">Entwicklungsversionen</string>
<string name="mcl_setting_veroption_oldalpha">Alte Alpha</string>
<string name="mcl_setting_veroption_oldbeta">Alte Beta</string>
<string name="mcl_setting_java_sandbox">.jar in einer Sandbox ausführen</string>
<string name="mcl_setting_java_sandbox_subtitle">Verfügbarkeit des Sandbox-Security-Managers beim Ausführen einer .jar-Datei einstellen.</string>
<string name="mcl_version_clone">Duplizieren</string>
<!-- Global strings -->
<string name="global_error">I want to login</string>
<string name="global_load">Laden</string>
<string name="global_name">Name</string>
<string name="global_clone">Duplizieren</string>
<string name="global_restart">Neustart</string>
<string name="global_save">Speichern</string>
<!-- MainActivity: strings -->
<!-- MainActivity: Control buttons -->
<!-- MainActivity: Menu advanced controls -->
@@ -26,4 +71,7 @@
<string name="control_more3"></string>
<string name="control_more4"></string>
-->
<string name="profiles_profile_name">Name</string>
<string name="pedit_renderer">Renderer</string>
<string name="of_dl_progress">Lade %s herunter</string>
</resources>
@@ -1,16 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<!-- App name part -->
<string name="app_name">PojavLauncher (Minecraft: Java Edition for Android)</string>
<string name="app_short_name">PojavLauncher</string>
<!-- Action bar part -->
<!-- Languages list part -->
<!-- Login strings -->
<string name="login_online_username_hint">البريد الإلكتروني أو اسم المستخدم</string>
<string name="login_online_username_hint">اسم المستخدم</string>
<string name="login_online_login_label">تسجيل الدخول</string>
<!-- Hint -->
<string name="hint_control_mapping">"أضغط على أيقونة الإعداد لفتح قائمة التعديلات أضغط على زر \n ⚙: للتعديل، تغير الحجم، حذف
، أو تعديل ازرار التحكم."</string>
<!-- Warnings -->
<string name="warning_remove_account">سيتم إزالة هذا الحساب!</string>
<!-- AlertDialog title -->
@@ -38,28 +36,27 @@
<string name="mcl_option_customcontrol">تخصيص التحكم</string>
<string name="mcl_setting_title_use_surface_view">استخدام عرض الأسطح البديل</string>
<string name="mcl_setting_subtitle_use_surface_view">قد يساعد الأداء في سيناريوهات المعتمدة على GPU.</string>
<string name="mcl_setting_title_ignore_notch">تجاهل النوتش</string>
<string name="mcl_setting_title_ignore_notch">تجاهل النوتش (الجزء المفقود من أعلى الشاشة مع الكاميرا الأمامية)</string>
<string name="mcl_setting_subtitle_ignore_notch">تجاهل النوتش وتوسيع الشاشة أسفلها.\nيعطيك تجرِبة أكثر انغماساً.</string>
<string name="mcl_setting_title_resolution_scaler">مقياس الدقة</string>
<string name="mcl_setting_subtitle_resolution_scaler">يسمح لك بتخفيض دقة اللعبة. 100% هي الدقة الكاملة.</string>
<string name="mcl_setting_title_longpresstrigger">فعل التأخير للضغط المطول</string>
<string name="mcl_setting_subtitle_longpresstrigger">تغيير مدة \"تفعيل الضغط المطول\" عند تدمير الأشياء و إسقاط العناصر.</string>
<string name="mcl_setting_title_buttonscale">ضبط حجم أزرار التحكم</string>
<string name="mcl_setting_subtitle_buttonscale">ضبط حجم الأزرار إذا كانت صغيرة جدآ.</string>
<string name="mcl_setting_subtitle_buttonscale">كَبِر حجم الأزرار إذا كانت صغيرة جداً.</string>
<string name="mcl_setting_title_mousescale">ضبط حجم الفأرة</string>
<string name="mcl_setting_subtitle_mousescale">غير حجم مؤشر الفأرة الأفتراضية.</string>
<string name="mcl_setting_title_javaargs">حجج إطلاق JVM</string>
<string name="mcl_setting_subtitle_javaargs">كن حذرا، قد يجعل هذا اللعبة تتوقف إذا تم تعديلها بدون علم.</string>
<string name="mcl_setting_subtitle_mousescale">غير حجم مؤشر الفأرة الافتراضية.</string>
<string name="mcl_setting_title_javaargs">معلمات بَدْء تشغيل JVM</string>
<string name="mcl_setting_subtitle_javaargs">كن حذرا، تعديلها بغير علم قد يتسبب بتعطيل اللعبة.</string>
<string name="mcl_setting_category_renderer">عارض الرسوميات</string>
<string name="mcl_setting_renderer_gles2_4">Holy Gl4es - (جميع الإصدارات، بسرعة)</string>
<string name="mcl_setting_renderer_gles2_4">Holy GL4ES - (جميع الإصدارات، سريع)</string>
<string name="mcl_setting_renderer_vulkan_zink">Zink (Vulkan) - (جميع الإصدارات، متوسط)</string>
<string name="mcl_setting_renderer_angle">ANGLE (Vulkan) - (1.17+ فقط، متوسط)</string>
<string name="mcl_setting_veroption_release">إصدار نهائي</string>
<string name="mcl_setting_veroption_snapshot">اللمحات (سنابشوت)</string>
<string name="mcl_setting_veroption_snapshot">اللمحات \"سنابشوت\"</string>
<string name="mcl_setting_veroption_oldalpha">نسخ ألفا قديمة</string>
<string name="mcl_setting_veroption_oldbeta">نسخ بيتا قديمة</string>
<string name="mcl_setting_java_sandbox">تنفيذ Sandbox.jar</string>
<string name="mcl_setting_java_sandbox_subtitle">التحكم بقدرة وجود Sandbox Security Manger عند تشغيل ملف .jar</string>
<string name="mcl_setting_java_sandbox">تنفيذ ملف \".jar\" داخل Sandbox</string>
<string name="mcl_setting_java_sandbox_subtitle">التحكم بقدرة وجود Sandbox Security Manger عند تشغيل مِلَفّ .jar.</string>
<string name="mcl_version_clone">نسخ</string>
<!-- Global strings -->
<string name="global_edit">تعديل</string>
@@ -71,15 +68,15 @@
<string name="global_restart">اعادة تشغيل</string>
<string name="global_save">حفظ</string>
<string name="global_unpacking">جاري فك الضغط %s</string>
<string name="global_error_field_empty">لا يمكن لهذه الخانة ان تكون فارغة</string>
<string name="global_error_field_empty">لا يمكن لهذه الخانة أن تكون فارغة</string>
<string name="global_waiting">انتظر</string>
<string name="global_select">اختر</string>
<string name="global_retry">أعد المحاولة</string>
<string name="global_default">مستخدم دائما</string>
<string name="global_default">الافتراضي</string>
<!-- MainActivity: strings -->
<string name="mcn_exit_title">تم الخروج من التطبيق/اللعبة بخلل %d، تحقق من latestlog.txt لمزيد من التفاصيل.</string>
<string name="mcn_exit_confirm">هل أنت متأكد من أنك تريد الإغلاق؟</string>
<string name="mcn_check_fail_vulkan_support">عارض Zink (Vulkan) لا يدعم هذا الجهاز!</string>
<string name="mcn_exit_confirm">هل أنت متأكد من أنك تريد فرض الإغلاق؟</string>
<string name="mcn_check_fail_vulkan_support">عارض الرسوميات Zink (Vulkan) غير مدعوم على هذا الجهاز!</string>
<!-- MainActivity: Control buttons -->
<string name="control_chat">دردشة</string>
<string name="control_debug">Debug</string>
@@ -95,19 +92,19 @@
<string name="control_thirdperson">3rd</string>
<string name="control_listplayers">Tab</string>
<string name="control_mouse">الفأرة</string>
<string name="control_mouseoff">وضع الفأرة: موقفة</string>
<string name="control_mouseoff">وضع الفأرة: معطلة</string>
<string name="control_mouseon">وضع الفأرة: مفعلة </string>
<!-- MainActivity: Menu advanced controls -->
<string name="control_forceclose">فرض الإغلاق</string>
<string name="control_viewout">سجل الإخراج</string>
<string name="control_viewout">سِجل الإخراج</string>
<string name="control_adebug">مدخل التصحيح</string>
<string name="control_customkey">إرسال رمز مفتاحي مخصص</string>
<!-- ImportControlActivity Strings -->
<string name="import_control_label">استيراد مخطط التحكم</string>
<string name="import_control_invalid_file">المِلَفّ غير صالح أو تالف</string>
<string name="import_control_import_button">استيراد ازرار التحكم</string>
<string name="import_control_verifying_file">يتم التحقق من الملف، الرجاء الانتظار والمحاولة مرة أخرى…</string>
<string name="import_control_invalid_name">الاسم غير صالحا او المِلَفّ موجود مسبقًا</string>
<string name="import_control_label">استيراد مخطط أزرار تحكم</string>
<string name="import_control_invalid_file">المِلَفّ غير صالح أو تآلف</string>
<string name="import_control_import_button">استيراد مخطط لأزرار التحكم</string>
<string name="import_control_verifying_file">يتم التحقق من المِلَفّ، الرجاء الانتظار والمحاولة مرة أخرى…</string>
<string name="import_control_invalid_name">الاسم غير صالح أو المِلَفّ موجود مسبقًا</string>
<string name="import_control_done">تم الاستيراد</string>
<!--
<string name="control_more3"></string>
@@ -116,72 +113,72 @@
<string name="customctrl_toggle">تبديلي</string>
<string name="customctrl_size">الحجم</string>
<string name="customctrl_mapping">تخطيط الأزرار</string>
<string name="customctrl_orientation">الإتجاة</string>
<string name="customctrl_orientation">الاتجاه</string>
<string name="customctrl_background_color">لون الخلفية</string>
<string name="customctrl_corner_radius">تقوس الزاوية</string>
<string name="customctrl_corner_radius">تقوس زاوية الأركان</string>
<string name="customctrl_stroke_width">عرض الخط</string>
<string name="customctrl_stroke_color">لون الخط</string>
<string name="customctrl_button_opacity">شفافية الزر</string>
<string name="customctrl_addbutton">إضافة زر</string>
<string name="customctrl_addbutton_drawer">اضافة درج</string>
<string name="customctrl_addbutton_drawer">إضافة درج</string>
<string name="customctrl_addbutton_joystick">اضف عصا تحكم</string>
<string name="customctrl_addsubbutton">إضافة زر فرعي</string>
<string name="customctrl_selectdefault">اختار مخطط التحكم</string>
<string name="customctrl_selectdefault">اختيار تخطيط تحكم افتراضي</string>
<string name="customctrl_export">استخرج مخطط التحكم</string>
<string name="main_share_logs">مشاركة ملف السجل</string>
<string name="main_install_jar_file">نفذ ملف .jar</string>
<string name="main_play">إبدأ اللعب</string>
<string name="main_install_jar_file">نفذ مِلَفّ .jar</string>
<string name="main_play">ابدأ اللعب</string>
<string name="autoram_info_msg">تم تعيين الذاكرة إلى %d ميغابايت</string>
<string name="mcl_setting_check_libraries">التحقق من المكتبات بعد التحميل</string>
<string name="mcl_setting_check_libraries_subtitle">هذا الخيار يجبر البرنامج على التحقق من بيانات الملف إذا كان متاحاً. يمنع الأخطاء من الحدوث اثناء التنزيل.</string>
<string name="dl_library_sha_fail">المكتبة %s تالفة وسيتم إعادة تحميلها</string>
<string name="dl_library_sha_unknown">لا يمكن التحقق من الملفات المكتبية %s ، يجب أن تفترض أنها جيدة</string>
<string name="dl_library_sha_pass">المكتبة %s جيدة وقابلة للاستخدام</string>
<string name="mcl_setting_check_libraries_subtitle">هذا الخِيار يجبر البرنامَج على التحقق من بيانات المِلَفّ إذا كان متاحاً. يمنع الأخطاء من الحدوث خلال التنزيل.</string>
<string name="dl_library_sha_fail">المكتبة %s تآلفه وسيتم إعادة تحميلها</string>
<string name="dl_library_sha_unknown">لا يمكن التحقق من ملفات المكتبة %s، يجب افتراض أنها بحالة جيدة</string>
<string name="dl_library_sha_pass">المكتبة %s بحالة جيدة وقابلة للاستخدام</string>
<string name="mcl_disable_gestures">تعطيل الإيماءات</string>
<string name="mcl_disable_gestures_subtitle">تعطيل الإيماءات، مثل تثبيت الضغط لكسر كتلة، والنقر لوضع كتلة.</string>
<string name="mcl_disable_swap_hand">تعطيل الضغط مرتين لتبديل اليدين</string>
<string name="mcl_disable_swap_hand_subtitle">يعطل تبديل العنصر المحمول لليد الأخرى عند الضغط مرتين.</string>
<string name="mcl_setting_title_mousespeed">سرعة الفأرة</string>
<string name="mcl_setting_subtitle_mousespeed">يغير سرعة مؤشر الفأرة الأفتراضية.</string>
<string name="customctrl_passthru">سماح تحريك أزرار الشاشة</string>
<string name="mcl_setting_title_mousespeed">سرعة تحرك الفأرة</string>
<string name="mcl_setting_subtitle_mousespeed">يغير سرعة مؤشر الفأرة الافتراضية.</string>
<string name="customctrl_passthru">سماح تحريك الشاشة في أثناء استخدام الزر</string>
<string name="customctrl_swipeable">قابل للسحب</string>
<string name="customctrl_forward_lock">قفل إلى الأمام</string>
<string name="memory_warning_msg">الكمية الحالية من ذاكرة الوصول العشوائي المجانية (%d) أقل من ذاكرة الوصول العشوائي المحددة (%d)، مما قد يؤدي إلى حدوث أعطال. قم بتغيير التخصيص إذا تحطمت اللعبة.</string>
<string name="mcl_memory_allocation">تخصيص الذاكرة.</string>
<string name="mcl_memory_allocation_subtitle">يتحكم في كمية الذاكرة المعطاة لـ Minecraft.</string>
<string name="multirt_runtime_corrupt">مشغل جافا فاسد</string>
<string name="customctrl_absolute_tracking">تتبع الأصابع بشكل مطلق</string>
<string name="memory_warning_msg">الكَمَيَّة الحالية من ذاكرة الوصول العشوائي المتاحة للاستخدام (%d) أقل من ذاكرة الوصول العشوائي المحددة (%d)، مما قد يؤدي إلى حدوث أعطال. غير الذاكرة المخصصة إذا توقفت اللعبة.</string>
<string name="mcl_memory_allocation">الذاكرة المخصصة للاستخدام</string>
<string name="mcl_memory_allocation_subtitle">يتحكم في كَمَيَّة الذاكرة المعطاة لـ Minecraft.</string>
<string name="multirt_runtime_corrupt">بيئة تشغيل Java تالفة</string>
<string name="multirt_runtime_incompatiblearch">بنية غير متوافقة: %s</string>
<string name="multirt_config_title">أوقات تشغيل Java</string>
<string name="multirt_config_add">أضف واحدًا جديدا</string>
<string name="multirt_title">مدير مشغلات الجافا</string>
<string name="multirt_subtitle">تحكم بالJava Runtimes المثبتة.</string>
<string name="multirt_config_title">بيئة تشغيل Java</string>
<string name="multirt_config_add">إضافة جديد</string>
<string name="multirt_title">مدير بيئة تشغيل Java</string>
<string name="multirt_subtitle">إدارة مشغلات جافا المثبتة.</string>
<string name="multirt_progress_caching">تخزين المعلومات...</string>
<string name="multirt_config_setdefault">تعيين لإستخدام دائم</string>
<string name="multirt_config_setdefault_already">مستخدم دائما</string>
<string name="multirt_config_removeerror_last">يجب ان يكون هناك Java runtime واحد مثبت على الأقل.</string>
<string name="multirt_nocompatiblert">لا يمكن العثور على أي اصدار جافا صالح. هذا الإصدار يتطلب جافا %d أو أحدث.</string>
<string name="multirt_nojava8rt">لا يمكن العثور على Java 8. لاستخدام هذا الخيار، تحتاج إلى تثبيت Java 8.</string>
<string name="multirt_delete_runtime">حذف Runtime</string>
<string name="multirt_config_setdefault">تعيين كافتراضي</string>
<string name="multirt_config_setdefault_already">الافتراضي</string>
<string name="multirt_config_removeerror_last">يجب أن يكون لديك على الأقل بيئة تشغيل جافا واحدة مثبتة.</string>
<string name="multirt_nojava8rt">لا يمكن العثور على Java 8. لاستخدام هذا الخِيار، تحتاج إلى تثبيت Java 8.</string>
<string name="multirt_delete_runtime">حذف بيئة التشغيل</string>
<string name="pvc_gameDirectory">مكان تخزين اللعبة</string>
<string name="pvc_jvmArgs">مدخلات JVM</string>
<string name="preference_mouse_start_title">البَدْء بالفأرة الافتراضية مشغله</string>
<string name="preference_mouse_start_description">سيظهر مؤشر الفأرة الأفتراضية عند التشغيل اذا فعلت هذا الخيار.</string>
<string name="preference_mouse_start_title">البَدْء بالفأرة الافتراضية مشغلة</string>
<string name="preference_mouse_start_description">عند تفعيل هذا الخِيار سوف تظهر الفأرة الافتراضية بمجرد التشغيل.</string>
<string name="preference_video_title">الفيديو و عارض الرسوميات</string>
<string name="preference_video_description">الدقة، عارض الرسوميات، الأداء</string>
<string name="preference_control_title">تخصيص التحكم</string>
<string name="preference_control_description">الإيماءات، الازرار، و تغيير الحجم</string>
<string name="preference_video_description">الدِّقَّة، عارض الرسوميات، الأداء</string>
<string name="preference_control_title">تخصيص أزرار التحكم</string>
<string name="preference_control_description">الإيماءات، الأزرار، و تغيير الحجم</string>
<string name="preference_java_title">تعديلات جافا</string>
<string name="preference_java_description">Java Runtimes, Jvm Arguments, حجم الذاكرة العشوائية و Sandbox</string>
<string name="preference_misc_title">أعدادات متنوعة</string>
<string name="preference_misc_description">قائمة الإصدار، والتحقق من المكاتب</string>
<string name="preference_experimental_title">أشياء تجريبيه</string>
<string name="preference_experimental_description">استخدم هذا الخيار بحذر، لن يتم مساعدتك</string>
<string name="preference_experimental_title">أشياء تجريبية</string>
<string name="preference_experimental_description">استخدم هذه الخِيارات بحذر، لن يتم مساعدتك</string>
<string name="preference_sustained_performance_title">تمكين وضع الأداء المستقر</string>
<string name="preference_sustained_performance_description">الحد من الاختناق الحراري عن طريق الحد من الأداء الأقصى.</string>
<string name="preference_force_vsync_title">اجبر تفعيل Vsync</string>
<string name="preference_force_vsync_description">الحد من الاختناق الحراري عن طريق الحد من الأداء الأقصى.</string>
<string name="preference_sustained_performance_description">الحد من الاختناق الحراري عن طريق حد الأداء الأقصى.</string>
<string name="preference_force_vsync_title">أجبار على تفعيل VSync</string>
<string name="preference_force_vsync_description">الحد من الاختناق الحراري عن طريق حد الأداء الأقصى.</string>
<string name="preference_force_english_title">إجبار تحويل اللغة إلى اللغة الإنجليزية</string>
<string name="preference_force_english_description">يسمح لك برؤية النصوص الأصلية، مثلا ما ارادوه المطورين. يتطلب إعادة التشغيل.</string>
<string name="preference_force_english_description">يسمح لك برؤية النصوص الأصلية، كما أرادها المطورون. يتطلب إعادة التشغيل.</string>
<string name="preference_edit_controls_title">تعديل مخطط التحكم</string>
<string name="preference_edit_controls_summary">عدل مخطط التحكم لتلبي احتياجاتك.</string>
<string name="preference_category_gyro_controls">تحكم باستخدام الجايروسكوب</string>
@@ -189,17 +186,17 @@
<string name="preference_gyro_invert_x_axis">عكس المحور الأفقي</string>
<string name="preference_gyro_invert_y_axis">عكس المحور العمودي</string>
<string name="preference_gyro_invert_x_axis_description">اعكس المحور الأفقي.</string>
<string name="preference_gyro_invert_y_axis_description">اعكس المحور العامودي.</string>
<string name="preference_gyro_smoothing_title">فعل سلاسة الجايروسكوب</string>
<string name="preference_gyro_invert_y_axis_description">اعكس المحور العمودي.</string>
<string name="preference_gyro_smoothing_title">فعل تسليس حركة الجايروسكوب</string>
<string name="preference_gyro_smoothing_description">سلاسة اكثر مقابل التأخير.</string>
<string name="preference_back_title">العودة إلى الشاشة الأخيرة</string>
<string name="unnamed">بلا اسم</string>
<string name="profiles_latest_snapshot">أحدث اصدار تجريبي</string>
<string name="unnamed">غير مسمى</string>
<string name="profiles_latest_snapshot">آخر لمحة (سنابشوت)</string>
<string name="profiles_latest_release">أحدث إصدار</string>
<string name="profiles_profile_name">الاسم</string>
<string name="profiles_profile_version">الإصدار</string>
<string name="global_delete">حذف</string>
<string name="pedit_java_runtime">Java Runtime</string>
<string name="pedit_java_runtime">بيئة تشغيل Java</string>
<string name="pedit_renderer">عارض الرسوميات</string>
<string name="arc_capes_title">Cosmetica Capes</string>
<string name="arc_capes_desc">يفعل أوشحه من Cosmetica, (المعروفة مسبقًا ب Arc). لمزيد من المعلومات، يرجى زيارة https://cosmetica.cc, يتطلب Optifine لكي يعمل.</string>
@@ -282,6 +279,7 @@
<string name="preference_vulkan_driver_system_description">اجبر البرنامج على استخدام Vulkan driver الخاص بالنظام بدلاً من Turnip على Adreno GPUs، فقط يؤثر بZink و المودات المستخدمة ل Vulkan.</string>
<string name="generic_install">تثبيت</string>
<string name="generic_apply">طبّق</string>
<string name="generic_debug">Debug</string>
<string name="search_modpack_no_result">لم يتم العثور على مودباك</string>
<string name="search_modpack_error">فشل العثور على مودباك</string>
<string name="search_modpack_download_error">فشل تنزيل البيانات التعريفية للمودباك</string>
@@ -320,4 +318,16 @@
<string name="notification_permission_toast">O</string>
<string name="preference_ask_for_notification_title">السماح بالإشعارات</string>
<string name="preference_ask_for_notification_description">.</string>
<string name="preference_vsync_in_zink_title">السماح بتفعيل V-Sync مع Zink</string>
<string name="preference_vsync_in_zink_description">يسمح للمشغل باستخدام APIs النظام الداخلي لتمكين V-Sync للزنك. قم بإيقاف تشغيل هذا إذا تعطل المشغل فجأة مع الزنك بعد تحديث النظام.</string>
<string name="exception_failed_to_unpack_jre17">فشل تثبيت JRE 17</string>
<string name="newdl_starting">قراءة بيانات تعريف اللعبة…</string>
<string name="newdl_downloading_metadata">تحميل بيانات تعريف اللعبة (%s)</string>
<string name="controller_button_a">A</string>
<string name="controller_button_b">B</string>
<string name="controller_button_x">X</string>
<string name="controller_button_y">Y</string>
<string name="controller_button_start">Start</string>
<string name="controller_button_select">اختر</string>
<string name="customctrl_visibility_title">الظهور</string>
</resources>
@@ -1,14 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<!-- App name part -->
<string name="app_name">PojavLauncher (Minecraft: Java Edition Android üçün)</string>
<!-- Action bar part -->
<!-- Languages list part -->
<!-- Login strings -->
<string name="login_online_username_hint">E-poçt və ya istifadəçi adı</string>
<string name="login_online_username_hint">İstifadəçi adı</string>
<string name="login_online_login_label">Daxil ol</string>
<!-- Hint -->
<string name="hint_control_mapping">"Kontekst menyusunu açmaq üçün yuxarı orta dişli ikonaya toxunun ⚙\nFərdiləşdirmə üçün düyməyə toxunun: onun klaviaturasını redaktə edin, ölçüsünü dəyişin, silin və ya fərdiləşdirin."</string>
<!-- Warnings -->
<string name="warning_remove_account">Bu hesab silinəcək!</string>
<!-- AlertDialog title -->
@@ -51,7 +50,6 @@
<string name="mcl_setting_category_renderer">Renderer</string>
<string name="mcl_setting_renderer_gles2_4">Holy GL4ES - (bütün versiyalar, sürətli)</string>
<string name="mcl_setting_renderer_vulkan_zink">Zink (Vulkan) - (bütün versiyalar, orta)</string>
<string name="mcl_setting_renderer_angle">ANGLE (Vulkan) - (yalnız 1.17+, orta)</string>
<string name="mcl_setting_veroption_release">Buraxın</string>
<string name="mcl_setting_veroption_snapshot">Snapshot</string>
<string name="mcl_setting_veroption_oldalpha">Köhnə-alfa</string>
@@ -158,7 +156,6 @@
<string name="multirt_config_setdefault">Defolt təyin edin</string>
<string name="multirt_config_setdefault_already">Defolt</string>
<string name="multirt_config_removeerror_last">Ən azı bir Java Runtime quraşdırılmış olmalıdır.</string>
<string name="multirt_nocompatiblert">Heç bir uyğun gələn Java Runtime tapılmadı. Bu versiya Java %d və ya daha yenisini tələb edir.</string>
<string name="multirt_nojava8rt">Java 8-i tapmaq mümkün deyil. Bu seçimdən istifadə etmək üçün Java 8-i quraşdırmalısınız.</string>
<string name="multirt_delete_runtime">Runtime-ı silin</string>
<string name="pvc_gameDirectory">Oyun kataloqu</string>
@@ -281,6 +278,7 @@
<string name="preference_vulkan_driver_system_description">Başladıcını Adreno GPU-larda Turnip əvəzinə sistem Vulkan sürücüsündən istifadə etməyə məcbur edin. Yalnız Zink və Vulkandan istifadə edən modlara təsir edir.</string>
<string name="generic_install">Quraşdır</string>
<string name="generic_apply">Tətbiq et</string>
<string name="generic_debug">Sazlama</string>
<string name="search_modpack_no_result">Heç bir modpaket tapılmadı</string>
<string name="search_modpack_error">Mod paketləri tapmaq alınmadı</string>
<string name="search_modpack_download_error">Modpack metadatasını endirmək alınmadı</string>
@@ -327,5 +325,11 @@
<string name="exception_failed_to_unpack_jre17">JRE 17 quraşdırmaq alınmadı</string>
<string name="newdl_starting">Oyun metadatası oxunur…</string>
<string name="newdl_downloading_metadata">Oyun metadatası endirilir (%s)</string>
<string name="newdl_downloading_game_files">Oyun faylları endirilir... (%d/%d, %.2f MB)</string>
<string name="controller_button_a">A</string>
<string name="controller_button_b">B</string>
<string name="controller_button_x">X</string>
<string name="controller_button_y">Y</string>
<string name="controller_button_start">Başlat</string>
<string name="controller_button_select">Seç</string>
<string name="customctrl_visibility_title">Görünüş</string>
</resources>
@@ -1,36 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<!-- App name part -->
<string name="app_name">PojavLauncher (Android өсөн Minecraft: Java Edition)</string>
<string name="app_short_name">PojavLauncher</string>
<!-- Action bar part -->
<!-- Languages list part -->
<!-- Login strings -->
<string name="login_online_username_hint">Email йәки ҡулланыусы исеме</string>
<string name="login_online_login_label">Керергә</string>
<!-- Hint -->
<!-- Warnings -->
<string name="warning_remove_account">Был хисап яҙма юйыла!</string>
<!-- AlertDialog title -->
<string name="alerttitle_installmod">Мода ҡуйыусыһын һайлағыҙ</string>
<!-- Error messages -->
<string name="error_fatal">Көтмәгәндә PojavLauncher программаһының эше боҙолоп китә</string>
<string name="error_no_version">Версиялар юҡ!</string>
<string name="error_show_more">Күберәк</string>
<string name="error_show_less">Әҙерәк</string>
<!-- Toast messages -->
<string name="toast_permission_denied">Уҡыу/яҙыу өсөн һаҡлағыста рөхсәт талап ителә!</string>
<string name="toast_optifine_success">Урынлаштырылды</string>
<!--
<string name="toast_3">Exit</string>
-->
<!-- MCLauncherActivity: Tabs -->
<string name="mcl_tab_wiki">Вики</string>
<!-- MCLauncherActivity: Account status -->
<!-- MCLauncherActivity: Strings -->
<string name="mcl_launch_cleancache">Кэш файлдарын таҙартыу</string>
<string name="mcl_launch_downloading">Йөкләү %s</string>
<string name="mcl_launch_downloading_progress">"Йөкләү %s (%.2f МБ/%.2f МБ)"</string>
<string name="mcl_launch_download_assets">Ресурстарҙы йөкләүгә әҙерлек</string>
<string name="mcl_options">Опциялар</string>
<string name="mcl_option_customcontrol">Ҡулланыусы идара итеү элементтары</string>
<string name="mcl_setting_title_use_surface_view">Өҫкө йөҙҙөң альтернатив рендерын ҡулланығыҙ</string>
<string name="mcl_setting_subtitle_use_surface_view">График процессор менән бәйле сценарийҙарҙа етештереүсәнлекте арттыра ала.</string>
<string name="mcl_setting_title_ignore_notch">Зазубринаны һанға һуҡмау</string>
<string name="mcl_setting_subtitle_ignore_notch">Экранды уның аҫтына сығара.\nБыл һеҙгә тағы ла мауыҡтырғыс тәжрибә бирә.</string>
<string name="mcl_setting_title_resolution_scaler">Резолюцияны арттырыу өсөн ҡоролма</string>
<string name="mcl_setting_subtitle_resolution_scaler">Уйындың рөхсәтен кәметергә мөмкинлек бирә. 100% - тулы резолюция.</string>
<string name="mcl_setting_title_longpresstrigger">Асыу ырғағына баҫып тороуҙың оҙайлы тотҡарлығы</string>
<string name="mcl_setting_subtitle_longpresstrigger">Блоктарҙы юҡ итеү һәм әйберҙәрҙең төшөүе өсөн оҙаҡ баҫҡанда эшләтеү тотҡарлығын үҙгәртегеҙ.</string>
<string name="mcl_setting_title_buttonscale">Масштаблауҙы идара итеү төймәләре</string>
<string name="mcl_setting_subtitle_buttonscale">Төймәләре бик бәләкәй булһа, уларҙың ҙурлығын арттырығыҙ.</string>
<string name="mcl_setting_title_mousescale">Сысҡан ярҙамында масштаблау</string>
<string name="mcl_setting_subtitle_mousescale">Виртуаль сысҡандың ҙурлығын үҙгәртегеҙ.</string>
<string name="mcl_setting_title_javaargs">JVM-ды эшләтеп ебәреү аргументтары</string>
<string name="mcl_setting_subtitle_javaargs">Һаҡ булығыҙ, әгәр ҡулланыусы белмәһә, үҙгәрештәр индерһәгеҙ, уйындың боҙолоуына килтереүе ихтимал.</string>
<string name="mcl_setting_category_renderer">Рендерер</string>
<string name="mcl_setting_renderer_gles2_4">Holy GL4ES (бөтә версиялар, тиҙ)</string>
<string name="mcl_setting_renderer_vulkan_zink">Zink (Vulkan) (бөтә версиялар, уртаса)</string>
<string name="mcl_setting_veroption_release">Релиздар</string>
<string name="mcl_setting_veroption_snapshot">Снапшотттар</string>
<string name="mcl_setting_veroption_oldalpha">Иҫке альфалар</string>
<string name="mcl_setting_veroption_oldbeta">Иҫке беталар</string>
<string name="mcl_setting_java_sandbox">Sandbox Башҡарыуы .jar</string>
<string name="mcl_setting_java_sandbox_subtitle">Jar-файл эшләгәндә sandbox security manager-тың асыҡлығын контролдә тотоғоҙ.</string>
<!-- Global strings -->
<string name="global_edit">Үҙгәртергә</string>
<string name="global_error">Хата</string>
@@ -1,15 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation">
<!-- App name part -->
<string name="app_name">পোজাভলন্চার(মাইনক্রাফট: জাভা এডিশন আ্যন্ডরয়েডের জন্য)</string>
<string name="app_short_name">পোজাভলন্চার</string>
<!-- Action bar part -->
<!-- Languages list part -->
<!-- Login strings -->
<string name="login_online_username_hint">ব্যবহারকারীর নাম বা ইমেল</string>
<string name="login_online_login_label">লগইন</string>
<!-- Hint -->
<string name="hint_control_mapping">"কনটেক্সট মেনু খুলতে টপ সেন্টার কগ আইকনে ট্যাপ করুন ⚙\nকাস্টমাইজ করতে একটি বোতামে ট্যাপ করুন: এর কীবাইন্ড এডিট, রিসাইজ, ডিলিট বা কাস্টমাইজ করুন."</string>
<!-- Warnings -->
<string name="warning_remove_account">এই একাউন্টটি মুছে যাবে!</string>
<!-- AlertDialog title -->
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff. Show more