Compare commits
102
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b41cf6dbd8 | ||
|
|
8e850d19b5 | ||
|
|
4f8fa7ae0c | ||
|
|
fa482de030 | ||
|
|
da92e8ab6d | ||
|
|
4668d9c9a2 | ||
|
|
1dd0ba572d | ||
|
|
1513156262 | ||
|
|
beb58d72eb | ||
|
|
51e1bb1dd8 | ||
|
|
80f35bb7e2 | ||
|
|
36b0e88666 | ||
|
|
8dd34c8153 | ||
|
|
ae48e8e2f9 | ||
|
|
3b1ad64342 | ||
|
|
3912db6e21 | ||
|
|
3f630420f2 | ||
|
|
827d7db46c | ||
|
|
2982852b2e | ||
|
|
992ac0f3c4 | ||
|
|
9e77841126 | ||
|
|
d8f0c27e7e | ||
|
|
045018f8e0 | ||
|
|
ed048fb4cb | ||
|
|
181f81131f | ||
|
|
7631e3c9e7 | ||
|
|
348fc84cb4 | ||
|
|
ea5b6013f6 | ||
|
|
df0b762cf3 | ||
|
|
74492eaa7e | ||
|
|
5a01b89eef | ||
|
|
332de88620 | ||
|
|
879a8d9fb5 | ||
|
|
d23bdb9ffa | ||
|
|
856bace37c | ||
|
|
2364203366 | ||
|
|
eccef88183 | ||
|
|
0797b7942e | ||
|
|
bdc7f3347d | ||
|
|
94bc4ebb90 | ||
|
|
f0daae373e | ||
|
|
8230106715 | ||
|
|
2dc2aa43bf | ||
|
|
34125274cb | ||
|
|
f872f118f0 | ||
|
|
164739839d | ||
|
|
b03bb6298e | ||
|
|
872fc4c39f | ||
|
|
3443b049b6 | ||
|
|
85a9f217e5 | ||
|
|
2164b5be89 | ||
|
|
84aca2e182 | ||
|
|
5cd0a70d0e | ||
|
|
5522317464 | ||
|
|
b2aa573879 | ||
|
|
7614989b09 | ||
|
|
754bdf3047 | ||
|
|
0a1adca2d3 | ||
|
|
e302a467a2 | ||
|
|
aab37d1fef | ||
|
|
5884451735 | ||
|
|
619e87420d | ||
|
|
11e0be0ec6 | ||
|
|
d965ef0bc5 | ||
|
|
94c81cd882 | ||
|
|
1ca991d489 | ||
|
|
9e38150470 | ||
|
|
08bd0f2b64 | ||
|
|
7d674f2181 | ||
|
|
4caa308276 | ||
|
|
f8eddc0eb5 | ||
|
|
af3d4abd75 | ||
|
|
8cf2b39eff | ||
|
|
0512ebb6b8 | ||
|
|
fdd0570084 | ||
|
|
13cad686ec | ||
|
|
7add2f85dd | ||
|
|
916dfbfc7b | ||
|
|
251e90c4b3 | ||
|
|
0725de8386 | ||
|
|
6bac7ee10b | ||
|
|
781341eafd | ||
|
|
e6d5e073d8 | ||
|
|
e89c409807 | ||
|
|
1fdb483c1f | ||
|
|
b876d3c3a5 | ||
|
|
93cf884d8b | ||
|
|
91467ef78f | ||
|
|
e7265671c6 | ||
|
|
d676ca8d6a | ||
|
|
7ab3510d4d | ||
|
|
959d4c4edd | ||
|
|
2967d5c639 | ||
|
|
cf788d8e73 | ||
|
|
dda7a4e45c | ||
|
|
73532d13ff | ||
|
|
60c01ead50 | ||
|
|
bbedb3ae9c | ||
|
|
9cc8107f13 | ||
|
|
3b610eb622 | ||
|
|
7cf6820add | ||
|
|
0163c6fedc |
No files matched your search
@@ -1,2 +1 @@
|
||||
open_collective: pojavlauncher
|
||||
patreon: pojavlauncher
|
||||
@@ -11,7 +11,7 @@ body:
|
||||
Give us some details into the problem, and how this affects it.
|
||||
placeholder: 'Example: You should add a version selector because of the text box being too small.'
|
||||
validations:
|
||||
required: false
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
@@ -20,7 +20,7 @@ body:
|
||||
What do you want to see changed, added, or removed? Make sure to be specific.
|
||||
placeholder: 'Example: A scrollable version picker.'
|
||||
validations:
|
||||
required: false
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
|
||||
@@ -43,9 +43,19 @@ jobs:
|
||||
path: app_pojavlauncher/src/main/assets/components/jre-new
|
||||
workflow_conclusion: success
|
||||
repo: PojavLauncherTeam/android-openjdk-build-multiarch
|
||||
branch: buildjre17
|
||||
branch: buildjre17-21
|
||||
name: jre17-pojav
|
||||
|
||||
- name: Get JRE21
|
||||
uses: dawidd6/action-download-artifact@v2
|
||||
with:
|
||||
workflow: build.yml
|
||||
path: app_pojavlauncher/src/main/assets/components/jre-21
|
||||
workflow_conclusion: success
|
||||
repo: PojavLauncherTeam/android-openjdk-build-multiarch
|
||||
branch: buildjre17-21
|
||||
name: jre21-pojav
|
||||
|
||||
- uses: gradle/gradle-build-action@v2
|
||||
with:
|
||||
gradle-version: 7.6.1
|
||||
@@ -80,19 +90,20 @@ jobs:
|
||||
run: |
|
||||
rm -r app_pojavlauncher/src/main/assets/components/jre
|
||||
rm -r app_pojavlauncher/src/main/assets/components/jre-new
|
||||
rm -r app_pojavlauncher/src/main/assets/components/jre-21
|
||||
gradle assembleDebug
|
||||
mv app_pojavlauncher/build/outputs/apk/debug/app_pojavlauncher-debug.apk out/app-debug-noruntime.apk
|
||||
- name: Gen md5sums
|
||||
run: |
|
||||
md5sum out/app-debug.apk > out/app-debug.md5
|
||||
md5sum out/app-debug-noruntime.apk > out/app-debug-noruntime.md5
|
||||
|
||||
|
||||
- name: Upload APK
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: app-debug
|
||||
path: out/app-debug.*
|
||||
|
||||
|
||||
- name: Upload AAB
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
/build
|
||||
/*/build
|
||||
app_pojavlauncher/src/main/assets/components/jre
|
||||
/app_pojavlauncher/src/main/assets/components/jre-new/
|
||||
/app_pojavlauncher/src/main/assets/components/jre-21/
|
||||
local.properties
|
||||
.idea/
|
||||
app_pojavlauncher/.cxx/
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
[](https://crowdin.com/project/pojavlauncher)
|
||||
[](https://discord.com/invite/pojavlauncher-724163890803638273)
|
||||
[](https://twitter.com/PLaunchTeam)
|
||||
---------
|
||||
|
||||
* From [Boardwalk](https://github.com/zhuowei/Boardwalk)'s ashes here comes PojavLauncher!
|
||||
|
||||
* PojavLauncher is a launcher that allows you to play Minecraft: Java Edition on your Android device!
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
## Introduction
|
||||
* PojavLauncher is a Minecraft: Java Edition launcher for Android and iOS based on [Boardwalk](https://github.com/zhuowei/Boardwalk).
|
||||
* This launcher can launch almost all available Minecraft versions ranging from rd-132211 to 1.19 snapshots (including Combat Test versions).
|
||||
* This launcher can launch almost all available Minecraft versions ranging from rd-132211 to 1.21 snapshots (including Combat Test versions).
|
||||
* Modding via Forge and Fabric are also supported.
|
||||
* This repository contains source code for Android.
|
||||
* For iOS/iPadOS, check out [PojavLauncher_iOS](https://github.com/PojavLauncherTeam/PojavLauncher_iOS).
|
||||
@@ -129,7 +129,7 @@ Any code change to this repository (or iOS) should be submitted as a pull reques
|
||||
- [LWJGLX](https://github.com/PojavLauncherTeam/lwjglx) (LWJGL2 API compatibility layer for LWJGL3): unknown license.<br>
|
||||
- [Mesa 3D Graphics Library](https://gitlab.freedesktop.org/mesa/mesa): [MIT License](https://docs.mesa3d.org/license.html).
|
||||
- [pro-grade](https://github.com/pro-grade/pro-grade) (Java sandboxing security manager): [Apache License 2.0](https://github.com/pro-grade/pro-grade/blob/master/LICENSE.txt).
|
||||
- [xHook](https://github.com/iqiyi/xHook) (Used for exit code trapping): [MIT and BSD-style licenses](https://github.com/iqiyi/xHook/blob/master/LICENSE).
|
||||
- [bhook](https://github.com/bytedance/bhook) (Used for exit code trapping): [MIT license](https://github.com/bytedance/bhook/blob/main/LICENSE).
|
||||
- [libepoxy](https://github.com/anholt/libepoxy): [MIT License](https://github.com/anholt/libepoxy/blob/master/COPYING).
|
||||
- [virglrenderer](https://github.com/PojavLauncherTeam/virglrenderer): [MIT License](https://gitlab.freedesktop.org/virgl/virglrenderer/-/blob/master/COPYING).
|
||||
- Thanks to [MCHeads](https://mc-heads.net) for providing Minecraft avatars.
|
||||
@@ -51,7 +51,7 @@ def getVersionName = {
|
||||
return ("LOCAL-" + "${getDate()}")
|
||||
}else {
|
||||
// Used by github actions
|
||||
TAG_STRING = 'edelweiss-' + "${getDate()}" + "-" + TAG_PART_COMMIT.toString().trim()
|
||||
TAG_STRING = 'foxglove-' + "${getDate()}" + "-" + TAG_PART_COMMIT.toString().trim()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -90,7 +90,7 @@ configurations {
|
||||
android {
|
||||
namespace 'net.kdt.pojavlaunch'
|
||||
|
||||
compileSdk = 33
|
||||
compileSdk = 34
|
||||
|
||||
lintOptions {
|
||||
abortOnError false
|
||||
@@ -114,7 +114,7 @@ android {
|
||||
defaultConfig {
|
||||
applicationId "net.kdt.pojavlaunch"
|
||||
minSdkVersion 21
|
||||
targetSdkVersion 33
|
||||
targetSdkVersion 34
|
||||
versionCode getDateSeconds()
|
||||
versionName getVersionName()
|
||||
multiDexEnabled true //important
|
||||
@@ -203,14 +203,15 @@ dependencies {
|
||||
implementation 'com.github.PojavLauncherTeam:portrait-sdp:ed33e89cbc'
|
||||
implementation 'com.github.PojavLauncherTeam:portrait-ssp:6c02fd739b'
|
||||
implementation 'com.github.Mathias-Boulay:ExtendedView:1.0.0'
|
||||
implementation 'com.github.Mathias-Boulay:android_gamepad_remapper:a0fe7e72f2'
|
||||
implementation 'com.github.Mathias-Boulay:android_gamepad_remapper:2.0.3'
|
||||
implementation 'com.github.Mathias-Boulay:virtual-joystick-android:2e7aa25e50'
|
||||
|
||||
// implementation 'com.intuit.sdp:sdp-android:1.0.5'
|
||||
// implementation 'com.intuit.ssp:ssp-android:1.0.5'
|
||||
|
||||
implementation 'org.tukaani:xz:1.8'
|
||||
implementation 'com.github.PojavLauncherTeam:exp4j:60eaec6f78'
|
||||
// Our version of exp4j can be built from source at
|
||||
// https://github.com/PojavLauncherTeam/exp4j
|
||||
implementation 'net.sourceforge.htmlcleaner:htmlcleaner:2.6.1'
|
||||
implementation 'com.bytedance:bytehook:1.0.9'
|
||||
|
||||
|
||||
Binary file not shown.
@@ -18,6 +18,8 @@
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE"/>
|
||||
|
||||
<application
|
||||
android:name=".PojavApplication"
|
||||
@@ -119,10 +121,13 @@
|
||||
</intent-filter>
|
||||
</provider>
|
||||
|
||||
<service android:name=".services.ProgressService" />
|
||||
<service
|
||||
android:name=".services.GameService"
|
||||
android:process=":game" />
|
||||
<service android:name=".services.ProgressService"
|
||||
android:foregroundServiceType="dataSync"/>
|
||||
<service android:name=".services.GameService" android:process=":game"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="This application is intended to run a 3rd-party piece of software which cannot be managed using the activity's saved instance state. This service is used for background persistence of this piece of software."/>
|
||||
</service>
|
||||
</application>
|
||||
<queries>
|
||||
<package android:name="net.kdt.pojavlaunch.ffmpeg"/>
|
||||
|
||||
Binary file not shown.
@@ -1 +1 @@
|
||||
1703946470579
|
||||
1720909595576
|
||||
@@ -5,7 +5,6 @@ import android.graphics.Typeface;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
import android.widget.ImageButton;
|
||||
import android.widget.ScrollView;
|
||||
import android.widget.TextView;
|
||||
import android.widget.ToggleButton;
|
||||
|
||||
@@ -22,8 +21,8 @@ import net.kdt.pojavlaunch.R;
|
||||
*/
|
||||
public class LoggerView extends ConstraintLayout {
|
||||
private Logger.eventLogListener mLogListener;
|
||||
private ToggleButton mToggleButton;
|
||||
private ScrollView mScrollView;
|
||||
private ToggleButton mLogToggle;
|
||||
private DefocusableScrollView mScrollView;
|
||||
private TextView mLogTextView;
|
||||
|
||||
|
||||
@@ -40,7 +39,7 @@ public class LoggerView extends ConstraintLayout {
|
||||
public void setVisibility(int visibility) {
|
||||
super.setVisibility(visibility);
|
||||
// Triggers the log view shown state by default when viewing it
|
||||
mToggleButton.setChecked(visibility == VISIBLE);
|
||||
mLogToggle.setChecked(visibility == VISIBLE);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,8 +55,8 @@ public class LoggerView extends ConstraintLayout {
|
||||
mLogTextView.setVisibility(GONE);
|
||||
|
||||
// Toggle log visibility
|
||||
mToggleButton = findViewById(R.id.content_log_toggle_log);
|
||||
mToggleButton.setOnCheckedChangeListener(
|
||||
mLogToggle = findViewById(R.id.content_log_toggle_log);
|
||||
mLogToggle.setOnCheckedChangeListener(
|
||||
(compoundButton, isChecked) -> {
|
||||
mLogTextView.setVisibility(isChecked ? VISIBLE : GONE);
|
||||
if(isChecked) {
|
||||
@@ -68,7 +67,7 @@ public class LoggerView extends ConstraintLayout {
|
||||
// NOTE: was tested by rapidly smashing the log on/off button, no sync issues found :)
|
||||
}
|
||||
});
|
||||
mToggleButton.setChecked(false);
|
||||
mLogToggle.setChecked(false);
|
||||
|
||||
// Remove the loggerView from the user View
|
||||
ImageButton cancelButton = findViewById(R.id.log_view_cancel);
|
||||
@@ -76,13 +75,24 @@ public class LoggerView extends ConstraintLayout {
|
||||
|
||||
// Set the scroll view
|
||||
mScrollView = findViewById(R.id.content_log_scroll);
|
||||
mScrollView.setKeepFocusing(true);
|
||||
|
||||
//Set up the autoscroll switch
|
||||
ToggleButton autoscrollToggle = findViewById(R.id.content_log_toggle_autoscroll);
|
||||
autoscrollToggle.setOnCheckedChangeListener(
|
||||
(compoundButton, isChecked) -> {
|
||||
if(isChecked) mScrollView.fullScroll(View.FOCUS_DOWN);
|
||||
mScrollView.setKeepFocusing(isChecked);
|
||||
}
|
||||
);
|
||||
autoscrollToggle.setChecked(true);
|
||||
|
||||
// Listen to logs
|
||||
mLogListener = text -> {
|
||||
if(mLogTextView.getVisibility() != VISIBLE) return;
|
||||
post(() -> {
|
||||
mLogTextView.append(text + '\n');
|
||||
mScrollView.fullScroll(View.FOCUS_DOWN);
|
||||
if(mScrollView.isKeepFocusing()) mScrollView.fullScroll(View.FOCUS_DOWN);
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
@@ -8,19 +8,24 @@ import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.drawable.BitmapDrawable;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.net.Uri;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.Log;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.BaseAdapter;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.Keep;
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.appcompat.widget.AppCompatSpinner;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
|
||||
import net.kdt.pojavlaunch.PojavProfile;
|
||||
@@ -39,6 +44,7 @@ import net.kdt.pojavlaunch.value.MinecraftAccount;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
import fr.spse.extended_view.ExtendedTextView;
|
||||
@@ -251,7 +257,7 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
|
||||
}
|
||||
|
||||
String[] accountArray = mAccountList.toArray(new String[0]);
|
||||
ArrayAdapter<String> accountAdapter = new ArrayAdapter<>(getContext(), R.layout.item_minecraft_account, accountArray);
|
||||
AccountAdapter accountAdapter = new AccountAdapter(getContext(), R.layout.item_minecraft_account, accountArray);
|
||||
accountAdapter.setDropDownViewResource(R.layout.item_minecraft_account);
|
||||
setAdapter(accountAdapter);
|
||||
|
||||
@@ -306,6 +312,12 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
|
||||
}
|
||||
|
||||
mSelectecAccount = selectedAccount;
|
||||
setImageFromSelectedAccount();
|
||||
}
|
||||
|
||||
@Deprecated()
|
||||
/* Legacy behavior, update the head image manually for the selected account */
|
||||
private void setImageFromSelectedAccount(){
|
||||
BitmapDrawable oldBitmapDrawable = mHeadDrawable;
|
||||
|
||||
if(mSelectecAccount != null){
|
||||
@@ -314,21 +326,54 @@ public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.On
|
||||
Bitmap bitmap = mSelectecAccount.getSkinFace();
|
||||
if(bitmap != null) {
|
||||
mHeadDrawable = new BitmapDrawable(getResources(), bitmap);
|
||||
mHeadDrawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
|
||||
|
||||
view.setCompoundDrawables(mHeadDrawable, null, null, null);
|
||||
view.postProcessDrawables();
|
||||
}else{
|
||||
view.setCompoundDrawables(null, null, null, null);
|
||||
view.postProcessDrawables();
|
||||
}
|
||||
view.postProcessDrawables();
|
||||
}
|
||||
}
|
||||
|
||||
if(oldBitmapDrawable != null){
|
||||
oldBitmapDrawable.getBitmap().recycle();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static class AccountAdapter extends ArrayAdapter<String> {
|
||||
|
||||
private final HashMap<String, Drawable> mImageCache = new HashMap<>();
|
||||
public AccountAdapter(@NonNull Context context, int resource, @NonNull String[] objects) {
|
||||
super(context, resource, objects);
|
||||
}
|
||||
|
||||
@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;
|
||||
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);
|
||||
else {
|
||||
String username = super.getItem(position);
|
||||
Drawable accountHead = mImageCache.get(username);
|
||||
if (accountHead == null){
|
||||
accountHead = new BitmapDrawable(parent.getResources(), MinecraftAccount.getSkinFace(username));
|
||||
mImageCache.put(username, accountHead);
|
||||
}
|
||||
textview.setCompoundDrawables(accountHead, null, null, null);
|
||||
}
|
||||
return convertView;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -85,7 +85,7 @@ public class mcVersionSpinner extends ExtendedTextView {
|
||||
if(currentSelection instanceof ProfileAdapterExtra) {
|
||||
performExtraAction((ProfileAdapterExtra) currentSelection);
|
||||
}else{
|
||||
Tools.swapFragment(fragmentActivity, ProfileEditorFragment.class, ProfileEditorFragment.TAG, true, null);
|
||||
Tools.swapFragment(fragmentActivity, ProfileEditorFragment.class, ProfileEditorFragment.TAG, null);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ public class mcVersionSpinner extends ExtendedTextView {
|
||||
//Replace with switch-case if you want to add more extra actions
|
||||
if (extra.id == VERSION_SPINNER_PROFILE_CREATE) {
|
||||
Tools.swapFragment((FragmentActivity) getContext(), ProfileTypeSelectFragment.class,
|
||||
ProfileTypeSelectFragment.TAG, true, null);
|
||||
ProfileTypeSelectFragment.TAG, null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,5 +3,5 @@ package com.oracle.dalvik;
|
||||
public final class VMLauncher {
|
||||
private VMLauncher() {
|
||||
}
|
||||
public static native void launchJVM(String jvmPath, String[] vmArgs, String classpath, String mainClass, String[] applicationArgs);
|
||||
public static native int launchJVM(String[] args);
|
||||
}
|
||||
@@ -12,6 +12,22 @@ public class Architecture {
|
||||
public static final int ARCH_X86 = 0x4;
|
||||
public static final int ARCH_X86_64 = 0x8;
|
||||
|
||||
/* On both 32-bit ARM and x86, the top 1GB is reserved for kernel use. */
|
||||
public static final long ADDRESS_SPACE_LIMIT_32_BIT = 0xbfffffffL;
|
||||
/*
|
||||
* Technically, this is supposed to be 48 bits on x86_64, but nobody's allocating
|
||||
* 524288 terabytes of RAM on Pojav any time soon.
|
||||
*/
|
||||
public static final long ADDRESS_SPACE_LIMIT_64_BIT = 0x7fffffffffL;
|
||||
|
||||
/**
|
||||
* Get the highest byte accessible within the process's address space.
|
||||
* @return the highest byte accessible within the process's address space.
|
||||
*/
|
||||
public static long getAddressSpaceLimit() {
|
||||
return is64BitsDevice() ? ADDRESS_SPACE_LIMIT_64_BIT : ADDRESS_SPACE_LIMIT_32_BIT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tell us if the device supports 64 bits architecture
|
||||
* @return If the device supports 64 bits architecture
|
||||
|
||||
@@ -47,6 +47,11 @@ public abstract class BaseActivity extends AppCompatActivity {
|
||||
protected void onPostResume() {
|
||||
super.onPostResume();
|
||||
Tools.setFullscreen(this, setFullscreen());
|
||||
Tools.ignoreNotch(PREF_IGNORE_NOTCH,this);
|
||||
Tools.ignoreNotch(shouldIgnoreNotch(),this);
|
||||
}
|
||||
|
||||
/** @return Whether or not the notch should be ignored */
|
||||
protected boolean shouldIgnoreNotch(){
|
||||
return PREF_IGNORE_NOTCH;
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -118,6 +118,7 @@ public class EfficientAndroidLWJGLKeycode {
|
||||
|
||||
add(KeyEvent.KEYCODE_CAPS_LOCK, LwjglGlfwKeycode.GLFW_KEY_CAPS_LOCK);
|
||||
add(KeyEvent.KEYCODE_BREAK, LwjglGlfwKeycode.GLFW_KEY_PAUSE);
|
||||
add(KeyEvent.KEYCODE_MOVE_HOME, LwjglGlfwKeycode.GLFW_KEY_HOME);
|
||||
add(KeyEvent.KEYCODE_MOVE_END, LwjglGlfwKeycode.GLFW_KEY_END);
|
||||
add(KeyEvent.KEYCODE_INSERT, LwjglGlfwKeycode.GLFW_KEY_INSERT);
|
||||
|
||||
@@ -197,7 +198,7 @@ public class EfficientAndroidLWJGLKeycode {
|
||||
sendKeyPress(getValueByIndex(index));
|
||||
}
|
||||
|
||||
public static int getValueByIndex(int index) {
|
||||
public static short getValueByIndex(int index) {
|
||||
return sLwjglKeycodes[index];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import android.content.*;
|
||||
import android.os.*;
|
||||
import androidx.appcompat.app.*;
|
||||
import android.util.*;
|
||||
import android.content.ClipData;
|
||||
import android.content.ClipboardManager;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
import androidx.appcompat.app.AppCompatActivity;
|
||||
|
||||
public class FatalErrorActivity extends AppCompatActivity {
|
||||
|
||||
@@ -13,8 +16,13 @@ public class FatalErrorActivity extends AppCompatActivity {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
Bundle extras = getIntent().getExtras();
|
||||
boolean storageAllow = extras.getBoolean("storageAllow");
|
||||
final String stackTrace = Log.getStackTraceString((Throwable) extras.getSerializable("throwable"));
|
||||
if(extras == null) {
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
boolean storageAllow = extras.getBoolean("storageAllow", false);
|
||||
Throwable throwable = (Throwable) extras.getSerializable("throwable");
|
||||
final String stackTrace = throwable != null ? Tools.printToString(throwable) : "<null>";
|
||||
String strSavePath = extras.getString("savePath");
|
||||
String errHeader = storageAllow ?
|
||||
"Crash stack trace saved to " + strSavePath + "." :
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import static net.kdt.pojavlaunch.Architecture.archAsString;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.res.AssetManager;
|
||||
import android.util.Log;
|
||||
|
||||
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
|
||||
import net.kdt.pojavlaunch.multirt.Runtime;
|
||||
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
|
||||
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class JRE17Util {
|
||||
public static final String NEW_JRE_NAME = "Internal-17";
|
||||
public static boolean checkInternalNewJre(AssetManager assetManager) {
|
||||
String launcher_jre17_version;
|
||||
String installed_jre17_version = MultiRTUtils.__internal__readBinpackVersion(NEW_JRE_NAME);
|
||||
try {
|
||||
launcher_jre17_version = Tools.read(assetManager.open("components/jre-new/version"));
|
||||
}catch (IOException exc) {
|
||||
//we don't have a runtime included!
|
||||
return installed_jre17_version != null; //if we have one installed -> return true -> proceed (no updates but the current one should be functional)
|
||||
//if we don't -> return false -> Cannot find compatible Java runtime
|
||||
}
|
||||
if(!launcher_jre17_version.equals(installed_jre17_version)) // this implicitly checks for null, so it will unpack the runtime even if we don't have one installed
|
||||
return unpackJre17(assetManager, launcher_jre17_version);
|
||||
else return true;
|
||||
}
|
||||
|
||||
private static boolean unpackJre17(AssetManager assetManager, String rt_version) {
|
||||
try {
|
||||
MultiRTUtils.installRuntimeNamedBinpack(
|
||||
assetManager.open("components/jre-new/universal.tar.xz"),
|
||||
assetManager.open("components/jre-new/bin-" + archAsString(Tools.DEVICE_ARCHITECTURE) + ".tar.xz"),
|
||||
"Internal-17", rt_version);
|
||||
MultiRTUtils.postPrepare("Internal-17");
|
||||
return true;
|
||||
}catch (IOException e) {
|
||||
Log.e("JRE17Auto", "Internal JRE unpack failed", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public static boolean isInternalNewJRE(String s_runtime) {
|
||||
Runtime runtime = MultiRTUtils.read(s_runtime);
|
||||
if(runtime == null) return false;
|
||||
return NEW_JRE_NAME.equals(runtime.name);
|
||||
}
|
||||
|
||||
/** @return true if everything is good, false otherwise. */
|
||||
public static boolean installNewJreIfNeeded(Activity activity, JMinecraftVersionList.Version versionInfo) {
|
||||
//Now we have the reliable information to check if our runtime settings are good enough
|
||||
if (versionInfo.javaVersion == null || versionInfo.javaVersion.component.equalsIgnoreCase("jre-legacy"))
|
||||
return true;
|
||||
|
||||
LauncherProfiles.load();
|
||||
MinecraftProfile minecraftProfile = LauncherProfiles.getCurrentProfile();
|
||||
|
||||
String selectedRuntime = Tools.getSelectedRuntime(minecraftProfile);
|
||||
|
||||
Runtime runtime = MultiRTUtils.read(selectedRuntime);
|
||||
if (runtime.javaVersion >= versionInfo.javaVersion.majorVersion) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String appropriateRuntime = MultiRTUtils.getNearestJreName(versionInfo.javaVersion.majorVersion);
|
||||
if (appropriateRuntime != null) {
|
||||
if (JRE17Util.isInternalNewJRE(appropriateRuntime)) {
|
||||
JRE17Util.checkInternalNewJre(activity.getAssets());
|
||||
}
|
||||
minecraftProfile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX + appropriateRuntime;
|
||||
LauncherProfiles.load();
|
||||
} else {
|
||||
if (versionInfo.javaVersion.majorVersion <= 17) { // there's a chance we have an internal one for this case
|
||||
if (!JRE17Util.checkInternalNewJre(activity.getAssets())){
|
||||
showRuntimeFail(activity, versionInfo);
|
||||
return false;
|
||||
} else {
|
||||
minecraftProfile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX + JRE17Util.NEW_JRE_NAME;
|
||||
LauncherProfiles.load();
|
||||
}
|
||||
} else {
|
||||
showRuntimeFail(activity, versionInfo);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void showRuntimeFail(Activity activity, JMinecraftVersionList.Version verInfo) {
|
||||
Tools.dialogOnUiThread(activity, activity.getString(R.string.global_error),
|
||||
activity.getString(R.string.multirt_nocompartiblert, verInfo.javaVersion.majorVersion));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import android.widget.LinearLayout;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.activity.OnBackPressedCallback;
|
||||
import androidx.appcompat.app.AlertDialog;
|
||||
|
||||
import com.kdt.LoggerView;
|
||||
|
||||
@@ -185,6 +186,7 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
|
||||
try {
|
||||
File cacheFile = new File(getCacheDir(), "mod-installer-temp");
|
||||
InputStream contentStream = getContentResolver().openInputStream(uri);
|
||||
if(contentStream == null) throw new IOException("Failed to open content stream");
|
||||
try (FileOutputStream fileOutputStream = new FileOutputStream(cacheFile)) {
|
||||
IOUtils.copy(contentStream, fileOutputStream);
|
||||
}
|
||||
@@ -195,23 +197,71 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
|
||||
}
|
||||
}
|
||||
|
||||
public Runtime selectRuntime(File modFile) {
|
||||
int javaVersion = getJavaVersion(modFile);
|
||||
if(javaVersion == -1) {
|
||||
finalErrorDialog(getString(R.string.execute_jar_failed_to_read_file));
|
||||
return null;
|
||||
}
|
||||
String nearestRuntime = MultiRTUtils.getNearestJreName(javaVersion);
|
||||
if(nearestRuntime == null) {
|
||||
finalErrorDialog(getString(R.string.multirt_nocompatiblert, javaVersion));
|
||||
return null;
|
||||
}
|
||||
Runtime selectedRuntime = MultiRTUtils.forceReread(nearestRuntime);
|
||||
int selectedJavaVersion = Math.max(javaVersion, selectedRuntime.javaVersion);
|
||||
// Don't allow versions higher than Java 17 because our caciocavallo implementation does not allow for it
|
||||
if(selectedJavaVersion > 17) {
|
||||
finalErrorDialog(getString(R.string.execute_jar_incompatible_runtime, selectedJavaVersion));
|
||||
return null;
|
||||
}
|
||||
return selectedRuntime;
|
||||
}
|
||||
|
||||
private File findModPath(List<String> argList) {
|
||||
int argsSize = argList.size();
|
||||
for(int i = 0; i < argsSize; i++) {
|
||||
// Look for the -jar argument
|
||||
if(!argList.get(i).equals("-jar")) continue;
|
||||
int pathIndex = i+1;
|
||||
// Check if the supposed path is out of the argument bounds
|
||||
if(pathIndex >= argsSize) return null;
|
||||
// Use the path as a file
|
||||
return new File(argList.get(pathIndex));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void startModInstaller(File modFile, String javaArgs) {
|
||||
new Thread(() -> {
|
||||
Runtime runtime = pickJreForMod(modFile);
|
||||
launchJavaRuntime(runtime, modFile, javaArgs);
|
||||
// Maybe replace with more advanced arg parsing logic later
|
||||
List<String> argList = javaArgs != null ? Arrays.asList(javaArgs.split(" ")) : null;
|
||||
File selectedMod = modFile;
|
||||
if(selectedMod == null && argList != null) {
|
||||
// If modFile is not specified directly, try to extract the -jar argument from the javaArgs
|
||||
selectedMod = findModPath(argList);
|
||||
}
|
||||
Runtime selectedRuntime;
|
||||
if(selectedMod == null) {
|
||||
// We were unable to find out the path to the mod. In that case, use the default runtime.
|
||||
selectedRuntime = MultiRTUtils.forceReread(LauncherPreferences.PREF_DEFAULT_RUNTIME);
|
||||
}else {
|
||||
// Autoselect it properly in the other case.
|
||||
selectedRuntime = selectRuntime(selectedMod);
|
||||
// If the selection failed, just return. The autoselect function has already shown the dialog.
|
||||
if(selectedRuntime == null) return;
|
||||
}
|
||||
launchJavaRuntime(selectedRuntime, modFile, argList);
|
||||
}, "JREMainThread").start();
|
||||
}
|
||||
|
||||
private Runtime pickJreForMod(File modFile) {
|
||||
String jreName = LauncherPreferences.PREF_DEFAULT_RUNTIME;
|
||||
if(modFile != null) {
|
||||
int javaVersion = getJavaVersion(modFile);
|
||||
if(javaVersion != -1) {
|
||||
String autoselectRuntime = MultiRTUtils.getNearestJreName(javaVersion);
|
||||
if (autoselectRuntime != null) jreName = autoselectRuntime;
|
||||
}
|
||||
}
|
||||
return MultiRTUtils.forceReread(jreName);
|
||||
private void finalErrorDialog(CharSequence msg) {
|
||||
runOnUiThread(()-> new AlertDialog.Builder(this)
|
||||
.setTitle(R.string.global_error)
|
||||
.setMessage(msg)
|
||||
.setPositiveButton(android.R.string.ok, (d,w)->this.finish())
|
||||
.setCancelable(false)
|
||||
.show());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -301,21 +351,20 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
|
||||
Toast.LENGTH_SHORT).show();
|
||||
}
|
||||
|
||||
public void launchJavaRuntime(Runtime runtime, File modFile, String javaArgs) {
|
||||
public void launchJavaRuntime(Runtime runtime, File modFile, List<String> javaArgs) {
|
||||
JREUtils.redirectAndPrintJRELog();
|
||||
try {
|
||||
List<String> javaArgList = new ArrayList<>();
|
||||
|
||||
// Enable Caciocavallo
|
||||
Tools.getCacioJavaArgs(javaArgList,runtime.javaVersion == 8);
|
||||
|
||||
if (javaArgs != null) {
|
||||
javaArgList.addAll(Arrays.asList(javaArgs.split(" ")));
|
||||
} else {
|
||||
if(javaArgs != null) {
|
||||
javaArgList.addAll(javaArgs);
|
||||
}
|
||||
if(modFile != null) {
|
||||
javaArgList.add("-jar");
|
||||
javaArgList.add(modFile.getAbsolutePath());
|
||||
}
|
||||
|
||||
|
||||
if (LauncherPreferences.PREF_JAVA_SANDBOX) {
|
||||
Collections.reverse(javaArgList);
|
||||
@@ -327,7 +376,7 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
|
||||
|
||||
Logger.appendToLog("Info: Java arguments: " + Arrays.toString(javaArgList.toArray(new String[0])));
|
||||
|
||||
//JREUtils.launchJavaVM(this, runtime,null,javaArgList, LauncherPreferences.PREF_CUSTOM_JAVA_ARGS);
|
||||
JREUtils.launchJavaVM(this, runtime,null,javaArgList, LauncherPreferences.PREF_CUSTOM_JAVA_ARGS);
|
||||
} catch (Throwable th) {
|
||||
Tools.showError(this, th, true);
|
||||
}
|
||||
@@ -374,7 +423,7 @@ public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouc
|
||||
Log.i("JavaGUILauncher", majorVersion+","+minorVersion);
|
||||
return classVersionToJavaVersion(majorVersion);
|
||||
}catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Log.e("JavaVersion", "Exception thrown", e);
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
|
||||
import android.Manifest;
|
||||
import android.app.NotificationManager;
|
||||
import android.content.Context;
|
||||
@@ -23,7 +24,6 @@ import androidx.fragment.app.FragmentManager;
|
||||
import com.kdt.mcgui.ProgressLayout;
|
||||
import com.kdt.mcgui.mcAccountSpinner;
|
||||
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
|
||||
import net.kdt.pojavlaunch.contracts.OpenDocumentWithExtension;
|
||||
import net.kdt.pojavlaunch.extra.ExtraConstants;
|
||||
import net.kdt.pojavlaunch.extra.ExtraCore;
|
||||
@@ -31,6 +31,8 @@ import net.kdt.pojavlaunch.extra.ExtraListener;
|
||||
import net.kdt.pojavlaunch.fragments.MainMenuFragment;
|
||||
import net.kdt.pojavlaunch.fragments.MicrosoftLoginFragment;
|
||||
import net.kdt.pojavlaunch.fragments.SelectAuthFragment;
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextAwareDoneListener;
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
|
||||
import net.kdt.pojavlaunch.modloaders.modpacks.ModloaderInstallTracker;
|
||||
import net.kdt.pojavlaunch.modloaders.modpacks.imagecache.IconCacheJanitor;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
@@ -40,7 +42,6 @@ import net.kdt.pojavlaunch.progresskeeper.TaskCountListener;
|
||||
import net.kdt.pojavlaunch.services.ProgressServiceKeeper;
|
||||
import net.kdt.pojavlaunch.tasks.AsyncMinecraftDownloader;
|
||||
import net.kdt.pojavlaunch.tasks.AsyncVersionList;
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextAwareDoneListener;
|
||||
import net.kdt.pojavlaunch.tasks.MinecraftDownloader;
|
||||
import net.kdt.pojavlaunch.utils.NotificationUtils;
|
||||
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
|
||||
@@ -85,7 +86,7 @@ public class LauncherActivity extends BaseActivity {
|
||||
// Allow starting the add account only from the main menu, should it be moved to fragment itself ?
|
||||
if(!(fragment instanceof MainMenuFragment)) return false;
|
||||
|
||||
Tools.swapFragment(this, SelectAuthFragment.class, SelectAuthFragment.TAG, true, null);
|
||||
Tools.swapFragment(this, SelectAuthFragment.class, SelectAuthFragment.TAG, null);
|
||||
return false;
|
||||
};
|
||||
|
||||
@@ -93,12 +94,10 @@ public class LauncherActivity extends BaseActivity {
|
||||
private final View.OnClickListener mSettingButtonListener = v -> {
|
||||
Fragment fragment = getSupportFragmentManager().findFragmentById(mFragmentView.getId());
|
||||
if(fragment instanceof MainMenuFragment){
|
||||
Tools.swapFragment(this, LauncherPreferenceFragment.class, SETTING_FRAGMENT_TAG, true, null);
|
||||
Tools.swapFragment(this, LauncherPreferenceFragment.class, SETTING_FRAGMENT_TAG, null);
|
||||
} else{
|
||||
// The setting button doubles as a home button now
|
||||
while(!(getSupportFragmentManager().findFragmentById(mFragmentView.getId()) instanceof MainMenuFragment)){
|
||||
getSupportFragmentManager().popBackStackImmediate();
|
||||
}
|
||||
Tools.backToMainMenu(this);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -155,10 +154,28 @@ public class LauncherActivity extends BaseActivity {
|
||||
private ActivityResultLauncher<String> mRequestNotificationPermissionLauncher;
|
||||
private WeakReference<Runnable> mRequestNotificationPermissionRunnable;
|
||||
|
||||
@Override
|
||||
protected boolean shouldIgnoreNotch() {
|
||||
return getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT || super.shouldIgnoreNotch();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
setContentView(R.layout.activity_pojav_launcher);
|
||||
FragmentManager fragmentManager = getSupportFragmentManager();
|
||||
// If we don't have a back stack root yet...
|
||||
if(fragmentManager.getBackStackEntryCount() < 1) {
|
||||
// Manually add the first fragment to the backstack to get easily back to it
|
||||
// There must be a better way to handle the root though...
|
||||
// (artDev: No, there is not. I've spent days researching this for another unrelated project.)
|
||||
fragmentManager.beginTransaction()
|
||||
.setReorderingAllowed(true)
|
||||
.addToBackStack("ROOT")
|
||||
.add(R.id.container_fragment, MainMenuFragment.class, null, "ROOT").commit();
|
||||
}
|
||||
|
||||
|
||||
IconCacheJanitor.runJanitor();
|
||||
mRequestNotificationPermissionLauncher = registerForActivityResult(
|
||||
new ActivityResultContracts.RequestPermission(),
|
||||
@@ -245,6 +262,11 @@ public class LauncherActivity extends BaseActivity {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we are at the root then
|
||||
if(getVisibleFragment("ROOT") != null){
|
||||
finish();
|
||||
}
|
||||
|
||||
super.onBackPressed();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import static net.kdt.pojavlaunch.Architecture.ARCH_X86;
|
||||
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
|
||||
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_SUSTAINED_PERFORMANCE;
|
||||
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_USE_ALTERNATE_SURFACE;
|
||||
@@ -17,7 +16,6 @@ import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.ServiceConnection;
|
||||
import android.content.pm.PackageManager;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.drawable.ColorDrawable;
|
||||
@@ -27,8 +25,10 @@ import android.os.Bundle;
|
||||
import android.os.IBinder;
|
||||
import android.provider.DocumentsContract;
|
||||
import android.util.Log;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.webkit.MimeTypeMap;
|
||||
import android.widget.AdapterView;
|
||||
@@ -39,12 +39,12 @@ import android.widget.TextView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.RequiresApi;
|
||||
import androidx.core.content.ContextCompat;
|
||||
import androidx.drawerlayout.widget.DrawerLayout;
|
||||
|
||||
import com.kdt.LoggerView;
|
||||
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
|
||||
import net.kdt.pojavlaunch.customcontrols.ControlButtonMenuListener;
|
||||
import net.kdt.pojavlaunch.customcontrols.ControlData;
|
||||
import net.kdt.pojavlaunch.customcontrols.ControlDrawerData;
|
||||
@@ -54,6 +54,9 @@ import net.kdt.pojavlaunch.customcontrols.CustomControls;
|
||||
import net.kdt.pojavlaunch.customcontrols.EditorExitable;
|
||||
import net.kdt.pojavlaunch.customcontrols.keyboard.LwjglCharSender;
|
||||
import net.kdt.pojavlaunch.customcontrols.keyboard.TouchCharInput;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.GyroControl;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.Touchpad;
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
import net.kdt.pojavlaunch.services.GameService;
|
||||
import net.kdt.pojavlaunch.utils.JREUtils;
|
||||
@@ -363,16 +366,6 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
|
||||
Logger.appendToLog("Info: Custom Java arguments: \"" + javaArguments + "\"");
|
||||
}
|
||||
|
||||
private void checkVulkanZinkIsSupported() {
|
||||
if (Tools.DEVICE_ARCHITECTURE == ARCH_X86
|
||||
|| Build.VERSION.SDK_INT < 25
|
||||
|| !getPackageManager().hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_LEVEL)
|
||||
|| !getPackageManager().hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION)) {
|
||||
Logger.appendToLog("Error: Vulkan Zink renderer is not supported!");
|
||||
throw new RuntimeException(getString(R.string. mcn_check_fail_vulkan_support));
|
||||
}
|
||||
}
|
||||
|
||||
private void dialogSendCustomKey() {
|
||||
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
|
||||
dialog.setTitle(R.string.control_customkey);
|
||||
@@ -630,7 +623,7 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
|
||||
public void onServiceConnected(ComponentName name, IBinder service) {
|
||||
GameService.LocalBinder localBinder = (GameService.LocalBinder) service;
|
||||
mServiceBinder = localBinder;
|
||||
minecraftGLView.start(localBinder.isActive);
|
||||
minecraftGLView.start(localBinder.isActive, touchpad);
|
||||
localBinder.isActive = true;
|
||||
}
|
||||
|
||||
@@ -638,4 +631,26 @@ public class MainActivity extends BaseActivity implements ControlButtonMenuListe
|
||||
public void onServiceDisconnected(ComponentName name) {
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* Android 14 (or some devices, at least) seems to dispatch the the captured mouse events as trackball events
|
||||
* due to a bug(?) somewhere(????)
|
||||
*/
|
||||
@RequiresApi(api = Build.VERSION_CODES.O)
|
||||
private boolean checkCaptureDispatchConditions(MotionEvent event) {
|
||||
int eventSource = event.getSource();
|
||||
// On my device, the mouse sends events as a relative mouse device.
|
||||
// Not comparing with == here because apparently `eventSource` is a mask that can
|
||||
// sometimes indicate multiple sources, like in the case of InputDevice.SOURCE_TOUCHPAD
|
||||
// (which is *also* an InputDevice.SOURCE_MOUSE when controlling a cursor)
|
||||
return (eventSource & InputDevice.SOURCE_MOUSE_RELATIVE) != 0 ||
|
||||
(eventSource & InputDevice.SOURCE_MOUSE) != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean dispatchTrackballEvent(MotionEvent ev) {
|
||||
if(MainActivity.isAndroid8OrHigher() && checkCaptureDispatchConditions(ev))
|
||||
return minecraftGLView.dispatchCapturedPointerEvent(ev);
|
||||
else return super.dispatchTrackballEvent(ev);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,7 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import static net.kdt.pojavlaunch.MainActivity.touchCharInput;
|
||||
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_DISABLE_SWAP_HAND;
|
||||
import static net.kdt.pojavlaunch.utils.MCOptionUtils.getMcScale;
|
||||
import static org.lwjgl.glfw.CallbackBridge.sendKeyPress;
|
||||
import static org.lwjgl.glfw.CallbackBridge.sendMouseButton;
|
||||
import static org.lwjgl.glfw.CallbackBridge.windowHeight;
|
||||
import static org.lwjgl.glfw.CallbackBridge.windowWidth;
|
||||
@@ -12,9 +10,7 @@ import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.graphics.SurfaceTexture;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.os.Message;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.util.Log;
|
||||
import android.view.InputDevice;
|
||||
@@ -31,11 +27,16 @@ import androidx.annotation.NonNull;
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
import net.kdt.pojavlaunch.customcontrols.ControlLayout;
|
||||
import net.kdt.pojavlaunch.customcontrols.gamepad.DefaultDataProvider;
|
||||
import net.kdt.pojavlaunch.customcontrols.gamepad.Gamepad;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.AbstractTouchpad;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.AndroidPointerCapture;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.InGUIEventProcessor;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.InGameEventProcessor;
|
||||
import net.kdt.pojavlaunch.customcontrols.mouse.TouchEventProcessor;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
import net.kdt.pojavlaunch.utils.JREUtils;
|
||||
import net.kdt.pojavlaunch.utils.MCOptionUtils;
|
||||
import net.kdt.pojavlaunch.utils.MathUtils;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
@@ -62,76 +63,25 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
.remapLeftShoulder(true)
|
||||
.remapRightShoulder(true)
|
||||
.remapLeftTrigger(true)
|
||||
.remapRightTrigger(true));
|
||||
.remapRightTrigger(true)
|
||||
.remapDpad(true));
|
||||
|
||||
/* Resolution scaler option, allow downsizing a window */
|
||||
private final float mScaleFactor = LauncherPreferences.PREF_SCALE_FACTOR/100f;
|
||||
/* Sensitivity, adjusted according to screen size */
|
||||
private final double mSensitivityFactor = (1.4 * (1080f/ Tools.getDisplayMetrics((Activity) getContext()).heightPixels));
|
||||
/* Use to detect simple and double taps */
|
||||
private final TapDetector mSingleTapDetector = new TapDetector(1, TapDetector.DETECTION_METHOD_BOTH);
|
||||
private final TapDetector mDoubleTapDetector = new TapDetector(2, TapDetector.DETECTION_METHOD_DOWN);
|
||||
/* MC GUI scale, listened by MCOptionUtils */
|
||||
private int mGuiScale;
|
||||
@SuppressWarnings("FieldCanBeLocal") // it can't, otherwise the weak reference will disappear
|
||||
private final MCOptionUtils.MCOptionListener mGuiScaleListener = () -> mGuiScale = getMcScale();
|
||||
|
||||
/* Surface ready listener, used by the activity to launch minecraft */
|
||||
SurfaceReadyListener mSurfaceReadyListener = null;
|
||||
final Object mSurfaceReadyListenerLock = new Object();
|
||||
/* View holding the surface, either a SurfaceView or a TextureView */
|
||||
View mSurface;
|
||||
|
||||
/* List of hotbarKeys, used when clicking on the hotbar */
|
||||
private static final int[] HOTBAR_KEYS = {
|
||||
LwjglGlfwKeycode.GLFW_KEY_1, LwjglGlfwKeycode.GLFW_KEY_2, LwjglGlfwKeycode.GLFW_KEY_3,
|
||||
LwjglGlfwKeycode.GLFW_KEY_4, LwjglGlfwKeycode.GLFW_KEY_5, LwjglGlfwKeycode.GLFW_KEY_6,
|
||||
LwjglGlfwKeycode.GLFW_KEY_7, LwjglGlfwKeycode.GLFW_KEY_8, LwjglGlfwKeycode.GLFW_KEY_9};
|
||||
/* Last hotbar button (0-9) registered */
|
||||
private int mLastHotbarKey = -1;
|
||||
/* Events can start with only a move instead of an pointerDown due to mouse passthrough */
|
||||
private boolean mShouldBeDown = false;
|
||||
/* When fingers are really near to each other, it tends to either swap or remove a pointer ! */
|
||||
private int mLastPointerCount = 0;
|
||||
/* Previous MotionEvent position, not scale */
|
||||
private float mPrevX, mPrevY;
|
||||
/* PointerID used for the moving camera */
|
||||
private int mCurrentPointerID = -1000;
|
||||
/* Initial first pointer positions non-scaled, used to test touch sloppiness */
|
||||
private float mInitialX, mInitialY;
|
||||
/* Last first pointer positions non-scaled, used to scroll distance */
|
||||
private float mScrollLastInitialX, mScrollLastInitialY;
|
||||
/* How much distance a finger has to go for touch sloppiness to be disabled */
|
||||
public static final int FINGER_STILL_THRESHOLD = (int) Tools.dpToPx(9);
|
||||
/* How much distance a finger has to go to scroll */
|
||||
public static final int FINGER_SCROLL_THRESHOLD = (int) Tools.dpToPx(6);
|
||||
/* Whether the button was triggered, used by the handler */
|
||||
private static boolean triggeredLeftMouseButton = false;
|
||||
/* Handle hotbar throw button and mouse mining button */
|
||||
public static final int MSG_LEFT_MOUSE_BUTTON_CHECK = 1028;
|
||||
public static final int MSG_DROP_ITEM_BUTTON_CHECK = 1029;
|
||||
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
|
||||
public void handleMessage(Message msg) {
|
||||
if(msg.what == MSG_LEFT_MOUSE_BUTTON_CHECK) {
|
||||
if (LauncherPreferences.PREF_DISABLE_GESTURES) return;
|
||||
float x = CallbackBridge.mouseX;
|
||||
float y = CallbackBridge.mouseY;
|
||||
if (CallbackBridge.isGrabbing() &&
|
||||
MathUtils.dist(x, y, mInitialX, mInitialY) < FINGER_STILL_THRESHOLD) {
|
||||
triggeredLeftMouseButton = true;
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if(msg.what == MSG_DROP_ITEM_BUTTON_CHECK) {
|
||||
if(CallbackBridge.isGrabbing()){
|
||||
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q);
|
||||
mHandler.sendEmptyMessageDelayed(MSG_DROP_ITEM_BUTTON_CHECK, 600);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
private final InGameEventProcessor mIngameProcessor = new InGameEventProcessor(mSensitivityFactor);
|
||||
private final InGUIEventProcessor mInGUIProcessor = new InGUIEventProcessor(mScaleFactor);
|
||||
private TouchEventProcessor mCurrentTouchProcessor = mInGUIProcessor;
|
||||
private AndroidPointerCapture mPointerCapture;
|
||||
private boolean mLastGrabState = false;
|
||||
|
||||
public MinecraftGLSurface(Context context) {
|
||||
this(context, null);
|
||||
@@ -140,15 +90,23 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
public MinecraftGLSurface(Context context, AttributeSet attributeSet) {
|
||||
super(context, attributeSet);
|
||||
setFocusable(true);
|
||||
}
|
||||
|
||||
MCOptionUtils.addMCOptionListener(mGuiScaleListener);
|
||||
@RequiresApi(api = Build.VERSION_CODES.O)
|
||||
private void setUpPointerCapture(AbstractTouchpad touchpad) {
|
||||
if(mPointerCapture != null) mPointerCapture.detach();
|
||||
mPointerCapture = new AndroidPointerCapture(touchpad, this, mScaleFactor);
|
||||
}
|
||||
|
||||
/** Initialize the view and all its settings
|
||||
* @param isAlreadyRunning set to true to tell the view that the game is already running
|
||||
* (only updates the window without calling the start listener)
|
||||
* @param touchpad the optional cursor-emulating touchpad, used for touch event processing
|
||||
* when the cursor is not grabbed
|
||||
*/
|
||||
public void start(boolean isAlreadyRunning){
|
||||
public void start(boolean isAlreadyRunning, AbstractTouchpad touchpad){
|
||||
if(MainActivity.isAndroid8OrHigher()) setUpPointerCapture(touchpad);
|
||||
mInGUIProcessor.setAbstractTouchpad(touchpad);
|
||||
if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){
|
||||
SurfaceView surfaceView = new SurfaceView(getContext());
|
||||
mSurface = surfaceView;
|
||||
@@ -216,7 +174,6 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* The touch event for both grabbed an non-grabbed mouse state on the touch screen
|
||||
* Does not cover the virtual mouse touchpad
|
||||
@@ -229,170 +186,26 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
|
||||
// Looking for a mouse to handle, won't have an effect if no mouse exists.
|
||||
for (int i = 0; i < e.getPointerCount(); i++) {
|
||||
if(e.getToolType(i) != MotionEvent.TOOL_TYPE_MOUSE && e.getToolType(i) != MotionEvent.TOOL_TYPE_STYLUS ) continue;
|
||||
int toolType = e.getToolType(i);
|
||||
if(toolType == MotionEvent.TOOL_TYPE_MOUSE) {
|
||||
if(MainActivity.isAndroid8OrHigher() &&
|
||||
mPointerCapture != null) {
|
||||
mPointerCapture.handleAutomaticCapture();
|
||||
return true;
|
||||
}
|
||||
}else if(toolType != MotionEvent.TOOL_TYPE_STYLUS) continue;
|
||||
|
||||
// Mouse found
|
||||
if(CallbackBridge.isGrabbing()) return false;
|
||||
CallbackBridge.sendCursorPos( e.getX(i) * mScaleFactor, e.getY(i) * mScaleFactor);
|
||||
return true; //mouse event handled successfully
|
||||
}
|
||||
if (mIngameProcessor == null || mInGUIProcessor == null) return true;
|
||||
return mCurrentTouchProcessor.processTouchEvent(e);
|
||||
}
|
||||
|
||||
// System.out.println("Pre touch, isTouchInHotbar=" + Boolean.toString(isTouchInHotbar) + ", action=" + MotionEvent.actionToString(e.getActionMasked()));
|
||||
|
||||
//Getting scaled position from the event
|
||||
/* Tells if a double tap happened [MOUSE GRAB ONLY]. Doesn't tell where though. */
|
||||
if(!CallbackBridge.isGrabbing()) {
|
||||
CallbackBridge.mouseX = (e.getX() * mScaleFactor);
|
||||
CallbackBridge.mouseY = (e.getY() * mScaleFactor);
|
||||
//One android click = one MC click
|
||||
if(mSingleTapDetector.onTouchEvent(e)){
|
||||
CallbackBridge.putMouseEventWithCoords(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check double tap state, used for the hotbar
|
||||
boolean hasDoubleTapped = mDoubleTapDetector.onTouchEvent(e);
|
||||
|
||||
switch (e.getActionMasked()) {
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
int pointerCount = e.getPointerCount();
|
||||
|
||||
// In-menu interactions
|
||||
if(!CallbackBridge.isGrabbing()){
|
||||
|
||||
// Touch hover
|
||||
if(pointerCount == 1){
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
mPrevX = e.getX();
|
||||
mPrevY = e.getY();
|
||||
break;
|
||||
}
|
||||
|
||||
// Scrolling feature
|
||||
if(LauncherPreferences.PREF_DISABLE_GESTURES) break;
|
||||
// The pointer count can never be 0, and it is not 1, therefore it is >= 2
|
||||
int hScroll = ((int) (e.getX() - mScrollLastInitialX)) / FINGER_SCROLL_THRESHOLD;
|
||||
int vScroll = ((int) (e.getY() - mScrollLastInitialY)) / FINGER_SCROLL_THRESHOLD;
|
||||
|
||||
if(vScroll != 0 || hScroll != 0){
|
||||
CallbackBridge.sendScroll(hScroll, vScroll);
|
||||
mScrollLastInitialX = e.getX();
|
||||
mScrollLastInitialY = e.getY();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Camera movement
|
||||
int pointerIndex = e.findPointerIndex(mCurrentPointerID);
|
||||
int hudKeyHandled = handleGuiBar((int)e.getX(), (int) e.getY());
|
||||
// Start movement, due to new pointer or loss of pointer
|
||||
if (pointerIndex == -1 || mLastPointerCount != pointerCount || !mShouldBeDown) {
|
||||
if(hudKeyHandled != -1) break; //No pointer attribution on hotbar
|
||||
|
||||
mShouldBeDown = true;
|
||||
mCurrentPointerID = e.getPointerId(0);
|
||||
mPrevX = e.getX();
|
||||
mPrevY = e.getY();
|
||||
break;
|
||||
}
|
||||
// Continue movement as usual
|
||||
if(hudKeyHandled == -1){ //No camera on hotbar
|
||||
CallbackBridge.mouseX += (e.getX(pointerIndex) - mPrevX) * mSensitivityFactor;
|
||||
CallbackBridge.mouseY += (e.getY(pointerIndex) - mPrevY) * mSensitivityFactor;
|
||||
}
|
||||
|
||||
mPrevX = e.getX(pointerIndex);
|
||||
mPrevY = e.getY(pointerIndex);
|
||||
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_DOWN: // 0
|
||||
hudKeyHandled = handleGuiBar((int)e.getX(), (int) e.getY());
|
||||
boolean isTouchInHotbar = hudKeyHandled != -1;
|
||||
if (isTouchInHotbar) {
|
||||
sendKeyPress(hudKeyHandled);
|
||||
if(hasDoubleTapped && hudKeyHandled == mLastHotbarKey && !PREF_DISABLE_SWAP_HAND){
|
||||
//Prevent double tapping Event on two different slots
|
||||
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_F);
|
||||
} else {
|
||||
mHandler.sendEmptyMessageDelayed(MSG_DROP_ITEM_BUTTON_CHECK, 350);
|
||||
}
|
||||
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
mLastHotbarKey = hudKeyHandled;
|
||||
break;
|
||||
}
|
||||
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
mPrevX = e.getX();
|
||||
mPrevY = e.getY();
|
||||
|
||||
if (CallbackBridge.isGrabbing()) {
|
||||
mCurrentPointerID = e.getPointerId(0);
|
||||
// It cause hold left mouse while moving camera
|
||||
mInitialX = CallbackBridge.mouseX;
|
||||
mInitialY = CallbackBridge.mouseY;
|
||||
mHandler.sendEmptyMessageDelayed(MSG_LEFT_MOUSE_BUTTON_CHECK, LauncherPreferences.PREF_LONGPRESS_TRIGGER);
|
||||
}
|
||||
mLastHotbarKey = hudKeyHandled;
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_UP: // 1
|
||||
case MotionEvent.ACTION_CANCEL: // 3
|
||||
mShouldBeDown = false;
|
||||
mCurrentPointerID = -1;
|
||||
|
||||
hudKeyHandled = handleGuiBar((int)e.getX(), (int) e.getY());
|
||||
isTouchInHotbar = hudKeyHandled != -1;
|
||||
// We only treat in world events
|
||||
if (!CallbackBridge.isGrabbing()) break;
|
||||
|
||||
// Stop the dropping of items
|
||||
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q, 0, false);
|
||||
mHandler.removeMessages(MSG_DROP_ITEM_BUTTON_CHECK);
|
||||
|
||||
// Remove the mouse left button
|
||||
if(triggeredLeftMouseButton){
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false);
|
||||
triggeredLeftMouseButton = false;
|
||||
break;
|
||||
}
|
||||
mHandler.removeMessages(MSG_LEFT_MOUSE_BUTTON_CHECK);
|
||||
|
||||
// In case of a short click, just send a quick right click
|
||||
if(!LauncherPreferences.PREF_DISABLE_GESTURES &&
|
||||
MathUtils.dist(mInitialX, mInitialY, CallbackBridge.mouseX, CallbackBridge.mouseY) < FINGER_STILL_THRESHOLD){
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, true);
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, false);
|
||||
}
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_POINTER_DOWN: // 5
|
||||
//TODO Hey we could have some sort of middle click detection ?
|
||||
|
||||
mScrollLastInitialX = e.getX();
|
||||
mScrollLastInitialY = e.getY();
|
||||
//Checking if we are pressing the hotbar to select the item
|
||||
hudKeyHandled = handleGuiBar((int)e.getX(e.getPointerCount()-1), (int) e.getY(e.getPointerCount()-1));
|
||||
if(hudKeyHandled != -1){
|
||||
sendKeyPress(hudKeyHandled);
|
||||
if(hasDoubleTapped && hudKeyHandled == mLastHotbarKey){
|
||||
//Prevent double tapping Event on two different slots
|
||||
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_F);
|
||||
}
|
||||
}
|
||||
|
||||
mLastHotbarKey = hudKeyHandled;
|
||||
break;
|
||||
|
||||
}
|
||||
|
||||
// Actualise the pointer count
|
||||
mLastPointerCount = e.getPointerCount();
|
||||
|
||||
return true;
|
||||
private void createGamepad(View contextView, InputDevice inputDevice) {
|
||||
mGamepad = new Gamepad(contextView, inputDevice, DefaultDataProvider.INSTANCE, true);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -404,9 +217,7 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
int mouseCursorIndex = -1;
|
||||
|
||||
if(Gamepad.isGamepadEvent(event)){
|
||||
if(mGamepad == null){
|
||||
mGamepad = new Gamepad(this, event.getDevice());
|
||||
}
|
||||
if(mGamepad == null) createGamepad(this, event.getDevice());
|
||||
|
||||
mInputManager.handleMotionEventInput(getContext(), event, mGamepad);
|
||||
return true;
|
||||
@@ -441,32 +252,6 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
}
|
||||
}
|
||||
|
||||
//TODO MOVE THIS SOMEWHERE ELSE
|
||||
/** The input event for mouse with a captured pointer */
|
||||
@RequiresApi(26)
|
||||
@Override
|
||||
public boolean dispatchCapturedPointerEvent(MotionEvent e) {
|
||||
CallbackBridge.mouseX += (e.getX()* mScaleFactor);
|
||||
CallbackBridge.mouseY += (e.getY()* mScaleFactor);
|
||||
|
||||
// Position is updated by many events, hence it is send regardless of the event value
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
|
||||
switch (e.getActionMasked()) {
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
return true;
|
||||
case MotionEvent.ACTION_BUTTON_PRESS:
|
||||
return sendMouseButtonUnconverted(e.getActionButton(), true);
|
||||
case MotionEvent.ACTION_BUTTON_RELEASE:
|
||||
return sendMouseButtonUnconverted(e.getActionButton(), false);
|
||||
case MotionEvent.ACTION_SCROLL:
|
||||
CallbackBridge.sendScroll(e.getAxisValue(MotionEvent.AXIS_HSCROLL), e.getAxisValue(MotionEvent.AXIS_VSCROLL));
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The event for keyboard/ gamepad button inputs */
|
||||
public boolean processKeyEvent(KeyEvent event) {
|
||||
//Log.i("KeyEvent", event.toString());
|
||||
@@ -504,9 +289,7 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
}
|
||||
|
||||
if(Gamepad.isGamepadEvent(event)){
|
||||
if(mGamepad == null){
|
||||
mGamepad = new Gamepad(this, event.getDevice());
|
||||
}
|
||||
if(mGamepad == null) createGamepad(this, event.getDevice());
|
||||
|
||||
mInputManager.handleKeyEventInput(getContext(), event, mGamepad);
|
||||
return true;
|
||||
@@ -545,25 +328,7 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
|
||||
|
||||
|
||||
/** @return the hotbar key, given the position. -1 if no key are pressed */
|
||||
public int handleGuiBar(int x, int y) {
|
||||
if (!CallbackBridge.isGrabbing()) return -1;
|
||||
|
||||
int barHeight = mcscale(20);
|
||||
int barY = CallbackBridge.physicalHeight - barHeight;
|
||||
if(y < barY) return -1;
|
||||
|
||||
int barWidth = mcscale(180);
|
||||
int barX = (CallbackBridge.physicalWidth / 2) - (barWidth / 2);
|
||||
if(x < barX || x >= barX + barWidth) return -1;
|
||||
|
||||
return HOTBAR_KEYS[(int) net.kdt.pojavlaunch.utils.MathUtils.map(x, barX, barX + barWidth, 0, 9)];
|
||||
}
|
||||
|
||||
/** Return the size, given the UI scale size */
|
||||
private int mcscale(int input) {
|
||||
return (int)((mGuiScale * input)/ mScaleFactor);
|
||||
}
|
||||
|
||||
/** Called when the size need to be set at any point during the surface lifecycle **/
|
||||
public void refreshSize(){
|
||||
@@ -621,30 +386,16 @@ public class MinecraftGLSurface extends View implements GrabListener {
|
||||
post(()->updateGrabState(isGrabbing));
|
||||
}
|
||||
|
||||
private void updateGrabState(boolean isGrabbing) {
|
||||
if(!MainActivity.isAndroid8OrHigher()) return;
|
||||
|
||||
boolean hasPointerCapture = hasPointerCapture();
|
||||
if(isGrabbing){
|
||||
if(!hasPointerCapture) {
|
||||
requestFocus();
|
||||
if(hasWindowFocus()) requestPointerCapture();
|
||||
// Otherwise, onWindowFocusChanged() would get called.
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if(hasPointerCapture) {
|
||||
releasePointerCapture();
|
||||
clearFocus();
|
||||
}
|
||||
private TouchEventProcessor pickEventProcessor(boolean isGrabbing) {
|
||||
return isGrabbing ? mIngameProcessor : mInGUIProcessor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWindowFocusChanged(boolean hasWindowFocus) {
|
||||
super.onWindowFocusChanged(hasWindowFocus);
|
||||
if(hasWindowFocus && CallbackBridge.isGrabbing() &&
|
||||
MainActivity.isAndroid8OrHigher()) requestPointerCapture();
|
||||
private void updateGrabState(boolean isGrabbing) {
|
||||
if(mLastGrabState != isGrabbing) {
|
||||
mCurrentTouchProcessor.cancelPendingActions();
|
||||
mCurrentTouchProcessor = pickEventProcessor(isGrabbing);
|
||||
mLastGrabState = isGrabbing;
|
||||
}
|
||||
}
|
||||
|
||||
/** A small interface called when the listener is ready for the first time */
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import static net.kdt.pojavlaunch.Architecture.archAsString;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.res.AssetManager;
|
||||
import android.util.Log;
|
||||
|
||||
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
|
||||
import net.kdt.pojavlaunch.multirt.Runtime;
|
||||
import net.kdt.pojavlaunch.utils.MathUtils;
|
||||
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
|
||||
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class NewJREUtil {
|
||||
private static boolean checkInternalRuntime(AssetManager assetManager, InternalRuntime internalRuntime) {
|
||||
String launcher_runtime_version;
|
||||
String installed_runtime_version = MultiRTUtils.readInternalRuntimeVersion(internalRuntime.name);
|
||||
try {
|
||||
launcher_runtime_version = Tools.read(assetManager.open(internalRuntime.path+"/version"));
|
||||
}catch (IOException exc) {
|
||||
//we don't have a runtime included!
|
||||
//if we have one installed -> return true -> proceed (no updates but the current one should be functional)
|
||||
//if we don't -> return false -> Cannot find compatible Java runtime
|
||||
return installed_runtime_version != null;
|
||||
}
|
||||
// this implicitly checks for null, so it will unpack the runtime even if we don't have one installed
|
||||
if(!launcher_runtime_version.equals(installed_runtime_version))
|
||||
return unpackInternalRuntime(assetManager, internalRuntime, launcher_runtime_version);
|
||||
else return true;
|
||||
}
|
||||
|
||||
private static boolean unpackInternalRuntime(AssetManager assetManager, InternalRuntime internalRuntime, String version) {
|
||||
try {
|
||||
MultiRTUtils.installRuntimeNamedBinpack(
|
||||
assetManager.open(internalRuntime.path+"/universal.tar.xz"),
|
||||
assetManager.open(internalRuntime.path+"/bin-" + archAsString(Tools.DEVICE_ARCHITECTURE) + ".tar.xz"),
|
||||
internalRuntime.name, version);
|
||||
MultiRTUtils.postPrepare(internalRuntime.name);
|
||||
return true;
|
||||
}catch (IOException e) {
|
||||
Log.e("NewJREAuto", "Internal JRE unpack failed", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static InternalRuntime getInternalRuntime(Runtime runtime) {
|
||||
for(InternalRuntime internalRuntime : InternalRuntime.values()) {
|
||||
if(internalRuntime.name.equals(runtime.name)) return internalRuntime;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static MathUtils.RankedValue<Runtime> getNearestInstalledRuntime(int targetVersion) {
|
||||
List<Runtime> runtimes = MultiRTUtils.getRuntimes();
|
||||
return MathUtils.findNearestPositive(targetVersion, runtimes, (runtime)->runtime.javaVersion);
|
||||
}
|
||||
|
||||
private static MathUtils.RankedValue<InternalRuntime> getNearestInternalRuntime(int targetVersion) {
|
||||
List<InternalRuntime> runtimeList = Arrays.asList(InternalRuntime.values());
|
||||
return MathUtils.findNearestPositive(targetVersion, runtimeList, (runtime)->runtime.majorVersion);
|
||||
}
|
||||
|
||||
|
||||
/** @return true if everything is good, false otherwise. */
|
||||
public static boolean installNewJreIfNeeded(Activity activity, JMinecraftVersionList.Version versionInfo) {
|
||||
//Now we have the reliable information to check if our runtime settings are good enough
|
||||
if (versionInfo.javaVersion == null || versionInfo.javaVersion.component.equalsIgnoreCase("jre-legacy"))
|
||||
return true;
|
||||
|
||||
int gameRequiredVersion = versionInfo.javaVersion.majorVersion;
|
||||
|
||||
LauncherProfiles.load();
|
||||
AssetManager assetManager = activity.getAssets();
|
||||
MinecraftProfile minecraftProfile = LauncherProfiles.getCurrentProfile();
|
||||
String profileRuntime = Tools.getSelectedRuntime(minecraftProfile);
|
||||
Runtime runtime = MultiRTUtils.read(profileRuntime);
|
||||
// Partly trust the user with his own selection, if the game can even try to run in this case
|
||||
if (runtime.javaVersion >= gameRequiredVersion) {
|
||||
// Check whether the selection is an internal runtime
|
||||
InternalRuntime internalRuntime = getInternalRuntime(runtime);
|
||||
// If it is, check if updates are available from the APK file
|
||||
if(internalRuntime != null) {
|
||||
// Not calling showRuntimeFail on failure here because we did, technically, find the compatible runtime
|
||||
return checkInternalRuntime(assetManager, internalRuntime);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// If the runtime version selected by the user is not appropriate for this version (which means the game won't run at all)
|
||||
// automatically pick from either an already installed runtime, or a runtime packed with the launcher
|
||||
MathUtils.RankedValue<?> nearestInstalledRuntime = getNearestInstalledRuntime(gameRequiredVersion);
|
||||
MathUtils.RankedValue<?> nearestInternalRuntime = getNearestInternalRuntime(gameRequiredVersion);
|
||||
|
||||
MathUtils.RankedValue<?> selectedRankedRuntime = MathUtils.objectMin(
|
||||
nearestInternalRuntime, nearestInstalledRuntime, (value)->value.rank
|
||||
);
|
||||
|
||||
// No possible selections
|
||||
if(selectedRankedRuntime == null) {
|
||||
showRuntimeFail(activity, versionInfo);
|
||||
return false;
|
||||
}
|
||||
|
||||
Object selected = selectedRankedRuntime.value;
|
||||
String appropriateRuntime;
|
||||
InternalRuntime internalRuntime;
|
||||
|
||||
// Perform checks on the picked runtime
|
||||
if(selected instanceof Runtime) {
|
||||
// If it's an already installed runtime, save its name and check if
|
||||
// it's actually an internal one (just in case)
|
||||
Runtime selectedRuntime = (Runtime) selected;
|
||||
appropriateRuntime = selectedRuntime.name;
|
||||
internalRuntime = getInternalRuntime(selectedRuntime);
|
||||
} else if (selected instanceof InternalRuntime) {
|
||||
// If it's an internal runtime, set it's name as the appropriate one.
|
||||
internalRuntime = (InternalRuntime) selected;
|
||||
appropriateRuntime = internalRuntime.name;
|
||||
} else {
|
||||
throw new RuntimeException("Unexpected type of selected: "+selected.getClass().getName());
|
||||
}
|
||||
|
||||
// If it turns out the selected runtime is actually an internal one, attempt automatic installation or update
|
||||
if(internalRuntime != null && !checkInternalRuntime(assetManager, internalRuntime)) {
|
||||
// Not calling showRuntimeFail here because we did, technically, find the compatible runtime
|
||||
return false;
|
||||
}
|
||||
|
||||
minecraftProfile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX + appropriateRuntime;
|
||||
LauncherProfiles.write();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void showRuntimeFail(Activity activity, JMinecraftVersionList.Version verInfo) {
|
||||
Tools.dialogOnUiThread(activity, activity.getString(R.string.global_error),
|
||||
activity.getString(R.string.multirt_nocompatiblert, verInfo.javaVersion.majorVersion));
|
||||
}
|
||||
|
||||
private enum InternalRuntime {
|
||||
JRE_17(17, "Internal-17", "components/jre-new"),
|
||||
JRE_21(21, "Internal-21", "components/jre-21");
|
||||
public final int majorVersion;
|
||||
public final String name;
|
||||
public final String path;
|
||||
InternalRuntime(int majorVersion, String name, String path) {
|
||||
this.majorVersion = majorVersion;
|
||||
this.name = name;
|
||||
this.path = path;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -57,7 +57,6 @@ public class PojavApplication extends Application {
|
||||
|
||||
try {
|
||||
super.onCreate();
|
||||
Tools.APP_NAME = getResources().getString(R.string.app_short_name);
|
||||
|
||||
Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent();
|
||||
Tools.DIR_CACHE = getCacheDir();
|
||||
|
||||
@@ -3,6 +3,8 @@ package net.kdt.pojavlaunch;
|
||||
import android.view.*;
|
||||
import android.view.GestureDetector.*;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
public class SingleTapConfirm extends SimpleOnGestureListener {
|
||||
@Override
|
||||
public boolean onSingleTapUp(MotionEvent event) {
|
||||
|
||||
@@ -43,7 +43,6 @@ import androidx.appcompat.app.AppCompatActivity;
|
||||
import androidx.core.app.NotificationManagerCompat;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.fragment.app.FragmentActivity;
|
||||
import androidx.fragment.app.FragmentTransaction;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
@@ -51,6 +50,8 @@ import com.google.gson.GsonBuilder;
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
|
||||
import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask;
|
||||
import net.kdt.pojavlaunch.lifecycle.LifecycleAwareAlertDialog;
|
||||
import net.kdt.pojavlaunch.memory.MemoryHoleFinder;
|
||||
import net.kdt.pojavlaunch.memory.SelfMapsParser;
|
||||
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
|
||||
import net.kdt.pojavlaunch.multirt.Runtime;
|
||||
import net.kdt.pojavlaunch.plugins.FFmpegPlugin;
|
||||
@@ -94,7 +95,7 @@ import java.util.Map;
|
||||
public final class Tools {
|
||||
public static final float BYTE_TO_MB = 1024 * 1024;
|
||||
public static final Handler MAIN_HANDLER = new Handler(Looper.getMainLooper());
|
||||
public static String APP_NAME = "null";
|
||||
public static String APP_NAME = "PojavLauncher";
|
||||
|
||||
public static final Gson GLOBAL_GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
@@ -171,9 +172,20 @@ public final class Tools {
|
||||
public static void launchMinecraft(final AppCompatActivity activity, MinecraftAccount minecraftAccount,
|
||||
MinecraftProfile minecraftProfile, String versionId, int versionJavaRequirement) throws Throwable {
|
||||
int freeDeviceMemory = getFreeDeviceMemory(activity);
|
||||
int localeString;
|
||||
int freeAddressSpace = Architecture.is32BitsDevice() ? getMaxContinuousAddressSpaceSize() : -1;
|
||||
Log.i("MemStat", "Free RAM: " + freeDeviceMemory + " Addressable: " + freeAddressSpace);
|
||||
if(freeDeviceMemory > freeAddressSpace && freeAddressSpace != -1) {
|
||||
freeDeviceMemory = freeAddressSpace;
|
||||
localeString = R.string.address_memory_warning_msg;
|
||||
} else {
|
||||
localeString = R.string.memory_warning_msg;
|
||||
}
|
||||
|
||||
if(LauncherPreferences.PREF_RAM_ALLOCATION > freeDeviceMemory) {
|
||||
int finalDeviceMemory = freeDeviceMemory;
|
||||
LifecycleAwareAlertDialog.DialogCreator dialogCreator = (dialog, builder) ->
|
||||
builder.setMessage(activity.getString(R.string.memory_warning_msg, freeDeviceMemory, LauncherPreferences.PREF_RAM_ALLOCATION))
|
||||
builder.setMessage(activity.getString(localeString, finalDeviceMemory, LauncherPreferences.PREF_RAM_ALLOCATION))
|
||||
.setPositiveButton(android.R.string.ok, (d, w)->{});
|
||||
|
||||
if(LifecycleAwareAlertDialog.haltOnDialog(activity.getLifecycle(), activity, dialogCreator)) {
|
||||
@@ -210,25 +222,16 @@ public final class Tools {
|
||||
javaArgList.add("-Dlog4j.configurationFile=" + configFile);
|
||||
}
|
||||
javaArgList.addAll(Arrays.asList(getMinecraftJVMArgs(versionId, gamedir)));
|
||||
//javaArgList.add("-cp");
|
||||
//javaArgList.add(getLWJGL3ClassPath() + ":" + launchClassPath);
|
||||
javaArgList.add("-cp");
|
||||
javaArgList.add(getLWJGL3ClassPath() + ":" + launchClassPath);
|
||||
|
||||
//javaArgList.add(versionInfo.mainClass);
|
||||
//javaArgList.addAll(Arrays.asList(launchArgs));
|
||||
javaArgList.add(versionInfo.mainClass);
|
||||
javaArgList.addAll(Arrays.asList(launchArgs));
|
||||
// ctx.appendlnToLog("full args: "+javaArgList.toString());
|
||||
String args = LauncherPreferences.PREF_CUSTOM_JAVA_ARGS;
|
||||
if(Tools.isValidString(minecraftProfile.javaArgs)) args = minecraftProfile.javaArgs;
|
||||
FFmpegPlugin.discover(activity);
|
||||
JREUtils.launchJavaVM(
|
||||
activity,
|
||||
runtime,
|
||||
gamedir,
|
||||
javaArgList,
|
||||
getLWJGL3ClassPath() + ":" + launchClassPath,
|
||||
versionInfo.mainClass,
|
||||
launchArgs,
|
||||
args
|
||||
);
|
||||
JREUtils.launchJavaVM(activity, runtime, gamedir, javaArgList, args);
|
||||
// If we returned, this means that the JVM exit dialog has been shown and we don't need to be active anymore.
|
||||
// We never return otherwise. The process will be killed anyway, and thus we will become inactive
|
||||
}
|
||||
@@ -610,7 +613,7 @@ public final class Tools {
|
||||
.setNegativeButton(showMore ? R.string.error_show_less : R.string.error_show_more, (p1, p2) -> showError(ctx, titleId, rolledMessage, e, exitIfOk, !showMore))
|
||||
.setNeutralButton(android.R.string.copy, (p1, p2) -> {
|
||||
ClipboardManager mgr = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
|
||||
mgr.setPrimaryClip(ClipData.newPlainText("error", Log.getStackTraceString(e)));
|
||||
mgr.setPrimaryClip(ClipData.newPlainText("error", printToString(e)));
|
||||
if(exitIfOk) {
|
||||
if (ctx instanceof MainActivity) {
|
||||
MainActivity.fullyExit();
|
||||
@@ -766,31 +769,34 @@ public final class Tools {
|
||||
"releaseTime", "time", "type"
|
||||
);
|
||||
|
||||
List<DependentLibrary> libList = new ArrayList<>(Arrays.asList(inheritsVer.libraries));
|
||||
try {
|
||||
loop_1:
|
||||
for (DependentLibrary lib : customVer.libraries) {
|
||||
String libName = lib.name.substring(0, lib.name.lastIndexOf(":"));
|
||||
for (int i = 0; i < libList.size(); i++) {
|
||||
DependentLibrary libAdded = libList.get(i);
|
||||
String libAddedName = libAdded.name.substring(0, libAdded.name.lastIndexOf(":"));
|
||||
// Go through the libraries, remove the ones overridden by the custom version
|
||||
List<DependentLibrary> inheritLibraryList = new ArrayList<>(Arrays.asList(inheritsVer.libraries));
|
||||
outer_loop:
|
||||
for(DependentLibrary library : customVer.libraries){
|
||||
// Clean libraries overridden by the custom version
|
||||
String libName = library.name.substring(0, library.name.lastIndexOf(":"));
|
||||
|
||||
if (libAddedName.equals(libName)) {
|
||||
Log.d(APP_NAME, "Library " + libName + ": Replaced version " +
|
||||
libName.substring(libName.lastIndexOf(":") + 1) + " with " +
|
||||
libAddedName.substring(libAddedName.lastIndexOf(":") + 1));
|
||||
libList.set(i, lib);
|
||||
continue loop_1;
|
||||
}
|
||||
for(DependentLibrary inheritLibrary : inheritLibraryList) {
|
||||
String inheritLibName = inheritLibrary.name.substring(0, inheritLibrary.name.lastIndexOf(":"));
|
||||
|
||||
if(libName.equals(inheritLibName)){
|
||||
Log.d(APP_NAME, "Library " + libName + ": Replaced version " +
|
||||
libName.substring(libName.lastIndexOf(":") + 1) + " with " +
|
||||
inheritLibName.substring(inheritLibName.lastIndexOf(":") + 1));
|
||||
|
||||
// Remove the library , superseded by the overriding libs
|
||||
inheritLibraryList.remove(inheritLibrary);
|
||||
continue outer_loop;
|
||||
}
|
||||
|
||||
libList.add(0, lib);
|
||||
}
|
||||
} finally {
|
||||
inheritsVer.libraries = libList.toArray(new DependentLibrary[0]);
|
||||
preProcessLibraries(inheritsVer.libraries);
|
||||
}
|
||||
|
||||
// Fuse libraries
|
||||
inheritLibraryList.addAll(Arrays.asList(customVer.libraries));
|
||||
inheritsVer.libraries = inheritLibraryList.toArray(new DependentLibrary[0]);
|
||||
preProcessLibraries(inheritsVer.libraries);
|
||||
|
||||
|
||||
// Inheriting Minecraft 1.13+ with append custom args
|
||||
if (inheritsVer.arguments != null && customVer.arguments != null) {
|
||||
List totalArgList = new ArrayList(Arrays.asList(inheritsVer.arguments.game));
|
||||
@@ -930,6 +936,23 @@ public final class Tools {
|
||||
return (int) (memInfo.availMem / 1048576L);
|
||||
}
|
||||
|
||||
private static int internalGetMaxContinuousAddressSpaceSize() throws Exception{
|
||||
MemoryHoleFinder memoryHoleFinder = new MemoryHoleFinder();
|
||||
new SelfMapsParser(memoryHoleFinder).run();
|
||||
long largestHole = memoryHoleFinder.getLargestHole();
|
||||
if(largestHole == -1) return -1;
|
||||
else return (int)(largestHole / 1048576L);
|
||||
}
|
||||
|
||||
public static int getMaxContinuousAddressSpaceSize() {
|
||||
try {
|
||||
return internalGetMaxContinuousAddressSpaceSize();
|
||||
}catch (Exception e){
|
||||
Log.w("Tools", "Failed to find the largest uninterrupted address space");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public static int getDisplayFriendlyRes(int displaySideRes, float scaling){
|
||||
displaySideRes *= scaling;
|
||||
if(displaySideRes % 2 != 0) displaySideRes --;
|
||||
@@ -949,20 +972,23 @@ public final class Tools {
|
||||
|
||||
/** Swap the main fragment with another */
|
||||
public static void swapFragment(FragmentActivity fragmentActivity , Class<? extends Fragment> fragmentClass,
|
||||
@Nullable String fragmentTag, boolean addCurrentToBackstack, @Nullable Bundle bundle) {
|
||||
@Nullable String fragmentTag, @Nullable Bundle bundle) {
|
||||
// When people tab out, it might happen
|
||||
//TODO handle custom animations
|
||||
FragmentTransaction transaction = fragmentActivity.getSupportFragmentManager().beginTransaction()
|
||||
fragmentActivity.getSupportFragmentManager().beginTransaction()
|
||||
.setReorderingAllowed(true)
|
||||
.replace(R.id.container_fragment, fragmentClass, bundle, fragmentTag);
|
||||
if(addCurrentToBackstack) transaction.addToBackStack(null);
|
||||
.addToBackStack(fragmentClass.getName())
|
||||
.replace(R.id.container_fragment, fragmentClass, bundle, fragmentTag).commit();
|
||||
}
|
||||
|
||||
transaction.commit();
|
||||
public static void backToMainMenu(FragmentActivity fragmentActivity) {
|
||||
fragmentActivity.getSupportFragmentManager()
|
||||
.popBackStack("ROOT", 0);
|
||||
}
|
||||
|
||||
/** Remove the current fragment */
|
||||
public static void removeCurrentFragment(FragmentActivity fragmentActivity){
|
||||
fragmentActivity.getSupportFragmentManager().popBackStackImmediate();
|
||||
fragmentActivity.getSupportFragmentManager().popBackStack();
|
||||
}
|
||||
|
||||
public static void installMod(Activity activity, boolean customJavaArgs) {
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
|
||||
import static net.kdt.pojavlaunch.MinecraftGLSurface.FINGER_SCROLL_THRESHOLD;
|
||||
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
|
||||
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.GestureDetector;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageView;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
/**
|
||||
* Class dealing with the virtual mouse
|
||||
*/
|
||||
public class Touchpad extends FrameLayout implements GrabListener{
|
||||
/* Whether the Touchpad should be displayed */
|
||||
private boolean mDisplayState;
|
||||
/* Mouse pointer icon used by the touchpad */
|
||||
private final ImageView mMousePointerImageView = new ImageView(getContext());
|
||||
/* Detect a classic android Tap */
|
||||
private final GestureDetector mSingleTapDetector = new GestureDetector(getContext(), new SingleTapConfirm());
|
||||
/* Resolution scaler option, allow downsizing a window */
|
||||
private final float mScaleFactor = DEFAULT_PREF.getInt("resolutionRatio",100)/100f;
|
||||
/* Current pointer ID to move the mouse */
|
||||
private int mCurrentPointerID = -1000;
|
||||
/* Previous MotionEvent position, not scale */
|
||||
private float mPrevX, mPrevY;
|
||||
/* Last first pointer positions non-scaled, used to scroll distance */
|
||||
private float mScrollLastInitialX, mScrollLastInitialY;
|
||||
/* Handler and message to check if we are grabbing */
|
||||
|
||||
public Touchpad(@NonNull Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public Touchpad(@NonNull Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init();
|
||||
}
|
||||
|
||||
@SuppressWarnings("accessibility")
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
// MotionEvent reports input details from the touch screen
|
||||
// and other input controls. In this case, you are only
|
||||
// interested in events where the touch position changed.
|
||||
// int index = event.getActionIndex();
|
||||
if(CallbackBridge.isGrabbing()) {
|
||||
disable();
|
||||
return false;
|
||||
}
|
||||
int action = event.getActionMasked();
|
||||
|
||||
float x = event.getX();
|
||||
float y = event.getY();
|
||||
float mouseX = mMousePointerImageView.getX();
|
||||
float mouseY = mMousePointerImageView.getY();
|
||||
|
||||
if (mSingleTapDetector.onTouchEvent(event)) {
|
||||
CallbackBridge.mouseX = (mouseX * mScaleFactor);
|
||||
CallbackBridge.mouseY = (mouseY * mScaleFactor);
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
CallbackBridge.sendMouseKeycode(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case MotionEvent.ACTION_POINTER_DOWN: // 5
|
||||
mScrollLastInitialX = event.getX();
|
||||
mScrollLastInitialY = event.getY();
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mPrevX = x;
|
||||
mPrevY = y;
|
||||
mCurrentPointerID = event.getPointerId(0);
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_MOVE: // 2
|
||||
//Scrolling feature
|
||||
if (!LauncherPreferences.PREF_DISABLE_GESTURES && !CallbackBridge.isGrabbing() && event.getPointerCount() >= 2) {
|
||||
int hScroll = ((int) (event.getX() - mScrollLastInitialX)) / FINGER_SCROLL_THRESHOLD;
|
||||
int vScroll = ((int) (event.getY() - mScrollLastInitialY)) / FINGER_SCROLL_THRESHOLD;
|
||||
|
||||
if(vScroll != 0 || hScroll != 0){
|
||||
CallbackBridge.sendScroll(hScroll, vScroll);
|
||||
mScrollLastInitialX = event.getX();
|
||||
mScrollLastInitialY = event.getY();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Mouse movement
|
||||
if(mCurrentPointerID == event.getPointerId(0)) {
|
||||
mouseX = Math.max(0, Math.min(currentDisplayMetrics.widthPixels, mouseX + (x - mPrevX) * LauncherPreferences.PREF_MOUSESPEED));
|
||||
mouseY = Math.max(0, Math.min(currentDisplayMetrics.heightPixels, mouseY + (y - mPrevY) * LauncherPreferences.PREF_MOUSESPEED));
|
||||
|
||||
placeMouseAt(mouseX, mouseY);
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
}else mCurrentPointerID = event.getPointerId(0);
|
||||
|
||||
mPrevX = x;
|
||||
mPrevY = y;
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_UP:
|
||||
mPrevX = x;
|
||||
mPrevY = y;
|
||||
mCurrentPointerID = -1000;
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Enable the touchpad */
|
||||
public void enable(){
|
||||
setVisibility(VISIBLE);
|
||||
placeMouseAt(currentDisplayMetrics.widthPixels / 2f, currentDisplayMetrics.heightPixels / 2f);
|
||||
}
|
||||
|
||||
/** Disable the touchpad and hides the mouse */
|
||||
public void disable(){
|
||||
setVisibility(GONE);
|
||||
}
|
||||
|
||||
/** @return The new state, enabled or disabled */
|
||||
public boolean switchState(){
|
||||
mDisplayState = !mDisplayState;
|
||||
if(!CallbackBridge.isGrabbing()) {
|
||||
if(mDisplayState) enable();
|
||||
else disable();
|
||||
}
|
||||
return mDisplayState;
|
||||
}
|
||||
|
||||
public void placeMouseAt(float x, float y) {
|
||||
mMousePointerImageView.setX(x);
|
||||
mMousePointerImageView.setY(y);
|
||||
CallbackBridge.mouseX = (x * mScaleFactor);
|
||||
CallbackBridge.mouseY = (y * mScaleFactor);
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
}
|
||||
|
||||
private void init(){
|
||||
// Setup mouse pointer
|
||||
mMousePointerImageView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_mouse_pointer, getContext().getTheme()));
|
||||
mMousePointerImageView.post(() -> {
|
||||
ViewGroup.LayoutParams params = mMousePointerImageView.getLayoutParams();
|
||||
params.width = (int) (36 / 100f * LauncherPreferences.PREF_MOUSESCALE);
|
||||
params.height = (int) (54 / 100f * LauncherPreferences.PREF_MOUSESCALE);
|
||||
});
|
||||
addView(mMousePointerImageView);
|
||||
setFocusable(false);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
setDefaultFocusHighlightEnabled(false);
|
||||
}
|
||||
|
||||
// When the game is grabbing, we should not display the mouse
|
||||
disable();
|
||||
mDisplayState = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGrabState(boolean isGrabbing) {
|
||||
post(()->updateGrabState(isGrabbing));
|
||||
}
|
||||
private void updateGrabState(boolean isGrabbing) {
|
||||
if(!isGrabbing) {
|
||||
if(mDisplayState && getVisibility() != VISIBLE) enable();
|
||||
if(!mDisplayState && getVisibility() == VISIBLE) disable();
|
||||
}else{
|
||||
if(getVisibility() != View.GONE) disable();
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
@@ -40,6 +40,7 @@ public class MicrosoftBackgroundLogin {
|
||||
private static final String xstsAuthUrl = "https://xsts.auth.xboxlive.com/xsts/authorize";
|
||||
private static final String mcLoginUrl = "https://api.minecraftservices.com/authentication/login_with_xbox";
|
||||
private static final String mcProfileUrl = "https://api.minecraftservices.com/minecraft/profile";
|
||||
private static final String mcStoreUrl = "https://api.minecraftservices.com/entitlements/mcstore";
|
||||
|
||||
private final boolean mIsRefresh;
|
||||
private final String mAuthCode;
|
||||
@@ -81,6 +82,7 @@ public class MicrosoftBackgroundLogin {
|
||||
notifyProgress(progressListener, 4);
|
||||
String mcToken = acquireMinecraftToken(xsts[0], xsts[1]);
|
||||
notifyProgress(progressListener, 5);
|
||||
fetchOwnedItems(mcToken);
|
||||
checkMcProfile(mcToken);
|
||||
|
||||
MinecraftAccount acc = MinecraftAccount.load(mcName);
|
||||
@@ -255,6 +257,21 @@ public class MicrosoftBackgroundLogin {
|
||||
}
|
||||
}
|
||||
|
||||
private void fetchOwnedItems(String mcAccessToken) throws IOException {
|
||||
URL url = new URL(mcStoreUrl);
|
||||
|
||||
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
|
||||
conn.setRequestProperty("Authorization", "Bearer " + mcAccessToken);
|
||||
conn.setUseCaches(false);
|
||||
conn.connect();
|
||||
if(conn.getResponseCode() < 200 || conn.getResponseCode() >= 300) {
|
||||
throw getResponseThrowable(conn);
|
||||
}
|
||||
// We don't need any data from this request, it just needs to happen in order for
|
||||
// the MS servers to work properly. The data from this is practically useless
|
||||
// as it does not indicate whether the user owns the game through Game Pass.
|
||||
}
|
||||
|
||||
private void checkMcProfile(String mcAccessToken) throws IOException, JSONException {
|
||||
URL url = new URL(mcProfileUrl);
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ public class ControlData {
|
||||
}
|
||||
|
||||
// Internal usage only
|
||||
public boolean isHideable;
|
||||
public transient boolean isHideable;
|
||||
/**
|
||||
* Both fields below are dynamic position data, auto updates
|
||||
* X and Y position, unlike the original one which uses fixed
|
||||
@@ -53,7 +53,7 @@ public class ControlData {
|
||||
* bigger device or vice versa.
|
||||
*/
|
||||
public String dynamicX, dynamicY;
|
||||
public boolean isDynamicBtn, isToggle, passThruEnabled;
|
||||
public boolean isToggle, passThruEnabled;
|
||||
public String name;
|
||||
public int[] keycodes; //Should store up to 4 keys
|
||||
public float opacity; //Alpha value from 0 to 1;
|
||||
@@ -93,7 +93,6 @@ public class ControlData {
|
||||
|
||||
public ControlData(String name, int[] keycodes, float x, float y, float width, float height) {
|
||||
this(name, keycodes, Float.toString(x), Float.toString(y), width, height, false);
|
||||
this.isDynamicBtn = false;
|
||||
}
|
||||
|
||||
public ControlData(String name, int[] keycodes, String dynamicX, String dynamicY) {
|
||||
@@ -119,7 +118,6 @@ public class ControlData {
|
||||
this.dynamicY = dynamicY;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.isDynamicBtn = false;
|
||||
this.isToggle = isToggle;
|
||||
this.opacity = opacity;
|
||||
this.bgColor = bgColor;
|
||||
|
||||
+3
-3
@@ -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 = 6;
|
||||
version = 7;
|
||||
}
|
||||
|
||||
|
||||
public void save(String path) throws IOException {
|
||||
//Current version is the V3.0 so the version as to be marked as 6 !
|
||||
version = 6;
|
||||
//Current version is the V3.1 so the version as to be marked as 7 !
|
||||
version = 7;
|
||||
|
||||
Tools.write(path, Tools.GLOBAL_GSON.toJson(this));
|
||||
}
|
||||
|
||||
+1
-2
@@ -30,7 +30,7 @@ public class LayoutConverter {
|
||||
return layout;
|
||||
}else if (layoutJobj.getInt("version") >= 3 && layoutJobj.getInt("version") <= 5) {
|
||||
return LayoutConverter.convertV3_4Layout(layoutJobj);
|
||||
} else if (layoutJobj.getInt("version") == 6) {
|
||||
} else if (layoutJobj.getInt("version") == 6 || layoutJobj.getInt("version") == 7) {
|
||||
return Tools.GLOBAL_GSON.fromJson(jsonLayoutData, CustomControls.class);
|
||||
} else {
|
||||
return null;
|
||||
@@ -105,7 +105,6 @@ public class LayoutConverter {
|
||||
LwjglGlfwKeycode.GLFW_KEY_UNKNOWN,
|
||||
LwjglGlfwKeycode.GLFW_KEY_UNKNOWN,
|
||||
LwjglGlfwKeycode.GLFW_KEY_UNKNOWN};
|
||||
n_button.isDynamicBtn = button.getBoolean("isDynamicBtn");
|
||||
n_button.dynamicX = button.getString("dynamicX");
|
||||
n_button.dynamicY = button.getString("dynamicY");
|
||||
if (!Tools.isValidString(n_button.dynamicX) && button.has("x")) {
|
||||
|
||||
+6
-14
@@ -371,13 +371,10 @@ public interface ControlInterface extends View.OnLongClickListener, GrabListener
|
||||
if (Math.abs(event.getRawX() - downRawX) > 8 || Math.abs(event.getRawY() - downRawY) > 8)
|
||||
mCanTriggerLongClick = false;
|
||||
getControlLayoutParent().adaptPanelPosition();
|
||||
|
||||
if (!getProperties().isDynamicBtn) {
|
||||
snapAndAlign(
|
||||
MathUtils.clamp(event.getRawX() - downX, 0, CallbackBridge.physicalWidth - view.getWidth()),
|
||||
MathUtils.clamp(event.getRawY() - downY, 0, CallbackBridge.physicalHeight - view.getHeight())
|
||||
);
|
||||
}
|
||||
snapAndAlign(
|
||||
MathUtils.clamp(event.getRawX() - downX, 0, CallbackBridge.physicalWidth - view.getWidth()),
|
||||
MathUtils.clamp(event.getRawY() - downY, 0, CallbackBridge.physicalHeight - view.getHeight())
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -393,13 +390,8 @@ public interface ControlInterface extends View.OnLongClickListener, GrabListener
|
||||
setBackground();
|
||||
|
||||
// Re-calculate position
|
||||
if (!getProperties().isDynamicBtn) {
|
||||
getControlView().setX(getControlView().getX());
|
||||
getControlView().setY(getControlView().getY());
|
||||
} else {
|
||||
getControlView().setX(getProperties().insertDynamicPos(getProperties().dynamicX));
|
||||
getControlView().setY(getProperties().insertDynamicPos(getProperties().dynamicY));
|
||||
}
|
||||
getControlView().setX(getControlView().getX());
|
||||
getControlView().setY(getControlView().getY());
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
-1
@@ -26,7 +26,6 @@ public class ControlSubButton extends ControlButton {
|
||||
mProperties.setHeight(parentDrawer.getProperties().getHeight());
|
||||
mProperties.setWidth(parentDrawer.getProperties().getWidth());
|
||||
}
|
||||
mProperties.isDynamicBtn = false;
|
||||
|
||||
setProperties(mProperties, false);
|
||||
}
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.gamepad;
|
||||
|
||||
import net.kdt.pojavlaunch.GrabListener;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
public class DefaultDataProvider implements GamepadDataProvider {
|
||||
public static final DefaultDataProvider INSTANCE = new DefaultDataProvider();
|
||||
|
||||
// Cannot instantiate this class publicly
|
||||
private DefaultDataProvider() {}
|
||||
|
||||
@Override
|
||||
public GamepadMap getGameMap() {
|
||||
return GamepadMapStore.getGameMap();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public GamepadMap getMenuMap() {
|
||||
return GamepadMapStore.getMenuMap();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGrabbing() {
|
||||
return CallbackBridge.isGrabbing();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void attachGrabListener(GrabListener grabListener) {
|
||||
CallbackBridge.addGrabListener(grabListener);
|
||||
}
|
||||
}
|
||||
+52
-32
@@ -19,7 +19,6 @@ import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.FrameLayout;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.Toast;
|
||||
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
import androidx.core.math.MathUtils;
|
||||
@@ -27,7 +26,6 @@ import androidx.core.math.MathUtils;
|
||||
import net.kdt.pojavlaunch.GrabListener;
|
||||
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
import net.kdt.pojavlaunch.R;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
import net.kdt.pojavlaunch.utils.MCOptionUtils;
|
||||
|
||||
@@ -75,12 +73,11 @@ public class Gamepad implements GrabListener, GamepadHandler {
|
||||
private double mMouseAngle;
|
||||
private double mMouseSensitivity = 19;
|
||||
|
||||
private final GamepadMap mGameMap = GamepadMap.getDefaultGameMap();
|
||||
private final GamepadMap mMenuMap = GamepadMap.getDefaultMenuMap();
|
||||
private GamepadMap mCurrentMap = mGameMap;
|
||||
private GamepadMap mGameMap;
|
||||
private GamepadMap mMenuMap;
|
||||
private GamepadMap mCurrentMap;
|
||||
|
||||
// The negation is to force trigger the onGrabState
|
||||
private boolean isGrabbing = !CallbackBridge.isGrabbing();
|
||||
private boolean isGrabbing;
|
||||
|
||||
|
||||
/* Choreographer with time to compute delta on ticking */
|
||||
@@ -91,7 +88,9 @@ public class Gamepad implements GrabListener, GamepadHandler {
|
||||
@SuppressWarnings("FieldCanBeLocal") //the field is used in a WeakReference
|
||||
private final MCOptionUtils.MCOptionListener mGuiScaleListener = () -> notifyGUISizeChange(getMcScale());
|
||||
|
||||
public Gamepad(View contextView, InputDevice inputDevice){
|
||||
private final GamepadDataProvider mMapProvider;
|
||||
|
||||
public Gamepad(View contextView, InputDevice inputDevice, GamepadDataProvider mapProvider, boolean showCursor){
|
||||
Settings.setDeadzoneScale(PREF_DEADZONE_SCALE);
|
||||
|
||||
mScreenChoreographer = Choreographer.getInstance();
|
||||
@@ -120,16 +119,34 @@ public class Gamepad implements GrabListener, GamepadHandler {
|
||||
int size = (int) ((22 * getMcScale()) / mScaleFactor);
|
||||
mPointerImageView.setLayoutParams(new FrameLayout.LayoutParams(size, size));
|
||||
|
||||
mMapProvider = mapProvider;
|
||||
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.windowWidth/2f, CallbackBridge.windowHeight/2f);
|
||||
((ViewGroup)contextView.getParent()).addView(mPointerImageView);
|
||||
|
||||
if(showCursor) {
|
||||
((ViewGroup)contextView.getParent()).addView(mPointerImageView);
|
||||
}
|
||||
|
||||
|
||||
placePointerView(CallbackBridge.physicalWidth/2, CallbackBridge.physicalHeight/2);
|
||||
|
||||
CallbackBridge.addGrabListener(this);
|
||||
reloadGamepadMaps();
|
||||
mMapProvider.attachGrabListener(this);
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void reloadGamepadMaps() {
|
||||
if(mGameMap != null) mGameMap.resetPressedState();
|
||||
if(mMenuMap != null) mMenuMap.resetPressedState();
|
||||
GamepadMapStore.load();
|
||||
mGameMap = mMapProvider.getGameMap();
|
||||
mMenuMap = mMapProvider.getMenuMap();
|
||||
mCurrentMap = mGameMap;
|
||||
// Force state refresh
|
||||
boolean currentGrab = CallbackBridge.isGrabbing();
|
||||
isGrabbing = !currentGrab;
|
||||
onGrabState(currentGrab);
|
||||
}
|
||||
|
||||
public void updateJoysticks(){
|
||||
updateDirectionalJoystick();
|
||||
@@ -144,8 +161,8 @@ public class Gamepad implements GrabListener, GamepadHandler {
|
||||
}
|
||||
|
||||
|
||||
public static void sendInput(int[] keycodes, boolean isDown){
|
||||
for(int keycode : keycodes){
|
||||
public static void sendInput(short[] keycodes, boolean isDown){
|
||||
for(short keycode : keycodes){
|
||||
switch (keycode){
|
||||
case GamepadMap.MOUSE_SCROLL_DOWN:
|
||||
if(isDown) CallbackBridge.sendScroll(0, -1);
|
||||
@@ -153,20 +170,23 @@ public class Gamepad implements GrabListener, GamepadHandler {
|
||||
case GamepadMap.MOUSE_SCROLL_UP:
|
||||
if(isDown) CallbackBridge.sendScroll(0, 1);
|
||||
break;
|
||||
|
||||
case LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT:
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, isDown);
|
||||
break;
|
||||
case LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT:
|
||||
case GamepadMap.MOUSE_LEFT:
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, isDown);
|
||||
break;
|
||||
|
||||
case GamepadMap.MOUSE_MIDDLE:
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_MIDDLE, isDown);
|
||||
break;
|
||||
case GamepadMap.MOUSE_RIGHT:
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, isDown);
|
||||
break;
|
||||
case GamepadMap.UNSPECIFIED:
|
||||
break;
|
||||
|
||||
default:
|
||||
sendKeyPress(keycode, CallbackBridge.getCurrentMods(), isDown);
|
||||
CallbackBridge.setModifiers(keycode, isDown);
|
||||
break;
|
||||
}
|
||||
CallbackBridge.setModifiers(keycode, isDown);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -261,32 +281,32 @@ public class Gamepad implements GrabListener, GamepadHandler {
|
||||
private static void sendDirectionalKeycode(int direction, boolean isDown, GamepadMap map){
|
||||
switch (direction){
|
||||
case DIRECTION_NORTH:
|
||||
sendInput(map.DIRECTION_FORWARD, isDown);
|
||||
map.DIRECTION_FORWARD.update(isDown);
|
||||
break;
|
||||
case DIRECTION_NORTH_EAST:
|
||||
sendInput(map.DIRECTION_FORWARD, isDown);
|
||||
sendInput(map.DIRECTION_RIGHT, isDown);
|
||||
map.DIRECTION_FORWARD.update(isDown);
|
||||
map.DIRECTION_RIGHT.update(isDown);
|
||||
break;
|
||||
case DIRECTION_EAST:
|
||||
sendInput(map.DIRECTION_RIGHT, isDown);
|
||||
map.DIRECTION_RIGHT.update(isDown);
|
||||
break;
|
||||
case DIRECTION_SOUTH_EAST:
|
||||
sendInput(map.DIRECTION_RIGHT, isDown);
|
||||
sendInput(map.DIRECTION_BACKWARD, isDown);
|
||||
map.DIRECTION_RIGHT.update(isDown);
|
||||
map.DIRECTION_BACKWARD.update(isDown);
|
||||
break;
|
||||
case DIRECTION_SOUTH:
|
||||
sendInput(map.DIRECTION_BACKWARD, isDown);
|
||||
map.DIRECTION_BACKWARD.update(isDown);
|
||||
break;
|
||||
case DIRECTION_SOUTH_WEST:
|
||||
sendInput(map.DIRECTION_BACKWARD, isDown);
|
||||
sendInput(map.DIRECTION_LEFT, isDown);
|
||||
map.DIRECTION_BACKWARD.update(isDown);
|
||||
map.DIRECTION_LEFT.update(isDown);
|
||||
break;
|
||||
case DIRECTION_WEST:
|
||||
sendInput(map.DIRECTION_LEFT, isDown);
|
||||
map.DIRECTION_LEFT.update(isDown);
|
||||
break;
|
||||
case DIRECTION_NORTH_WEST:
|
||||
sendInput(map.DIRECTION_FORWARD, isDown);
|
||||
sendInput(map.DIRECTION_LEFT, isDown);
|
||||
map.DIRECTION_FORWARD.update(isDown);
|
||||
map.DIRECTION_LEFT.update(isDown);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
+15
-31
@@ -1,46 +1,30 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.gamepad;
|
||||
|
||||
import android.view.KeyEvent;
|
||||
|
||||
/**
|
||||
* Simple button able to store its state and some properties
|
||||
* This class corresponds to a button that does exist on the gamepad
|
||||
*/
|
||||
public class GamepadButton {
|
||||
|
||||
public int[] keycodes;
|
||||
public class GamepadButton extends GamepadEmulatedButton {
|
||||
public boolean isToggleable = false;
|
||||
private boolean mIsDown = false;
|
||||
private boolean mIsToggled = false;
|
||||
|
||||
public void update(KeyEvent event){
|
||||
boolean isKeyDown = (event.getAction() == KeyEvent.ACTION_DOWN);
|
||||
update(isKeyDown);
|
||||
}
|
||||
|
||||
public void update(boolean isKeyDown){
|
||||
if(isKeyDown != mIsDown){
|
||||
mIsDown = isKeyDown;
|
||||
if(isToggleable){
|
||||
if(isKeyDown){
|
||||
mIsToggled = !mIsToggled;
|
||||
Gamepad.sendInput(keycodes, mIsToggled);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Gamepad.sendInput(keycodes, mIsDown);
|
||||
@Override
|
||||
protected void onDownStateChanged(boolean isDown) {
|
||||
if(isToggleable && isDown){
|
||||
mIsToggled = !mIsToggled;
|
||||
Gamepad.sendInput(keycodes, mIsToggled);
|
||||
return;
|
||||
}
|
||||
super.onDownStateChanged(isDown);
|
||||
}
|
||||
|
||||
public void resetButtonState(){
|
||||
if(mIsDown || mIsToggled){
|
||||
@Override
|
||||
public void resetButtonState() {
|
||||
if(!mIsDown && mIsToggled) {
|
||||
Gamepad.sendInput(keycodes, false);
|
||||
mIsToggled = false;
|
||||
} else {
|
||||
super.resetButtonState();
|
||||
}
|
||||
mIsDown = false;
|
||||
mIsToggled = false;
|
||||
}
|
||||
|
||||
public boolean isDown(){
|
||||
return isToggleable ? mIsToggled : mIsDown;
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.gamepad;
|
||||
|
||||
import net.kdt.pojavlaunch.GrabListener;
|
||||
|
||||
public interface GamepadDataProvider {
|
||||
GamepadMap getMenuMap();
|
||||
GamepadMap getGameMap();
|
||||
boolean isGrabbing();
|
||||
void attachGrabListener(GrabListener grabListener);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.gamepad;
|
||||
|
||||
import android.view.KeyEvent;
|
||||
|
||||
/**
|
||||
* This class corresponds to a button that does not physically exist on the gamepad, but is
|
||||
* emulated from other inputs on it (like WASD directional keys)
|
||||
*/
|
||||
public class GamepadEmulatedButton {
|
||||
public short[] keycodes;
|
||||
protected boolean mIsDown = false;
|
||||
|
||||
public void update(KeyEvent event) {
|
||||
boolean isKeyDown = (event.getAction() == KeyEvent.ACTION_DOWN);
|
||||
update(isKeyDown);
|
||||
}
|
||||
|
||||
public void update(boolean isKeyDown){
|
||||
if(isKeyDown != mIsDown){
|
||||
mIsDown = isKeyDown;
|
||||
onDownStateChanged(mIsDown);
|
||||
}
|
||||
}
|
||||
|
||||
public void resetButtonState() {
|
||||
if(mIsDown) Gamepad.sendInput(keycodes, false);
|
||||
mIsDown = false;
|
||||
}
|
||||
|
||||
protected void onDownStateChanged(boolean isDown) {
|
||||
Gamepad.sendInput(keycodes, mIsDown);
|
||||
}
|
||||
}
|
||||
+102
-86
@@ -4,8 +4,16 @@ import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
|
||||
public class GamepadMap {
|
||||
|
||||
public static final int MOUSE_SCROLL_DOWN = -1;
|
||||
public static final int MOUSE_SCROLL_UP = -2;
|
||||
|
||||
public static final short MOUSE_SCROLL_DOWN = -1;
|
||||
public static final short MOUSE_SCROLL_UP = -2;
|
||||
// Made mouse keycodes their own specials because managing special keycodes above 0
|
||||
// proved to be complicated
|
||||
public static final short MOUSE_LEFT = -3;
|
||||
public static final short MOUSE_MIDDLE = -4;
|
||||
public static final short MOUSE_RIGHT = -5;
|
||||
// Workaround, because GLFW_KEY_UNKNOWN and GLFW_MOUSE_BUTTON_LEFT are both 0
|
||||
public static final short UNSPECIFIED = -6;
|
||||
|
||||
/*
|
||||
This class is just here to store the mapping
|
||||
@@ -14,33 +22,11 @@ public class GamepadMap {
|
||||
Be warned, you should define ALL keys if you want to avoid a non defined exception
|
||||
*/
|
||||
|
||||
public final GamepadButton BUTTON_A = new GamepadButton();
|
||||
public final GamepadButton BUTTON_B = new GamepadButton();
|
||||
public final GamepadButton BUTTON_X = new GamepadButton();
|
||||
public final GamepadButton BUTTON_Y = new GamepadButton();
|
||||
|
||||
public final GamepadButton BUTTON_START = new GamepadButton();
|
||||
public final GamepadButton BUTTON_SELECT = new GamepadButton();
|
||||
|
||||
public final GamepadButton TRIGGER_RIGHT = new GamepadButton(); //R2
|
||||
public final GamepadButton TRIGGER_LEFT = new GamepadButton(); //L2
|
||||
|
||||
public final GamepadButton SHOULDER_RIGHT = new GamepadButton(); //R1
|
||||
public final GamepadButton SHOULDER_LEFT = new GamepadButton(); //L1
|
||||
|
||||
public int[] DIRECTION_FORWARD;
|
||||
public int[] DIRECTION_BACKWARD;
|
||||
public int[] DIRECTION_RIGHT;
|
||||
public int[] DIRECTION_LEFT;
|
||||
|
||||
public final GamepadButton THUMBSTICK_RIGHT = new GamepadButton(); //R3
|
||||
public final GamepadButton THUMBSTICK_LEFT = new GamepadButton(); //L3
|
||||
|
||||
public final GamepadButton DPAD_UP = new GamepadButton();
|
||||
public final GamepadButton DPAD_RIGHT = new GamepadButton();
|
||||
public final GamepadButton DPAD_DOWN = new GamepadButton();
|
||||
public final GamepadButton DPAD_LEFT = new GamepadButton();
|
||||
public GamepadButton BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y, BUTTON_START, BUTTON_SELECT,
|
||||
TRIGGER_RIGHT, TRIGGER_LEFT, SHOULDER_RIGHT, SHOULDER_LEFT, THUMBSTICK_RIGHT,
|
||||
THUMBSTICK_LEFT, DPAD_UP, DPAD_DOWN, DPAD_RIGHT, DPAD_LEFT;
|
||||
|
||||
public GamepadEmulatedButton DIRECTION_FORWARD, DIRECTION_BACKWARD, DIRECTION_RIGHT, DIRECTION_LEFT;
|
||||
|
||||
/*
|
||||
* Sets all buttons to a not pressed state, sending an input if needed
|
||||
@@ -70,39 +56,70 @@ public class GamepadMap {
|
||||
|
||||
}
|
||||
|
||||
private static GamepadMap createAndInitializeButtons() {
|
||||
GamepadMap gamepadMap = new GamepadMap();
|
||||
gamepadMap.BUTTON_A = new GamepadButton();
|
||||
gamepadMap.BUTTON_B = new GamepadButton();
|
||||
gamepadMap.BUTTON_X = new GamepadButton();
|
||||
gamepadMap.BUTTON_Y = new GamepadButton();
|
||||
|
||||
gamepadMap.BUTTON_START = new GamepadButton();
|
||||
gamepadMap.BUTTON_SELECT = new GamepadButton();
|
||||
|
||||
gamepadMap.TRIGGER_RIGHT = new GamepadButton();
|
||||
gamepadMap.TRIGGER_LEFT = new GamepadButton();
|
||||
|
||||
gamepadMap.SHOULDER_RIGHT = new GamepadButton();
|
||||
gamepadMap.SHOULDER_LEFT = new GamepadButton();
|
||||
|
||||
gamepadMap.DIRECTION_FORWARD = new GamepadEmulatedButton();
|
||||
gamepadMap.DIRECTION_BACKWARD = new GamepadEmulatedButton();
|
||||
gamepadMap.DIRECTION_RIGHT = new GamepadEmulatedButton();
|
||||
gamepadMap.DIRECTION_LEFT = new GamepadEmulatedButton();
|
||||
|
||||
gamepadMap.THUMBSTICK_RIGHT = new GamepadButton();
|
||||
gamepadMap.THUMBSTICK_LEFT = new GamepadButton();
|
||||
|
||||
gamepadMap.DPAD_UP = new GamepadButton();
|
||||
gamepadMap.DPAD_RIGHT = new GamepadButton();
|
||||
gamepadMap.DPAD_DOWN = new GamepadButton();
|
||||
gamepadMap.DPAD_LEFT = new GamepadButton();
|
||||
return gamepadMap;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns a pre-done mapping used when the mouse is grabbed by the game.
|
||||
*/
|
||||
public static GamepadMap getDefaultGameMap(){
|
||||
GamepadMap gameMap = new GamepadMap();
|
||||
GamepadMap gameMap = GamepadMap.createEmptyMap();
|
||||
|
||||
gameMap.BUTTON_A.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_SPACE};
|
||||
gameMap.BUTTON_B.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_Q};
|
||||
gameMap.BUTTON_X.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_E};
|
||||
gameMap.BUTTON_Y.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_F};
|
||||
gameMap.BUTTON_A.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_SPACE;
|
||||
gameMap.BUTTON_B.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_Q;
|
||||
gameMap.BUTTON_X.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_E;
|
||||
gameMap.BUTTON_Y.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_F;
|
||||
|
||||
gameMap.DIRECTION_FORWARD = new int[]{LwjglGlfwKeycode.GLFW_KEY_W};
|
||||
gameMap.DIRECTION_BACKWARD = new int[]{LwjglGlfwKeycode.GLFW_KEY_S};
|
||||
gameMap.DIRECTION_RIGHT = new int[]{LwjglGlfwKeycode.GLFW_KEY_D};
|
||||
gameMap.DIRECTION_LEFT = new int[]{LwjglGlfwKeycode.GLFW_KEY_A};
|
||||
gameMap.DIRECTION_FORWARD.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_W;
|
||||
gameMap.DIRECTION_BACKWARD.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_S;
|
||||
gameMap.DIRECTION_RIGHT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_D;
|
||||
gameMap.DIRECTION_LEFT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_A;
|
||||
|
||||
gameMap.DPAD_UP.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT};
|
||||
gameMap.DPAD_DOWN.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_O}; //For mods ?
|
||||
gameMap.DPAD_RIGHT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_K}; //For mods ?
|
||||
gameMap.DPAD_LEFT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_J}; //For mods ?
|
||||
gameMap.DPAD_UP.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT;
|
||||
gameMap.DPAD_DOWN.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_O; //For mods ?
|
||||
gameMap.DPAD_RIGHT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_K; //For mods ?
|
||||
gameMap.DPAD_LEFT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_J; //For mods ?
|
||||
|
||||
gameMap.SHOULDER_LEFT.keycodes = new int[]{GamepadMap.MOUSE_SCROLL_UP};
|
||||
gameMap.SHOULDER_RIGHT.keycodes = new int[]{GamepadMap.MOUSE_SCROLL_DOWN};
|
||||
gameMap.SHOULDER_LEFT.keycodes[0] = GamepadMap.MOUSE_SCROLL_UP;
|
||||
gameMap.SHOULDER_RIGHT.keycodes[0] = GamepadMap.MOUSE_SCROLL_DOWN;
|
||||
|
||||
gameMap.TRIGGER_LEFT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT};
|
||||
gameMap.TRIGGER_RIGHT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT};
|
||||
gameMap.TRIGGER_LEFT.keycodes[0] = GamepadMap.MOUSE_RIGHT;
|
||||
gameMap.TRIGGER_RIGHT.keycodes[0] = GamepadMap.MOUSE_LEFT;
|
||||
|
||||
gameMap.THUMBSTICK_LEFT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL};
|
||||
gameMap.THUMBSTICK_RIGHT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT};
|
||||
gameMap.THUMBSTICK_LEFT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL;
|
||||
gameMap.THUMBSTICK_RIGHT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT;
|
||||
gameMap.THUMBSTICK_RIGHT.isToggleable = true;
|
||||
|
||||
gameMap.BUTTON_START.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_ESCAPE};
|
||||
gameMap.BUTTON_SELECT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_TAB};
|
||||
gameMap.BUTTON_START.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_ESCAPE;
|
||||
gameMap.BUTTON_SELECT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_TAB;
|
||||
|
||||
return gameMap;
|
||||
}
|
||||
@@ -111,64 +128,63 @@ public class GamepadMap {
|
||||
* Returns a pre-done mapping used when the mouse is NOT grabbed by the game.
|
||||
*/
|
||||
public static GamepadMap getDefaultMenuMap(){
|
||||
GamepadMap menuMap = new GamepadMap();
|
||||
GamepadMap menuMap = GamepadMap.createEmptyMap();
|
||||
|
||||
menuMap.BUTTON_A.keycodes = new int[]{LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT};
|
||||
menuMap.BUTTON_B.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_ESCAPE};
|
||||
menuMap.BUTTON_X.keycodes = new int[]{LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT};
|
||||
menuMap.BUTTON_Y.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT, LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT}; //Oops, doesn't work since left shift isn't properly applied.
|
||||
menuMap.BUTTON_A.keycodes[0] = GamepadMap.MOUSE_LEFT;
|
||||
menuMap.BUTTON_B.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_ESCAPE;
|
||||
menuMap.BUTTON_X.keycodes[0] = GamepadMap.MOUSE_RIGHT;
|
||||
{
|
||||
short[] keycodes = menuMap.BUTTON_Y.keycodes;
|
||||
keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT;
|
||||
keycodes[1] = GamepadMap.MOUSE_RIGHT;
|
||||
}
|
||||
|
||||
menuMap.DIRECTION_FORWARD = new int[]{GamepadMap.MOUSE_SCROLL_UP, GamepadMap.MOUSE_SCROLL_UP, GamepadMap.MOUSE_SCROLL_UP, GamepadMap.MOUSE_SCROLL_UP, GamepadMap.MOUSE_SCROLL_UP};
|
||||
menuMap.DIRECTION_BACKWARD = new int[]{GamepadMap.MOUSE_SCROLL_DOWN, GamepadMap.MOUSE_SCROLL_DOWN, GamepadMap.MOUSE_SCROLL_DOWN, GamepadMap.MOUSE_SCROLL_DOWN, GamepadMap.MOUSE_SCROLL_DOWN};
|
||||
menuMap.DIRECTION_RIGHT = new int[]{};
|
||||
menuMap.DIRECTION_LEFT = new int[]{};
|
||||
{
|
||||
short[] keycodes = menuMap.DIRECTION_FORWARD.keycodes;
|
||||
keycodes[0] = keycodes[1] = keycodes[2] = keycodes[3] = GamepadMap.MOUSE_SCROLL_UP;
|
||||
}
|
||||
{
|
||||
short[] keycodes = menuMap.DIRECTION_BACKWARD.keycodes;
|
||||
keycodes[0] = keycodes[1] = keycodes[2] = keycodes[3] = GamepadMap.MOUSE_SCROLL_DOWN;
|
||||
}
|
||||
|
||||
menuMap.DPAD_UP.keycodes = new int[]{};
|
||||
menuMap.DPAD_DOWN.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_O}; //For mods ?
|
||||
menuMap.DPAD_RIGHT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_K}; //For mods ?
|
||||
menuMap.DPAD_LEFT.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_J}; //For mods ?
|
||||
menuMap.DPAD_DOWN.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_O; //For mods ?
|
||||
menuMap.DPAD_RIGHT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_K; //For mods ?
|
||||
menuMap.DPAD_LEFT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_J; //For mods ?
|
||||
|
||||
menuMap.SHOULDER_LEFT.keycodes = new int[]{GamepadMap.MOUSE_SCROLL_UP};
|
||||
menuMap.SHOULDER_RIGHT.keycodes = new int[]{GamepadMap.MOUSE_SCROLL_DOWN};
|
||||
menuMap.SHOULDER_LEFT.keycodes[0] = GamepadMap.MOUSE_SCROLL_UP;
|
||||
menuMap.SHOULDER_RIGHT.keycodes[0] = GamepadMap.MOUSE_SCROLL_DOWN;
|
||||
|
||||
menuMap.TRIGGER_LEFT.keycodes = new int[]{};
|
||||
menuMap.TRIGGER_RIGHT.keycodes = new int[]{};
|
||||
|
||||
menuMap.THUMBSTICK_LEFT.keycodes = new int[]{};
|
||||
menuMap.THUMBSTICK_RIGHT.keycodes = new int[]{};
|
||||
|
||||
menuMap.BUTTON_START.keycodes = new int[]{LwjglGlfwKeycode.GLFW_KEY_ESCAPE};
|
||||
menuMap.BUTTON_SELECT.keycodes = new int[]{};
|
||||
menuMap.BUTTON_SELECT.keycodes[0] = LwjglGlfwKeycode.GLFW_KEY_ESCAPE;
|
||||
|
||||
return menuMap;
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns all GamepadButtons, does not include directional keys
|
||||
* Returns all GamepadEmulatedButtons of the controller key map.
|
||||
*/
|
||||
public GamepadButton[] getButtons(){
|
||||
return new GamepadButton[]{ BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y,
|
||||
public GamepadEmulatedButton[] getButtons(){
|
||||
return new GamepadEmulatedButton[]{ BUTTON_A, BUTTON_B, BUTTON_X, BUTTON_Y,
|
||||
BUTTON_SELECT, BUTTON_START,
|
||||
TRIGGER_LEFT, TRIGGER_RIGHT,
|
||||
SHOULDER_LEFT, SHOULDER_RIGHT,
|
||||
THUMBSTICK_LEFT, THUMBSTICK_RIGHT,
|
||||
DPAD_UP, DPAD_RIGHT, DPAD_DOWN, DPAD_LEFT};
|
||||
DPAD_UP, DPAD_RIGHT, DPAD_DOWN, DPAD_LEFT,
|
||||
DIRECTION_FORWARD, DIRECTION_BACKWARD,
|
||||
DIRECTION_LEFT, DIRECTION_RIGHT};
|
||||
}
|
||||
|
||||
/*
|
||||
* Returns an pre-initialized GamepadMap with only empty keycodes
|
||||
*/
|
||||
@SuppressWarnings("unused") public static GamepadMap getEmptyMap(){
|
||||
GamepadMap emptyMap = new GamepadMap();
|
||||
for(GamepadButton button : emptyMap.getButtons())
|
||||
button.keycodes = new int[]{};
|
||||
|
||||
emptyMap.DIRECTION_LEFT = new int[]{};
|
||||
emptyMap.DIRECTION_FORWARD = new int[]{};
|
||||
emptyMap.DIRECTION_RIGHT = new int[]{};
|
||||
emptyMap.DIRECTION_BACKWARD = new int[]{};
|
||||
|
||||
@SuppressWarnings("unused") public static GamepadMap createEmptyMap(){
|
||||
GamepadMap emptyMap = createAndInitializeButtons();
|
||||
for(GamepadEmulatedButton button : emptyMap.getButtons())
|
||||
button.keycodes = new short[] {UNSPECIFIED, UNSPECIFIED, UNSPECIFIED, UNSPECIFIED};
|
||||
return emptyMap;
|
||||
}
|
||||
|
||||
public static String[] getSpecialKeycodeNames() {
|
||||
return new String[] {"UNSPECIFIED", "MOUSE_RIGHT", "MOUSE_MIDDLE", "MOUSE_LEFT", "SCROLL_UP", "SCROLL_DOWN"};
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.gamepad;
|
||||
|
||||
import android.util.Log;
|
||||
|
||||
import com.google.gson.JsonParseException;
|
||||
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.utils.FileUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class GamepadMapStore {
|
||||
private static final File STORE_FILE = new File(Tools.DIR_DATA, "gamepad_map.json");
|
||||
private static GamepadMapStore sMapStore;
|
||||
private GamepadMap mInMenuMap;
|
||||
private GamepadMap mInGameMap;
|
||||
private static GamepadMapStore createDefault() {
|
||||
GamepadMapStore mapStore = new GamepadMapStore();
|
||||
mapStore.mInGameMap = GamepadMap.getDefaultGameMap();
|
||||
mapStore.mInMenuMap = GamepadMap.getDefaultMenuMap();
|
||||
return mapStore;
|
||||
}
|
||||
|
||||
private static void loadIfNecessary() {
|
||||
if(sMapStore == null) return;
|
||||
load();
|
||||
}
|
||||
|
||||
public static void load() {
|
||||
GamepadMapStore mapStore = null;
|
||||
if(STORE_FILE.exists() && STORE_FILE.canRead()) {
|
||||
try {
|
||||
String storeFileContent = Tools.read(STORE_FILE);
|
||||
mapStore = Tools.GLOBAL_GSON.fromJson(storeFileContent, GamepadMapStore.class);
|
||||
} catch (JsonParseException | IOException e) {
|
||||
Log.w("GamepadMapStore", "Map store failed to load!", e);
|
||||
}
|
||||
}
|
||||
if(mapStore == null) mapStore = createDefault();
|
||||
sMapStore = mapStore;
|
||||
}
|
||||
|
||||
public static void save() throws IOException {
|
||||
if(sMapStore == null) throw new RuntimeException("Must load map store first!");
|
||||
FileUtils.ensureParentDirectory(STORE_FILE);
|
||||
String jsonData = Tools.GLOBAL_GSON.toJson(sMapStore);
|
||||
Tools.write(STORE_FILE.getAbsolutePath(), jsonData);
|
||||
}
|
||||
|
||||
public static GamepadMap getGameMap() {
|
||||
loadIfNecessary();
|
||||
return sMapStore.mInGameMap;
|
||||
}
|
||||
|
||||
public static GamepadMap getMenuMap() {
|
||||
loadIfNecessary();
|
||||
return sMapStore.mInMenuMap;
|
||||
}
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.gamepad;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.content.Context;
|
||||
import android.graphics.Color;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.Spinner;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import net.kdt.pojavlaunch.EfficientAndroidLWJGLKeycode;
|
||||
import net.kdt.pojavlaunch.GrabListener;
|
||||
import net.kdt.pojavlaunch.R;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
|
||||
import android.widget.TextView;
|
||||
|
||||
public class GamepadMapperAdapter extends RecyclerView.Adapter<GamepadMapperAdapter.ViewHolder> implements GamepadDataProvider {
|
||||
private static final int BUTTON_COUNT = 20;
|
||||
|
||||
private GamepadMap mSimulatedGamepadMap;
|
||||
private RebinderButton[] mRebinderButtons;
|
||||
private GamepadEmulatedButton[] mRealButtons;
|
||||
private final ArrayAdapter<String> mKeyAdapter;
|
||||
private final int mSpecialKeycodeCount;
|
||||
private GrabListener mGamepadGrabListener;
|
||||
private boolean mGrabState = false;
|
||||
private boolean mOldState = false;
|
||||
|
||||
public GamepadMapperAdapter(Context context) {
|
||||
GamepadMapStore.load();
|
||||
mKeyAdapter = new ArrayAdapter<>(context, R.layout.item_centered_textview_large);
|
||||
String[] specialKeycodeNames = GamepadMap.getSpecialKeycodeNames();
|
||||
mSpecialKeycodeCount = specialKeycodeNames.length;
|
||||
mKeyAdapter.addAll(specialKeycodeNames);
|
||||
mKeyAdapter.addAll(EfficientAndroidLWJGLKeycode.generateKeyName());
|
||||
createRebinderMap();
|
||||
updateRealButtons();
|
||||
}
|
||||
|
||||
private void createRebinderMap() {
|
||||
mRebinderButtons = new RebinderButton[BUTTON_COUNT];
|
||||
mRealButtons = new GamepadEmulatedButton[BUTTON_COUNT];
|
||||
mSimulatedGamepadMap = new GamepadMap();
|
||||
int index = 0;
|
||||
mSimulatedGamepadMap.BUTTON_A = mRebinderButtons[index++] = new RebinderButton(R.drawable.button_a, R.string.controller_button_a);
|
||||
mSimulatedGamepadMap.BUTTON_B = mRebinderButtons[index++] = new RebinderButton(R.drawable.button_b, R.string.controller_button_b);
|
||||
mSimulatedGamepadMap.BUTTON_X = mRebinderButtons[index++] = new RebinderButton(R.drawable.button_x, R.string.controller_button_x);
|
||||
mSimulatedGamepadMap.BUTTON_Y = mRebinderButtons[index++] = new RebinderButton(R.drawable.button_y, R.string.controller_button_y);
|
||||
mSimulatedGamepadMap.BUTTON_START = mRebinderButtons[index++] = new RebinderButton(R.drawable.button_start, R.string.controller_button_start);
|
||||
mSimulatedGamepadMap.BUTTON_SELECT = mRebinderButtons[index++] = new RebinderButton(R.drawable.button_select, R.string.controller_button_select);
|
||||
mSimulatedGamepadMap.TRIGGER_RIGHT = mRebinderButtons[index++] = new RebinderButton(R.drawable.trigger_right, R.string.controller_button_trigger_right);
|
||||
mSimulatedGamepadMap.TRIGGER_LEFT = mRebinderButtons[index++] = new RebinderButton(R.drawable.trigger_left, R.string.controller_button_trigger_left);
|
||||
mSimulatedGamepadMap.SHOULDER_RIGHT = mRebinderButtons[index++] = new RebinderButton(R.drawable.shoulder_right, R.string.controller_button_shoulder_right);
|
||||
mSimulatedGamepadMap.SHOULDER_LEFT = mRebinderButtons[index++] = new RebinderButton(R.drawable.shoulder_left, R.string.controller_button_shoulder_left);
|
||||
mSimulatedGamepadMap.DIRECTION_FORWARD = mRebinderButtons[index++] = new RebinderButton(R.drawable.stick_right, R.string.controller_direction_forward);
|
||||
mSimulatedGamepadMap.DIRECTION_RIGHT = mRebinderButtons[index++] = new RebinderButton(R.drawable.stick_right, R.string.controller_direction_right);
|
||||
mSimulatedGamepadMap.DIRECTION_LEFT = mRebinderButtons[index++] = new RebinderButton(R.drawable.stick_right, R.string.controller_direction_left);
|
||||
mSimulatedGamepadMap.DIRECTION_BACKWARD = mRebinderButtons[index++] = new RebinderButton(R.drawable.stick_right, R.string.controller_direction_backward);
|
||||
mSimulatedGamepadMap.THUMBSTICK_RIGHT = mRebinderButtons[index++] = new RebinderButton(R.drawable.stick_right_click, R.string.controller_stick_press_r);
|
||||
mSimulatedGamepadMap.THUMBSTICK_LEFT = mRebinderButtons[index++] = new RebinderButton(R.drawable.stick_left_click, R.string.controller_stick_press_l);
|
||||
mSimulatedGamepadMap.DPAD_UP = mRebinderButtons[index++] = new RebinderButton(R.drawable.dpad_up, R.string.controller_dpad_up);
|
||||
mSimulatedGamepadMap.DPAD_DOWN = mRebinderButtons[index++] = new RebinderButton(R.drawable.dpad_down, R.string.controller_dpad_down);
|
||||
mSimulatedGamepadMap.DPAD_RIGHT = mRebinderButtons[index++] = new RebinderButton(R.drawable.dpad_right, R.string.controller_dpad_right);
|
||||
mSimulatedGamepadMap.DPAD_LEFT = mRebinderButtons[index] = new RebinderButton(R.drawable.dpad_left, R.string.controller_dpad_left);
|
||||
}
|
||||
|
||||
private void updateRealButtons() {
|
||||
GamepadMap currentRealMap = mGrabState ? GamepadMapStore.getGameMap() : GamepadMapStore.getMenuMap();
|
||||
int index = 0;
|
||||
mRealButtons[index++] = currentRealMap.BUTTON_A;
|
||||
mRealButtons[index++] = currentRealMap.BUTTON_B;
|
||||
mRealButtons[index++] = currentRealMap.BUTTON_X;
|
||||
mRealButtons[index++] = currentRealMap.BUTTON_Y;
|
||||
mRealButtons[index++] = currentRealMap.BUTTON_START;
|
||||
mRealButtons[index++] = currentRealMap.BUTTON_SELECT;
|
||||
mRealButtons[index++] = currentRealMap.TRIGGER_RIGHT;
|
||||
mRealButtons[index++] = currentRealMap.TRIGGER_LEFT;
|
||||
mRealButtons[index++] = currentRealMap.SHOULDER_RIGHT;
|
||||
mRealButtons[index++] = currentRealMap.SHOULDER_LEFT;
|
||||
mRealButtons[index++] = currentRealMap.DIRECTION_FORWARD;
|
||||
mRealButtons[index++] = currentRealMap.DIRECTION_RIGHT;
|
||||
mRealButtons[index++] = currentRealMap.DIRECTION_LEFT;
|
||||
mRealButtons[index++] = currentRealMap.DIRECTION_BACKWARD;
|
||||
mRealButtons[index++] = currentRealMap.THUMBSTICK_RIGHT;
|
||||
mRealButtons[index++] = currentRealMap.THUMBSTICK_LEFT;
|
||||
mRealButtons[index++] = currentRealMap.DPAD_UP;
|
||||
mRealButtons[index++] = currentRealMap.DPAD_DOWN;
|
||||
mRealButtons[index++] = currentRealMap.DPAD_RIGHT;
|
||||
mRealButtons[index] = currentRealMap.DPAD_LEFT;
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
|
||||
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
|
||||
View view = layoutInflater.inflate(R.layout.item_controller_mapping, parent, false);
|
||||
return new ViewHolder(view);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
|
||||
holder.attach(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewRecycled(@NonNull ViewHolder holder) {
|
||||
super.onViewRecycled(holder);
|
||||
holder.detach();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return mRebinderButtons.length;
|
||||
}
|
||||
|
||||
private void updateStickIcons() {
|
||||
// Which stick is used for keyboard emulation depends on grab state, so we need
|
||||
// to update the mapper UI icons accordingly
|
||||
int stickIcon = mGrabState ? R.drawable.stick_left : R.drawable.stick_right;
|
||||
((RebinderButton)mSimulatedGamepadMap.DIRECTION_FORWARD).iconResourceId = stickIcon;
|
||||
((RebinderButton)mSimulatedGamepadMap.DIRECTION_BACKWARD).iconResourceId = stickIcon;
|
||||
((RebinderButton)mSimulatedGamepadMap.DIRECTION_RIGHT).iconResourceId = stickIcon;
|
||||
((RebinderButton)mSimulatedGamepadMap.DIRECTION_LEFT).iconResourceId = stickIcon;
|
||||
}
|
||||
|
||||
private static class RebinderButton extends GamepadButton {
|
||||
public int iconResourceId;
|
||||
public final int localeResourceId;
|
||||
private GamepadMapperAdapter.ViewHolder mButtonHolder;
|
||||
|
||||
public RebinderButton(int iconResourceId, int localeResourceId) {
|
||||
this.iconResourceId = iconResourceId;
|
||||
this.localeResourceId = localeResourceId;
|
||||
}
|
||||
|
||||
public void changeViewHolder(GamepadMapperAdapter.ViewHolder viewHolder) {
|
||||
mButtonHolder = viewHolder;
|
||||
if(mButtonHolder != null) mButtonHolder.setPressed(mIsDown);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDownStateChanged(boolean isDown) {
|
||||
if(mButtonHolder == null) return;
|
||||
mButtonHolder.setPressed(isDown);
|
||||
}
|
||||
}
|
||||
|
||||
public class ViewHolder extends RecyclerView.ViewHolder implements AdapterView.OnItemSelectedListener, View.OnClickListener {
|
||||
private static final int COLOR_ACTIVE_BUTTON = 0x2000FF00;
|
||||
private final Context mContext;
|
||||
private final ImageView mButtonIcon;
|
||||
private final ImageView mExpansionIndicator;
|
||||
private final Spinner[] mKeySpinners;
|
||||
private final View mExpandedView;
|
||||
private final TextView mKeycodeLabel;
|
||||
private int mAttachedPosition = -1;
|
||||
private short[] mKeycodes;
|
||||
|
||||
public ViewHolder(@NonNull View itemView) {
|
||||
super(itemView);
|
||||
mContext = itemView.getContext();
|
||||
mButtonIcon = itemView.findViewById(R.id.controller_mapper_button);
|
||||
mExpandedView = itemView.findViewById(R.id.controller_mapper_expanded_view);
|
||||
mExpansionIndicator = itemView.findViewById(R.id.controller_mapper_expand_button);
|
||||
mKeycodeLabel = itemView.findViewById(R.id.controller_mapper_keycode_label);
|
||||
View defaultView = itemView.findViewById(R.id.controller_mapper_default_view);
|
||||
defaultView.setOnClickListener(this);
|
||||
mKeySpinners = new Spinner[4];
|
||||
mKeySpinners[0] = itemView.findViewById(R.id.controller_mapper_key_spinner1);
|
||||
mKeySpinners[1] = itemView.findViewById(R.id.controller_mapper_key_spinner2);
|
||||
mKeySpinners[2] = itemView.findViewById(R.id.controller_mapper_key_spinner3);
|
||||
mKeySpinners[3] = itemView.findViewById(R.id.controller_mapper_key_spinner4);
|
||||
for(Spinner spinner : mKeySpinners) {
|
||||
spinner.setAdapter(mKeyAdapter);
|
||||
spinner.setOnItemSelectedListener(this);
|
||||
}
|
||||
}
|
||||
private void attach(int index) {
|
||||
RebinderButton rebinderButton = mRebinderButtons[index];
|
||||
mExpandedView.setVisibility(View.GONE);
|
||||
mButtonIcon.setImageResource(rebinderButton.iconResourceId);
|
||||
String buttonName = mContext.getString(rebinderButton.localeResourceId);
|
||||
mButtonIcon.setContentDescription(buttonName);
|
||||
rebinderButton.changeViewHolder(this);
|
||||
|
||||
GamepadEmulatedButton realButton = mRealButtons[index];
|
||||
|
||||
mKeycodes = realButton.keycodes;
|
||||
|
||||
int spinnerIndex;
|
||||
|
||||
// Populate spinners with known keycodes until we run out of keycodes
|
||||
for(spinnerIndex = 0; spinnerIndex < mKeycodes.length; spinnerIndex++) {
|
||||
Spinner keySpinner = mKeySpinners[spinnerIndex];
|
||||
keySpinner.setEnabled(true);
|
||||
short keyCode = mKeycodes[spinnerIndex];
|
||||
int selected;
|
||||
if(keyCode < 0) selected = keyCode + mSpecialKeycodeCount;
|
||||
else selected = EfficientAndroidLWJGLKeycode.getIndexByValue(keyCode) + mSpecialKeycodeCount;
|
||||
keySpinner.setSelection(selected);
|
||||
}
|
||||
// In case if there is too much spinners, disable the rest of them
|
||||
for(;spinnerIndex < mKeySpinners.length; spinnerIndex++) {
|
||||
mKeySpinners[spinnerIndex].setEnabled(false);
|
||||
}
|
||||
updateKeycodeLabel();
|
||||
|
||||
mAttachedPosition = index;
|
||||
}
|
||||
private void detach() {
|
||||
mRebinderButtons[mAttachedPosition].changeViewHolder(null);
|
||||
mAttachedPosition = -1;
|
||||
}
|
||||
private void setPressed(boolean pressed) {
|
||||
itemView.setBackgroundColor(pressed ? COLOR_ACTIVE_BUTTON : Color.TRANSPARENT);
|
||||
}
|
||||
|
||||
private void updateKeycodeLabel() {
|
||||
StringBuilder labelBuilder = new StringBuilder();
|
||||
boolean first = true;
|
||||
int unspecifiedPosition = GamepadMap.UNSPECIFIED + mSpecialKeycodeCount;
|
||||
for (Spinner keySpinner : mKeySpinners) {
|
||||
if (keySpinner.getSelectedItemPosition() == unspecifiedPosition) continue;
|
||||
if (!first) labelBuilder.append(" + ");
|
||||
else first = false;
|
||||
labelBuilder.append(keySpinner.getSelectedItem().toString());
|
||||
}
|
||||
if(labelBuilder.length() == 0) labelBuilder.append(mKeyAdapter.getItem(unspecifiedPosition));
|
||||
mKeycodeLabel.setText(labelBuilder.toString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> adapterView, View view, int selectionIndex, long selectionId) {
|
||||
if(mAttachedPosition == -1) return;
|
||||
int editedKeycodeIndex = -1;
|
||||
for(int i = 0; i < mKeySpinners.length && i < mKeycodes.length; i++) {
|
||||
if(!adapterView.equals(mKeySpinners[i])) continue;
|
||||
editedKeycodeIndex = i;
|
||||
break;
|
||||
}
|
||||
if(editedKeycodeIndex == -1) return;
|
||||
int keycode_offset = selectionIndex - mSpecialKeycodeCount;
|
||||
if(selectionIndex <= mSpecialKeycodeCount) mKeycodes[editedKeycodeIndex] = (short) (keycode_offset);
|
||||
else mKeycodes[editedKeycodeIndex] = EfficientAndroidLWJGLKeycode.getValueByIndex(keycode_offset);
|
||||
updateKeycodeLabel();
|
||||
try {
|
||||
GamepadMapStore.save();
|
||||
}catch (Exception e) {
|
||||
Tools.showError(adapterView.getContext(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> adapterView) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
int visibility = mExpandedView.getVisibility();
|
||||
switch (visibility) {
|
||||
case View.INVISIBLE:
|
||||
case View.GONE:
|
||||
mExpansionIndicator.setRotation(0);
|
||||
mExpandedView.setVisibility(View.VISIBLE);
|
||||
break;
|
||||
case View.VISIBLE:
|
||||
mExpansionIndicator.setRotation(180);
|
||||
mExpandedView.setVisibility(View.GONE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public GamepadMap getMenuMap() {
|
||||
return mSimulatedGamepadMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public GamepadMap getGameMap() {
|
||||
return mSimulatedGamepadMap;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isGrabbing() {
|
||||
return mGrabState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void attachGrabListener(GrabListener grabListener) {
|
||||
mGamepadGrabListener = grabListener;
|
||||
grabListener.onGrabState(mGrabState);
|
||||
}
|
||||
|
||||
// Cannot do it another way
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
public void setGrabState(boolean newState) {
|
||||
mGrabState = newState;
|
||||
if(mGamepadGrabListener != null) mGamepadGrabListener.onGrabState(newState);
|
||||
if(mGrabState == mOldState) return;
|
||||
updateRealButtons();
|
||||
updateStickIcons();
|
||||
notifyDataSetChanged();
|
||||
mOldState = mGrabState;
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
public interface AbstractTouchpad {
|
||||
/**
|
||||
* Get the supposed display state of the mouse (whether it should be shown when the user is in a GUI)
|
||||
* Note that this does *not* reflect the actual visibility state of the mouse
|
||||
* @return current supposed enabled state
|
||||
*/
|
||||
boolean getDisplayState();
|
||||
|
||||
/**
|
||||
* Apply a motion vector to the mouse in form of a two-entry float array. This will move the mouse
|
||||
* on the screen and send the new cursor position to the game.
|
||||
* @param vector the array that contains the vector
|
||||
*/
|
||||
default void applyMotionVector(float[] vector) {
|
||||
applyMotionVector(vector[0], vector[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a motion vector to the mouse in form of the separate X/Y coordinates. This will move the mouse
|
||||
* on the screen and send the new cursor position to the game.
|
||||
* @param x the relative X coordinate of the vector
|
||||
* @param y the relative Y coordinate for the vector
|
||||
*/
|
||||
void applyMotionVector(float x, float y);
|
||||
|
||||
/**
|
||||
* Sets the state of the touchpad to "enabled"
|
||||
* @param supposed if set to true, this will set the supposed display state to enabled but may not
|
||||
* affect the touchpad until internal conditions are met
|
||||
* if set to false it will turn the touchpad on regardless of internal conditions
|
||||
*/
|
||||
void enable(boolean supposed);
|
||||
/**
|
||||
* Sets the state of the touchpad to "disabled".
|
||||
*/
|
||||
void disable();
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.os.Build;
|
||||
import android.view.InputDevice;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewTreeObserver;
|
||||
|
||||
import androidx.annotation.RequiresApi;
|
||||
|
||||
import net.kdt.pojavlaunch.MainActivity;
|
||||
import net.kdt.pojavlaunch.MinecraftGLSurface;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
@RequiresApi(api = Build.VERSION_CODES.O)
|
||||
public class AndroidPointerCapture implements ViewTreeObserver.OnWindowFocusChangeListener, View.OnCapturedPointerListener {
|
||||
private static final float TOUCHPAD_SCROLL_THRESHOLD = 1;
|
||||
private final AbstractTouchpad mTouchpad;
|
||||
private final View mHostView;
|
||||
private final float mScaleFactor;
|
||||
private final float mMousePrescale = Tools.dpToPx(1);
|
||||
private final PointerTracker mPointerTracker = new PointerTracker();
|
||||
private final Scroller mScroller = new Scroller(TOUCHPAD_SCROLL_THRESHOLD);
|
||||
private final float[] mVector = mPointerTracker.getMotionVector();
|
||||
|
||||
private int mInputDeviceIdentifier;
|
||||
private boolean mDeviceSupportsRelativeAxis;
|
||||
|
||||
public AndroidPointerCapture(AbstractTouchpad touchpad, View hostView, float scaleFactor) {
|
||||
this.mScaleFactor = scaleFactor;
|
||||
this.mTouchpad = touchpad;
|
||||
this.mHostView = hostView;
|
||||
hostView.setOnCapturedPointerListener(this);
|
||||
hostView.getViewTreeObserver().addOnWindowFocusChangeListener(this);
|
||||
}
|
||||
|
||||
private void enableTouchpadIfNecessary() {
|
||||
if(!mTouchpad.getDisplayState()) mTouchpad.enable(true);
|
||||
}
|
||||
|
||||
public void handleAutomaticCapture() {
|
||||
if(!mHostView.hasWindowFocus()) {
|
||||
mHostView.requestFocus();
|
||||
} else {
|
||||
mHostView.requestPointerCapture();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCapturedPointer(View view, MotionEvent event) {
|
||||
checkSameDevice(event.getDevice());
|
||||
// Yes, we actually not only receive relative mouse events here, but also absolute touchpad ones!
|
||||
// Therefore, we need to know when it's a touchpad and when it's a mouse.
|
||||
|
||||
if((event.getSource() & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
|
||||
// If the source claims to be a relative device by belonging to the trackball class,
|
||||
// use its coordinates directly.
|
||||
if(mDeviceSupportsRelativeAxis) {
|
||||
// If some OEM decides to do a funny and make an absolute touchpad report itself as
|
||||
// a trackball, we will at least have semi-valid relative positions
|
||||
mVector[0] = event.getAxisValue(MotionEvent.AXIS_RELATIVE_X);
|
||||
mVector[1] = event.getAxisValue(MotionEvent.AXIS_RELATIVE_Y);
|
||||
}else {
|
||||
// Otherwise trust the OS, i guess??
|
||||
mVector[0] = event.getX();
|
||||
mVector[1] = event.getY();
|
||||
}
|
||||
}else {
|
||||
// If it's not a trackball, it's likely a touchpad and needs tracking like a touchscreen.
|
||||
mPointerTracker.trackEvent(event);
|
||||
// The relative position will already be written down into the mVector variable.
|
||||
}
|
||||
|
||||
if(!CallbackBridge.isGrabbing()) {
|
||||
enableTouchpadIfNecessary();
|
||||
// Yes, if the user's touchpad is multi-touch we will also receive events for that.
|
||||
// So, handle the scrolling gesture ourselves.
|
||||
mVector[0] *= mMousePrescale;
|
||||
mVector[1] *= mMousePrescale;
|
||||
if(event.getPointerCount() < 2) {
|
||||
mTouchpad.applyMotionVector(mVector);
|
||||
mScroller.resetScrollOvershoot();
|
||||
} else {
|
||||
mScroller.performScroll(mVector);
|
||||
}
|
||||
} else {
|
||||
// Position is updated by many events, hence it is send regardless of the event value
|
||||
CallbackBridge.mouseX += (mVector[0] * mScaleFactor);
|
||||
CallbackBridge.mouseY += (mVector[1] * mScaleFactor);
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
}
|
||||
|
||||
switch (event.getActionMasked()) {
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
return true;
|
||||
case MotionEvent.ACTION_BUTTON_PRESS:
|
||||
return MinecraftGLSurface.sendMouseButtonUnconverted(event.getActionButton(), true);
|
||||
case MotionEvent.ACTION_BUTTON_RELEASE:
|
||||
return MinecraftGLSurface.sendMouseButtonUnconverted(event.getActionButton(), false);
|
||||
case MotionEvent.ACTION_SCROLL:
|
||||
CallbackBridge.sendScroll(
|
||||
event.getAxisValue(MotionEvent.AXIS_HSCROLL),
|
||||
event.getAxisValue(MotionEvent.AXIS_VSCROLL)
|
||||
);
|
||||
return true;
|
||||
case MotionEvent.ACTION_UP:
|
||||
mPointerTracker.cancelTracking();
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void checkSameDevice(InputDevice inputDevice) {
|
||||
int newIdentifier = inputDevice.getId();
|
||||
if(mInputDeviceIdentifier != newIdentifier) {
|
||||
reinitializeDeviceSpecificProperties(inputDevice);
|
||||
mInputDeviceIdentifier = newIdentifier;
|
||||
}
|
||||
}
|
||||
|
||||
private void reinitializeDeviceSpecificProperties(InputDevice inputDevice) {
|
||||
mPointerTracker.cancelTracking();
|
||||
boolean relativeXSupported = inputDevice.getMotionRange(MotionEvent.AXIS_RELATIVE_X) != null;
|
||||
boolean relativeYSupported = inputDevice.getMotionRange(MotionEvent.AXIS_RELATIVE_Y) != null;
|
||||
mDeviceSupportsRelativeAxis = relativeXSupported && relativeYSupported;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onWindowFocusChanged(boolean hasFocus) {
|
||||
if(hasFocus && MainActivity.isAndroid8OrHigher()) mHostView.requestPointerCapture();
|
||||
}
|
||||
|
||||
public void detach() {
|
||||
mHostView.setOnCapturedPointerListener(null);
|
||||
mHostView.getViewTreeObserver().removeOnWindowFocusChangeListener(this);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import static org.lwjgl.glfw.CallbackBridge.sendKeyPress;
|
||||
|
||||
import android.os.Handler;
|
||||
|
||||
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
|
||||
public class DropGesture implements Runnable{
|
||||
private final Handler mHandler;
|
||||
private boolean mActive;
|
||||
|
||||
public DropGesture(Handler mHandler) {
|
||||
this.mHandler = mHandler;
|
||||
}
|
||||
|
||||
public void submit() {
|
||||
if(!mActive) {
|
||||
mActive = true;
|
||||
mHandler.postDelayed(this, LauncherPreferences.PREF_LONGPRESS_TRIGGER);
|
||||
}
|
||||
}
|
||||
|
||||
public void cancel() {
|
||||
mActive = false;
|
||||
mHandler.removeCallbacks(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if(!mActive) return;
|
||||
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q);
|
||||
mHandler.postDelayed(this, 250);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
@@ -10,6 +10,7 @@ import android.view.OrientationEventListener;
|
||||
import android.view.Surface;
|
||||
import android.view.WindowManager;
|
||||
|
||||
import net.kdt.pojavlaunch.GrabListener;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.content.Context;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.view.ViewGroup;
|
||||
import android.view.ViewParent;
|
||||
|
||||
import androidx.annotation.Nullable;
|
||||
|
||||
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
import net.kdt.pojavlaunch.utils.MCOptionUtils;
|
||||
import net.kdt.pojavlaunch.utils.MathUtils;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
public class HotbarView extends View implements MCOptionUtils.MCOptionListener, View.OnLayoutChangeListener, Runnable {
|
||||
private final TapDetector mDoubleTapDetector = new TapDetector(2, TapDetector.DETECTION_METHOD_DOWN);
|
||||
private View mParentView;
|
||||
private static final int[] HOTBAR_KEYS = {
|
||||
LwjglGlfwKeycode.GLFW_KEY_1, LwjglGlfwKeycode.GLFW_KEY_2, LwjglGlfwKeycode.GLFW_KEY_3,
|
||||
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 float mScaleFactor = LauncherPreferences.PREF_SCALE_FACTOR/100f;
|
||||
private int mWidth;
|
||||
private int mLastIndex;
|
||||
private int mGuiScale;
|
||||
|
||||
public HotbarView(Context context) {
|
||||
super(context);
|
||||
initialize();
|
||||
}
|
||||
|
||||
public HotbarView(Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
initialize();
|
||||
}
|
||||
|
||||
public HotbarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
|
||||
super(context, attrs, defStyleAttr);
|
||||
initialize();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused") // You suggested me this constructor, Android
|
||||
public HotbarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
|
||||
super(context, attrs, defStyleAttr, defStyleRes);
|
||||
initialize();
|
||||
}
|
||||
|
||||
private void initialize() {
|
||||
MCOptionUtils.addMCOptionListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onAttachedToWindow() {
|
||||
super.onAttachedToWindow();
|
||||
ViewParent parent = getParent();
|
||||
if(parent == null) return;
|
||||
if(parent instanceof View) {
|
||||
mParentView = (View) parent;
|
||||
mParentView.addOnLayoutChangeListener(this);
|
||||
}
|
||||
mGuiScale = MCOptionUtils.getMcScale();
|
||||
repositionView();
|
||||
}
|
||||
|
||||
private void repositionView() {
|
||||
ViewGroup.LayoutParams layoutParams = getLayoutParams();
|
||||
if(!(layoutParams instanceof ViewGroup.MarginLayoutParams))
|
||||
throw new RuntimeException("Incorrect LayoutParams type, expected ViewGroup.MarginLayoutParams");
|
||||
ViewGroup.MarginLayoutParams marginLayoutParams = (ViewGroup.MarginLayoutParams) layoutParams;
|
||||
int height;
|
||||
marginLayoutParams.width = mWidth = mcScale(180);
|
||||
marginLayoutParams.height = height = mcScale(20);
|
||||
marginLayoutParams.leftMargin = (CallbackBridge.physicalWidth / 2) - (mWidth / 2);
|
||||
marginLayoutParams.topMargin = CallbackBridge.physicalHeight - height;
|
||||
setLayoutParams(marginLayoutParams);
|
||||
}
|
||||
|
||||
@SuppressWarnings("ClickableViewAccessibility") // performClick does not report coordinates.
|
||||
@Override
|
||||
public boolean onTouchEvent(MotionEvent event) {
|
||||
if(!CallbackBridge.isGrabbing()) return false;
|
||||
boolean hasDoubleTapped = mDoubleTapDetector.onTouchEvent(event);
|
||||
|
||||
// Check if we need to cancel the drop event
|
||||
int actionMasked = event.getActionMasked();
|
||||
if(isLastEventInGesture(actionMasked)) mDropGesture.cancel();
|
||||
else mDropGesture.submit();
|
||||
// Determine the hotbar slot
|
||||
float x = event.getX();
|
||||
if(x < 0 || x > mWidth) {
|
||||
// If out of bounds, cancel the hotbar gesture to avoid dropping items on last hotbar slots
|
||||
mDropGesture.cancel();
|
||||
return true;
|
||||
}
|
||||
int hotbarIndex = (int)MathUtils.map(x, 0, mWidth, 0, HOTBAR_KEYS.length);
|
||||
// Check if the slot changed and we need to make a key press
|
||||
if(hotbarIndex == mLastIndex) {
|
||||
// Only check for doubletapping if the slot has not changed
|
||||
if(hasDoubleTapped && !LauncherPreferences.PREF_DISABLE_SWAP_HAND) CallbackBridge.sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_F);
|
||||
return true;
|
||||
}
|
||||
mLastIndex = hotbarIndex;
|
||||
int hotbarKey = HOTBAR_KEYS[hotbarIndex];
|
||||
CallbackBridge.sendKeyPress(hotbarKey);
|
||||
// Cancel the event since we changed hotbar slots.
|
||||
mDropGesture.cancel();
|
||||
// Only resubmit the gesture only if it isn't the last event we will receive.
|
||||
if(!isLastEventInGesture(actionMasked)) mDropGesture.submit();
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean isLastEventInGesture(int actionMasked) {
|
||||
return actionMasked == MotionEvent.ACTION_UP || actionMasked == MotionEvent.ACTION_CANCEL;
|
||||
}
|
||||
|
||||
private int mcScale(int input) {
|
||||
return (int)((mGuiScale * input)/ mScaleFactor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onOptionChanged() {
|
||||
post(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
if(getParent() == null) return;
|
||||
int scale = MCOptionUtils.getMcScale();
|
||||
if(scale == mGuiScale) return;
|
||||
mGuiScale = scale;
|
||||
repositionView();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
|
||||
// We need to check whether dimensions match or not because here we are looking specifically for changes of dimensions
|
||||
// and Android keeps calling this without dimensions actually changing for some reason.
|
||||
if(v.equals(mParentView) && (left != oldLeft || right != oldRight || top != oldTop || bottom != oldBottom)) {
|
||||
// Need to post this, because it is not correct to resize the view
|
||||
// during a layout pass.
|
||||
post(this::repositionView);
|
||||
}
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.view.GestureDetector;
|
||||
import android.view.MotionEvent;
|
||||
|
||||
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
import net.kdt.pojavlaunch.SingleTapConfirm;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
public class InGUIEventProcessor implements TouchEventProcessor {
|
||||
public static final float FINGER_SCROLL_THRESHOLD = Tools.dpToPx(6);
|
||||
public static final float FINGER_STILL_THRESHOLD = Tools.dpToPx(5);
|
||||
|
||||
private final PointerTracker mTracker = new PointerTracker();
|
||||
private final TapDetector mSingleTapDetector;
|
||||
private AbstractTouchpad mTouchpad;
|
||||
private boolean mIsMouseDown = false;
|
||||
private float mStartX, mStartY;
|
||||
private final float mScaleFactor;
|
||||
private final Scroller mScroller = new Scroller(FINGER_SCROLL_THRESHOLD);
|
||||
|
||||
public InGUIEventProcessor(float scaleFactor) {
|
||||
mSingleTapDetector = new TapDetector(1, TapDetector.DETECTION_METHOD_BOTH);
|
||||
mScaleFactor = scaleFactor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processTouchEvent(MotionEvent motionEvent) {
|
||||
boolean singleTap = mSingleTapDetector.onTouchEvent(motionEvent);
|
||||
|
||||
switch (motionEvent.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mTracker.startTracking(motionEvent);
|
||||
if(!touchpadDisplayed()) {
|
||||
sendTouchCoordinates(motionEvent.getX(), motionEvent.getY());
|
||||
|
||||
// disabled gestures means no scrolling possible, send gesture early
|
||||
if (LauncherPreferences.PREF_DISABLE_GESTURES) enableMouse();
|
||||
else setGestureStart(motionEvent);
|
||||
}
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
int pointerCount = motionEvent.getPointerCount();
|
||||
int pointerIndex = mTracker.trackEvent(motionEvent);
|
||||
if(pointerCount == 1 || LauncherPreferences.PREF_DISABLE_GESTURES) {
|
||||
if(touchpadDisplayed()) {
|
||||
mTouchpad.applyMotionVector(mTracker.getMotionVector());
|
||||
} else {
|
||||
float mainPointerX = motionEvent.getX(pointerIndex);
|
||||
float mainPointerY = motionEvent.getY(pointerIndex);
|
||||
sendTouchCoordinates(mainPointerX, mainPointerY);
|
||||
|
||||
if(!mIsMouseDown) {
|
||||
if(!hasGestureStarted()) setGestureStart(motionEvent);
|
||||
if(!LeftClickGesture.isFingerStill(mStartX, mStartY, FINGER_STILL_THRESHOLD))
|
||||
enableMouse();
|
||||
}
|
||||
|
||||
}
|
||||
} else mScroller.performScroll(mTracker.getMotionVector());
|
||||
break;
|
||||
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
case MotionEvent.ACTION_UP:
|
||||
mScroller.resetScrollOvershoot();
|
||||
mTracker.cancelTracking();
|
||||
|
||||
// Handle single tap on gestures
|
||||
if((!LauncherPreferences.PREF_DISABLE_GESTURES || touchpadDisplayed()) && !mIsMouseDown && singleTap) {
|
||||
CallbackBridge.putMouseEventWithCoords(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
}
|
||||
|
||||
if(mIsMouseDown) disableMouse();
|
||||
resetGesture();
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean touchpadDisplayed() {
|
||||
return mTouchpad != null && mTouchpad.getDisplayState();
|
||||
}
|
||||
|
||||
public void setAbstractTouchpad(AbstractTouchpad touchpad) {
|
||||
mTouchpad = touchpad;
|
||||
}
|
||||
|
||||
private void sendTouchCoordinates(float x, float y) {
|
||||
CallbackBridge.sendCursorPos( x * mScaleFactor, y * mScaleFactor);
|
||||
}
|
||||
|
||||
private void enableMouse() {
|
||||
CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true);
|
||||
mIsMouseDown = true;
|
||||
}
|
||||
|
||||
private void disableMouse() {
|
||||
CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false);
|
||||
mIsMouseDown = false;
|
||||
}
|
||||
|
||||
private void setGestureStart(MotionEvent event) {
|
||||
mStartX = event.getX() * mScaleFactor;
|
||||
mStartY = event.getY() * mScaleFactor;
|
||||
}
|
||||
|
||||
private void resetGesture() {
|
||||
mStartX = mStartY = -1;
|
||||
}
|
||||
|
||||
private boolean hasGestureStarted() {
|
||||
return mStartX != -1 || mStartY != -1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelPendingActions() {
|
||||
mScroller.resetScrollOvershoot();
|
||||
disableMouse();
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.MotionEvent;
|
||||
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
public class InGameEventProcessor implements TouchEventProcessor {
|
||||
private final Handler mGestureHandler = new Handler(Looper.getMainLooper());
|
||||
private final double mSensitivity;
|
||||
private boolean mEventTransitioned = true;
|
||||
private final PointerTracker mTracker = new PointerTracker();
|
||||
private final LeftClickGesture mLeftClickGesture = new LeftClickGesture(mGestureHandler);
|
||||
private final RightClickGesture mRightClickGesture = new RightClickGesture(mGestureHandler);
|
||||
|
||||
public InGameEventProcessor(double sensitivity) {
|
||||
mSensitivity = sensitivity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean processTouchEvent(MotionEvent motionEvent) {
|
||||
switch (motionEvent.getActionMasked()) {
|
||||
case MotionEvent.ACTION_DOWN:
|
||||
mTracker.startTracking(motionEvent);
|
||||
if(LauncherPreferences.PREF_DISABLE_GESTURES) break;
|
||||
mEventTransitioned = false;
|
||||
checkGestures();
|
||||
break;
|
||||
case MotionEvent.ACTION_MOVE:
|
||||
mTracker.trackEvent(motionEvent);
|
||||
float[] motionVector = mTracker.getMotionVector();
|
||||
CallbackBridge.mouseX += motionVector[0] * mSensitivity;
|
||||
CallbackBridge.mouseY += motionVector[1] * mSensitivity;
|
||||
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
|
||||
if(LauncherPreferences.PREF_DISABLE_GESTURES) break;
|
||||
checkGestures();
|
||||
break;
|
||||
case MotionEvent.ACTION_UP:
|
||||
case MotionEvent.ACTION_CANCEL:
|
||||
mTracker.cancelTracking();
|
||||
cancelGestures(false);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelPendingActions() {
|
||||
cancelGestures(true);
|
||||
}
|
||||
|
||||
private void checkGestures() {
|
||||
mLeftClickGesture.inputEvent();
|
||||
// Only register right click events if it's a fresh event stream, not one after a transition.
|
||||
// This is done to avoid problems when people hold the button for just a bit too long after
|
||||
// exiting a menu for example.
|
||||
if(!mEventTransitioned) mRightClickGesture.inputEvent();
|
||||
}
|
||||
|
||||
private void cancelGestures(boolean isSwitching) {
|
||||
mEventTransitioned = true;
|
||||
mLeftClickGesture.cancel(isSwitching);
|
||||
mRightClickGesture.cancel(isSwitching);
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import static org.lwjgl.glfw.CallbackBridge.sendMouseButton;
|
||||
|
||||
import android.os.Handler;
|
||||
|
||||
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
import net.kdt.pojavlaunch.utils.MathUtils;
|
||||
|
||||
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 boolean mMouseActivated;
|
||||
|
||||
public LeftClickGesture(Handler handler) {
|
||||
super(handler, LauncherPreferences.PREF_LONGPRESS_TRIGGER);
|
||||
}
|
||||
|
||||
public final void inputEvent() {
|
||||
if(submit()) {
|
||||
mGestureStartX = CallbackBridge.mouseX;
|
||||
mGestureStartY = CallbackBridge.mouseY;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean checkAndTrigger() {
|
||||
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, FINGER_STILL_THRESHOLD);
|
||||
// If the finger is still, fire the gesture.
|
||||
if(fingerStill) {
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true);
|
||||
mMouseActivated = true;
|
||||
}
|
||||
// Otherwise, don't click but still keep it active
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGestureCancelled(boolean isSwitching) {
|
||||
if(mMouseActivated) {
|
||||
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false);
|
||||
mMouseActivated = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the finger is still when compared to mouseX/mouseY in CallbackBridge.
|
||||
* @param startX the starting X of the gesture
|
||||
* @param startY the starting Y of the gesture
|
||||
* @return whether the finger's position counts as "still" or not
|
||||
*/
|
||||
public static boolean isFingerStill(float startX, float startY, float threshold) {
|
||||
return MathUtils.dist(
|
||||
CallbackBridge.mouseX,
|
||||
CallbackBridge.mouseY,
|
||||
startX,
|
||||
startY
|
||||
) <= threshold;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.view.MotionEvent;
|
||||
|
||||
public class PointerTracker {
|
||||
private boolean mColdStart = true;
|
||||
private int mTrackedPointerId;
|
||||
private int mPointerCount;
|
||||
private float mLastX, mLastY;
|
||||
private final float[] mMotionVector = new float[2];
|
||||
|
||||
public void startTracking(MotionEvent motionEvent) {
|
||||
mColdStart = false;
|
||||
mTrackedPointerId = motionEvent.getPointerId(0);
|
||||
mPointerCount = motionEvent.getPointerCount();
|
||||
mLastX = motionEvent.getX();
|
||||
mLastY = motionEvent.getY();
|
||||
}
|
||||
|
||||
public void cancelTracking() {
|
||||
mColdStart = true;
|
||||
}
|
||||
|
||||
public int trackEvent(MotionEvent motionEvent) {
|
||||
int trackedPointerIndex = motionEvent.findPointerIndex(mTrackedPointerId);
|
||||
int pointerCount = motionEvent.getPointerCount();
|
||||
if(trackedPointerIndex == -1 || mPointerCount != pointerCount || mColdStart) {
|
||||
startTracking(motionEvent);
|
||||
trackedPointerIndex = 0;
|
||||
}
|
||||
float trackedX = motionEvent.getX(trackedPointerIndex);
|
||||
float trackedY = motionEvent.getY(trackedPointerIndex);
|
||||
mMotionVector[0] = trackedX - mLastX;
|
||||
mMotionVector[1] = trackedY - mLastY;
|
||||
mLastX = trackedX;
|
||||
mLastY = trackedY;
|
||||
return trackedPointerIndex;
|
||||
}
|
||||
|
||||
public float[] getMotionVector() {
|
||||
return mMotionVector;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.os.Handler;
|
||||
|
||||
import net.kdt.pojavlaunch.LwjglGlfwKeycode;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
public class RightClickGesture extends ValidatorGesture{
|
||||
private boolean mGestureEnabled = true;
|
||||
private boolean mGestureValid = true;
|
||||
private float mGestureStartX, mGestureStartY;
|
||||
public RightClickGesture(Handler mHandler) {
|
||||
super(mHandler, 150);
|
||||
}
|
||||
|
||||
public final void inputEvent() {
|
||||
if(!mGestureEnabled) return;
|
||||
if(submit()) {
|
||||
mGestureStartX = CallbackBridge.mouseX;
|
||||
mGestureStartY = CallbackBridge.mouseY;
|
||||
mGestureEnabled = false;
|
||||
mGestureValid = true;
|
||||
}
|
||||
}
|
||||
|
||||
@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.
|
||||
mGestureValid = false;
|
||||
// Never call onGestureCancelled. This way we will be able to reserve that only for when
|
||||
// the gesture is stopped in the code (when the user lets go of the screen or the tap was
|
||||
// cancelled by turning on the grab)
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGestureCancelled(boolean isSwitching) {
|
||||
mGestureEnabled = true;
|
||||
if(!mGestureValid || isSwitching) return;
|
||||
boolean fingerStill = LeftClickGesture.isFingerStill(mGestureStartX, mGestureStartY, LeftClickGesture.FINGER_STILL_THRESHOLD);
|
||||
if(!fingerStill) return;
|
||||
CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, true);
|
||||
CallbackBridge.sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, false);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
public class Scroller {
|
||||
|
||||
private float mScrollOvershootH, mScrollOvershootV;
|
||||
private final float mScrollThreshold;
|
||||
|
||||
public Scroller(float mScrollThreshold) {
|
||||
this.mScrollThreshold = mScrollThreshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a scrolling gesture.
|
||||
* @param dx the X coordinate of the primary pointer's vector
|
||||
* @param dy the Y coordinate of the primary pointer's vector
|
||||
*/
|
||||
public void performScroll(float dx, float dy) {
|
||||
float hScroll = (dx / mScrollThreshold) + mScrollOvershootH;
|
||||
float vScroll = (dy / mScrollThreshold) + mScrollOvershootV;
|
||||
int hScrollRound = (int) hScroll, vScrollRound = (int) vScroll;
|
||||
if(hScrollRound != 0 || vScrollRound != 0) CallbackBridge.sendScroll(hScroll, vScroll);
|
||||
mScrollOvershootH = hScroll - hScrollRound;
|
||||
mScrollOvershootV = vScroll - vScrollRound;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform a scrolling gesture.
|
||||
* @param vector a 2-component vector that stores the relative position of the primary pointer.
|
||||
*/
|
||||
public void performScroll(float[] vector) {
|
||||
performScroll(vector[0], vector[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset scroll overshoot values. Scroll overshoot makes the scrolling feel less
|
||||
* choppy, but will cause anomailes if not reset on the end of a scrolling gesture.
|
||||
*/
|
||||
public void resetScrollOvershoot() {
|
||||
mScrollOvershootH = mScrollOvershootV = 0f;
|
||||
}
|
||||
}
|
||||
+13
-5
@@ -1,4 +1,4 @@
|
||||
package net.kdt.pojavlaunch;
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.view.MotionEvent;
|
||||
|
||||
@@ -7,6 +7,8 @@ import static android.view.MotionEvent.ACTION_POINTER_DOWN;
|
||||
import static android.view.MotionEvent.ACTION_POINTER_UP;
|
||||
import static android.view.MotionEvent.ACTION_UP;
|
||||
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
|
||||
/**
|
||||
* Class aiming at better detecting X-tap events regardless of the POINTERS
|
||||
* Only uses the least amount of events possible,
|
||||
@@ -18,9 +20,9 @@ public class TapDetector {
|
||||
public final static int DETECTION_METHOD_UP = 0x2;
|
||||
public final static int DETECTION_METHOD_BOTH = 0x3; //Unused for now
|
||||
|
||||
private final static int TAP_MIN_DELTA_MS = 10;
|
||||
private final static int TAP_MIN_DELTA_MS = -1;
|
||||
private final static int TAP_MAX_DELTA_MS = 300;
|
||||
private final static int TAP_SLOP_SQUARE_PX = (int) Math.pow(Tools.dpToPx(100), 2);
|
||||
private final static int TAP_SLOP_SQUARE_PX = (int) Tools.dpToPx(2500);
|
||||
|
||||
private final int mTapNumberToDetect;
|
||||
private int mCurrentTapNumber = 0;
|
||||
@@ -81,8 +83,14 @@ public class TapDetector {
|
||||
if(mCurrentTapNumber > 0){
|
||||
if ((deltaTime < TAP_MIN_DELTA_MS || deltaTime > TAP_MAX_DELTA_MS) ||
|
||||
((deltaX*deltaX + deltaY*deltaY) > TAP_SLOP_SQUARE_PX)) {
|
||||
// We invalidate previous taps, not this one though
|
||||
mCurrentTapNumber = 0;
|
||||
if (mDetectionMethod == DETECTION_METHOD_BOTH && (eventAction == ACTION_UP || eventAction == ACTION_POINTER_UP)) {
|
||||
// For the both method, the user is expected to start with a down action.
|
||||
resetTapDetectionState();
|
||||
return false;
|
||||
} else {
|
||||
// We invalidate previous taps, not this one though
|
||||
mCurrentTapNumber = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.view.MotionEvent;
|
||||
|
||||
public interface TouchEventProcessor {
|
||||
boolean processTouchEvent(MotionEvent motionEvent);
|
||||
void cancelPendingActions();
|
||||
}
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
|
||||
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.os.Build;
|
||||
import android.util.AttributeSet;
|
||||
import android.view.View;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.core.content.res.ResourcesCompat;
|
||||
|
||||
import net.kdt.pojavlaunch.GrabListener;
|
||||
import net.kdt.pojavlaunch.R;
|
||||
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
|
||||
|
||||
import org.lwjgl.glfw.CallbackBridge;
|
||||
|
||||
/**
|
||||
* Class dealing with the virtual mouse
|
||||
*/
|
||||
public class Touchpad extends View implements GrabListener, AbstractTouchpad {
|
||||
/* Whether the Touchpad should be displayed */
|
||||
private boolean mDisplayState;
|
||||
/* Mouse pointer icon used by the touchpad */
|
||||
private Drawable mMousePointerDrawable;
|
||||
private float mMouseX, mMouseY;
|
||||
/* Resolution scaler option, allow downsizing a window */
|
||||
private final float mScaleFactor = DEFAULT_PREF.getInt("resolutionRatio",100)/100f;
|
||||
public Touchpad(@NonNull Context context) {
|
||||
this(context, null);
|
||||
}
|
||||
|
||||
public Touchpad(@NonNull Context context, @Nullable AttributeSet attrs) {
|
||||
super(context, attrs);
|
||||
init();
|
||||
}
|
||||
|
||||
/** Enable the touchpad */
|
||||
private void _enable(){
|
||||
setVisibility(VISIBLE);
|
||||
placeMouseAt(currentDisplayMetrics.widthPixels / 2f, currentDisplayMetrics.heightPixels / 2f);
|
||||
}
|
||||
|
||||
/** Disable the touchpad and hides the mouse */
|
||||
private void _disable(){
|
||||
setVisibility(GONE);
|
||||
}
|
||||
|
||||
/** @return The new state, enabled or disabled */
|
||||
public boolean switchState(){
|
||||
mDisplayState = !mDisplayState;
|
||||
if(!CallbackBridge.isGrabbing()) {
|
||||
if(mDisplayState) _enable();
|
||||
else _disable();
|
||||
}
|
||||
return mDisplayState;
|
||||
}
|
||||
|
||||
public void placeMouseAt(float x, float y) {
|
||||
mMouseX = x;
|
||||
mMouseY = y;
|
||||
updateMousePosition();
|
||||
}
|
||||
|
||||
private void sendMousePosition() {
|
||||
CallbackBridge.sendCursorPos((mMouseX * mScaleFactor), (mMouseY * mScaleFactor));
|
||||
}
|
||||
|
||||
private void updateMousePosition() {
|
||||
sendMousePosition();
|
||||
// I wanted to implement a dirty rect for this, but it is ignored since API level 21
|
||||
// (which is our min API)
|
||||
// Let's hope the "internally calculated area" is good enough.
|
||||
invalidate();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onDraw(Canvas canvas) {
|
||||
canvas.translate(mMouseX, mMouseY);
|
||||
mMousePointerDrawable.draw(canvas);
|
||||
}
|
||||
|
||||
private void init(){
|
||||
// Setup mouse pointer
|
||||
mMousePointerDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_mouse_pointer, getContext().getTheme());
|
||||
// For some reason it's annotated as Nullable even though it doesn't seem to actually
|
||||
// ever return null
|
||||
assert mMousePointerDrawable != null;
|
||||
mMousePointerDrawable.setBounds(
|
||||
0, 0,
|
||||
(int) (36 / 100f * LauncherPreferences.PREF_MOUSESCALE),
|
||||
(int) (54 / 100f * LauncherPreferences.PREF_MOUSESCALE)
|
||||
);
|
||||
setFocusable(false);
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
setDefaultFocusHighlightEnabled(false);
|
||||
}
|
||||
|
||||
// When the game is grabbing, we should not display the mouse
|
||||
disable();
|
||||
mDisplayState = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onGrabState(boolean isGrabbing) {
|
||||
post(()->updateGrabState(isGrabbing));
|
||||
}
|
||||
private void updateGrabState(boolean isGrabbing) {
|
||||
if(!isGrabbing) {
|
||||
if(mDisplayState && getVisibility() != VISIBLE) _enable();
|
||||
if(!mDisplayState && getVisibility() == VISIBLE) _disable();
|
||||
}else{
|
||||
if(getVisibility() != View.GONE) _disable();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getDisplayState() {
|
||||
return mDisplayState;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyMotionVector(float x, float y) {
|
||||
mMouseX = Math.max(0, Math.min(currentDisplayMetrics.widthPixels, mMouseX + x * LauncherPreferences.PREF_MOUSESPEED));
|
||||
mMouseY = Math.max(0, Math.min(currentDisplayMetrics.heightPixels, mMouseY + y * LauncherPreferences.PREF_MOUSESPEED));
|
||||
updateMousePosition();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enable(boolean supposed) {
|
||||
if(mDisplayState) return;
|
||||
mDisplayState = true;
|
||||
if(supposed && CallbackBridge.isGrabbing()) return;
|
||||
_enable();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
if(!mDisplayState) return;
|
||||
mDisplayState = false;
|
||||
_disable();
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package net.kdt.pojavlaunch.customcontrols.mouse;
|
||||
|
||||
import android.os.Handler;
|
||||
|
||||
/**
|
||||
* This class implements an abstract "validator gesture", meant as a base for implementation of
|
||||
* more complex gestures with finger position tracking and such.
|
||||
*/
|
||||
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) {
|
||||
this.mHandler = mHandler;
|
||||
this.mRequiredDuration = mRequiredDuration;
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit the gesture, starting the timer and marking this gesture as "active".
|
||||
* If the gesture was already active, this call will be ignored
|
||||
* @return true if the gesture was submitted, false if the call was ignored
|
||||
*/
|
||||
public final boolean submit() {
|
||||
if(mGestureActive) return false;
|
||||
mHandler.postDelayed(this, mRequiredDuration);
|
||||
mGestureActive = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the gesture, stopping the timer and marking this gesture as "inactive".
|
||||
* If the gesture was already inactive, this call will be ignored.
|
||||
* @param isSwitching true if this gesture was cancelled due to user interaction (the user let go of the finger)
|
||||
* false if this gesture is cancelled due a request from the programmer or the OS.
|
||||
* Note that returning false from checkAndTrigger() counts as user interaction.
|
||||
*/
|
||||
public final void cancel(boolean isSwitching) {
|
||||
if(!mGestureActive) return;
|
||||
mHandler.removeCallbacks(this);
|
||||
onGestureCancelled(isSwitching);
|
||||
mGestureActive = false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void run() {
|
||||
if(checkAndTrigger()) return;
|
||||
mGestureActive = false;
|
||||
onGestureCancelled(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will be called after mRequiredDuration milliseconds, if the gesture was not cancelled.
|
||||
* @return false if you want to mark this gesture as "inactive"
|
||||
* true otherwise
|
||||
*/
|
||||
public abstract boolean checkAndTrigger();
|
||||
|
||||
/**
|
||||
* This method will be called if the gesture was cancelled using the cancel() method or by returning false
|
||||
* from checkAndTrigger().
|
||||
* @param isSwitching true if this gesture was cancelled due to user interaction (the user let go of the finger)
|
||||
* false if this gesture is cancelled due a request from the programmer or the OS.
|
||||
*/
|
||||
public abstract void onGestureCancelled(boolean isSwitching);
|
||||
}
|
||||
+1
@@ -25,6 +25,7 @@ import java.io.File;
|
||||
public class FileSelectorFragment extends Fragment {
|
||||
public static final String TAG = "FileSelectorFragment";
|
||||
public static final String BUNDLE_SELECT_FOLDER = "select_folder";
|
||||
public static final String BUNDLE_SELECT_FILE = "select_file";
|
||||
public static final String BUNDLE_SHOW_FILE = "show_file";
|
||||
public static final String BUNDLE_SHOW_FOLDER = "show_folder";
|
||||
public static final String BUNDLE_ROOT_PATH = "root_path";
|
||||
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package net.kdt.pojavlaunch.fragments;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.view.InputDevice;
|
||||
import android.view.KeyEvent;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import android.widget.AdapterView;
|
||||
import android.widget.ArrayAdapter;
|
||||
import android.widget.Spinner;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
import androidx.annotation.Nullable;
|
||||
import androidx.fragment.app.Fragment;
|
||||
import androidx.recyclerview.widget.LinearLayoutManager;
|
||||
import androidx.recyclerview.widget.RecyclerView;
|
||||
|
||||
import net.kdt.pojavlaunch.R;
|
||||
import net.kdt.pojavlaunch.customcontrols.gamepad.Gamepad;
|
||||
import net.kdt.pojavlaunch.customcontrols.gamepad.GamepadMapperAdapter;
|
||||
|
||||
import fr.spse.gamepad_remapper.RemapperManager;
|
||||
import fr.spse.gamepad_remapper.RemapperView;
|
||||
|
||||
public class GamepadMapperFragment extends Fragment implements
|
||||
View.OnKeyListener, View.OnGenericMotionListener, AdapterView.OnItemSelectedListener {
|
||||
public static final String TAG = "GamepadMapperFragment";
|
||||
private final RemapperView.Builder mRemapperViewBuilder = new RemapperView.Builder(null)
|
||||
.remapA(true)
|
||||
.remapB(true)
|
||||
.remapX(true)
|
||||
.remapY(true)
|
||||
.remapLeftJoystick(true)
|
||||
.remapRightJoystick(true)
|
||||
.remapStart(true)
|
||||
.remapSelect(true)
|
||||
.remapLeftShoulder(true)
|
||||
.remapRightShoulder(true)
|
||||
.remapLeftTrigger(true)
|
||||
.remapRightTrigger(true)
|
||||
.remapDpad(true);
|
||||
private final Handler mExitHandler = new Handler(Looper.getMainLooper());
|
||||
private final Runnable mExitRunnable = () -> {
|
||||
Activity activity = getActivity();
|
||||
if(activity == null) return;
|
||||
activity.onBackPressed();
|
||||
};
|
||||
private RemapperManager mInputManager;
|
||||
private GamepadMapperAdapter mMapperAdapter;
|
||||
private Gamepad mGamepad;
|
||||
public GamepadMapperFragment() {
|
||||
super(R.layout.fragment_controller_remapper);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
RecyclerView buttonRecyclerView = view.findViewById(R.id.gamepad_remapper_recycler);
|
||||
mMapperAdapter = new GamepadMapperAdapter(view.getContext());
|
||||
buttonRecyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
|
||||
buttonRecyclerView.setAdapter(mMapperAdapter);
|
||||
buttonRecyclerView.setOnKeyListener(this);
|
||||
buttonRecyclerView.setOnGenericMotionListener(this);
|
||||
buttonRecyclerView.requestFocus();
|
||||
mInputManager = new RemapperManager(view.getContext(), mRemapperViewBuilder);
|
||||
Spinner grabStateSpinner = view.findViewById(R.id.gamepad_remapper_mode_spinner);
|
||||
ArrayAdapter<String> mGrabStateAdapter = new ArrayAdapter<>(view.getContext(), R.layout.support_simple_spinner_dropdown_item);
|
||||
mGrabStateAdapter.addAll(getString(R.string.customctrl_visibility_in_menus), getString(R.string.customctrl_visibility_ingame));
|
||||
grabStateSpinner.setAdapter(mGrabStateAdapter);
|
||||
grabStateSpinner.setSelection(0);
|
||||
grabStateSpinner.setOnItemSelectedListener(this);
|
||||
}
|
||||
|
||||
private void createGamepad(View mainView, InputDevice inputDevice) {
|
||||
mGamepad = new Gamepad(mainView, inputDevice, mMapperAdapter, false) {
|
||||
@Override
|
||||
public void handleGamepadInput(int keycode, float value) {
|
||||
if(keycode == KeyEvent.KEYCODE_BUTTON_SELECT) {
|
||||
handleExitButton(value > 0.5);
|
||||
}
|
||||
super.handleGamepadInput(keycode, value);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void handleExitButton(boolean isPressed) {
|
||||
if(isPressed) mExitHandler.postDelayed(mExitRunnable, 400);
|
||||
else mExitHandler.removeCallbacks(mExitRunnable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onKey(View view, int i, KeyEvent keyEvent) {
|
||||
View mainView = getView();
|
||||
if(!Gamepad.isGamepadEvent(keyEvent) || mainView == null) return false;
|
||||
if(mGamepad == null) createGamepad(mainView, keyEvent.getDevice());
|
||||
mInputManager.handleKeyEventInput(mainView.getContext(), keyEvent, mGamepad);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onGenericMotion(View view, MotionEvent motionEvent) {
|
||||
View mainView = getView();
|
||||
if(!Gamepad.isGamepadEvent(motionEvent) || mainView == null) return false;
|
||||
if(mGamepad == null) createGamepad(mainView, motionEvent.getDevice());
|
||||
mInputManager.handleMotionEventInput(mainView.getContext(), motionEvent, mGamepad);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
|
||||
boolean grab = i == 1;
|
||||
mMapperAdapter.setGrabState(grab);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onNothingSelected(AdapterView<?> adapterView) {
|
||||
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -14,6 +14,8 @@ import net.kdt.pojavlaunch.extra.ExtraConstants;
|
||||
import net.kdt.pojavlaunch.extra.ExtraCore;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class LocalLoginFragment extends Fragment {
|
||||
public static final String TAG = "LOCAL_LOGIN_FRAGMENT";
|
||||
@@ -33,7 +35,7 @@ public class LocalLoginFragment extends Fragment {
|
||||
ExtraCore.setValue(ExtraConstants.MOJANG_LOGIN_TODO, new String[]{
|
||||
mUsernameEditText.getText().toString(), "" });
|
||||
|
||||
Tools.swapFragment(requireActivity(), MainMenuFragment.class, MainMenuFragment.TAG, false, null);
|
||||
Tools.swapFragment(requireActivity(), MainMenuFragment.class, MainMenuFragment.TAG, null);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -43,10 +45,13 @@ public class LocalLoginFragment extends Fragment {
|
||||
|
||||
String text = mUsernameEditText.getText().toString();
|
||||
|
||||
Pattern pattern = Pattern.compile("[^a-zA-Z0-9_]");
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
return !(text.isEmpty()
|
||||
|| text.length() < 3
|
||||
|| text.length() > 16
|
||||
|| !text.matches("\\w+")
|
||||
|| matcher.find()
|
||||
|| new File(Tools.DIR_ACCOUNT_NEW + "/" + text + ".json").exists()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.extra.ExtraConstants;
|
||||
import net.kdt.pojavlaunch.extra.ExtraCore;
|
||||
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
|
||||
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
|
||||
|
||||
public class MainMenuFragment extends Fragment {
|
||||
public static final String TAG = "MainMenuFragment";
|
||||
@@ -35,6 +34,7 @@ public class MainMenuFragment extends Fragment {
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
Button mNewsButton = view.findViewById(R.id.news_button);
|
||||
Button mDiscordButton = view.findViewById(R.id.discord_button);
|
||||
Button mCustomControlButton = view.findViewById(R.id.custom_control_button);
|
||||
Button mInstallJarButton = view.findViewById(R.id.install_jar_button);
|
||||
Button mShareLogsButton = view.findViewById(R.id.share_logs_button);
|
||||
@@ -44,6 +44,7 @@ public class MainMenuFragment extends Fragment {
|
||||
mVersionSpinner = view.findViewById(R.id.mc_version_spinner);
|
||||
|
||||
mNewsButton.setOnClickListener(v -> Tools.openURL(requireActivity(), Tools.URL_HOME));
|
||||
mDiscordButton.setOnClickListener(v -> Tools.openURL(requireActivity(), getString(R.string.discord_invite)));
|
||||
mCustomControlButton.setOnClickListener(v -> startActivity(new Intent(requireContext(), CustomControlsActivity.class)));
|
||||
mInstallJarButton.setOnClickListener(v -> runInstallerWithConfirmation(false));
|
||||
mInstallJarButton.setOnLongClickListener(v->{
|
||||
@@ -57,7 +58,7 @@ public class MainMenuFragment extends Fragment {
|
||||
mShareLogsButton.setOnClickListener((v) -> shareLog(requireContext()));
|
||||
|
||||
mNewsButton.setOnLongClickListener((v)->{
|
||||
Tools.swapFragment(requireActivity(), SearchModFragment.class, SearchModFragment.TAG, true, null);
|
||||
Tools.swapFragment(requireActivity(), GamepadMapperFragment.class, GamepadMapperFragment.TAG, null);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
+19
-5
@@ -25,6 +25,8 @@ import net.kdt.pojavlaunch.extra.ExtraCore;
|
||||
public class MicrosoftLoginFragment extends Fragment {
|
||||
public static final String TAG = "MICROSOFT_LOGIN_FRAGMENT";
|
||||
private WebView mWebview;
|
||||
// Technically the client is blank (or there is none) when the fragment is initialized
|
||||
private boolean mBlankClient = true;
|
||||
|
||||
@Override
|
||||
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
|
||||
@@ -43,6 +45,7 @@ public class MicrosoftLoginFragment extends Fragment {
|
||||
WebSettings settings = mWebview.getSettings();
|
||||
settings.setJavaScriptEnabled(true);
|
||||
mWebview.setWebViewClient(new WebViewTrackClient());
|
||||
mBlankClient = false;
|
||||
}
|
||||
|
||||
private void startNewSession() {
|
||||
@@ -69,14 +72,25 @@ public class MicrosoftLoginFragment extends Fragment {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onStart() {
|
||||
super.onStart();
|
||||
// If we have switched to a blank client and haven't fully gone though the lifecycle callbacks to restore it,
|
||||
// restore it here.
|
||||
if(mBlankClient) mWebview.setWebViewClient(new WebViewTrackClient());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSaveInstanceState(@NonNull Bundle outState) {
|
||||
// Since the value cannot be null, just creaqte a "blank" client. This is done to not let Android
|
||||
// kill us if something happens after onSaveInstanceState
|
||||
// Since the value cannot be null, just create a "blank" client. This is done to not let Android
|
||||
// kill us if something happens after the state gets saved, when we can't do fragment transitions
|
||||
mWebview.setWebViewClient(new WebViewClient());
|
||||
mWebview.saveState(outState);
|
||||
// For some dumb reason state is saved even when Android won't actually destroy the activity.
|
||||
// Let the fragment know that the client is blank so that we can restore it in onStart()
|
||||
// (it was the earliest lifecycle call actually invoked in this case)
|
||||
mBlankClient = true;
|
||||
super.onSaveInstanceState(outState);
|
||||
// if something happens after this, well, too bad
|
||||
mWebview.saveState(outState);
|
||||
}
|
||||
|
||||
/* Expose webview actions to others */
|
||||
@@ -92,7 +106,7 @@ public class MicrosoftLoginFragment extends Fragment {
|
||||
// Should be captured by the activity to kill the fragment and get
|
||||
ExtraCore.setValue(ExtraConstants.MICROSOFT_LOGIN_TODO, Uri.parse(url));
|
||||
Toast.makeText(view.getContext(), "Login started !", Toast.LENGTH_SHORT).show();
|
||||
Tools.removeCurrentFragment(requireActivity());
|
||||
Tools.backToMainMenu(requireActivity());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
+5
-3
@@ -93,7 +93,7 @@ public class ProfileEditorFragment extends Fragment implements CropperUtils.Crop
|
||||
mSaveButton.setOnClickListener(v -> {
|
||||
ProfileIconCache.dropIcon(mProfileKey);
|
||||
save();
|
||||
Tools.removeCurrentFragment(requireActivity());
|
||||
Tools.backToMainMenu(requireActivity());
|
||||
});
|
||||
|
||||
mDeleteButton.setOnClickListener(v -> {
|
||||
@@ -115,15 +115,17 @@ public class ProfileEditorFragment extends Fragment implements CropperUtils.Crop
|
||||
mValueToConsume = FileSelectorFragment.BUNDLE_SELECT_FOLDER;
|
||||
|
||||
Tools.swapFragment(requireActivity(),
|
||||
FileSelectorFragment.class, FileSelectorFragment.TAG, true, bundle);
|
||||
FileSelectorFragment.class, FileSelectorFragment.TAG, bundle);
|
||||
});
|
||||
|
||||
mControlSelectButton.setOnClickListener(v -> {
|
||||
Bundle bundle = new Bundle(3);
|
||||
bundle.putBoolean(FileSelectorFragment.BUNDLE_SELECT_FOLDER, false);
|
||||
bundle.putString(FileSelectorFragment.BUNDLE_ROOT_PATH, Tools.CTRLMAP_PATH);
|
||||
mValueToConsume = FileSelectorFragment.BUNDLE_SELECT_FILE;
|
||||
|
||||
Tools.swapFragment(requireActivity(),
|
||||
FileSelectorFragment.class, FileSelectorFragment.TAG, true, bundle);
|
||||
FileSelectorFragment.class, FileSelectorFragment.TAG, bundle);
|
||||
});
|
||||
|
||||
// Setup the expendable list behavior
|
||||
|
||||
+6
-6
@@ -20,20 +20,20 @@ public class ProfileTypeSelectFragment extends Fragment {
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
view.findViewById(R.id.vanilla_profile).setOnClickListener(v -> Tools.swapFragment(requireActivity(), ProfileEditorFragment.class,
|
||||
ProfileEditorFragment.TAG, false, new Bundle(1)));
|
||||
ProfileEditorFragment.TAG, new Bundle(1)));
|
||||
|
||||
// NOTE: Special care needed! If you wll decide to add these to the back stack, please read
|
||||
// the comment in FabricInstallFragment.onDownloadFinished() and amend the code
|
||||
// in FabricInstallFragment.onDownloadFinished() and ModVersionListFragment.onDownloadFinished()
|
||||
view.findViewById(R.id.optifine_profile).setOnClickListener(v -> Tools.swapFragment(requireActivity(), OptiFineInstallFragment.class,
|
||||
OptiFineInstallFragment.TAG, false, null));
|
||||
OptiFineInstallFragment.TAG, null));
|
||||
view.findViewById(R.id.modded_profile_fabric).setOnClickListener((v)->
|
||||
Tools.swapFragment(requireActivity(), FabricInstallFragment.class, FabricInstallFragment.TAG, false, null));
|
||||
Tools.swapFragment(requireActivity(), FabricInstallFragment.class, FabricInstallFragment.TAG, null));
|
||||
view.findViewById(R.id.modded_profile_forge).setOnClickListener((v)->
|
||||
Tools.swapFragment(requireActivity(), ForgeInstallFragment.class, ForgeInstallFragment.TAG, false, null));
|
||||
Tools.swapFragment(requireActivity(), ForgeInstallFragment.class, ForgeInstallFragment.TAG, null));
|
||||
view.findViewById(R.id.modded_profile_modpack).setOnClickListener((v)->
|
||||
Tools.swapFragment(requireActivity(), SearchModFragment.class, SearchModFragment.TAG, false, null));
|
||||
Tools.swapFragment(requireActivity(), SearchModFragment.class, SearchModFragment.TAG, null));
|
||||
view.findViewById(R.id.modded_profile_quilt).setOnClickListener((v)->
|
||||
Tools.swapFragment(requireActivity(), QuiltInstallFragment.class, QuiltInstallFragment.TAG, false, null));
|
||||
Tools.swapFragment(requireActivity(), QuiltInstallFragment.class, QuiltInstallFragment.TAG, null));
|
||||
}
|
||||
}
|
||||
+12
-4
@@ -86,10 +86,9 @@ public class SearchModFragment extends Fragment implements ModItemAdapter.Search
|
||||
mRecyclerview.addOnScrollListener(mOverlayPositionListener);
|
||||
|
||||
mSearchEditText.setOnEditorActionListener((v, actionId, event) -> {
|
||||
mSearchProgressBar.setVisibility(View.VISIBLE);
|
||||
mSearchFilters.name = mSearchEditText.getText().toString();
|
||||
mModItemAdapter.performSearchQuery(mSearchFilters);
|
||||
return true;
|
||||
searchMods(mSearchEditText.getText().toString());
|
||||
mSearchEditText.clearFocus();
|
||||
return false;
|
||||
});
|
||||
|
||||
mOverlay.post(()->{
|
||||
@@ -100,6 +99,8 @@ public class SearchModFragment extends Fragment implements ModItemAdapter.Search
|
||||
mRecyclerview.getPaddingBottom());
|
||||
});
|
||||
mFilterButton.setOnClickListener(v -> displayFilterDialog());
|
||||
|
||||
searchMods(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -131,6 +132,12 @@ public class SearchModFragment extends Fragment implements ModItemAdapter.Search
|
||||
}
|
||||
}
|
||||
|
||||
private void searchMods(String name) {
|
||||
mSearchProgressBar.setVisibility(View.VISIBLE);
|
||||
mSearchFilters.name = name == null ? "" : name;
|
||||
mModItemAdapter.performSearchQuery(mSearchFilters);
|
||||
}
|
||||
|
||||
private void displayFilterDialog() {
|
||||
AlertDialog dialog = new AlertDialog.Builder(requireContext())
|
||||
.setView(R.layout.dialog_mod_filters)
|
||||
@@ -155,6 +162,7 @@ public class SearchModFragment extends Fragment implements ModItemAdapter.Search
|
||||
// Apply the new settings
|
||||
mApplyButton.setOnClickListener(v -> {
|
||||
mSearchFilters.mcVersion = mSelectedVersion.getText().toString();
|
||||
searchMods(mSearchEditText.getText().toString());
|
||||
dialogInterface.dismiss();
|
||||
});
|
||||
});
|
||||
|
||||
+2
-2
@@ -23,7 +23,7 @@ public class SelectAuthFragment extends Fragment {
|
||||
Button mMicrosoftButton = view.findViewById(R.id.button_microsoft_authentication);
|
||||
Button mLocalButton = view.findViewById(R.id.button_local_authentication);
|
||||
|
||||
mMicrosoftButton.setOnClickListener(v -> Tools.swapFragment(requireActivity(), MicrosoftLoginFragment.class, MicrosoftLoginFragment.TAG, false, null));
|
||||
mLocalButton.setOnClickListener(v -> Tools.swapFragment(requireActivity(), LocalLoginFragment.class, LocalLoginFragment.TAG, false, null));
|
||||
mMicrosoftButton.setOnClickListener(v -> Tools.swapFragment(requireActivity(), MicrosoftLoginFragment.class, MicrosoftLoginFragment.TAG, null));
|
||||
mLocalButton.setOnClickListener(v -> Tools.swapFragment(requireActivity(), LocalLoginFragment.class, LocalLoginFragment.TAG, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package net.kdt.pojavlaunch.memory;
|
||||
|
||||
import net.kdt.pojavlaunch.Architecture;
|
||||
|
||||
public class MemoryHoleFinder implements SelfMapsParser.Callback {
|
||||
private long mPreviousEnd = 0;
|
||||
private long mLargestHole = -1;
|
||||
private final long mAddressingLimit = Architecture.getAddressSpaceLimit();
|
||||
@Override
|
||||
public boolean process(long begin, long end, String wholeLine) {
|
||||
if(begin >= mAddressingLimit) begin = mAddressingLimit;
|
||||
long holeSize = begin - mPreviousEnd;
|
||||
if(mLargestHole < holeSize) mLargestHole = holeSize;
|
||||
if(begin == mAddressingLimit) return false;
|
||||
mPreviousEnd = end;
|
||||
return true;
|
||||
}
|
||||
|
||||
public long getLargestHole() {
|
||||
return mLargestHole;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package net.kdt.pojavlaunch.memory;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class SelfMapsParser {
|
||||
private final Callback mCallback;
|
||||
public SelfMapsParser(Callback callback) {
|
||||
mCallback = callback;
|
||||
}
|
||||
|
||||
public void run() throws IOException, NumberFormatException {
|
||||
try (FileInputStream fileInputStream = new FileInputStream("/proc/self/maps")) {
|
||||
Scanner scanner = new Scanner(fileInputStream);
|
||||
while(scanner.hasNextLine()) {
|
||||
if(!forEachLine(scanner.nextLine())) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean forEachLine(String line) throws NumberFormatException {
|
||||
int firstSpaceIndex = line.indexOf(' ');
|
||||
String addresses = line.substring(0, firstSpaceIndex);
|
||||
String[] addressArray = addresses.split("-");
|
||||
if(addressArray.length < 2) return true;
|
||||
long begin = Long.parseLong(addressArray[0], 16);
|
||||
long end = Long.parseLong(addressArray[1], 16);
|
||||
return mCallback.process(begin, end, line);
|
||||
}
|
||||
|
||||
public interface Callback {
|
||||
boolean process(long startAddress, long endAddress, String wholeLine);
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,6 @@ public class DownloadMirror {
|
||||
"https://bmclapi2.bangbang93.com",
|
||||
"https://bmclapi2.bangbang93.com/assets"
|
||||
};
|
||||
private static final String[] MIRROR_MCBBS = {
|
||||
"https://download.mcbbs.net/maven",
|
||||
"https://download.mcbbs.net",
|
||||
"https://download.mcbbs.net/assets"
|
||||
};
|
||||
|
||||
/**
|
||||
* Download a file with the current mirror. If the file is missing on the mirror,
|
||||
@@ -83,7 +78,6 @@ public class DownloadMirror {
|
||||
|
||||
private static String[] getMirrorSettings() {
|
||||
switch (LauncherPreferences.PREF_DOWNLOAD_SOURCE) {
|
||||
case "mcbbs": return MIRROR_MCBBS;
|
||||
case "bmclapi": return MIRROR_BMCLAPI;
|
||||
case "default":
|
||||
default:
|
||||
|
||||
+12
-2
@@ -30,9 +30,19 @@ public class ModrinthApi implements ModpackApi{
|
||||
@Override
|
||||
public SearchResult searchMod(SearchFilters searchFilters, SearchResult previousPageResult) {
|
||||
ModrinthSearchResult modrinthSearchResult = (ModrinthSearchResult) previousPageResult;
|
||||
HashMap<String, Object> params = new HashMap<>();
|
||||
|
||||
// Fixes an issue where the offset being equal or greater than total_hits is ignored
|
||||
if (modrinthSearchResult != null && modrinthSearchResult.previousOffset >= modrinthSearchResult.totalResultCount) {
|
||||
ModrinthSearchResult emptyResult = new ModrinthSearchResult();
|
||||
emptyResult.results = new ModItem[0];
|
||||
emptyResult.totalResultCount = modrinthSearchResult.totalResultCount;
|
||||
emptyResult.previousOffset = modrinthSearchResult.previousOffset;
|
||||
return emptyResult;
|
||||
}
|
||||
|
||||
|
||||
// Build the facets filters
|
||||
HashMap<String, Object> params = new HashMap<>();
|
||||
StringBuilder facetString = new StringBuilder();
|
||||
facetString.append("[");
|
||||
facetString.append(String.format("[\"project_type:%s\"]", searchFilters.isModpack ? "modpack" : "mod"));
|
||||
@@ -40,7 +50,7 @@ public class ModrinthApi implements ModpackApi{
|
||||
facetString.append(String.format(",[\"versions:%s\"]", searchFilters.mcVersion));
|
||||
facetString.append("]");
|
||||
params.put("facets", facetString.toString());
|
||||
params.put("query", searchFilters.name.replace(' ', '+'));
|
||||
params.put("query", searchFilters.name);
|
||||
params.put("limit", 50);
|
||||
params.put("index", "relevance");
|
||||
if(modrinthSearchResult != null)
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.kdt.mcgui.ProgressLayout;
|
||||
|
||||
import net.kdt.pojavlaunch.R;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.utils.MathUtils;
|
||||
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
@@ -60,19 +61,11 @@ public class MultiRTUtils {
|
||||
|
||||
public static String getNearestJreName(int majorVersion) {
|
||||
List<Runtime> runtimes = getRuntimes();
|
||||
int diff_factor = Integer.MAX_VALUE;
|
||||
String result = null;
|
||||
for(Runtime r : runtimes) {
|
||||
if(r.javaVersion < majorVersion) continue; // lower - not useful
|
||||
|
||||
int currentFactor = r.javaVersion - majorVersion;
|
||||
if(diff_factor > currentFactor) {
|
||||
result = r.name;
|
||||
diff_factor = currentFactor;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
MathUtils.RankedValue<Runtime> nearestRankedRuntime = MathUtils.findNearestPositive(majorVersion, runtimes, (runtime)->runtime.javaVersion);
|
||||
if(nearestRankedRuntime == null) return null;
|
||||
Runtime nearestRuntime = nearestRankedRuntime.value;
|
||||
if(nearestRuntime == null) return null;
|
||||
return nearestRuntime.name;
|
||||
}
|
||||
|
||||
public static void installRuntimeNamed(String nativeLibDir, InputStream runtimeInputStream, String name) throws IOException {
|
||||
@@ -120,11 +113,11 @@ public class MultiRTUtils {
|
||||
}
|
||||
|
||||
|
||||
public static String __internal__readBinpackVersion(String name) {
|
||||
File binpack_verfile = new File(RUNTIME_FOLDER,"/" + name + "/pojav_version");
|
||||
public static String readInternalRuntimeVersion(String name) {
|
||||
File versionFile = new File(RUNTIME_FOLDER,"/" + name + "/pojav_version");
|
||||
try {
|
||||
if (binpack_verfile.exists()) {
|
||||
return Tools.read(binpack_verfile.getAbsolutePath());
|
||||
if (versionFile.exists()) {
|
||||
return Tools.read(versionFile.getAbsolutePath());
|
||||
}else{
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -7,10 +7,16 @@ import static net.kdt.pojavlaunch.Architecture.is32BitsDevice;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.*;
|
||||
import android.content.res.Configuration;
|
||||
import android.graphics.Rect;
|
||||
import android.os.Build;
|
||||
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;
|
||||
@@ -161,17 +167,20 @@ public class LauncherPreferences {
|
||||
/** Compute the notch size to avoid being out of bounds */
|
||||
public static void computeNotchSize(Activity activity) {
|
||||
if (Build.VERSION.SDK_INT < P) return;
|
||||
|
||||
try {
|
||||
final Rect cutout;
|
||||
if(SDK_INT >= Build.VERSION_CODES.S){
|
||||
Rect notchRect = activity.getWindowManager().getCurrentWindowMetrics().getWindowInsets().getDisplayCutout().getBoundingRects().get(0);
|
||||
LauncherPreferences.PREF_NOTCH_SIZE = Math.min(notchRect.width(), notchRect.height());
|
||||
Tools.updateWindowSize(activity);
|
||||
return;
|
||||
cutout = activity.getWindowManager().getCurrentWindowMetrics().getWindowInsets().getDisplayCutout().getBoundingRects().get(0);
|
||||
} else {
|
||||
cutout = activity.getWindow().getDecorView().getRootWindowInsets().getDisplayCutout().getBoundingRects().get(0);
|
||||
}
|
||||
Rect notchRect = activity.getWindow().getDecorView().getRootWindowInsets().getDisplayCutout().getBoundingRects().get(0);
|
||||
// Math min is to handle all rotations
|
||||
LauncherPreferences.PREF_NOTCH_SIZE = Math.min(notchRect.width(), notchRect.height());
|
||||
|
||||
// Notch values are rotation sensitive, handle all cases
|
||||
int orientation = activity.getResources().getConfiguration().orientation;
|
||||
if (orientation == Configuration.ORIENTATION_PORTRAIT) LauncherPreferences.PREF_NOTCH_SIZE = cutout.height();
|
||||
else if (orientation == Configuration.ORIENTATION_LANDSCAPE) LauncherPreferences.PREF_NOTCH_SIZE = cutout.width();
|
||||
else LauncherPreferences.PREF_NOTCH_SIZE = Math.min(cutout.width(), cutout.height());
|
||||
|
||||
}catch (Exception e){
|
||||
Log.i("NOTCH DETECTION", "No notch detected, or the device if in split screen mode");
|
||||
LauncherPreferences.PREF_NOTCH_SIZE = -1;
|
||||
|
||||
+1
-2
@@ -3,7 +3,6 @@ package net.kdt.pojavlaunch.prefs.screens;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.SharedPreferences;
|
||||
import android.graphics.Color;
|
||||
import android.os.Bundle;
|
||||
import android.view.View;
|
||||
|
||||
@@ -24,7 +23,7 @@ public class LauncherPreferenceFragment extends PreferenceFragmentCompat impleme
|
||||
|
||||
@Override
|
||||
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
|
||||
view.setBackgroundColor(Color.parseColor("#232323"));
|
||||
view.setBackgroundColor(getResources().getColor(R.color.background_app));
|
||||
super.onViewCreated(view, savedInstanceState);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ public class LauncherPreferenceJavaFragment extends LauncherPreferenceFragment {
|
||||
int maxRAM;
|
||||
int deviceRam = getTotalDeviceMemory(seek7.getContext());
|
||||
|
||||
if(is32BitsDevice() || deviceRam < 2048) maxRAM = Math.min(1000, deviceRam);
|
||||
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);
|
||||
|
||||
+1
-1
@@ -90,8 +90,8 @@ public class ProgressKeeper {
|
||||
public void onUpdateTaskCount(int taskCount) {
|
||||
if(taskCount == 0) {
|
||||
runnable.run();
|
||||
removeTaskCountListener(this);
|
||||
}
|
||||
removeTaskCountListener(this);
|
||||
}
|
||||
};
|
||||
addTaskCountListener(listener);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package net.kdt.pojavlaunch.services;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.os.Binder;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
@@ -43,7 +45,13 @@ public class GameService extends Service {
|
||||
.addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.notification_terminate), pendingKillIntent)
|
||||
.setSmallIcon(R.drawable.notif_icon)
|
||||
.setNotificationSilent();
|
||||
startForeground(NotificationUtils.NOTIFICATION_ID_GAME_SERVICE, notificationBuilder.build());
|
||||
|
||||
Notification notification = notificationBuilder.build();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(NotificationUtils.NOTIFICATION_ID_GAME_SERVICE, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST);
|
||||
} else {
|
||||
startForeground(NotificationUtils.NOTIFICATION_ID_GAME_SERVICE, notification);
|
||||
}
|
||||
return START_NOT_STICKY; // non-sticky so android wont try restarting the game after the user uses the "Quit" button
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package net.kdt.pojavlaunch.services;
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Notification;
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.pm.ServiceInfo;
|
||||
import android.os.Build;
|
||||
import android.os.IBinder;
|
||||
import android.os.Process;
|
||||
@@ -64,7 +66,12 @@ public class ProgressService extends Service implements TaskCountListener {
|
||||
}
|
||||
Log.d("ProgressService", "Started!");
|
||||
mNotificationBuilder.setContentText(getString(R.string.progresslayout_tasks_in_progress, ProgressKeeper.getTaskCount()));
|
||||
startForeground(NotificationUtils.NOTIFICATION_ID_PROGRESS_SERVICE, mNotificationBuilder.build());
|
||||
Notification notification = mNotificationBuilder.build();
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
startForeground(NotificationUtils.NOTIFICATION_ID_PROGRESS_SERVICE, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MANIFEST);
|
||||
} else {
|
||||
startForeground(NotificationUtils.NOTIFICATION_ID_PROGRESS_SERVICE, notification);
|
||||
}
|
||||
if(ProgressKeeper.getTaskCount() < 1) stopSelf();
|
||||
else ProgressKeeper.addTaskCountListener(this, false);
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ public class AsyncAssetManager {
|
||||
public static void unpackRuntime(AssetManager am) {
|
||||
/* Check if JRE is included */
|
||||
String rt_version = null;
|
||||
String current_rt_version = MultiRTUtils.__internal__readBinpackVersion("Internal");
|
||||
String current_rt_version = MultiRTUtils.readInternalRuntimeVersion("Internal");
|
||||
try {
|
||||
rt_version = Tools.read(am.open("components/jre/version"));
|
||||
} catch (IOException e) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import com.kdt.mcgui.ProgressLayout;
|
||||
import net.kdt.pojavlaunch.JAssetInfo;
|
||||
import net.kdt.pojavlaunch.JAssets;
|
||||
import net.kdt.pojavlaunch.JMinecraftVersionList;
|
||||
import net.kdt.pojavlaunch.JRE17Util;
|
||||
import net.kdt.pojavlaunch.NewJREUtil;
|
||||
import net.kdt.pojavlaunch.R;
|
||||
import net.kdt.pojavlaunch.Tools;
|
||||
import net.kdt.pojavlaunch.mirrors.DownloadMirror;
|
||||
@@ -203,7 +203,7 @@ public class MinecraftDownloader {
|
||||
throw new IOException("Unable to read Version JSON for version " + versionName);
|
||||
}
|
||||
|
||||
if(activity != null && !JRE17Util.installNewJreIfNeeded(activity, verInfo)){
|
||||
if(activity != null && !NewJREUtil.installNewJreIfNeeded(activity, verInfo)){
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -137,7 +137,11 @@ public class DownloadUtils {
|
||||
|
||||
public static <T> T ensureSha1(File outputFile, @Nullable String sha1, Callable<T> downloadFunction) throws IOException {
|
||||
// Skip if needed
|
||||
if(sha1 == null) return downloadFile(downloadFunction);
|
||||
if(sha1 == null) {
|
||||
// If the file exists and we don't know it's SHA1, don't try to redownload it.
|
||||
if(outputFile.exists()) return null;
|
||||
else return downloadFile(downloadFunction);
|
||||
}
|
||||
|
||||
int attempts = 0;
|
||||
boolean fileOkay = verifyFile(outputFile, sha1);
|
||||
|
||||
@@ -273,14 +273,7 @@ public class JREUtils {
|
||||
// return ldLibraryPath;
|
||||
}
|
||||
|
||||
public static void launchJavaVM(final AppCompatActivity activity,
|
||||
final Runtime runtime,
|
||||
File gameDirectory,
|
||||
final List<String> JVMArgs,
|
||||
final String classpath,
|
||||
final String mainClass,
|
||||
final String[] appArgs,
|
||||
final String userArgsString) throws Throwable {
|
||||
public static void launchJavaVM(final AppCompatActivity activity, final Runtime runtime, File gameDirectory, final List<String> JVMArgs, final String userArgsString) throws Throwable {
|
||||
String runtimeHome = MultiRTUtils.getRuntimeHome(runtime.name).getAbsolutePath();
|
||||
|
||||
JREUtils.relocateLibPath(runtime, runtimeHome);
|
||||
@@ -300,12 +293,18 @@ public class JREUtils {
|
||||
purgeArg(userArgs, "-XX:+UseLargePagesInMetaspace");
|
||||
purgeArg(userArgs, "-XX:+UseLargePages");
|
||||
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");
|
||||
|
||||
//Add automatically generated args
|
||||
userArgs.add("-Xms" + LauncherPreferences.PREF_RAM_ALLOCATION + "M");
|
||||
userArgs.add("-Xmx" + LauncherPreferences.PREF_RAM_ALLOCATION + "M");
|
||||
if(LOCAL_RENDERER != null) userArgs.add("-Dorg.lwjgl.opengl.libname=" + graphicsLib);
|
||||
|
||||
// Force LWJGL to use the Freetype library intended for it, instead of using the one
|
||||
// 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");
|
||||
|
||||
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);
|
||||
@@ -313,9 +312,17 @@ public class JREUtils {
|
||||
initJavaRuntime(runtimeHome);
|
||||
setupExitTrap(activity.getApplication());
|
||||
chdir(gameDirectory == null ? Tools.DIR_GAME_NEW : gameDirectory.getAbsolutePath());
|
||||
userArgs.add(0,"java"); //argv[0] is the program name according to C standard.
|
||||
|
||||
VMLauncher.launchJVM(jvmLibraryPath+"/libjvm.so", userArgs.toArray(new String[0]), classpath, mainClass.replace('.', '/'), appArgs);
|
||||
final int exitCode = VMLauncher.launchJVM(userArgs.toArray(new String[0]));
|
||||
Logger.appendToLog("Java Exit code: " + exitCode);
|
||||
if (exitCode != 0) {
|
||||
LifecycleAwareAlertDialog.DialogCreator dialogCreator = (dialog, builder)->
|
||||
builder.setMessage(activity.getString(R.string.mcn_exit_title, exitCode))
|
||||
.setPositiveButton(R.string.main_share_logs, (dialogInterface, which)-> shareLog(activity));
|
||||
|
||||
LifecycleAwareAlertDialog.haltOnDialog(activity.getLifecycle(), activity, dialogCreator);
|
||||
}
|
||||
MainActivity.fullyExit();
|
||||
}
|
||||
|
||||
@@ -565,7 +572,6 @@ public class JREUtils {
|
||||
static {
|
||||
System.loadLibrary("pojavexec");
|
||||
System.loadLibrary("pojavexec_awt");
|
||||
dlopen("libxhook.so");
|
||||
System.loadLibrary("istdio");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package net.kdt.pojavlaunch.utils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class MathUtils {
|
||||
|
||||
//Ported from https://www.arduino.cc/reference/en/language/functions/math/map/
|
||||
@@ -14,4 +16,64 @@ public class MathUtils {
|
||||
return (float) Math.hypot(x, y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the object T with the closest (or higher) value compared to targetValue
|
||||
* @param targetValue the target value
|
||||
* @param objects the list of objects that the search will be performed on
|
||||
* @param valueProvider the provider for each values
|
||||
* @return the RankedValue that wraps the object which has the closest value to targetValue, or null if values of all
|
||||
* objects are less than targetValue
|
||||
* @param <T> the object type that is used for the search.
|
||||
*/
|
||||
public static <T> RankedValue<T> findNearestPositive(int targetValue, List<T> objects, ValueProvider<T> valueProvider) {
|
||||
int delta = Integer.MAX_VALUE;
|
||||
T selectedObject = null;
|
||||
for(T object : objects) {
|
||||
int objectValue = valueProvider.getValue(object);
|
||||
if(objectValue < targetValue) continue;
|
||||
|
||||
int currentDelta = objectValue - targetValue;
|
||||
if(currentDelta == 0) return new RankedValue<>(object, 0);
|
||||
if(currentDelta >= delta) continue;
|
||||
|
||||
selectedObject = object;
|
||||
delta = currentDelta;
|
||||
}
|
||||
if(selectedObject == null) return null;
|
||||
return new RankedValue<>(selectedObject, delta);
|
||||
}
|
||||
|
||||
public interface ValueProvider<T> {
|
||||
int getValue(T object);
|
||||
}
|
||||
|
||||
public static final class RankedValue<T> {
|
||||
public final T value;
|
||||
public final int rank;
|
||||
public RankedValue(T value, int rank) {
|
||||
this.value = value;
|
||||
this.rank = rank;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Out of two objects, select one with the lowest value.
|
||||
* @param object1 Object 1 for comparsion
|
||||
* @param object2 Object 2 for comparsion
|
||||
* @param valueProvider Value provider for the objects
|
||||
* @return If value of object 1 is lower than or equal to object 2, returns object 1
|
||||
* Otherwise, returns object 2
|
||||
* @param <T> Type of objects
|
||||
*/
|
||||
public static <T> T objectMin(T object1, T object2, ValueProvider<T> valueProvider) {
|
||||
if(object1 == null) return object2;
|
||||
if(object2 == null) return object1;
|
||||
int value1 = valueProvider.getValue(object1);
|
||||
int value2 = valueProvider.getValue(object2);
|
||||
if(value1 <= value2) {
|
||||
return object1;
|
||||
} else {
|
||||
return object2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ import android.graphics.BitmapFactory;
|
||||
import android.util.Log;
|
||||
|
||||
import net.kdt.pojavlaunch.*;
|
||||
import net.kdt.pojavlaunch.utils.FileUtils;
|
||||
|
||||
import java.io.*;
|
||||
import com.google.gson.*;
|
||||
import android.graphics.Bitmap;
|
||||
@@ -25,14 +27,14 @@ public class MinecraftAccount {
|
||||
public boolean isMicrosoft = false;
|
||||
public String msaRefreshToken = "0";
|
||||
public String xuid;
|
||||
public String skinFaceBase64;
|
||||
public long expiresAt;
|
||||
public String skinFaceBase64;
|
||||
private Bitmap mFaceCache;
|
||||
|
||||
void updateSkinFace(String uuid) {
|
||||
try {
|
||||
File skinFile = File.createTempFile("skin", ".png", new File(Tools.DIR_DATA, "cache"));
|
||||
File skinFile = getSkinFaceFile(username);
|
||||
Tools.downloadFile("https://mc-heads.net/head/" + uuid + "/100", skinFile.getAbsolutePath());
|
||||
skinFaceBase64 = Base64.encodeToString(IOUtils.toByteArray(new FileInputStream(skinFile)), Base64.DEFAULT);
|
||||
|
||||
Log.i("SkinLoader", "Update skin face success");
|
||||
} catch (IOException e) {
|
||||
@@ -85,9 +87,6 @@ public class MinecraftAccount {
|
||||
if (acc.msaRefreshToken == null) {
|
||||
acc.msaRefreshToken = "0";
|
||||
}
|
||||
if (acc.skinFaceBase64 == null) {
|
||||
// acc.updateSkinFace("MHF_Steve");
|
||||
}
|
||||
return acc;
|
||||
} catch(IOException | JsonSyntaxException e) {
|
||||
Log.e(MinecraftAccount.class.getName(), "Caught an exception while loading the profile",e);
|
||||
@@ -96,11 +95,29 @@ public class MinecraftAccount {
|
||||
}
|
||||
|
||||
public Bitmap getSkinFace(){
|
||||
if(skinFaceBase64 == null){
|
||||
return null;
|
||||
if(isLocal()) return null;
|
||||
|
||||
File skinFaceFile = getSkinFaceFile(username);
|
||||
if (!skinFaceFile.exists()) {
|
||||
// Legacy version, storing the head inside the json as base 64
|
||||
if(skinFaceBase64 == null) return null;
|
||||
byte[] faceIconBytes = Base64.decode(skinFaceBase64, Base64.DEFAULT);
|
||||
return BitmapFactory.decodeByteArray(faceIconBytes, 0, faceIconBytes.length);
|
||||
} else {
|
||||
if(mFaceCache == null) {
|
||||
mFaceCache = BitmapFactory.decodeFile(skinFaceFile.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
byte[] faceIconBytes = Base64.decode(skinFaceBase64, Base64.DEFAULT);
|
||||
return BitmapFactory.decodeByteArray(faceIconBytes, 0, faceIconBytes.length);
|
||||
|
||||
return mFaceCache;
|
||||
}
|
||||
|
||||
public static Bitmap getSkinFace(String username) {
|
||||
return BitmapFactory.decodeFile(getSkinFaceFile(username).getAbsolutePath());
|
||||
}
|
||||
|
||||
private static File getSkinFaceFile(String username) {
|
||||
return new File(Tools.DIR_CACHE, username + ".png");
|
||||
}
|
||||
|
||||
private static boolean accountExists(String username){
|
||||
|
||||
@@ -32,7 +32,6 @@
|
||||
#define EVENT_TYPE_SCROLL 1007
|
||||
#define EVENT_TYPE_WINDOW_SIZE 1008
|
||||
|
||||
|
||||
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);
|
||||
@@ -105,6 +104,13 @@ void pojavPumpEvents(void* window) {
|
||||
// by spec, they will be called on the same thread so no synchronization here
|
||||
pojav_environ->isPumpingEvents = true;
|
||||
|
||||
if((pojav_environ->cLastX != pojav_environ->cursorX || pojav_environ->cLastY != pojav_environ->cursorY) && pojav_environ->GLFW_invoke_CursorPos) {
|
||||
pojav_environ->cLastX = pojav_environ->cursorX;
|
||||
pojav_environ->cLastY = pojav_environ->cursorY;
|
||||
pojav_environ->GLFW_invoke_CursorPos(window, floor(pojav_environ->cursorX),
|
||||
floor(pojav_environ->cursorY));
|
||||
}
|
||||
|
||||
size_t index = pojav_environ->outEventIndex;
|
||||
size_t targetIndex = pojav_environ->outTargetIndex;
|
||||
|
||||
@@ -140,12 +146,6 @@ void pojavPumpEvents(void* window) {
|
||||
if (index >= EVENT_WINDOW_SIZE)
|
||||
index -= EVENT_WINDOW_SIZE;
|
||||
}
|
||||
if((pojav_environ->cLastX != pojav_environ->cursorX || pojav_environ->cLastY != pojav_environ->cursorY) && pojav_environ->GLFW_invoke_CursorPos) {
|
||||
pojav_environ->cLastX = pojav_environ->cursorX;
|
||||
pojav_environ->cLastY = pojav_environ->cursorY;
|
||||
pojav_environ->GLFW_invoke_CursorPos(window, floor(pojav_environ->cursorX),
|
||||
floor(pojav_environ->cursorY));
|
||||
}
|
||||
|
||||
// The out target index is updated by the rewinder
|
||||
pojav_environ->isPumpingEvents = false;
|
||||
@@ -345,10 +345,9 @@ JNIEXPORT jstring JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(JNI
|
||||
#ifdef DEBUG
|
||||
LOGD("Debug: Clipboard access is going on\n", pojav_environ->isUseStackQueueCall);
|
||||
#endif
|
||||
#define dalvikEnv (scope.env)
|
||||
scope_t scope;
|
||||
scopeAttach(pojav_environ->dalvikJavaVMPtr, &scope);
|
||||
|
||||
JNIEnv *dalvikEnv;
|
||||
(*pojav_environ->dalvikJavaVMPtr)->AttachCurrentThread(pojav_environ->dalvikJavaVMPtr, &dalvikEnv, NULL);
|
||||
assert(dalvikEnv != NULL);
|
||||
assert(pojav_environ->bridgeClazz != NULL);
|
||||
|
||||
@@ -367,9 +366,8 @@ JNIEXPORT jstring JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeClipboard(JNI
|
||||
(*dalvikEnv)->DeleteLocalRef(dalvikEnv, copyDst);
|
||||
(*env)->ReleaseByteArrayElements(env, copySrc, (jbyte *)copySrcC, 0);
|
||||
}
|
||||
scopeDetach(pojav_environ->dalvikJavaVMPtr, &scope);
|
||||
(*pojav_environ->dalvikJavaVMPtr)->DetachCurrentThread(pojav_environ->dalvikJavaVMPtr);
|
||||
return pasteDst;
|
||||
#undef dalvikEnv
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL JavaCritical_org_lwjgl_glfw_CallbackBridge_nativeSetInputReady(jboolean inputReady) {
|
||||
@@ -382,17 +380,15 @@ JNIEXPORT jboolean JNICALL JavaCritical_org_lwjgl_glfw_CallbackBridge_nativeSetI
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeSetInputReady(__attribute__((unused)) JNIEnv* env, __attribute__((unused)) jclass clazz, jboolean inputReady) {
|
||||
JavaCritical_org_lwjgl_glfw_CallbackBridge_nativeSetInputReady(inputReady);
|
||||
return JavaCritical_org_lwjgl_glfw_CallbackBridge_nativeSetInputReady(inputReady);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_org_lwjgl_glfw_CallbackBridge_nativeSetGrabbing(__attribute__((unused)) JNIEnv* env, __attribute__((unused)) jclass clazz, jboolean grabbing) {
|
||||
#define dalvikEnv (scope.env)
|
||||
scope_t scope;
|
||||
scopeAttach(pojav_environ->dalvikJavaVMPtr, &scope);
|
||||
JNIEnv *dalvikEnv;
|
||||
(*pojav_environ->dalvikJavaVMPtr)->AttachCurrentThread(pojav_environ->dalvikJavaVMPtr, &dalvikEnv, NULL);
|
||||
(*dalvikEnv)->CallStaticVoidMethod(dalvikEnv, pojav_environ->bridgeClazz, pojav_environ->method_onGrabStateChanged, grabbing);
|
||||
scopeDetach(pojav_environ->dalvikJavaVMPtr, &scope);
|
||||
(*pojav_environ->dalvikJavaVMPtr)->DetachCurrentThread(pojav_environ->dalvikJavaVMPtr);
|
||||
pojav_environ->isGrabbing = grabbing;
|
||||
#undef dalvikEnv
|
||||
}
|
||||
|
||||
jboolean critical_send_char(jchar codepoint) {
|
||||
|
||||
@@ -37,232 +37,149 @@
|
||||
#include "utils.h"
|
||||
#include "environ/environ.h"
|
||||
|
||||
typedef jint (*JNI_CreateJavaVM_t)(JavaVM**, JNIEnv**, void*);
|
||||
// Uncomment to try redirect signal handling to JVM
|
||||
// #define TRY_SIG2JVM
|
||||
|
||||
typedef struct {
|
||||
void* handle;
|
||||
JNI_CreateJavaVM_t JNI_CreateJavaVM;
|
||||
} jvm_library_t;
|
||||
// PojavLancher: fixme: are these wrong?
|
||||
#define FULL_VERSION "1.8.0-internal"
|
||||
#define DOT_VERSION "1.8"
|
||||
|
||||
bool load_vm_library(JNIEnv *env, jstring path, jvm_library_t* library) {
|
||||
void* handle;
|
||||
if(path) {
|
||||
const char* jvm_path = (*env)->GetStringUTFChars(env, path, NULL);
|
||||
if(jvm_path == NULL) {
|
||||
printf("failed to get UTF contents of jvm_path\n");
|
||||
return false;
|
||||
}
|
||||
handle = dlopen(jvm_path, RTLD_NOW);
|
||||
(*env)->ReleaseStringUTFChars(env, path, jvm_path);
|
||||
} else {
|
||||
handle = dlopen("libjvm.so", RTLD_NOW);
|
||||
}
|
||||
if(!handle) {
|
||||
printf("failed to load JVM: %s\n", dlerror());
|
||||
return false;
|
||||
}
|
||||
library->JNI_CreateJavaVM = dlsym(handle, "JNI_CreateJavaVM");
|
||||
if(!library->JNI_CreateJavaVM) {
|
||||
printf("failed to load JVM: %s\n", dlerror());
|
||||
dlclose(handle);
|
||||
return false;
|
||||
}
|
||||
library->handle = handle;
|
||||
return true;
|
||||
static const char* const_progname = "java";
|
||||
static const char* const_launcher = "openjdk";
|
||||
static const char** const_jargs = NULL;
|
||||
static const char** const_appclasspath = NULL;
|
||||
static const jboolean const_javaw = JNI_FALSE;
|
||||
static const jboolean const_cpwildcard = JNI_TRUE;
|
||||
static const jint const_ergo_class = 0; // DEFAULT_POLICY
|
||||
static struct sigaction old_sa[NSIG];
|
||||
|
||||
void (*__old_sa)(int signal, siginfo_t *info, void *reserved);
|
||||
int (*JVM_handle_linux_signal)(int signo, siginfo_t* siginfo, void* ucontext, int abort_if_unrecognized);
|
||||
|
||||
void android_sigaction(int signal, siginfo_t *info, void *reserved) {
|
||||
printf("process killed with signal %d code %p addr %p\n", signal,info->si_code,info->si_addr);
|
||||
if (JVM_handle_linux_signal == NULL) { // should not happen, but still
|
||||
__old_sa = old_sa[signal].sa_sigaction;
|
||||
__old_sa(signal,info,reserved);
|
||||
exit(1);
|
||||
} else {
|
||||
// Based on https://github.com/PojavLauncherTeam/openjdk-multiarch-jdk8u/blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/os/linux/vm/os_linux.cpp#L4688-4693
|
||||
int orig_errno = errno; // Preserve errno value over signal handler.
|
||||
JVM_handle_linux_signal(signal, info, reserved, true);
|
||||
errno = orig_errno;
|
||||
}
|
||||
}
|
||||
typedef jint JNI_CreateJavaVM_func(JavaVM **pvm, void **penv, void *args);
|
||||
|
||||
typedef jint JLI_Launch_func(int argc, char ** argv, /* main argc, argc */
|
||||
int jargc, const char** jargv, /* java args */
|
||||
int appclassc, const char** appclassv, /* app classpath */
|
||||
const char* fullversion, /* full version defined */
|
||||
const char* dotversion, /* dot version defined */
|
||||
const char* pname, /* program name */
|
||||
const char* lname, /* launcher name */
|
||||
jboolean javaargs, /* JAVA_ARGS */
|
||||
jboolean cpwildcard, /* classpath wildcard*/
|
||||
jboolean javaw, /* windows-only javaw */
|
||||
jint ergo /* ergonomics class policy */
|
||||
);
|
||||
|
||||
static jint launchJVM(int margc, char** margv) {
|
||||
void* libjli = dlopen("libjli.so", RTLD_LAZY | RTLD_GLOBAL);
|
||||
|
||||
// Boardwalk: silence
|
||||
// LOGD("JLI lib = %x", (int)libjli);
|
||||
if (NULL == libjli) {
|
||||
LOGE("JLI lib = NULL: %s", dlerror());
|
||||
return -1;
|
||||
}
|
||||
LOGD("Found JLI lib");
|
||||
|
||||
JLI_Launch_func *pJLI_Launch =
|
||||
(JLI_Launch_func *)dlsym(libjli, "JLI_Launch");
|
||||
// Boardwalk: silence
|
||||
// LOGD("JLI_Launch = 0x%x", *(int*)&pJLI_Launch);
|
||||
|
||||
if (NULL == pJLI_Launch) {
|
||||
LOGE("JLI_Launch = NULL");
|
||||
return -1;
|
||||
}
|
||||
|
||||
LOGD("Calling JLI_Launch");
|
||||
|
||||
return pJLI_Launch(margc, margv,
|
||||
0, NULL, // sizeof(const_jargs) / sizeof(char *), const_jargs,
|
||||
0, NULL, // sizeof(const_appclasspath) / sizeof(char *), const_appclasspath,
|
||||
FULL_VERSION,
|
||||
DOT_VERSION,
|
||||
*margv, // (const_progname != NULL) ? const_progname : *margv,
|
||||
*margv, // (const_launcher != NULL) ? const_launcher : *margv,
|
||||
(const_jargs != NULL) ? JNI_TRUE : JNI_FALSE,
|
||||
const_cpwildcard, const_javaw, const_ergo_class);
|
||||
/*
|
||||
return pJLI_Launch(argc, argv,
|
||||
0, NULL, 0, NULL, FULL_VERSION,
|
||||
DOT_VERSION, *margv, *margv, // "java", "openjdk",
|
||||
JNI_FALSE, JNI_TRUE, JNI_FALSE, 0);
|
||||
*/
|
||||
}
|
||||
|
||||
void unload_vm_library(jvm_library_t* library) {
|
||||
dlclose(library->handle);
|
||||
}
|
||||
/*
|
||||
* Class: com_oracle_dalvik_VMLauncher
|
||||
* Method: launchJVM
|
||||
* Signature: ([Ljava/lang/String;)I
|
||||
*/
|
||||
JNIEXPORT jint JNICALL Java_com_oracle_dalvik_VMLauncher_launchJVM(JNIEnv *env, jclass clazz, jobjectArray argsArray) {
|
||||
#ifdef TRY_SIG2JVM
|
||||
void* libjvm = dlopen("libjvm.so", RTLD_LAZY | RTLD_GLOBAL);
|
||||
if (NULL == libjvm) {
|
||||
LOGE("JVM lib = NULL: %s", dlerror());
|
||||
return -1;
|
||||
}
|
||||
JVM_handle_linux_signal = dlsym(libjvm, "JVM_handle_linux_signal");
|
||||
#endif
|
||||
|
||||
bool transfer_arg(JNIEnv* env, jstring argJString, const char** argStringp) {
|
||||
jsize strlen = (*env)->GetStringUTFLength(env, argJString);
|
||||
char* argString = malloc((strlen + 1) * sizeof(char));
|
||||
if(argString == NULL) return false;
|
||||
(*env)->GetStringUTFRegion(env, argJString, 0, strlen, argString);
|
||||
// Add null terminator just in case if the implementation does not null terminate strings
|
||||
argString[strlen] = 0;
|
||||
*argStringp = argString;
|
||||
return true;
|
||||
}
|
||||
jint res = 0;
|
||||
// int i;
|
||||
//Prepare the signal trapper
|
||||
struct sigaction catcher;
|
||||
memset(&catcher,0,sizeof(sigaction));
|
||||
catcher.sa_sigaction = android_sigaction;
|
||||
catcher.sa_flags = SA_SIGINFO|SA_RESTART;
|
||||
// SA_RESETHAND;
|
||||
#define CATCHSIG(X) sigaction(X, &catcher, &old_sa[X])
|
||||
CATCHSIG(SIGILL);
|
||||
//CATCHSIG(SIGABRT);
|
||||
CATCHSIG(SIGBUS);
|
||||
CATCHSIG(SIGFPE);
|
||||
#ifdef TRY_SIG2JVM
|
||||
CATCHSIG(SIGSEGV);
|
||||
#endif
|
||||
CATCHSIG(SIGSTKFLT);
|
||||
CATCHSIG(SIGPIPE);
|
||||
CATCHSIG(SIGXFSZ);
|
||||
//Signal trapper ready
|
||||
|
||||
void free_vm_args(JavaVMOption* args, jsize length) {
|
||||
for(jsize i = 0; i < length; i++) {
|
||||
if(args[i].optionString != NULL) free((void*)args[i].optionString);
|
||||
}
|
||||
}
|
||||
// Save dalvik JNIEnv pointer for JVM launch thread
|
||||
pojav_environ->dalvikJNIEnvPtr_ANDROID = env;
|
||||
|
||||
static void exceptionCheck(JNIEnv *env) {
|
||||
if(!(*env)->ExceptionCheck(env)) return;
|
||||
(*env)->ExceptionDescribe(env);
|
||||
(*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
bool initialize_vm_args(JNIEnv* env, jobjectArray vmArgs, jsize length, JavaVMOption* args) {
|
||||
char* failureReason;
|
||||
if(args == NULL) {
|
||||
failureReason = "Out of memory (JavaVMOption* allocation)";
|
||||
goto fail;
|
||||
}
|
||||
if((*env)->PushLocalFrame(env, length) < 0) {
|
||||
exceptionCheck(env);
|
||||
failureReason = "Out of memory (local frame allocation)";
|
||||
goto fail;
|
||||
if (argsArray == NULL) {
|
||||
LOGE("Args array null, returning");
|
||||
//handle error
|
||||
return 0;
|
||||
}
|
||||
|
||||
for(jsize i = 0; i < length; i++) {
|
||||
jstring argJString = (*env)->GetObjectArrayElement(env, vmArgs, i);
|
||||
if(argJString == NULL) {
|
||||
exceptionCheck(env);
|
||||
failureReason = "One of the argument strings is NULL";
|
||||
goto fail_frame;
|
||||
}
|
||||
if(!transfer_arg(env, argJString, &(args[i].optionString))) {
|
||||
exceptionCheck(env);
|
||||
failureReason = "Argument string transfer failed";
|
||||
goto fail_frame;
|
||||
}
|
||||
}
|
||||
(*env)->PopLocalFrame(env, NULL);
|
||||
return true;
|
||||
fail_frame:
|
||||
(*env)->PopLocalFrame(env, NULL);
|
||||
fail:
|
||||
free_vm_args(args, length);
|
||||
printf("%s\n",failureReason);
|
||||
return false;
|
||||
}
|
||||
int argc = (*env)->GetArrayLength(env, argsArray);
|
||||
char **argv = convert_to_char_array(env, argsArray);
|
||||
|
||||
bool transfer_app_args(JNIEnv* host_env, JNIEnv* guest_env, jobjectArray hostArray, jobjectArray guestArray, jsize length) {
|
||||
char* failureReason;
|
||||
if((*host_env)->PushLocalFrame(host_env, length) < 0) {
|
||||
failureReason = "Out of memory (host local frame allocation)";
|
||||
goto fail;
|
||||
}
|
||||
if((*guest_env)->PushLocalFrame(guest_env, length) < 0) {
|
||||
failureReason = "Out of memory (guest local frame allocation)";
|
||||
goto fail1;
|
||||
}
|
||||
for(jsize i = 0; i < length; i++) {
|
||||
jstring hostEntry = (*host_env)->GetObjectArrayElement(host_env, hostArray, i);
|
||||
// All entries are initialized to null by default, so we can just skip null host entries
|
||||
if(hostEntry == NULL) continue;
|
||||
const char* hostEntryUTF = (*host_env)->GetStringUTFChars(host_env, hostEntry, NULL);
|
||||
if(hostEntryUTF == NULL) {
|
||||
failureReason = "Unable to get UTF contents of application argument string";
|
||||
goto fail2;
|
||||
}
|
||||
jstring guestEntry = (*guest_env)->NewStringUTF(guest_env, hostEntryUTF);
|
||||
if(guestEntry == NULL) {
|
||||
failureReason = "Out of memory (guest argument string allocation)";
|
||||
goto fail2;
|
||||
}
|
||||
(*guest_env)->SetObjectArrayElement(guest_env, guestArray, i, guestEntry);
|
||||
}
|
||||
(*guest_env)->PopLocalFrame(guest_env, NULL);
|
||||
(*host_env)->PopLocalFrame(host_env, NULL);
|
||||
return true;
|
||||
fail2:
|
||||
exceptionCheck(guest_env);
|
||||
(*guest_env)->PopLocalFrame(guest_env, NULL);
|
||||
fail1:
|
||||
exceptionCheck(guest_env);
|
||||
(*host_env)->PopLocalFrame(host_env, NULL);
|
||||
fail:
|
||||
exceptionCheck(guest_env);
|
||||
printf("%s\n", failureReason);
|
||||
return false;
|
||||
}
|
||||
LOGD("Done processing args");
|
||||
|
||||
#define CLASSPATH_ARG "-Djava.class.path="
|
||||
#define CLASSPATH_ARG_LEN 18
|
||||
res = launchJVM(argc, argv);
|
||||
|
||||
void setup_classpath(JNIEnv* env, jstring jclasspath, jsize length, char* classpath) {
|
||||
memcpy(classpath, CLASSPATH_ARG, CLASSPATH_ARG_LEN);
|
||||
(*env)->GetStringUTFRegion(env, jclasspath, 0, length, &classpath[CLASSPATH_ARG_LEN]);
|
||||
}
|
||||
LOGD("Going to free args");
|
||||
free_char_array(env, argsArray, argv);
|
||||
|
||||
void vmh_exit(int result) {
|
||||
printf("VM_EXIT %i\n", result);
|
||||
}
|
||||
LOGD("Free done");
|
||||
|
||||
#define EXIT(x) { \
|
||||
printf("%s\n", x); \
|
||||
goto exit; \
|
||||
}
|
||||
|
||||
#define EXITVM(x) { \
|
||||
printf("%s\n", x); \
|
||||
exceptionCheck(guest_env); \
|
||||
goto exit_destroyvm; \
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_oracle_dalvik_VMLauncher_launchJVM(JNIEnv *env,
|
||||
__attribute__((unused)) jclass clazz,
|
||||
jstring vmPath,
|
||||
jobjectArray vmArgs,
|
||||
jstring classpath,
|
||||
jstring mainClass,
|
||||
jobjectArray appArgs) {
|
||||
jvm_library_t library;
|
||||
if(!load_vm_library(env, vmPath, &library)) return;
|
||||
|
||||
|
||||
|
||||
jsize inSize = (*env)->GetArrayLength(env, vmArgs);
|
||||
jsize realSize = inSize + 2;
|
||||
JavaVMOption options[realSize];
|
||||
|
||||
jsize classpathLength = (*env)->GetStringUTFLength(env, classpath);
|
||||
size_t totalLength = CLASSPATH_ARG_LEN + classpathLength + 1;
|
||||
char classpath_c[totalLength];
|
||||
setup_classpath(env, classpath, classpathLength, classpath_c);
|
||||
classpath_c[totalLength - 1] = 0; // Null terminate in case if setup_classpath doesn't do it.
|
||||
options[inSize].optionString = classpath_c;
|
||||
|
||||
const char* cmainClass = (*env)->GetStringUTFChars(env, mainClass, NULL);
|
||||
if(cmainClass == NULL) EXIT("Failed to get classname string")
|
||||
|
||||
if(!initialize_vm_args(env, vmArgs, inSize, options)) goto exit;
|
||||
|
||||
options[inSize+1].optionString = "exit";
|
||||
options[inSize+1].extraInfo = vmh_exit;
|
||||
|
||||
JavaVMInitArgs initArgs;
|
||||
initArgs.options = options;
|
||||
initArgs.nOptions = realSize;
|
||||
initArgs.ignoreUnrecognized = JNI_FALSE;
|
||||
initArgs.version = JNI_VERSION_1_6;
|
||||
|
||||
for(jsize i = 0; i < initArgs.nOptions; i++) {
|
||||
printf("%s\n", initArgs.options[i].optionString);
|
||||
}
|
||||
|
||||
JavaVM *guest_jvm;
|
||||
JNIEnv *guest_env;
|
||||
jint res = library.JNI_CreateJavaVM(&guest_jvm, &guest_env, (void*)&initArgs);
|
||||
free_vm_args(options, inSize);
|
||||
if(res < 0) EXIT("Failed to initialize the Java VM")
|
||||
|
||||
jclass guest_main_class = (*guest_env)->FindClass(guest_env, cmainClass);
|
||||
(*env)->ReleaseStringUTFChars(env, mainClass, cmainClass);
|
||||
if(guest_main_class == NULL) EXITVM("Failed to locate main class")
|
||||
|
||||
jmethodID guest_main_method = (*guest_env)->GetStaticMethodID(guest_env, guest_main_class, "main", "([Ljava/lang/String;)V");
|
||||
if(guest_main_method == NULL) EXITVM("Failed to locate main method")
|
||||
|
||||
jclass guest_string_class = (*guest_env)->FindClass(guest_env, "java/lang/String");
|
||||
if(guest_string_class == NULL) EXITVM("Failed to locate String class")
|
||||
|
||||
jsize appArgsCount = (*env)->GetArrayLength(env, appArgs);
|
||||
jobjectArray guestArgsArray = (*guest_env)->NewObjectArray(guest_env, appArgsCount, guest_string_class, NULL);
|
||||
if(!transfer_app_args(env, guest_env, appArgs, guestArgsArray, appArgsCount)) goto exit_destroyvm;
|
||||
|
||||
(*guest_env)->CallStaticVoidMethod(guest_env, guest_main_class, guest_main_method, guestArgsArray);
|
||||
exceptionCheck(guest_env);
|
||||
exit_destroyvm:
|
||||
(*guest_jvm)->DetachCurrentThread(guest_jvm);
|
||||
(*guest_jvm)->DestroyJavaVM(guest_jvm);
|
||||
exit:
|
||||
unload_vm_library(&library);
|
||||
return res;
|
||||
}
|
||||
@@ -13,19 +13,6 @@ typedef void (*android_update_LD_LIBRARY_PATH_t)(char*);
|
||||
|
||||
long shared_awt_surface;
|
||||
|
||||
bool scopeAttach(JavaVM* vm, scope_t *scope) {
|
||||
jint err = (*vm)->GetEnv(vm, (void**)&scope->env, JNI_VERSION_1_6);
|
||||
if(err == JNI_EDETACHED) {
|
||||
err = (*vm)->AttachCurrentThread(vm, &scope->env, NULL);
|
||||
if(err == JNI_OK) scope->detach = true;
|
||||
}
|
||||
return err == JNI_OK;
|
||||
}
|
||||
|
||||
void scopeDetach(JavaVM* vm, scope_t *scope) {
|
||||
if(scope->detach) (*vm)->DetachCurrentThread(vm);
|
||||
}
|
||||
|
||||
char** convert_to_char_array(JNIEnv *env, jobjectArray jstringArray) {
|
||||
int num_rows = (*env)->GetArrayLength(env, jstringArray);
|
||||
char **cArray = (char **) malloc(num_rows * sizeof(char*));
|
||||
|
||||
@@ -2,13 +2,7 @@
|
||||
|
||||
#include <stdbool.h>
|
||||
|
||||
typedef struct {
|
||||
bool detach;
|
||||
JNIEnv *env;
|
||||
} scope_t;
|
||||
|
||||
bool scopeAttach(JavaVM*, scope_t*);
|
||||
void scopeDetach(JavaVM*, scope_t*);
|
||||
|
||||
char** convert_to_char_array(JNIEnv *env, jobjectArray jstringArray);
|
||||
jobjectArray convert_from_char_array(JNIEnv *env, char **charArray, int num_rows);
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Executable → Regular
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Executable → Regular
BIN
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 183 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user