Compare commits

..
Author SHA1 Message Date
khanhduytran0 ff09a46d68 Update README.md
Remove 2.4 table
2020-03-29 10:40:59 +07:00
khanhduytran0 a635772c91 Update README.md
Tested by @artdeell in Android 10
2020-03-24 19:49:48 +07:00
khanhduytran0 66ea82a9be Android 9 Minecraft 1.9 ? 2020-03-23 05:17:37 +07:00
khanhduytran0 6b5cbd171d Update README.md 2020-03-21 18:38:21 +07:00
khanhduytran0 d95049affb Update README.md 2020-03-21 18:36:32 +07:00
khanhduytran0 138b6ade98 Update README.md 2020-03-21 15:34:05 +07:00
khanhduytran0 223967a61b Begin table supported version 2.4.2
Not fully correctly.
2020-03-21 15:32:47 +07:00
khanhduytran0 94c80d91b7 Update supported version
Reported by https://www.youtube.com/channel/UClIJr2Jtv22ui89s5r7HFNA
2020-03-20 21:17:50 +07:00
khanhduytran0 56c8e2b485 Update README.md 2020-03-20 05:09:41 +07:00
khanhduytran0 6b8b28d91c Update README.md 2020-03-19 17:03:46 +07:00
khanhduytran0 99b699ad9d Fix wrong words
My English is not good.
2020-03-19 07:06:39 +07:00
khanhduytran0 96a15dd235 Add supported table 2020-03-19 07:04:40 +07:00
khanhduytran0 93bad479d5 Cancel v3 2020-03-19 05:21:56 +07:00
khanhduytran0 1aed2b82ee Cancel v3, add description 2020-03-19 05:17:53 +07:00
khanhduytran0 ba24131901 Cancel v3 2020-03-19 05:15:55 +07:00
khanhduytran0 9e0584deab Update README.md 2020-03-11 10:31:39 +07:00
khanhduytran0 35d33e836c Initial commit 2020-03-11 10:22:55 +07:00
633 changed files with 99 additions and 78699 deletions

No files matched your search

-1
View File
@@ -1 +0,0 @@
patreon: pojavlauncher
-70
View File
@@ -1,70 +0,0 @@
name: Bug report
description: ' Create a report to help us improve '
title: "[BUG] <Short description>"
labels: [bug]
body:
- type: textarea
id: version
attributes:
label: Describe the bug
description: >-
A clear and concise description of what the bug is.
placeholder: 'Example: I have to press CTRL for keyboard keys to work on my Keychron K2 keyboard when connected via Bluetooth'
validations:
required: true
- type: textarea
attributes:
label: The log file and images/videos
description: |
The log file called `latestlog.txt` is located under `/storage/emulated/0/Android/data/net.kdt.pojavlaunch/files` (on Android 10 and higher) or `/storage/emulated/0/games/PojavLauncher/` (on Android 9 and lower). You may have to activate an option in your file explorer to see hidden files and folders. Recommended file managers are ZArchiver and MiXplorer. |
You can also upload here screenshots or videos of the buggy behavior, if possible.
Tip: You can attach files by clicking this area to highlight it and then dragging files in or select them on 🖼 option at the toolbar. Do not click anything before the file successfully uploads, otherwise the upload is going to stop and the file won't attach.
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the issue.
placeholder: |
1. Start PojavLauncher
... *(your set of actions to reproduce the bug)*
render: markdown
validations:
required: true
- type: textarea
attributes:
label: Expected Behavior
description: A concise description of what you expected to happen.
placeholder: 'Example: I expect my keyboard to work correctly without having to hold CTRL.'
validations:
required: true
- type: textarea
attributes:
label: Platform
description: |
Examples:
- **Device model**: Huawei P30 Pro 8/512G
- **CPU architecture**: arm64 (can be arm64, arm, x86_64 or x86 depending on the device)
- **Android version**: 10
- **PojavLauncher version**: (can be found in Android Apps settings, for example `dahlia-20230813-5e8842b-v3_openjdk`)
value: |
- Device model:
- CPU architecture:
- Android version:
- PojavLauncher version:
render: markdown
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: |
Add any other context about the problem here.
validations:
required: false
-1
View File
@@ -1 +0,0 @@
blank_issues_enabled: false
@@ -1,31 +0,0 @@
name: Feature request
description: 'Ask for new features.'
title: "[F-Req] <Short description>"
labels: [enhancement]
body:
- type: textarea
id: version
attributes:
label: Is this request related to a bug?
description: |
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: true
- type: textarea
attributes:
label: Describe the request.
description: |
What do you want to see changed, added, or removed? Make sure to be specific.
placeholder: 'Example: A scrollable version picker.'
validations:
required: true
- type: textarea
attributes:
label: Anything else?
description: |
Add any other context about the problem here.
validations:
required: false
-17
View File
@@ -1,17 +0,0 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 4
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 1
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: true
-129
View File
@@ -1,129 +0,0 @@
name: Android CI
on:
pull_request:
branches-ignore:
- 'l10n_v3_openjdk2'
types: [ opened, reopened ]
push:
branches-ignore:
- 'l10n_v3_openjdk2'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-22.04
env:
GPLAY_KEYSTORE_PASSWORD: ${{ secrets.GPLAY_KEYSTORE_PASSWORD }}
CURSEFORGE_API_KEY: ${{ secrets.CURSEFORGE_API_KEY }}
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Set up JDK 8
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '8'
- name: Get JRE 8
uses: dawidd6/action-download-artifact@v2
with:
workflow: build.yml
path: app_pojavlauncher/src/main/assets/components/jre
workflow_conclusion: success
repo: PojavLauncherTeam/android-openjdk-build-multiarch
branch: buildjre8
name: jre8-pojav
- name: Get JRE17
uses: dawidd6/action-download-artifact@v2
with:
workflow: build.yml
path: app_pojavlauncher/src/main/assets/components/jre-new
workflow_conclusion: success
repo: PojavLauncherTeam/android-openjdk-build-multiarch
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/actions/setup-gradle@v4
with:
gradle-version: "8.11"
- name: Build JRE JAR files
run: |
./scripts/languagelist_updater.sh
mkdir out
# Build JRE JAR files (security manager, etc...)
gradle :jre_lwjgl3glfw:build --no-daemon
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
distribution: 'temurin'
java-version: '17'
- name: Build Google Play .aab
if: github.repository_owner == 'PojavLauncherTeam' && github.ref_name == 'v3_openjdk'
run: |
gradle :app_pojavlauncher:bundleGplay
mv app_pojavlauncher/build/outputs/bundle/gplay/app_pojavlauncher-gplay.aab out/app-gplay.aab
- name: Build Debug .apk
run: |
# Build the launcher
gradle :app_pojavlauncher:assembleDebug
mv app_pojavlauncher/build/outputs/apk/debug/app_pojavlauncher-debug.apk out/app-debug.apk
- name: Build APK without runtime
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:
name: app-release-aab
path: out/app-gplay.aab
- name: Upload onto the Google Play testing track
continue-on-error: true
if: github.repository_owner == 'PojavLauncherTeam' && github.ref_name == 'v3_openjdk'
uses: r0adkll/[email protected]
with:
serviceAccountJsonPlainText: ${{ secrets.GPLAY_SERVICE_JSON }}
packageName: net.kdt.pojavlaunch
releaseFiles: out/app-gplay.aab
track: internal
inAppUpdatePriority: 5
- name: Upload APK (without runtime)
uses: actions/upload-artifact@v3
with:
name: app-debug-noruntime
path: out/app-debug-noruntime.*
-11
View File
@@ -1,11 +0,0 @@
/.gradle
/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/
.vs/
/curseforge_key.txt
-3
View File
@@ -1,3 +0,0 @@
1. This app (while idle) does NOT collect any sensitive information, and does NOT use network (exception is the "News" page, it uses network to load the launcher news)
2. While running Minecraft, app also does NOT collect any sensitive information about your device. Snooper by Mojang does.
3. Some sensitive data is stored in crash reports after the game crashes, but it's not being shared to anyone except the current user.
-165
View File
@@ -1,165 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
-1
View File
@@ -1 +0,0 @@
Данное приложения не отправляет какие либо данные пользователя в сеть "Интернет", и не собирает никакой информации о пользователе при использовании.
+99 -130
View File
@@ -1,135 +1,104 @@
<H1 align="center">PojavLauncher</H1>
# PojavLauncher
A Minecraft: Java Edition launcher for Android based from Boardwalk. Support up-to Minecraft 1.12
<img src="https://github.com/PojavLauncherTeam/PojavLauncher/blob/v3_openjdk/app_pojavlauncher/src/main/assets/pojavlauncher.png" align="left" width="130" height="150" alt="PojavLauncher logo">
# Source code
Not yet, this repository currently for bug tracking.
[![Android CI](https://github.com/PojavLauncherTeam/PojavLauncher/workflows/Android%20CI/badge.svg)](https://github.com/PojavLauncherTeam/PojavLauncher/actions)
[![GitHub commit activity](https://img.shields.io/github/commit-activity/m/PojavLauncherTeam/PojavLauncher)](https://github.com/PojavLauncherTeam/PojavLauncher/actions)
[![Crowdin](https://badges.crowdin.net/pojavlauncher/localized.svg)](https://crowdin.com/project/pojavlauncher)
[![Discord](https://img.shields.io/discord/724163890803638273.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://discord.com/invite/aenk3EUvER)
[![Twitter Follow](https://img.shields.io/twitter/follow/plaunchteam?color=blue&style=flat-square)](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!
* It can run almost every version of Minecraft, allowing you to use .jar only installers to install modloaders such as [Forge](https://files.minecraftforge.net/) and [Fabric](http://fabricmc.net/), mods like [OptiFine](https://optifine.net) and [LabyMod](https://www.labymod.net/en), as well as hack clients like [Wurst](https://www.wurstclient.net/), and much more!
* For more details [check out our wiki](https://pojavlauncherteam.github.io/)
## Some notes to start with
- We do not have an official TikTok account. No one from the dev team makes TikTok videos.
- The official Twitter for PojavLauncher is [@PLaunchTeam](https://twitter.com/PLaunchTeam). Any others (most notably @PojavLauncher) are fake.
## Navigation
- [Introduction](#introduction)
- [Getting PojavLauncher](#getting-pojavlauncher)
- [Building](#building)
- [Current status](#current-status)
- [License](#license)
- [Contributing](#contributing)
- [Credits & Third party components and their licenses](#credits--third-party-components-and-their-licenses-if-available)
## 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.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).
## Getting PojavLauncher
You can get PojavLauncher via three methods:
1. You can get the prebuilt app from [stable releases](https://github.com/PojavLauncherTeam/PojavLauncher/releases) or [automatic builds](https://github.com/PojavLauncherTeam/PojavLauncher/actions).
2. You can get it from Google Play by clicking on this badge:
[![Google Play](https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png)](https://play.google.com/store/apps/details?id=net.kdt.pojavlaunch)
3. You can [build](#building) from source.
## Building
If you want to build from source code, follow the steps below.
### Java Runtime Environment (JRE)
- JRE for Android is [here](https://github.com/PojavLauncherTeam/openjdk-multiarch-jdk8u), and the build script is [here](https://github.com/PojavLauncherTeam/android-openjdk-build-multiarch).
- Follow build instruction on build script [README.md](https://github.com/PojavLauncherTeam/android-openjdk-build-multiarch/blob/buildjre8/README.md).
- You can also get [CI auto builds](https://github.com/PojavLauncherTeam/android-openjdk-build-multiarch/actions) if you are lazy or are failing to build it for some reason.
* Either get the `jre8-pojav` artifact from auto builds, or split all artifacts by yourself:</br>
- Get JREs for all of 4 supported architectures (arm, arm64, x86, x86_64) </br>
- Split JRE into parts:</br>
Platform-independent: .jar files, libraries, configs, etc...</br>
Platform-dependent: .so files, etc...</br>
- Create:</br>
A file named `universal.tar.xz` with all platform-independent files</br>
4 files named `bin-<arch>.tar.xz` with all platform-dependent files per-architecture</br>
- Put these in the `assets/components/jre/` folder</br>
- (If needed) update the Version file with the current date</br>
### LWJGL
The build instructions for the custom LWJGL are available over the [LWJGL repository](https://github.com/PojavLauncherTeam/lwjgl3)
### The Launcher
- Because languages are auto-added by Crowdin, you need to run the language list generator before building. In the project directory, run:
* On Linux, Mac OS:
```
chmod +x scripts/languagelist_updater.sh
bash scripts/languagelist_updater.sh
```
* On Windows:
```
scripts\languagelist_updater.bat
```
Then, run these commands ~~or build using Android Studio~~.
* Build GLFW stub:
```
./gradlew :jre_lwjgl3glfw:build
```
* Build the launcher
```
./gradlew :app_pojavlauncher:assembleDebug
```
(Replace `gradlew` with `gradlew.bat` if you are building on Windows).
## Current status
- [x] ~~OpenJDK 9 Mobile port: ARM32, ARM64, x86, x86_64.~~ Replaced by JRE8.
- [x] OpenJDK 8 Mobile port: ARM32, ARM64, x86, x86_64
- [x] OpenJDK 17 Mobile port: ARM32, ARM64, x86, x86_64
- [x] Headless mod installer
- [x] Mod installer with GUI. Used `Caciocavallo` project for AWT without X11.
- [x] OpenGL in OpenJDK environment
- [x] OpenAL (works on most devices)
- [x] Support for Minecraft 1.12.2 and below. Used [lwjglx](https://github.com/PojavLauncherTeam/lwjglx), a LWJGL2 compatibility layer for LWJGL3.
- [x] Support for Minecraft 1.13 and above. Used [GLFW stub](https://github.com/PojavLauncherTeam/lwjgl3-glfw-java).
- [x] Support for Minecraft 1.17 (22w13a to be exact) and above. Used [Holy GL4ES](https://github.com/PojavLauncherTeam/gl4es-114-extra)
- [x] Game surface zooming.
- [x] New input pipe rewritten to native code to boost performance.
- [x] Rewritten entire controls system (thanks to @Mathias-Boulay)
- [ ] More to come!
## Known Issues
- Controller mods aren't working.
- Random crashes could happen very often on Android 5.x when loading the game or joining a world.
- With big modpacks textures could be messed up
- Probably more, that's why we have a bug tracker ;)
## License
- PojavLauncher is licensed under [GNU LGPLv3](https://github.com/PojavLauncherTeam/PojavLauncher/blob/v3_openjdk/LICENSE).
## Contributing
Contributions are welcome! We welcome any type of contribution, not only code. For example, you can help the wiki shape up. You can help the [translation](https://crowdin.com/project/pojavlauncher) too!
# Planning
- ~~If [exagear_windows_emulator](https://github.com/khanhduytran0/exagear_windows_emulator) repository is runnable then I will make PojavLauncher v3.~~ There are too many probelms when switching to Exagear Windows Emulator code, read below.
- Adding custom version.
## Problem before switching to
- Source code not working.
## Problem after switching to
- Low performance.
- No mouse pointer.
- Can't compatible with some devices running Android 10 and above. [Reason?](https://issuetracker.google.com/issues/128554619)
Any code change to this repository (or iOS) should be submitted as a pull request. The description should explain what the code does and give steps to execute it.
# Minecraft versions worked in PojavLauncher 2.4.2
<table>
<thead>
<tr>
<th></th>
<th align="center" colspan="7">Minecraft version</th>
</tr>
<tr>
<th>Android</th>
<th align="center">1.7.10</th>
<th align="center">1.8</th>
<th align="center">1.9</th>
<th align="center">1.10</th>
<th align="center">1.11</th>
<th align="center">1.12</th>
<th align="center">1.12.2</th>
</tr>
</thead>
<tbody>
<tr>
<td>5.x</td>
<td align="center"><b>Yes</b></td>
<td align="center"><b>Yes</b></td>
<td align="center"><b>Yes</b></td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">No</a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">No</a></td>
</tr>
<tr>
<td>6.0</td>
<td align="center"><b>Yes</b></td>
<td align="center"><b>Yes</b></td>
<td align="center"><b>Yes</b></td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">No</a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">No</a></td>
</tr>
</tbody>
<tbody>
<tr>
<td>7.x</td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">No</a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">No</a></td>
</tr>
<tr>
<td>8.x</td>
<td align="center"><b>Yes</b></td>
<td align="center"><b>Yes</b></td>
<td align="center"><b>Yes</b></td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">Java8</a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">Java8</a></td>
</tr>
</tbody>
<tbody>
<tr>
<td>9.0</td>
<td align="center">???</td>
<td align="center"><b>Yes</b></td>
<td align="center">???</td>
<td align="center">???</td>
<td align="center"><b>Yes</b></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">Java8</a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">Java8</a></td>
</tr>
<tr>
<td>10.0</td>
<td align="center"><a href="https://github.com/khanhduytran0/PojavLauncher/issues/7#issue-586928527"><b>Yes</b></a></td>
<td align="center"><a href="https://github.com/khanhduytran0/PojavLauncher/issues/7#issue-586928527"><b>Yes</b></a></td>
<td align="center"><a href="https://github.com/khanhduytran0/PojavLauncher/issues/7#issue-586928527"><b>Yes</b></a></td>
<td align="center"><a href="https://github.com/khanhduytran0/PojavLauncher/issues/7#issue-586928527"><b>Yes</b></a></td>
<td align="center"><a href="https://github.com/khanhduytran0/PojavLauncher/issues/7#issue-586928527"><b>Yes</b></a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">Java8</a></td>
<td align="center"><a href="https://stackoverflow.com/a/57861173">Java8</a></td>
</tr>
</tbody>
</table>
## Credits & Third party components and their licenses (if available)
- [Boardwalk](https://github.com/zhuowei/Boardwalk) (JVM Launcher): Unknown License/[Apache License 2.0](https://github.com/zhuowei/Boardwalk/blob/master/LICENSE) or GNU GPLv2.
- Android Support Libraries: [Apache License 2.0](https://android.googlesource.com/platform/prebuilts/maven_repo/android/+/master/NOTICE.txt).
- [GL4ES](https://github.com/PojavLauncherTeam/gl4es): [MIT License](https://github.com/ptitSeb/gl4es/blob/master/LICENSE).<br>
- [OpenJDK](https://github.com/PojavLauncherTeam/openjdk-multiarch-jdk8u): [GNU GPLv2 License](https://openjdk.java.net/legal/gplv2+ce.html).<br>
- [LWJGL3](https://github.com/PojavLauncherTeam/lwjgl3): [BSD-3 License](https://github.com/LWJGL/lwjgl3/blob/master/LICENSE.md).
- [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).
- [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.
-153
View File
@@ -1,153 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id=":app_pojavlauncher" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="android-gradle" name="Android-Gradle">
<configuration>
<option name="GRADLE_PROJECT_PATH" value=":app_pojavlauncher" />
<option name="LAST_SUCCESSFUL_SYNC_AGP_VERSION" value="3.5.3" />
<option name="LAST_KNOWN_AGP_VERSION" value="3.5.3" />
</configuration>
</facet>
<facet type="native-android-gradle" name="Native-Android-Gradle">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug-x86" />
</configuration>
</facet>
<facet type="android" name="Android">
<configuration>
<option name="SELECTED_BUILD_VARIANT" value="debug" />
<option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
<option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
<afterSyncTasks>
<task>generateDebugSources</task>
</afterSyncTasks>
<option name="ALLOW_USER_CONFIGURATION" value="false" />
<option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
<option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
<option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
<option name="TEST_RES_FOLDERS_RELATIVE_PATH" value="" />
<option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/build/intermediates/javac/debug/classes" />
<output-test url="file://$MODULE_DIR$/build/intermediates/javac/debugUnitTest/classes" />
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/jni/awt_xawt" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/ap_generated_sources/debug/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debug/compileDebugAidl/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debug/compileDebugRenderscript/out" isTestSource="false" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/ap_generated_sources/debugAndroidTest/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/aidl_source_output_dir/debugAndroidTest/compileDebugAndroidTestAidl/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/renderscript_source_output_dir/debugAndroidTest/compileDebugAndroidTestRenderscript/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/build/generated/ap_generated_sources/debugUnitTest/out" isTestSource="true" generated="true" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/debug/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTestDebug/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/testDebug/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/aidl" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/jni" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.cxx" />
<excludeFolder url="file://$MODULE_DIR$/.externalNativeBuild" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="jdk" jdkName="Android API 29 Platform" jdkType="Android SDK" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Gradle: __local_aars__:C.\Users\Admin\AndroidStudioProjects\PojavLauncher\app_pojavlauncher\libs\ExagearApacheCommons.jar:unspecified@jar" level="project" />
<orderEntry type="library" name="Gradle: __local_aars__:C.\Users\Admin\AndroidStudioProjects\PojavLauncher\app_pojavlauncher\libs\gson-2.8.6.jar:unspecified@jar" level="project" />
<orderEntry type="library" name="Gradle: __local_aars__:C.\Users\Admin\AndroidStudioProjects\PojavLauncher\app_pojavlauncher\libs\PointerCapture26Wrapper.jar:unspecified@jar" level="project" />
<orderEntry type="library" name="Gradle: javax.annotation:javax.annotation-api:1.3.2@jar" level="project" />
<orderEntry type="library" name="Gradle: commons-codec:commons-codec:1.14@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.collection:collection:1.0.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-common:2.0.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.arch.core:core-common:2.0.0@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.annotation:annotation:1.0.0@jar" level="project" />
<orderEntry type="library" name="Gradle: org.tukaani:xz:1.8@jar" level="project" />
<orderEntry type="library" name="Gradle: net.objecthunter:exp4j:0.4.8@jar" level="project" />
<orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-v4:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.legacy:legacy-preference-v14:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.preference:preference:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: com.google.android.material:material:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.appcompat:appcompat:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.browser:browser:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.media:media:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.fragment:fragment:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.recyclerview:recyclerview:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable-animated:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-ui:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.legacy:legacy-support-core-utils:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.vectordrawable:vectordrawable:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.transition:transition:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.loader:loader:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.viewpager:viewpager:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.coordinatorlayout:coordinatorlayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.drawerlayout:drawerlayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.slidingpanelayout:slidingpanelayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.customview:customview:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.swiperefreshlayout:swiperefreshlayout:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.asynclayoutinflater:asynclayoutinflater:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.core:core:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.versionedparcelable:versionedparcelable:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.cursoradapter:cursoradapter:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.cardview:cardview:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.interpolator:interpolator:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-runtime:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.documentfile:documentfile:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.localbroadcastmanager:localbroadcastmanager:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.print:print:1.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-viewmodel:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.lifecycle:lifecycle-livedata-core:2.0.0@aar" level="project" />
<orderEntry type="library" name="Gradle: androidx.arch.core:core-runtime:2.0.0@aar" level="project" />
</component>
</module>
-231
View File
@@ -1,231 +0,0 @@
plugins {
id 'com.android.application' version '8.7.2'
}
static def getDate() { return new Date().format('yyyyMMdd') }
static def getDateSeconds() {
if (System.getenv("GITHUB_ACTIONS") == "true") {
return 9934841 + Integer.parseInt(System.getenv("GITHUB_RUN_NUMBER"))
} else {
return 172005
}
}
def getVersionName = {
// Get the last version tag, as well as the short head of the last commit
ByteArrayOutputStream TAG = new ByteArrayOutputStream()
ByteArrayOutputStream BRANCH = new ByteArrayOutputStream()
// Used by the fallback for github actions
ByteArrayOutputStream TAG_PART_COMMIT = new ByteArrayOutputStream()
String TAG_STRING
exec {
try {
commandLine 'git', 'describe', '--tags'
ignoreExitValue true
standardOutput = TAG
} catch (Exception e) {
e.printStackTrace();
}
}
if (TAG.toString() == "") {
exec {
// Fallback for action builds
try {
commandLine 'git', 'describe', '--always', '--tags'
ignoreExitValue true
standardOutput = TAG_PART_COMMIT
} catch (Exception e) {
}
}
}
if(TAG.toString() != ""){
TAG_STRING = TAG.toString()
}else {
if(TAG_PART_COMMIT.toString().trim() == ""){
//Fallback no repo
return ("LOCAL-" + "${getDate()}")
}else {
// Used by github actions
TAG_STRING = 'foxglove-' + "${getDate()}" + "-" + TAG_PART_COMMIT.toString().trim()
}
}
exec {
try {
commandLine 'git', 'branch', '--show-current'
ignoreExitValue true
standardOutput = BRANCH
} catch (Exception e) {
e.printStackTrace();
}
}
return TAG_STRING.trim().replace("-g", "-") + "-" + BRANCH.toString().trim()
}
def getCFApiKey = {
String key = System.getenv("CURSEFORGE_API_KEY");
if(key != null) return key;
File curseforgeKeyFile = new File("./curseforge_key.txt");
if(curseforgeKeyFile.canRead() && curseforgeKeyFile.isFile()) {
return curseforgeKeyFile.text;
}
logger.warn('BUILD: You have no CurseForge key, the curseforge api will get disabled !');
return "DUMMY";
}
configurations {
instrumentedClasspath {
canBeConsumed = false
canBeResolved = true
}
}
android {
namespace 'net.kdt.pojavlaunch'
compileSdk = 34
lintOptions {
abortOnError false
}
signingConfigs {
customDebug {
storeFile file("debug.keystore")
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
}
googlePlayBuild {
storeFile file("upload.jks")
storePassword System.getenv("GPLAY_KEYSTORE_PASSWORD")
keyAlias "upload"
keyPassword System.getenv("GPLAY_KEYSTORE_PASSWORD")
}
}
defaultConfig {
applicationId "net.kdt.pojavlaunch"
minSdkVersion 21
targetSdkVersion 34
versionCode getDateSeconds()
versionName getVersionName()
multiDexEnabled true //important
resValue 'string', 'curseforge_api_key', getCFApiKey()
}
buildTypes {
debug {
applicationIdSuffix '.debug'
minifyEnabled false
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.customDebug
resValue 'string', 'application_package', 'net.kdt.pojavlaunch.debug'
resValue 'string', 'storageProviderAuthorities', 'net.kdt.pojavlaunch.scoped.gamefolder.debug'
resValue 'string', 'shareProviderAuthority', 'net.kdt.pojavlaunch.scoped.controlfolder.debug'
}
proguard {
initWith debug
minifyEnabled true
shrinkResources true
}
proguardNoDebug {
initWith proguard
debuggable false
}
release {
// Don't set to true or java.awt will be a.a or something similar.
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// defaultConfig already set
// multiDexEnabled = true
// debuggable = true
resValue 'string', 'storageProviderAuthorities', 'net.kdt.pojavlaunch.scoped.gamefolder'
resValue 'string', 'application_package', 'net.kdt.pojavlaunch'
}
gplay {
initWith release
signingConfig signingConfigs.googlePlayBuild
}
}
ndkVersion = "25.2.9519653"
externalNativeBuild {
ndkBuild {
path file('src/main/jni/Android.mk')
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
bundle {
language {
enableSplit = false
}
}
packagingOptions {
jniLibs {
useLegacyPackaging = true
}
pickFirst '**/libbytehook.so'
}
buildFeatures {
prefab true
buildConfig true
}
buildToolsVersion = '34.0.0'
}
afterEvaluate {
// Explicit dependencies for which the apk relies on
tasks.mergeDebugAssets.dependsOn(":forge_installer:jar", ":arc_dns_injector:jar", ":jre_lwjgl3glfw:jar")
}
dependencies {
implementation 'javax.annotation:javax.annotation-api:1.3.2'
implementation 'commons-codec:commons-codec:1.15'
// implementation 'com.wu-man:android-bsf-api:3.1.3'
implementation 'androidx.preference:preference:1.2.0'
//implementation 'androidx.core:core:1.7.0'
implementation 'androidx.drawerlayout:drawerlayout:1.2.0'
implementation 'androidx.viewpager2:viewpager2:1.1.0-beta01'
implementation 'androidx.annotation:annotation:1.5.0'
implementation "androidx.constraintlayout:constraintlayout:2.1.4"
implementation 'com.github.duanhong169:checkerboarddrawable:1.0.2'
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:2.0.3'
implementation 'com.github.Mathias-Boulay:virtual-joystick-android:1.14'
// implementation 'com.intuit.sdp:sdp-android:1.0.5'
// implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'org.tukaani:xz:1.8'
// 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'
// implementation 'net.sourceforge.streamsupport:streamsupport-cfuture:1.7.0'
implementation fileTree(dir: 'libs', include: ['*.jar'])
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-27
View File
@@ -1,27 +0,0 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\tools\adt-bundle-windows-x86_64-20131030\sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# We use Reflection on the builder to avoid creating too many objects
-keep class net.objecthunter.exp4j.ExpressionBuilder**
-keepclassmembers class net.objecthunter.exp4j.ExpressionBuilder** {
*;
}
# Option screens
-keep class net.kdt.pojavlaunch.prefs.screens** {*;}
@@ -1,135 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:glEsVersion="0x00020000" />
<uses-feature
android:name="android.hardware.type.pc"
android:required="false" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.INTERNET" />
<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"
android:allowBackup="true"
android:allowNativeHeapPointerTagging="false"
android:appCategory="game"
android:hasFragileUserData="true"
android:icon="@mipmap/ic_launcher"
android:isGame="true"
android:label="@string/app_name"
android:process=":launcher"
android:resizeableActivity="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:theme="@style/AppTheme">
<activity
android:name=".MissingStorageActivity"
android:exported="false" />
<meta-data
android:name="android.max_aspect"
android:value="ratio_float" />
<activity
android:name=".TestStorageActivity"
android:exported="true"
android:label="@string/app_short_name"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LauncherActivity"
android:label="@string/app_short_name" />
<activity
android:name=".ImportControlActivity"
android:configChanges="keyboard|keyboardHidden"
android:exported="true"
android:launchMode="singleInstance"
android:windowSoftInputMode="stateVisible">
<intent-filter
android:label="@string/import_control_label"
android:scheme="content"
tools:ignore="AppLinkUrlError">
<action android:name="android.intent.action.VIEW" />
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/json" />
<data android:mimeType="text/json" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<activity
android:name=".FatalErrorActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"
android:theme="@style/Theme.AppCompat.DayNight.Dialog" />
<activity android:name=".ShowErrorActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"
android:theme="@style/Theme.AppCompat.DayNight.Dialog" />
<activity
android:name=".ExitActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"
android:theme="@style/Theme.AppCompat.DayNight.Dialog" />
<activity
android:process=":gui_installer"
android:name=".JavaGUILauncherActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|keyboard|navigation|uiMode"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".CustomControlsActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"
android:exported="false"
android:screenOrientation="sensorLandscape">
<intent-filter>
<action android:name=".CustomControlsActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|keyboard|navigation|uiMode"
android:launchMode="singleTop"
android:process=":game"
android:screenOrientation="sensorLandscape" />
<provider
android:name=".scoped.FolderProvider"
android:authorities="@string/storageProviderAuthorities"
android:exported="true"
android:grantUriPermissions="true"
android:permission="android.permission.MANAGE_DOCUMENTS">
<intent-filter>
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
</intent-filter>
</provider>
<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"/>
</queries>
</manifest>
@@ -1,24 +0,0 @@
%s (Minecraft Java Launcher for Android), version %s by Tran Khanh Duy (based on "Boardwalk" app)<br>
* License:<br>
• This application is licensed under <a href="https://github.com/PojavLauncherTeam/PojavLauncher/blob/master/LICENSE">GNU GPLv3</a>.<br>
* Credits / Third party components and their licenses:<br>
• Apache Commons Compress (unknown or Apache License 2.0).<br>
• exp4j: <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License 2.0</a>.<br>
• GL4ES: <a href="https://github.com/ptitSeb/gl4es/blob/master/LICENSE">MIT License</a>.<br>
• LegacyLauncher: (unknown license).<br>
• OpenJDK: <a href="https://openjdk.java.net/legal/gplv2+ce.html">GNU GPLv2 License</a>.<br>
• LWJGL: <a href="http://legacy.lwjgl.org/license.php.html">LWJGL 2's License</a>.<br><br>
• pro-gradle: <a href="https://github.com/pro-grade/pro-grade/blob/master/LICENSE.txt">Apache License 2.0</a>.<br>
• xHook: <a href="https://github.com/iqiyi/xHook/blob/master/LICENSE">Mixed licenses</a>.<br>
• <a href="https://github.com/PojavLauncherTeam/PojavLauncher#credits--third-party-components-and-their-licenses">More (check at GitHub)</a>.
• <a href="https://raw.githubusercontent.com/PojavLauncherTeam/PojavLauncher/v3_openjdk/GPLAY_PRIVACY_POLICY">Privacy policy</a>.
• Thanks to <a href="https://mc-heads.net">MCHeads</a> for providing Minecraft avatars.
* Notes:<br>
- This app is under development and might not be stable.<br>
- This app is not affiliated with Minecraft, Mojang or Microsoft.<br><br>
* Translators can be found at <a href="https://crowdin.com/project/pojavlauncher">Crowdin</a>
@@ -1 +0,0 @@
1687691695196
@@ -1 +0,0 @@
HEllo PeopLE1
@@ -1 +0,0 @@
20230712
@@ -1 +0,0 @@
1692525087345
@@ -1 +0,0 @@
1732218529630
@@ -1,17 +0,0 @@
// PojavLauncher JRE Sandbox
// DO NOT EDIT THIS FILE WITHOUT KNOWLEDGE!
// This file is important to protect you against viruses/malwares that could be come from unknown Java Programs (run on mod install) or a mod.
priority "grant";
grant {
permission java.io.FilePermission "./-", "read, write, delete";
permission java.io.FilePermission "${java.io.tmpdir}/-", "read, write, delete";
permission java.io.FilePermission "${user.home}/-", "read, write, delete";
};
deny {
permission java.io.FilePermission "${pojav.path.private.account}/-", "read, write, delete";
permission java.io.FilePermission "<<ALL FILES>>", "write, delete, execute";
};
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="SysOut" target="SYSTEM_OUT">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg{nolookups}%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<OnStartupTriggeringPolicy />
</Policies>
</Console>
<RollingRandomAccessFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg{nolookups}%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<OnStartupTriggeringPolicy />
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="info">
<filters>
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL" />
</filters>
<AppenderRef ref="SysOut"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="SysOut" target="SYSTEM_OUT">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<OnStartupTriggeringPolicy />
</Policies>
</Console>
<RollingRandomAccessFile name="File" fileName="logs/latest.log" filePattern="logs/%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout pattern="[%d{HH:mm:ss}] [%t/%level]: %msg%n" />
<Policies>
<TimeBasedTriggeringPolicy />
<OnStartupTriggeringPolicy />
</Policies>
</RollingRandomAccessFile>
</Appenders>
<Loggers>
<Root level="info">
<filters>
<MarkerFilter marker="NETWORK_PACKETS" onMatch="DENY" onMismatch="NEUTRAL" />
<RegexFilter regex="(?s).*\$\{[^}]*\}.*" onMatch="DENY" onMismatch="NEUTRAL"/>
</filters>
<AppenderRef ref="SysOut"/>
<AppenderRef ref="File"/>
</Root>
</Loggers>
</Configuration>
@@ -1 +0,0 @@
1
@@ -1 +0,0 @@
{"mControlDataList":[{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 3 + ${width} * 2","dynamicY":"${margin}","height":30,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[-1,0,0,0],"name":"Keyboard","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":80},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin}","dynamicY":"${bottom} - ${margin}","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[-2,0,0,0],"name":"GUI","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin}","dynamicY":"${screen_height} - ${margin} * 3 - ${height} * 3","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[-3,0,0,0],"name":"PRI","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 3 + ${width} * 2","dynamicY":"${screen_height} - ${margin} * 3 - ${height} * 3","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[-4,0,0,0],"name":"SEC","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${right}","dynamicY":"${margin}","height":30,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[-5,0,0,0],"name":"Mouse","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":80},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin}","dynamicY":"${margin}","height":30,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[292,0,0,0],"name":"Debug","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":80},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 2 + ${width}","dynamicY":"${margin}","height":30,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[84,0,0,0],"name":"Chat","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":80},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 4 + ${width} * 3","dynamicY":"${margin}","height":30,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[258,0,0,0],"name":"Tab","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":80},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin}","dynamicY":"${height} + ${margin}","height":30,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[294,0,0,0],"name":"3rd","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":80},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 2 + ${width}","dynamicY":"${bottom} - ${margin} * 3 - ${height} * 2","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[87,0,0,0],"name":"▲","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin}","dynamicY":"${bottom} - ${margin} * 2 - ${height}","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[65,0,0,0],"name":"◀","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 2 + ${width}","dynamicY":"${bottom} - ${margin}","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[83,0,0,0],"name":"▼","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 3 + ${width} * 2","dynamicY":"${bottom} - ${margin} * 2 - ${height}","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[68,0,0,0],"name":"▶","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 3 + ${width} * 2","dynamicY":"${bottom} - ${margin}","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":false,"keycodes":[69,0,0,0],"name":"Inv","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${margin} * 2 + ${width}","dynamicY":"${screen_height} - ${margin} * 2 - ${height} * 2","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":false,"isToggle":true,"keycodes":[340,0,0,0],"name":"◇","opacity":1,"passThruEnabled":false,"strokeColor":-1,"strokeWidth":0,"width":50},{"bgColor":1291845632,"cornerRadius":0,"dynamicX":"${right} - ${margin} * 2 - ${width}","dynamicY":"${bottom} - ${margin} * 2 - ${height}","height":50,"isDynamicBtn":false,"isHideable":false,"isSwipeable":falLine truncated
@@ -1,92 +0,0 @@
This Font Software is licensed under the SIL Open Font License,
Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font
creation efforts of academic and linguistic communities, and to
provide a free and open framework in which fonts may be shared and
improved in partnership with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply to
any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software
components as distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to,
deleting, or substituting -- in part or in whole -- any of the
components of the Original Version, by changing formats or by porting
the Font Software to a new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed,
modify, redistribute, and sell modified and unmodified copies of the
Font Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components, in
Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the
corresponding Copyright Holder. This restriction only applies to the
primary font name as presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created using
the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -1,39 +0,0 @@
values-af-rZA
values-ar-rSA
values-ba-rRU
values-ca-rES
values-cs-rCZ
values-da-rDK
values-de-rDE
values-el-rGR
values-en-rGB
values-en-rUS
values-es-rES
values-fil-rPH
values-fi-rFI
values-fr-rFR
values-hu-rHU
values-in-rID
values-it-rIT
values-iw-rIL
values-ja-rJP
values-kk-rKZ
values-ko-rKR
values-la-rLA
values-lt-rLT
values-nl-rNL
values-no-rNO
values-pl-rPL
values-pt-rBR
values-pt-rPT
values-ro-rRO
values-ru-rRU
values-sr-rSP
values-sv-rSE
values-th-rTH
values-tr-rTR
values-tt-rRU
values-uk-rUA
values-vi-rVN
values-zh-rCN
values-zh-rTW
@@ -1,9 +0,0 @@
{
"profiles": {
"(Default)": {
"name": "(Default)",
"lastVersionId": "1.7.10"
}
},
"selectedProfile": "(Default)"
}
@@ -1,96 +0,0 @@
invertYMouse:false
mouseSensitivity:0.5
fov:0.0
gamma:0.5070422
saturation:0.0
renderDistance:2
guiScale:3
particles:1
bobView:false
anaglyph3d:false
advancedOpengl:false
maxFps:260
fboEnable:true
difficulty:2
fancyGraphics:false
ao:0
clouds:true
resourcePacks:[]
lastServer:
lang:en_US
chatVisibility:0
chatColors:true
chatLinks:true
chatLinksPrompt:true
chatOpacity:1.0
snooperEnabled:true
fullscreen:true
enableVsync:false
hideServerAddress:false
advancedItemTooltips:false
pauseOnLostFocus:true
showCape:true
touchscreen:false
overrideWidth:0
overrideHeight:0
heldItemTooltips:true
chatHeightFocused:1.0
chatHeightUnfocused:0.44366196
chatScale:1.0
chatWidth:1.0
showInventoryAchievementHint:false
mipmapLevels:0
anisotropicFiltering:1
streamBytesPerPixel:0.5
streamMicVolume:1.0
streamSystemVolume:1.0
streamKbps:0.5412844
streamFps:0.31690142
streamCompression:1
streamSendMetadata:true
streamPreferredServer:
streamChatEnabled:0
streamChatUserFilter:0
streamMicToggleBehavior:0
forceUnicodeFont:false
key_key.attack:-100
key_key.use:-99
key_key.forward:17
key_key.left:30
key_key.back:31
key_key.right:32
key_key.jump:57
key_key.sneak:42
key_key.drop:16
key_key.inventory:18
key_key.chat:20
key_key.playerlist:15
key_key.pickItem:-98
key_key.command:53
key_key.screenshot:60
key_key.togglePerspective:63
key_key.smoothCamera:0
key_key.sprint:29
key_key.streamStartStop:64
key_key.streamPauseUnpause:65
key_key.streamCommercial:0
key_key.streamToggleMic:0
key_key.fullscreen:87
key_key.hotbar.1:2
key_key.hotbar.2:3
key_key.hotbar.3:4
key_key.hotbar.4:5
key_key.hotbar.5:6
key_key.hotbar.6:7
key_key.hotbar.7:8
key_key.hotbar.8:9
key_key.hotbar.9:10
soundCategory_master:1.0
soundCategory_music:1.0
soundCategory_record:1.0
soundCategory_weather:1.0
soundCategory_block:1.0
soundCategory_hostile:1.0
soundCategory_neutral:1.0
soundCategory_player:1.0
soundCategory_ambient:1.0
Binary file not shown.

Before

Width:  |  Height:  |  Size: 526 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

@@ -1,2 +0,0 @@
nameserver 8.8.8.8
nameserver 8.8.4.4
@@ -1,120 +0,0 @@
/*
* Copyright (C) 2012 Paul Burke
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ipaulpro.afilechooser;
import android.content.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.util.*;
import net.kdt.pojavlaunch.*;
/**
* List adapter for Files.
*
* @version 2013-12-11
* @author paulburke (ipaulpro)
*
* @addDate 2018-08-08
* @addToMyProject khanhduy032
*/
public class FileListAdapter extends BaseAdapter {
private final static int ICON_FOLDER = R.drawable.ic_folder;
private final static int ICON_FILE = R.drawable.ic_file;
private final LayoutInflater mInflater;
private List<File> mData = new ArrayList<File>();
public FileListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public void add(File file) {
mData.add(file);
notifyDataSetChanged();
}
public void remove(File file) {
mData.remove(file);
notifyDataSetChanged();
}
public void insert(File file, int index) {
mData.add(index, file);
notifyDataSetChanged();
}
public void clear() {
mData.clear();
notifyDataSetChanged();
}
@Override
public File getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return mData.size();
}
public List<File> getListItems() {
return mData;
}
/**
* Set the list items without notifying on the clear. This prevents loss of
* scroll position.
*
* @param data
*/
public void setListItems(List<File> data) {
mData = data;
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null)
row = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
TextView view = (TextView) row;
// Get the file at the current position
final File file = getItem(position);
// Set the TextView as the file name
view.setText(file.getName());
// If the item is not a directory, use the file icon
int icon = file.isDirectory() ? ICON_FOLDER : ICON_FILE;
view.setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
view.setCompoundDrawablePadding(20);
return row;
}
}
@@ -1,164 +0,0 @@
package com.kdt;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.SeekBar;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.R;
/**
* Seekbar with ability to handle ranges and increments
*/
@SuppressLint("AppCompatCustomView")
public class CustomSeekbar extends SeekBar {
private int mMin = 0;
private int mIncrement = 1;
private SeekBar.OnSeekBarChangeListener mListener;
private final OnSeekBarChangeListener mInternalListener = new OnSeekBarChangeListener() {
/** When using increments, this flag is used to prevent double calls to the listener */
private boolean internalChanges = false;
/** Store the previous progress to prevent double calls with increments */
private int previousProgress = 0;
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (internalChanges) return;
internalChanges = true;
progress += mMin;
progress = applyIncrement(progress);
if (progress != previousProgress) {
if (mListener != null) {
previousProgress = progress;
mListener.onProgressChanged(seekBar, progress, fromUser);
}
}
// Forces the thumb to snap to the increment
setProgress(progress);
internalChanges = false;
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (internalChanges) return;
if (mListener != null) {
mListener.onStartTrackingTouch(seekBar);
}
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (internalChanges) return;
internalChanges = true;
setProgress(seekBar.getProgress());
if (mListener != null) {
mListener.onStopTrackingTouch(seekBar);
}
internalChanges = false;
}
};
public CustomSeekbar(Context context) {
super(context);
setup(null);
}
public CustomSeekbar(Context context, AttributeSet attrs) {
super(context, attrs);
setup(attrs);
}
public CustomSeekbar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setup(attrs);
}
public void setIncrement(int increment) {
mIncrement = increment;
}
public void setRange(int min, int max) {
mMin = min;
setMax(max - min);
}
@Override
public synchronized void setProgress(int progress) {
super.setProgress(applyIncrement(progress - mMin));
}
@Override
public void setProgress(int progress, boolean animate) {
super.setProgress(applyIncrement(progress - mMin), animate);
}
@Override
public synchronized int getProgress() {
return applyIncrement(super.getProgress() + mMin);
}
@Override
public synchronized void setMin(int min) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
super.setMin(0);
}
mMin = min;
//todo perform something to update the progress ?
}
/**
* Wrapper to allow for a listener to be set around the internal listener
*/
@Override
public void setOnSeekBarChangeListener(OnSeekBarChangeListener l) {
mListener = l;
}
public void setup(@Nullable AttributeSet attrs) {
try (TypedArray attributes = getContext().obtainStyledAttributes(attrs, R.styleable.CustomSeekbar)) {
setIncrement(attributes.getInt(R.styleable.CustomSeekbar_seekBarIncrement, 1));
int min = attributes.getInt(R.styleable.CustomSeekbar_android_min, 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
super.setMin(0);
}
setRange(min, super.getMax());
}
// Due to issues with negative progress when setting up the seekbar
// We need to set a random progress to force the refresh of the thumb
if(super.getProgress() == 0) {
super.setProgress(super.getProgress() + 1);
post(() -> {
super.setProgress(super.getProgress() - 1);
post(() -> super.setOnSeekBarChangeListener(mInternalListener));
});
} else {
super.setOnSeekBarChangeListener(mInternalListener);
}
}
/**
* Apply increment to the progress
* @param progress Progress to apply increment to
* @return Progress with increment applied
*/
private int applyIncrement(int progress) {
if (mIncrement < 1) return progress;
progress = progress / mIncrement;
progress = progress * mIncrement;
return progress;
}
}
@@ -1,50 +0,0 @@
package com.kdt;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.ScrollView;
/**
Class allowing to ignore the focusing from an item such an EditText within it.
Ignoring it will stop the scrollView from refocusing on the view
*/
public class DefocusableScrollView extends ScrollView {
private boolean mKeepFocusing = false;
public DefocusableScrollView(Context context) {
super(context);
}
public DefocusableScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DefocusableScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public DefocusableScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public void setKeepFocusing(boolean shouldKeepFocusing){
mKeepFocusing = shouldKeepFocusing;
}
public boolean isKeepFocusing(){
return mKeepFocusing;
}
@Override
protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
if(!mKeepFocusing) return 0;
return super.computeScrollDeltaToGetChildRectOnScreen(rect);
}
}
@@ -1,101 +0,0 @@
package com.kdt;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import net.kdt.pojavlaunch.Logger;
import net.kdt.pojavlaunch.R;
/**
* A class able to display logs to the user.
* It has support for the Logger class
*/
public class LoggerView extends ConstraintLayout {
private Logger.eventLogListener mLogListener;
private ToggleButton mLogToggle;
private DefocusableScrollView mScrollView;
private TextView mLogTextView;
public LoggerView(@NonNull Context context) {
this(context, null);
}
public LoggerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
// Triggers the log view shown state by default when viewing it
mLogToggle.setChecked(visibility == VISIBLE);
}
/**
* Inflate the layout, and add component behaviors
*/
private void init(){
inflate(getContext(), R.layout.view_logger, this);
mLogTextView = findViewById(R.id.content_log_view);
mLogTextView.setTypeface(Typeface.MONOSPACE);
//TODO clamp the max text so it doesn't go oob
mLogTextView.setMaxLines(Integer.MAX_VALUE);
mLogTextView.setEllipsize(null);
mLogTextView.setVisibility(GONE);
// Toggle log visibility
mLogToggle = findViewById(R.id.content_log_toggle_log);
mLogToggle.setOnCheckedChangeListener(
(compoundButton, isChecked) -> {
mLogTextView.setVisibility(isChecked ? VISIBLE : GONE);
if(isChecked) {
Logger.setLogListener(mLogListener);
}else{
mLogTextView.setText("");
Logger.setLogListener(null); // Makes the JNI code be able to skip expensive logger callbacks
// NOTE: was tested by rapidly smashing the log on/off button, no sync issues found :)
}
});
mLogToggle.setChecked(false);
// Remove the loggerView from the user View
ImageButton cancelButton = findViewById(R.id.log_view_cancel);
cancelButton.setOnClickListener(view -> LoggerView.this.setVisibility(GONE));
// 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');
if(mScrollView.isKeepFocusing()) mScrollView.fullScroll(View.FOCUS_DOWN);
});
};
}
}
@@ -1,251 +0,0 @@
package com.kdt;
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.CallSuper;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.res.ResourcesCompat;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
/**
* The base class for side dialog views
* A side dialog is a dialog appearing from one side of the screen
*/
public abstract class SideDialogView {
private final ViewGroup mParent;
private final @LayoutRes int mLayoutId;
private ViewGroup mDialogLayout;
private DefocusableScrollView mScrollView;
protected View mDialogContent;
protected final int mMargin;
private ObjectAnimator mSideDialogAnimator;
protected boolean mDisplaying = false;
/* Whether the layout is built */
private boolean mIsInstantiated = false;
/* UI elements */
private Button mStartButton, mEndButton;
private TextView mTitleTextview;
private View mTitleDivider;
/* Data to store when the UI element has yet to be inflated */
private @StringRes int mStartButtonStringId, mEndButtonStringId, mTitleStringId;
private View.OnClickListener mStartButtonListener, mEndButtonListener;
public SideDialogView(Context context, ViewGroup parent, @LayoutRes int layoutId) {
mMargin = context.getResources().getDimensionPixelOffset(R.dimen._20sdp);
mParent = parent;
mLayoutId = layoutId;
}
public void setTitle(@StringRes int textId) {
mTitleStringId = textId;
if (mIsInstantiated) {
mTitleTextview.setText(textId);
mTitleTextview.setVisibility(View.VISIBLE);
mTitleDivider.setVisibility(View.VISIBLE);
}
}
public final void setStartButtonListener(@StringRes int textId, @Nullable View.OnClickListener listener) {
mStartButtonStringId = textId;
mStartButtonListener = listener;
if (mIsInstantiated) setButton(mStartButton, textId, listener);
}
public final void setEndButtonListener(@StringRes int textId, @Nullable View.OnClickListener listener) {
mEndButtonStringId = textId;
mEndButtonListener = listener;
if (mIsInstantiated) setButton(mEndButton, textId, listener);
}
private void setButton(@NonNull Button button, @StringRes int textId, @Nullable View.OnClickListener listener) {
button.setText(textId);
button.setOnClickListener(listener);
button.setVisibility(View.VISIBLE);
}
private void inflateLayout() {
if(mIsInstantiated) {
Log.w("SideDialogView", "Layout already inflated");
return;
}
// Inflate layouts
mDialogLayout = (ViewGroup) LayoutInflater.from(mParent.getContext()).inflate(R.layout.dialog_side_dialog, mParent, false);
mScrollView = mDialogLayout.findViewById(R.id.side_dialog_scrollview);
mStartButton = mDialogLayout.findViewById(R.id.side_dialog_start_button);
mEndButton = mDialogLayout.findViewById(R.id.side_dialog_end_button);
mTitleTextview = mDialogLayout.findViewById(R.id.side_dialog_title_textview);
mTitleDivider = mDialogLayout.findViewById(R.id.side_dialog_title_divider);
LayoutInflater.from(mParent.getContext()).inflate(mLayoutId, mScrollView, true);
mDialogContent = mScrollView.getChildAt(0);
// Attach layouts
mParent.addView(mDialogLayout);
mSideDialogAnimator = ObjectAnimator.ofFloat(mDialogLayout, "x", 0).setDuration(600);
mSideDialogAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
mDialogLayout.setElevation(10);
mDialogLayout.setTranslationZ(10);
mDialogLayout.setVisibility(View.VISIBLE);
mDialogLayout.setBackground(ResourcesCompat.getDrawable(mDialogLayout.getResources(), R.drawable.background_control_editor, null));
//TODO offset better according to view width
mDialogLayout.setX(-mDialogLayout.getResources().getDimensionPixelOffset(R.dimen._280sdp));
mIsInstantiated = true;
// Set up UI elements
if (mTitleStringId != 0) setTitle(mTitleStringId);
if (mStartButtonStringId != 0) setStartButtonListener(mStartButtonStringId, mStartButtonListener);
if (mEndButtonStringId != 0) setEndButtonListener(mEndButtonStringId, mEndButtonListener);
}
/** Destroy the layout, cleanup variables */
private void deflateLayout() {
if(!mIsInstantiated) {
Log.w("SideDialogView", "Layout not inflated");
return;
}
mParent.removeView(mDialogLayout);
mIsInstantiated = false;
mScrollView = null;
mSideDialogAnimator = null;
mDialogLayout = null;
mDialogContent = null;
mTitleTextview = null;
mTitleDivider = null;
mStartButton = null;
mEndButton = null;
}
/**
* Slide the layout into the visible screen area
*/
@CallSuper
public final void appear(boolean fromRight) {
if (!mIsInstantiated) {
inflateLayout();
onInflate();
}
// To avoid UI sizing issue when the dialog is not fully inflated
onAppear();
Tools.runOnUiThread(() -> {
if (fromRight) {
if (!mDisplaying || !isAtRight()) {
mSideDialogAnimator.setFloatValues(currentDisplayMetrics.widthPixels, currentDisplayMetrics.widthPixels - mScrollView.getWidth() - mMargin);
mSideDialogAnimator.start();
mDisplaying = true;
}
} else {
if (!mDisplaying || isAtRight()) {
mSideDialogAnimator.setFloatValues(-mDialogLayout.getWidth(), mMargin);
mSideDialogAnimator.start();
mDisplaying = true;
}
}
});
}
protected final boolean isAtRight() {
return mDialogLayout.getX() > currentDisplayMetrics.widthPixels / 2f;
}
/**
* Slide out the layout
* @param destroy Whether the layout should be destroyed after disappearing.
* Recommended to be true if the layout is not going to be used anymore
*/
@CallSuper
public final void disappear(boolean destroy) {
if(!mIsInstantiated) {
Log.w("SideDialogView", "Layout not inflated");
return;
}
if (!mDisplaying) {
if(destroy) {
onDisappear();
onDestroy();
deflateLayout();
}
return;
}
mDisplaying = false;
if (isAtRight())
mSideDialogAnimator.setFloatValues(currentDisplayMetrics.widthPixels - mDialogLayout.getWidth() - mMargin, currentDisplayMetrics.widthPixels);
else
mSideDialogAnimator.setFloatValues(mMargin, -mDialogLayout.getWidth());
if(destroy) {
onDisappear();
onDestroy();
mSideDialogAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mSideDialogAnimator.removeListener(this);
deflateLayout();
}
});
}
mSideDialogAnimator.start();
}
/** @return Whether the dialog is currently displaying */
public final boolean isDisplaying(){
return mDisplaying;
}
/**
* Called when the dialog is inflated, ideal for setting up UI elements bindings
*/
protected void onInflate() {}
/**
* Called after the dialog has appeared
*/
protected void onAppear() {}
/**
* Called after the dialog has disappeared
*/
protected void onDisappear() {}
/**
* Called before the dialog gets destroyed (removing views from parent)
* Ideal for cleaning up resources
*/
protected void onDestroy() {}
}
@@ -1,67 +0,0 @@
package com.kdt;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Collections;
import java.util.List;
/**
* Basic adapter, expect it uses the what is passed by the code, no the resources
* @param <T>
*/
public class SimpleArrayAdapter<T> extends BaseAdapter {
private List<T> mObjects;
public SimpleArrayAdapter(List<T> objects) {
setObjects(objects);
}
public void setObjects(@Nullable List<T> objects) {
if(objects == null){
if(mObjects != Collections.emptyList()) {
mObjects = Collections.emptyList();
notifyDataSetChanged();
}
} else {
if(objects != mObjects){
mObjects = objects;
notifyDataSetChanged();
}
}
}
@Override
public int getCount() {
return mObjects.size();
}
@Override
public T getItem(int position) {
return mObjects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
}
TextView v = (TextView) convertView;
v.setText(mObjects.get(position).toString());
return v;
}
}
@@ -1,50 +0,0 @@
package com.kdt.mcgui;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import net.kdt.pojavlaunch.R;
import fr.spse.extended_view.ExtendedButton;
public class LauncherMenuButton extends ExtendedButton {
public LauncherMenuButton(@NonNull Context context) {
super(context);
setSettings();
}
public LauncherMenuButton(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setSettings();
}
/** Set style stuff */
private void setSettings(){
Resources resources = getContext().getResources();
int padding = resources.getDimensionPixelSize(R.dimen._22sdp);
setCompoundDrawablePadding(padding);
setPaddingRelative(padding, 0, 0, 0);
setGravity(Gravity.CENTER_VERTICAL);
setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen._12ssp));
// Set drawable size
int[] sizes = getExtendedViewData().getSizeCompounds();
sizes[0] = resources.getDimensionPixelSize(R.dimen._30sdp);
getExtendedViewData().setSizeCompounds(sizes);
postProcessDrawables();
}
}
@@ -1,28 +0,0 @@
package com.kdt.mcgui;
import android.content.*;
import android.graphics.*;
import android.util.*;
import androidx.core.content.res.ResourcesCompat;
import net.kdt.pojavlaunch.R;
public class MineButton extends androidx.appcompat.widget.AppCompatButton {
public MineButton(Context ctx) {
this(ctx, null);
}
public MineButton(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
init();
}
public void init() {
setTypeface(ResourcesCompat.getFont(getContext(), R.font.noto_sans_bold));
setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.mine_button_background, null));
setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen._13ssp));
}
}
@@ -1,23 +0,0 @@
package com.kdt.mcgui;
import android.content.*;
import android.util.*;
import android.graphics.*;
import android.widget.EditText;
public class MineEditText extends androidx.appcompat.widget.AppCompatEditText {
public MineEditText(Context ctx) {
super(ctx);
init();
}
public MineEditText(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
init();
}
public void init() {
setBackgroundColor(Color.parseColor("#131313"));
setPadding(5, 5, 5, 5);
}
}
@@ -1,165 +0,0 @@
package com.kdt.mcgui;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.collection.ArrayMap;
import androidx.constraintlayout.widget.ConstraintLayout;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
import net.kdt.pojavlaunch.progresskeeper.ProgressListener;
import net.kdt.pojavlaunch.progresskeeper.TaskCountListener;
import net.kdt.pojavlaunch.services.ProgressService;
import java.util.ArrayList;
/** Class staring at specific values and automatically show something if the progress is present
* Since progress is posted in a specific way, The packing/unpacking is handheld by the class
*
* This class relies on ExtraCore for its behavior.
*/
public class ProgressLayout extends ConstraintLayout implements View.OnClickListener, TaskCountListener{
public static final String UNPACK_RUNTIME = "unpack_runtime";
public static final String DOWNLOAD_MINECRAFT = "download_minecraft";
public static final String DOWNLOAD_VERSION_LIST = "download_verlist";
public static final String AUTHENTICATE_MICROSOFT = "authenticate_microsoft";
public static final String INSTALL_MODPACK = "install_modpack";
public static final String EXTRACT_COMPONENTS = "extract_components";
public static final String EXTRACT_SINGLE_FILES = "extract_single_files";
public ProgressLayout(@NonNull Context context) {
super(context);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private final ArrayList<LayoutProgressListener> mMap = new ArrayList<>();
private LinearLayout mLinearLayout;
private TextView mTaskNumberDisplayer;
private ImageView mFlipArrow;
public void observe(String progressKey){
mMap.add(new LayoutProgressListener(progressKey));
}
public void cleanUpObservers() {
for(LayoutProgressListener progressListener : mMap) {
ProgressKeeper.removeListener(progressListener.progressKey, progressListener);
}
}
public boolean hasProcesses(){
return ProgressKeeper.getTaskCount() > 0;
}
private void init(){
inflate(getContext(), R.layout.view_progress, this);
mLinearLayout = findViewById(R.id.progress_linear_layout);
mTaskNumberDisplayer = findViewById(R.id.progress_textview);
mFlipArrow = findViewById(R.id.progress_flip_arrow);
setBackgroundColor(getResources().getColor(R.color.background_bottom_bar));
setOnClickListener(this);
}
/** Update the progress bar content */
public static void setProgress(String progressKey, int progress){
ProgressKeeper.submitProgress(progressKey, progress, -1, (Object)null);
}
/** Update the text and progress content */
public static void setProgress(String progressKey, int progress, @StringRes int resource, Object... message){
ProgressKeeper.submitProgress(progressKey, progress, resource, message);
}
/** Update the text and progress content */
public static void setProgress(String progressKey, int progress, String message){
setProgress(progressKey,progress, -1, message);
}
/** Update the text and progress content */
public static void clearProgress(String progressKey){
setProgress(progressKey, -1, -1);
}
@Override
public void onClick(View v) {
mLinearLayout.setVisibility(mLinearLayout.getVisibility() == GONE ? VISIBLE : GONE);
mFlipArrow.setRotation(mLinearLayout.getVisibility() == GONE? 0 : 180);
}
@Override
public void onUpdateTaskCount(int tc) {
post(()->{
if(tc > 0) {
mTaskNumberDisplayer.setText(getContext().getString(R.string.progresslayout_tasks_in_progress, tc));
setVisibility(VISIBLE);
}else
setVisibility(GONE);
});
}
class LayoutProgressListener implements ProgressListener {
final String progressKey;
final TextProgressBar textView;
final LinearLayout.LayoutParams params;
public LayoutProgressListener(String progressKey) {
this.progressKey = progressKey;
textView = new TextProgressBar(getContext());
textView.setTextPadding(getContext().getResources().getDimensionPixelOffset(R.dimen._6sdp));
params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, getResources().getDimensionPixelOffset(R.dimen._20sdp));
params.bottomMargin = getResources().getDimensionPixelOffset(R.dimen._6sdp);
ProgressKeeper.addListener(progressKey, this);
}
@Override
public void onProgressStarted() {
post(()-> {
Log.i("ProgressLayout", "onProgressStarted");
mLinearLayout.addView(textView, params);
});
}
@Override
public void onProgressUpdated(int progress, int resid, Object... va) {
post(()-> {
textView.setProgress(progress);
if(resid != -1) textView.setText(getContext().getString(resid, va));
else if(va.length > 0 && va[0] != null)textView.setText((String)va[0]);
else textView.setText("");
});
}
@Override
public void onProgressEnded() {
post(()-> {
mLinearLayout.removeView(textView);
});
}
}
}
@@ -1,68 +0,0 @@
package com.kdt.mcgui;
import android.content.Context;
import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ProgressBar;
import androidx.annotation.StringRes;
import androidx.core.content.res.ResourcesCompat;
import net.kdt.pojavlaunch.R;
public class TextProgressBar extends ProgressBar {
private int mTextPadding = 0;
public TextProgressBar(Context context) {super(context, null, android.R.attr.progressBarStyleHorizontal); init();}
public TextProgressBar(Context context, AttributeSet attrs) {super(context, attrs, android.R.attr.progressBarStyleHorizontal); init();}
public TextProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, android.R.attr.progressBarStyleHorizontal);
init();
}
public TextProgressBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, android.R.attr.progressBarStyleHorizontal, defStyleRes);
init();
}
private Paint mTextPaint;
private String mText = "";
private void init(){
setProgressDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.view_text_progressbar, null));
setProgress(35);
mTextPaint = new Paint();
mTextPaint.setColor(Color.WHITE);
mTextPaint.setFlags(Paint.FAKE_BOLD_TEXT_FLAG);
mTextPaint.setAntiAlias(true);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
mTextPaint.setTextSize((float) ((getHeight()- getPaddingBottom() - getPaddingTop()) * 0.55));
int xPos = (int) Math.max(Math.min((getProgress() * getWidth() / getMax()) + mTextPadding, getWidth() - mTextPaint.measureText(mText) - mTextPadding) , mTextPadding);
int yPos = (int) ((getHeight() / 2) - ((mTextPaint.descent() + mTextPaint.ascent()) / 2)) ;
canvas.drawText(mText, xPos, yPos, mTextPaint);
}
public final void setText(@StringRes int resid) {
setText(getContext().getResources().getText(resid).toString());
}
public final void setText(String text){
mText = text;
invalidate();
}
public final void setTextPadding(int padding){
mTextPadding = padding;
}
}
@@ -1,379 +0,0 @@
package com.kdt.mcgui;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
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;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.authenticator.listener.DoneListener;
import net.kdt.pojavlaunch.authenticator.listener.ErrorListener;
import net.kdt.pojavlaunch.authenticator.listener.ProgressListener;
import net.kdt.pojavlaunch.authenticator.microsoft.PresentedException;
import net.kdt.pojavlaunch.authenticator.microsoft.MicrosoftBackgroundLogin;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.extra.ExtraListener;
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;
public class mcAccountSpinner extends AppCompatSpinner implements AdapterView.OnItemSelectedListener {
public mcAccountSpinner(@NonNull Context context) {
this(context, null);
}
public mcAccountSpinner(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
private final List<String> mAccountList = new ArrayList<>(2);
private MinecraftAccount mSelectecAccount = null;
/* Display the head of the current profile, here just to allow bitmap recycling */
private BitmapDrawable mHeadDrawable;
/* Current animator to for the login bar, is swapped when changing step */
private ObjectAnimator mLoginBarAnimator;
private float mLoginBarWidth = -1;
/* Paint used to display the bottom bar, to show the login progress. */
private final Paint mLoginBarPaint = new Paint();
/* When a login is performed in the background, we need to know where we are */
private final static int MAX_LOGIN_STEP = 5;
private int mLoginStep = 0;
/* Login listeners */
private final ProgressListener mProgressListener = step -> {
// Animate the login bar, cosmetic purposes only
mLoginStep = step;
if(mLoginBarAnimator != null){
mLoginBarAnimator.cancel();
mLoginBarAnimator.setFloatValues( mLoginBarWidth, (getWidth()/MAX_LOGIN_STEP * mLoginStep));
}else{
mLoginBarAnimator = ObjectAnimator.ofFloat(this, "LoginBarWidth", mLoginBarWidth, (getWidth()/MAX_LOGIN_STEP * mLoginStep));
}
mLoginBarAnimator.start();
};
private final DoneListener mDoneListener = account -> {
Toast.makeText(getContext(), R.string.main_login_done, Toast.LENGTH_SHORT).show();
// Check if the account being added is not one that is already existing
// Like login twice on the same mc account...
for(String mcAccountName : mAccountList){
if(mcAccountName.equals(account.username)) return;
}
mSelectecAccount = account;
invalidate();
mAccountList.add(account.username);
reloadAccounts(false, mAccountList.size() -1);
};
private final ErrorListener mErrorListener = errorMessage -> {
mLoginBarPaint.setColor(Color.RED);
Context context = getContext();
if(errorMessage instanceof PresentedException) {
PresentedException exception = (PresentedException) errorMessage;
Throwable cause = exception.getCause();
if(cause == null) {
Tools.dialog(context, context.getString(R.string.global_error), exception.toString(context));
}else {
Tools.showError(context, exception.toString(context), exception.getCause());
}
}else {
Tools.showError(getContext(), errorMessage);
}
invalidate();
};
/* Triggered when we need to do microsoft login */
private final ExtraListener<Uri> mMicrosoftLoginListener = (key, value) -> {
mLoginBarPaint.setColor(getResources().getColor(R.color.minebutton_color));
new MicrosoftBackgroundLogin(false, value.getQueryParameter("code")).performLogin(
mProgressListener, mDoneListener, mErrorListener);
return false;
};
/* Triggered when we need to perform mojang login */
private final ExtraListener<String[]> mMojangLoginListener = (key, value) -> {
if(value[1].isEmpty()){ // Test mode
MinecraftAccount account = new MinecraftAccount();
account.username = value[0];
try {
account.save();
}catch (IOException e){
Log.e("McAccountSpinner", "Failed to save the account : " + e);
}
mDoneListener.onLoginDone(account);
}
return false;
};
@SuppressLint("ClickableViewAccessibility")
private void init(){
// Set visual properties
setBackgroundColor(getResources().getColor(R.color.background_status_bar));
mLoginBarPaint.setColor(getResources().getColor(R.color.minebutton_color));
mLoginBarPaint.setStrokeWidth(getResources().getDimensionPixelOffset(R.dimen._2sdp));
// Set behavior
reloadAccounts(true, 0);
setOnItemSelectedListener(this);
ExtraCore.addExtraListener(ExtraConstants.MOJANG_LOGIN_TODO, mMojangLoginListener);
ExtraCore.addExtraListener(ExtraConstants.MICROSOFT_LOGIN_TODO, mMicrosoftLoginListener);
}
@Override
public final void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){ // Add account button
if(mAccountList.size() > 1){
ExtraCore.setValue(ExtraConstants.SELECT_AUTH_METHOD, true);
}
return;
}
pickAccount(position);
if(mSelectecAccount != null)
performLogin(mSelectecAccount);
}
@Override
public final void onNothingSelected(AdapterView<?> parent) {}
@Override
protected void onDraw(Canvas canvas) {
if(mLoginBarWidth == -1) mLoginBarWidth = getWidth(); // Initial draw
float bottom = getHeight() - mLoginBarPaint.getStrokeWidth()/2;
canvas.drawLine(0, bottom, mLoginBarWidth, bottom, mLoginBarPaint);
}
public void removeCurrentAccount(){
int position = getSelectedItemPosition();
if(position == 0) return;
File accountFile = new File(Tools.DIR_ACCOUNT_NEW, mAccountList.get(position)+".json");
if(accountFile.exists()) accountFile.delete();
mAccountList.remove(position);
reloadAccounts(false, 0);
}
@Keep
public void setLoginBarWidth(float value){
mLoginBarWidth = value;
invalidate(); // Need to redraw each time this is changed
}
/** Allows checking whether we have an online account */
public boolean isAccountOnline(){
return mSelectecAccount != null && !mSelectecAccount.accessToken.equals("0");
}
public MinecraftAccount getSelectedAccount(){
return mSelectecAccount;
}
public int getLoginState(){
return mLoginStep;
}
public boolean isLoginDone(){
return mLoginStep >= MAX_LOGIN_STEP;
}
@SuppressLint("ClickableViewAccessibility")
private void setNoAccountBehavior(){
// Set custom behavior when no account are present, to make it act as a button
if(mAccountList.size() != 1){
// Remove any touch listener
setOnTouchListener(null);
return;
}
// Make the spinner act like a button, since there is no item to really select
setOnTouchListener((v, event) -> {
if(event.getAction() != MotionEvent.ACTION_UP) return false;
// The activity should intercept this and spawn another fragment
ExtraCore.setValue(ExtraConstants.SELECT_AUTH_METHOD, true);
return true;
});
}
/**
* Reload the spinner, from memory or from scratch. A default account can be selected
* @param fromFiles Whether we use files as the source of truth
* @param overridePosition Force the spinner to be at this position, if not 0
*/
private void reloadAccounts(boolean fromFiles, int overridePosition){
if(fromFiles){
mAccountList.clear();
mAccountList.add(getContext().getString(R.string.main_add_account));
File accountFolder = new File(Tools.DIR_ACCOUNT_NEW);
if(accountFolder.exists()){
for (String fileName : accountFolder.list()) {
mAccountList.add(fileName.substring(0, fileName.length() - 5));
}
}
}
String[] accountArray = mAccountList.toArray(new String[0]);
AccountAdapter accountAdapter = new AccountAdapter(getContext(), R.layout.item_minecraft_account, accountArray);
accountAdapter.setDropDownViewResource(R.layout.item_minecraft_account);
setAdapter(accountAdapter);
// Pick what's available, might just be the the add account "button"
pickAccount(overridePosition == 0 ? -1 : overridePosition);
if(mSelectecAccount != null)
performLogin(mSelectecAccount);
// Remove or add the behavior if needed
setNoAccountBehavior();
}
private void performLogin(MinecraftAccount minecraftAccount){
if(minecraftAccount.isLocal()) return;
mLoginBarPaint.setColor(getResources().getColor(R.color.minebutton_color));
if(minecraftAccount.isMicrosoft){
if(System.currentTimeMillis() > minecraftAccount.expiresAt){
// Perform login only if needed
new MicrosoftBackgroundLogin(true, minecraftAccount.msaRefreshToken)
.performLogin(mProgressListener, mDoneListener, mErrorListener);
}
return;
}
}
/** Pick the selected account, the one in settings if 0 is passed */
private void pickAccount(int position){
MinecraftAccount selectedAccount;
if(position != -1){
PojavProfile.setCurrentProfile(getContext(), mAccountList.get(position));
selectedAccount = PojavProfile.getCurrentProfileContent(getContext(), mAccountList.get(position));
// WORKAROUND
// Account file corrupted due to previous versions having improper encoding
if (selectedAccount == null){
removeCurrentAccount();
pickAccount(-1);
setSelection(0);
return;
}
setSelection(position);
}else {
// Get the current profile, or the first available profile if the wanted one is unavailable
selectedAccount = PojavProfile.getCurrentProfileContent(getContext(), null);
int spinnerPosition = selectedAccount == null
? mAccountList.size() <= 1 ? 0 : 1
: mAccountList.indexOf(selectedAccount.username);
setSelection(spinnerPosition, false);
}
mSelectecAccount = selectedAccount;
setImageFromSelectedAccount();
}
@Deprecated()
/* Legacy behavior, update the head image manually for the selected account */
private void setImageFromSelectedAccount(){
BitmapDrawable oldBitmapDrawable = mHeadDrawable;
if(mSelectecAccount != null){
ExtendedTextView view = ((ExtendedTextView) getSelectedView());
if(view != null){
Bitmap bitmap = mSelectecAccount.getSkinFace();
if(bitmap != null) {
mHeadDrawable = new BitmapDrawable(getResources(), bitmap);
view.setCompoundDrawables(mHeadDrawable, null, null, null);
}else{
view.setCompoundDrawables(null, null, null, null);
}
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;
}
}
}
@@ -1,201 +0,0 @@
package com.kdt.mcgui;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static net.kdt.pojavlaunch.fragments.ProfileEditorFragment.DELETED_PROFILE;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.transition.Slide;
import android.transition.Transition;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.PopupWindow;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.FragmentActivity;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.fragments.ProfileEditorFragment;
import net.kdt.pojavlaunch.fragments.ProfileTypeSelectFragment;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.profiles.ProfileAdapter;
import net.kdt.pojavlaunch.profiles.ProfileAdapterExtra;
import fr.spse.extended_view.ExtendedTextView;
/**
* A class implementing custom spinner like behavior, notably:
* dropdown popup view with a custom direction.
*/
public class mcVersionSpinner extends ExtendedTextView {
private static final int VERSION_SPINNER_PROFILE_CREATE = 0;
public mcVersionSpinner(@NonNull Context context) {
super(context);
init();
}
public mcVersionSpinner(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public mcVersionSpinner(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
/* The class is in charge of displaying its own list with adapter content being known in advance */
private ListView mListView = null;
private PopupWindow mPopupWindow = null;
private Object mPopupAnimation;
private int mSelectedIndex;
private final ProfileAdapter mProfileAdapter = new ProfileAdapter(new ProfileAdapterExtra[]{
new ProfileAdapterExtra(VERSION_SPINNER_PROFILE_CREATE,
R.string.create_profile,
ResourcesCompat.getDrawable(getResources(), R.drawable.ic_add, null)),
});
/** Set the selection AND saves it as a shared preference */
public void setProfileSelection(int position){
setSelection(position);
LauncherPreferences.DEFAULT_PREF.edit()
.putString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,
mProfileAdapter.getItem(position).toString())
.apply();
}
public void setSelection(int position){
if(mListView != null) mListView.setSelection(position);
mProfileAdapter.setView(this, mProfileAdapter.getItem(position), false);
mSelectedIndex = position;
}
public void openProfileEditor(FragmentActivity fragmentActivity) {
Object currentSelection = mProfileAdapter.getItem(mSelectedIndex);
if(currentSelection instanceof ProfileAdapterExtra) {
performExtraAction((ProfileAdapterExtra) currentSelection);
}else{
Tools.swapFragment(fragmentActivity, ProfileEditorFragment.class, ProfileEditorFragment.TAG, null);
}
}
/** Reload profiles from the file, forcing the spinner to consider the new data */
public void reloadProfiles(){
mProfileAdapter.reloadProfiles();
}
/** Initialize various behaviors */
private void init(){
// Setup various attributes
setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen._12ssp));
setGravity(Gravity.CENTER_VERTICAL);
int startPadding = getContext().getResources().getDimensionPixelOffset(R.dimen._17sdp);
int endPadding = getContext().getResources().getDimensionPixelOffset(R.dimen._5sdp);
setPaddingRelative(startPadding, 0, endPadding, 0);
setCompoundDrawablePadding(startPadding);
int profileIndex;
String extra_value = (String) ExtraCore.consumeValue(ExtraConstants.REFRESH_VERSION_SPINNER);
if(extra_value != null){
profileIndex = extra_value.equals(DELETED_PROFILE) ? 0
: getProfileAdapter().resolveProfileIndex(extra_value);
}else
profileIndex = mProfileAdapter.resolveProfileIndex(
LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,""));
setProfileSelection(Math.max(0,profileIndex));
// Popup window behavior
setOnClickListener(new OnClickListener() {
final int offset = -getContext().getResources().getDimensionPixelOffset(R.dimen._4sdp);
@Override
public void onClick(View v) {
if(mPopupWindow == null) getPopupWindow();
if(mPopupWindow.isShowing()){
mPopupWindow.dismiss();
return;
}
mPopupWindow.showAsDropDown(mcVersionSpinner.this, 0, offset);
// Post() is required for the layout inflation phase
post(() -> mListView.setSelection(mSelectedIndex));
}
});
}
private void performExtraAction(ProfileAdapterExtra extra) {
//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, null);
}
}
/** Create the listView and popup window for the interface, and set up the click behavior */
@SuppressLint("ClickableViewAccessibility")
private void getPopupWindow(){
mListView = (ListView) inflate(getContext(), R.layout.spinner_mc_version, null);
mListView.setAdapter(mProfileAdapter);
mListView.setOnItemClickListener((parent, view, position, id) -> {
Object item = mProfileAdapter.getItem(position);
if(item instanceof String) {
hidePopup(true);
setProfileSelection(position);
}else if(item instanceof ProfileAdapterExtra) {
hidePopup(false);
performExtraAction((ProfileAdapterExtra) item);
}
});
mPopupWindow = new PopupWindow(mListView, MATCH_PARENT, getContext().getResources().getDimensionPixelOffset(R.dimen._184sdp));
mPopupWindow.setElevation(5);
mPopupWindow.setClippingEnabled(false);
// Block clicking outside of the popup window
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setFocusable(true);
mPopupWindow.setTouchInterceptor((v, event) -> {
if(event.getAction() == MotionEvent.ACTION_OUTSIDE){
mPopupWindow.dismiss();
return true;
}
return false;
});
// Custom animation, nice slide in
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
mPopupAnimation = new Slide(Gravity.BOTTOM);
mPopupWindow.setEnterTransition((Transition) mPopupAnimation);
mPopupWindow.setExitTransition((Transition) mPopupAnimation);
}
}
private void hidePopup(boolean animate) {
if(mPopupWindow == null) return;
if(!animate && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mPopupWindow.setEnterTransition(null);
mPopupWindow.setExitTransition(null);
mPopupWindow.dismiss();
mPopupWindow.setEnterTransition((Transition) mPopupAnimation);
mPopupWindow.setExitTransition((Transition) mPopupAnimation);
}else {
mPopupWindow.dismiss();
}
}
public ProfileAdapter getProfileAdapter() {
return mProfileAdapter;
}
}
@@ -1,5 +0,0 @@
package com.kdt.pickafile;
public interface DialogTitleListener {
void onChangeDialogTitle(String newTitle);
}
@@ -1,187 +0,0 @@
package com.kdt.pickafile;
import androidx.appcompat.app.*;
import android.content.*;
import android.util.*;
import android.widget.*;
import com.ipaulpro.afilechooser.*;
import java.io.*;
import java.util.*;
import net.kdt.pojavlaunch.*;
import android.os.*;
public class FileListView extends LinearLayout
{
//For list view:
private File fullPath;
private ListView mainLv;
private Context context;
//For File selected listener:
private FileSelectedListener fileSelectedListener;
private DialogTitleListener dialogTitleListener;
private File lockPath = new File("/");
//For filtering by file types:
private final String[] fileSuffixes;
private boolean showFiles = true;
private boolean showFolders = true;
public FileListView(AlertDialog build) {
this(build.getContext(), null, new String[0]);
dialogToTitleListener(build);
}
public FileListView(AlertDialog build, String fileSuffix) {
this(build.getContext(), null, new String[]{fileSuffix});
dialogToTitleListener(build);
}
public FileListView(AlertDialog build, String[] fileSuffixes){
this(build.getContext(), null, fileSuffixes);
dialogToTitleListener(build);
}
public FileListView(Context context){
this(context, null);
}
public FileListView(Context context, AttributeSet attrs){
this(context, attrs, new String[0]);
}
public FileListView(Context context, AttributeSet attrs, String[] fileSuffixes) {
this(context, attrs, 0, fileSuffixes);
}
public FileListView(Context context, AttributeSet attrs, int defStyle, String[] fileSuffixes) {
super(context, attrs, defStyle);
this.fileSuffixes = fileSuffixes;
init(context);
}
private void dialogToTitleListener(AlertDialog dialog) {
if(dialog != null) dialogTitleListener = dialog::setTitle;
}
public void init(final Context context) {
//Main setup:
this.context = context;
LayoutParams layParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
setOrientation(VERTICAL);
mainLv = new ListView(context);
mainLv.setOnItemClickListener((p1, p2, p3, p4) -> {
// TODO: Implement this method
File mainFile = new File(p1.getItemAtPosition(p3).toString());
if (p3 == 0 && !lockPath.equals(fullPath)) {
parentDir();
} else {
listFileAt(mainFile);
}
});
mainLv.setOnItemLongClickListener((p1, p2, p3, p4) -> {
// TODO: Implement this method
File mainFile = new File(p1.getItemAtPosition(p3).toString());
if (mainFile.isFile()) {
fileSelectedListener.onFileLongClick(mainFile, mainFile.getAbsolutePath());
return true;
}
return false;
});
addView(mainLv, layParam);
try {
listFileAt(Environment.getExternalStorageDirectory());
} catch (NullPointerException e) {} // Android 10+ disallows access to sdcard
}
public void setFileSelectedListener(FileSelectedListener listener)
{
this.fileSelectedListener = listener;
}
public void setDialogTitleListener(DialogTitleListener listener) {
this.dialogTitleListener = listener;
}
public void listFileAt(final File path) {
try{
if(path.exists()){
if(path.isDirectory()){
fullPath = path;
File[] listFile = path.listFiles();
FileListAdapter fileAdapter = new FileListAdapter(context);
if(!path.equals(lockPath)){
fileAdapter.add(new File(path, ".."));
}
if(listFile != null && listFile.length != 0){
Arrays.sort(listFile, new SortFileName());
for(File file : listFile){
if(file.isDirectory()){
if(showFolders && ((!file.getName().startsWith(".")) || file.getName().equals(".minecraft")))
fileAdapter.add(file);
continue;
}
if(showFiles){
if(fileSuffixes.length > 0){
for(String suffix : fileSuffixes){
if(file.getName().endsWith("." + suffix)){
fileAdapter.add(file);
break;
}
}
}else {
fileAdapter.add(file);
}
}
}
}
mainLv.setAdapter(fileAdapter);
if(dialogTitleListener != null) dialogTitleListener.onChangeDialogTitle(path.getAbsolutePath());
} else {
fileSelectedListener.onFileSelected(path, path.getAbsolutePath());
}
} else {
Toast.makeText(context, "This folder (or file) doesn't exist", Toast.LENGTH_SHORT).show();
refreshPath();
}
} catch (Exception e){
Tools.showError(context, e);
}
}
public File getFullPath(){
return fullPath;
}
public void refreshPath() {
listFileAt(getFullPath());
}
public void parentDir() {
if(!fullPath.getAbsolutePath().equals("/")){
listFileAt(fullPath.getParentFile());
}
}
public void lockPathAt(File path) {
lockPath = path;
listFileAt(path);
}
public void setShowFiles(boolean showFiles){
this.showFiles = showFiles;
}
public void setShowFolders(boolean showFolders){
this.showFolders = showFolders;
}
}
@@ -1,9 +0,0 @@
package com.kdt.pickafile;
import java.io.File;
public abstract class FileSelectedListener
{
public abstract void onFileSelected(File file, String path);
public void onFileLongClick(File file, String path) {}
}
@@ -1,13 +0,0 @@
package com.kdt.pickafile;
import java.io.*;
import java.util.*;
public class SortFileName implements Comparator<File>
{
@Override
public int compare(File f1, File f2) {
return f1.getName().compareToIgnoreCase(f2.getName());
}
}
@@ -1,7 +0,0 @@
package com.oracle.dalvik;
public final class VMLauncher {
private VMLauncher() {
}
public static native int launchJVM(String[] args);
}
@@ -1,12 +0,0 @@
package dalvik.annotation.optimization;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Dummy CriticalNative annotation. On devices which dont have it this declaration will prevent errors.
// On devices that do have it it will be overridden by the system one and work as usual
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface CriticalNative {
}
@@ -1,116 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.*;
import android.graphics.*;
import android.text.*;
import android.util.*;
import android.view.*;
import java.util.*;
import net.kdt.pojavlaunch.utils.*;
public class AWTCanvasView extends TextureView implements TextureView.SurfaceTextureListener, Runnable {
public static final int AWT_CANVAS_WIDTH = 720;
public static final int AWT_CANVAS_HEIGHT = 600;
private static final int MAX_SIZE = 100;
private static final double NANOS = 1000000000.0;
private boolean mIsDestroyed = false;
private final TextPaint mFpsPaint;
// Temporary count fps https://stackoverflow.com/a/13729241
private final LinkedList<Long> mTimes = new LinkedList<Long>(){{add(System.nanoTime());}};
public AWTCanvasView(Context ctx) {
this(ctx, null);
}
public AWTCanvasView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
mFpsPaint = new TextPaint();
mFpsPaint.setColor(Color.WHITE);
mFpsPaint.setTextSize(20);
setSurfaceTextureListener(this);
post(this::refreshSize);
}
@Override
public void onSurfaceTextureAvailable(SurfaceTexture texture, int w, int h) {
getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT);
mIsDestroyed = false;
new Thread(this, "AndroidAWTRenderer").start();
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
mIsDestroyed = true;
return true;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int w, int h) {
getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT);
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture texture) {
getSurfaceTexture().setDefaultBufferSize(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT);
}
@Override
public void run() {
Canvas canvas;
Surface surface = new Surface(getSurfaceTexture());
Bitmap rgbArrayBitmap = Bitmap.createBitmap(AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT, Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
try {
while (!mIsDestroyed && surface.isValid()) {
canvas = surface.lockCanvas(null);
canvas.drawRGB(0, 0, 0);
int[] rgbArray = JREUtils.renderAWTScreenFrame(/* canvas, mWidth, mHeight */);
boolean mDrawing = rgbArray != null;
if (rgbArray != null) {
canvas.save();
rgbArrayBitmap.setPixels(rgbArray, 0, AWT_CANVAS_WIDTH, 0, 0, AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT);
canvas.drawBitmap(rgbArrayBitmap, 0, 0, paint);
canvas.restore();
}
canvas.drawText("FPS: " + (Math.round(fps() * 10) / 10) + ", drawing=" + mDrawing, 0, 20, mFpsPaint);
surface.unlockCanvasAndPost(canvas);
}
} catch (Throwable throwable) {
Tools.showError(getContext(), throwable);
}
rgbArrayBitmap.recycle();
surface.release();
}
/** Calculates and returns frames per second */
private double fps() {
long lastTime = System.nanoTime();
double difference = (lastTime - mTimes.getFirst()) / NANOS;
mTimes.addLast(lastTime);
int size = mTimes.size();
if (size > MAX_SIZE) {
mTimes.removeFirst();
}
return difference > 0 ? mTimes.size() / difference : 0.0;
}
/** Make the view fit the proper aspect ratio of the surface */
private void refreshSize(){
ViewGroup.LayoutParams layoutParams = getLayoutParams();
if(getHeight() < getWidth()){
layoutParams.width = AWT_CANVAS_WIDTH * getHeight() / AWT_CANVAS_HEIGHT;
}else{
layoutParams.height = AWT_CANVAS_HEIGHT * getWidth() / AWT_CANVAS_WIDTH;
}
setLayoutParams(layoutParams);
}
}
@@ -1,44 +0,0 @@
package net.kdt.pojavlaunch;
public class AWTInputBridge {
public static final int EVENT_TYPE_CHAR = 1000;
public static final int EVENT_TYPE_CURSOR_POS = 1003;
public static final int EVENT_TYPE_KEY = 1005;
public static final int EVENT_TYPE_MOUSE_BUTTON = 1006;
public static void sendKey(char keychar, int keycode) {
// TODO: Android -> AWT keycode mapping
nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, 1, 0);
nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, 0, 0);
}
public static void sendKey(char keychar, int keycode, int state) {
// TODO: Android -> AWT keycode mapping
nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, state, 0);
}
public static void sendChar(char keychar){
nativeSendData(EVENT_TYPE_CHAR, (int) keychar, 0, 0, 0);
}
public static void sendMousePress(int awtButtons, boolean isDown) {
nativeSendData(EVENT_TYPE_MOUSE_BUTTON, awtButtons, isDown ? 1 : 0, 0, 0);
}
public static void sendMousePress(int awtButtons) {
sendMousePress(awtButtons, true);
sendMousePress(awtButtons, false);
}
public static void sendMousePos(int x, int y) {
nativeSendData(EVENT_TYPE_CURSOR_POS, x, y, 0, 0);
}
static {
System.loadLibrary("pojavexec_awt");
}
public static native void nativeSendData(int type, int i1, int i2, int i3, int i4);
public static native void nativeClipboardReceived(String data, String mimeTypeSub);
public static native void nativeMoveWindow(int xoff, int yoff);
}
@@ -1,913 +0,0 @@
package net.kdt.pojavlaunch;
/*
* Copyright (c) 1996, 2009, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
@SuppressWarnings("unused")
public class AWTInputEvent {
// InputEvent
/**
* This flag indicates that the Shift key was down when the event
* occurred.
*/
public static final int SHIFT_MASK = 1; //first bit
/**
* This flag indicates that the Control key was down when the event
* occurred.
*/
public static final int CTRL_MASK = 1 << 1;
/**
* This flag indicates that the Meta key was down when the event
* occurred. For mouse events, this flag indicates that the right
* button was pressed or released.
*/
public static final int META_MASK = 1 << 2;
/**
* This flag indicates that the Alt key was down when
* the event occurred. For mouse events, this flag indicates that the
* middle mouse button was pressed or released.
*/
public static final int ALT_MASK = 1 << 3;
/**
* The AltGraph key modifier constant.
*/
public static final int ALT_GRAPH_MASK = 1 << 5;
/**
* The Mouse Button1 modifier constant.
* It is recommended that BUTTON1_DOWN_MASK be used instead.
*/
public static final int BUTTON1_MASK = 1 << 4;
/**
* The Mouse Button2 modifier constant.
* It is recommended that BUTTON2_DOWN_MASK be used instead.
* Note that BUTTON2_MASK has the same value as ALT_MASK.
*/
public static final int BUTTON2_MASK = ALT_MASK;
/**
* The Mouse Button3 modifier constant.
* It is recommended that BUTTON3_DOWN_MASK be used instead.
* Note that BUTTON3_MASK has the same value as META_MASK.
*/
public static final int BUTTON3_MASK = META_MASK;
/**
* The Shift key extended modifier constant.
* @since 1.4
*/
public static final int SHIFT_DOWN_MASK = 1 << 6;
/**
* The Control key extended modifier constant.
* @since 1.4
*/
public static final int CTRL_DOWN_MASK = 1 << 7;
/**
* The Meta key extended modifier constant.
* @since 1.4
*/
public static final int META_DOWN_MASK = 1 << 8;
/**
* The Alt key extended modifier constant.
* @since 1.4
*/
public static final int ALT_DOWN_MASK = 1 << 9;
/**
* The Mouse Button1 extended modifier constant.
* @since 1.4
*/
public static final int BUTTON1_DOWN_MASK = 1 << 10;
/**
* The Mouse Button2 extended modifier constant.
* @since 1.4
*/
public static final int BUTTON2_DOWN_MASK = 1 << 11;
/**
* The Mouse Button3 extended modifier constant.
* @since 1.4
*/
public static final int BUTTON3_DOWN_MASK = 1 << 12;
/**
* The AltGraph key extended modifier constant.
* @since 1.4
*/
public static final int ALT_GRAPH_DOWN_MASK = 1 << 13;
// KeyEvent
/**
* The first number in the range of ids used for key events.
*/
public static final int KEY_FIRST = 400;
/**
* The last number in the range of ids used for key events.
*/
public static final int KEY_LAST = 402;
/**
* The "key typed" event. This event is generated when a character is
* entered. In the simplest case, it is produced by a single key press.
* Often, however, characters are produced by series of key presses, and
* the mapping from key pressed events to key typed events may be
* many-to-one or many-to-many.
*/
public static final int KEY_TYPED = KEY_FIRST;
/**
* The "key pressed" event. This event is generated when a key
* is pushed down.
*/
public static final int KEY_PRESSED = 1 + KEY_FIRST; //Event.KEY_PRESS
/**
* The "key released" event. This event is generated when a key
* is let up.
*/
public static final int KEY_RELEASED = 2 + KEY_FIRST; //Event.KEY_RELEASE
/* Virtual key codes. */
public static final int VK_ENTER = '\n';
public static final int VK_BACK_SPACE = '\b';
public static final int VK_TAB = '\t';
public static final int VK_CANCEL = 0x03;
public static final int VK_CLEAR = 0x0C;
public static final int VK_SHIFT = 0x10;
public static final int VK_CONTROL = 0x11;
public static final int VK_ALT = 0x12;
public static final int VK_PAUSE = 0x13;
public static final int VK_CAPS_LOCK = 0x14;
public static final int VK_ESCAPE = 0x1B;
public static final int VK_SPACE = 0x20;
public static final int VK_PAGE_UP = 0x21;
public static final int VK_PAGE_DOWN = 0x22;
public static final int VK_END = 0x23;
public static final int VK_HOME = 0x24;
/**
* Constant for the non-numpad <b>left</b> arrow key.
* @see #VK_KP_LEFT
*/
public static final int VK_LEFT = 0x25;
/**
* Constant for the non-numpad <b>up</b> arrow key.
* @see #VK_KP_UP
*/
public static final int VK_UP = 0x26;
/**
* Constant for the non-numpad <b>right</b> arrow key.
* @see #VK_KP_RIGHT
*/
public static final int VK_RIGHT = 0x27;
/**
* Constant for the non-numpad <b>down</b> arrow key.
* @see #VK_KP_DOWN
*/
public static final int VK_DOWN = 0x28;
/**
* Constant for the comma key, ","
*/
public static final int VK_COMMA = 0x2C;
/**
* Constant for the minus key, "-"
* @since 1.2
*/
public static final int VK_MINUS = 0x2D;
/**
* Constant for the period key, "."
*/
public static final int VK_PERIOD = 0x2E;
/**
* Constant for the forward slash key, "/"
*/
public static final int VK_SLASH = 0x2F;
/** VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) */
public static final int VK_0 = 0x30;
public static final int VK_1 = 0x31;
public static final int VK_2 = 0x32;
public static final int VK_3 = 0x33;
public static final int VK_4 = 0x34;
public static final int VK_5 = 0x35;
public static final int VK_6 = 0x36;
public static final int VK_7 = 0x37;
public static final int VK_8 = 0x38;
public static final int VK_9 = 0x39;
/**
* Constant for the semicolon key, ";"
*/
public static final int VK_SEMICOLON = 0x3B;
/**
* Constant for the equals key, "="
*/
public static final int VK_EQUALS = 0x3D;
/** VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) */
public static final int VK_A = 0x41;
public static final int VK_B = 0x42;
public static final int VK_C = 0x43;
public static final int VK_D = 0x44;
public static final int VK_E = 0x45;
public static final int VK_F = 0x46;
public static final int VK_G = 0x47;
public static final int VK_H = 0x48;
public static final int VK_I = 0x49;
public static final int VK_J = 0x4A;
public static final int VK_K = 0x4B;
public static final int VK_L = 0x4C;
public static final int VK_M = 0x4D;
public static final int VK_N = 0x4E;
public static final int VK_O = 0x4F;
public static final int VK_P = 0x50;
public static final int VK_Q = 0x51;
public static final int VK_R = 0x52;
public static final int VK_S = 0x53;
public static final int VK_T = 0x54;
public static final int VK_U = 0x55;
public static final int VK_V = 0x56;
public static final int VK_W = 0x57;
public static final int VK_X = 0x58;
public static final int VK_Y = 0x59;
public static final int VK_Z = 0x5A;
/**
* Constant for the open bracket key, "["
*/
public static final int VK_OPEN_BRACKET = 0x5B;
/**
* Constant for the back slash key, "\"
*/
public static final int VK_BACK_SLASH = 0x5C;
/**
* Constant for the close bracket key, "]"
*/
public static final int VK_CLOSE_BRACKET = 0x5D;
public static final int VK_NUMPAD0 = 0x60;
public static final int VK_NUMPAD1 = 0x61;
public static final int VK_NUMPAD2 = 0x62;
public static final int VK_NUMPAD3 = 0x63;
public static final int VK_NUMPAD4 = 0x64;
public static final int VK_NUMPAD5 = 0x65;
public static final int VK_NUMPAD6 = 0x66;
public static final int VK_NUMPAD7 = 0x67;
public static final int VK_NUMPAD8 = 0x68;
public static final int VK_NUMPAD9 = 0x69;
public static final int VK_MULTIPLY = 0x6A;
public static final int VK_ADD = 0x6B;
/**
* This constant is obsolete, and is included only for backwards
* compatibility.
* @see #VK_SEPARATOR
*/
public static final int VK_SEPARATER = 0x6C;
/**
* Constant for the Numpad Separator key.
* @since 1.4
*/
public static final int VK_SEPARATOR = VK_SEPARATER;
public static final int VK_SUBTRACT = 0x6D;
public static final int VK_DECIMAL = 0x6E;
public static final int VK_DIVIDE = 0x6F;
public static final int VK_DELETE = 0x7F; /* ASCII DEL */
public static final int VK_NUM_LOCK = 0x90;
public static final int VK_SCROLL_LOCK = 0x91;
/** Constant for the F1 function key. */
public static final int VK_F1 = 0x70;
/** Constant for the F2 function key. */
public static final int VK_F2 = 0x71;
/** Constant for the F3 function key. */
public static final int VK_F3 = 0x72;
/** Constant for the F4 function key. */
public static final int VK_F4 = 0x73;
/** Constant for the F5 function key. */
public static final int VK_F5 = 0x74;
/** Constant for the F6 function key. */
public static final int VK_F6 = 0x75;
/** Constant for the F7 function key. */
public static final int VK_F7 = 0x76;
/** Constant for the F8 function key. */
public static final int VK_F8 = 0x77;
/** Constant for the F9 function key. */
public static final int VK_F9 = 0x78;
/** Constant for the F10 function key. */
public static final int VK_F10 = 0x79;
/** Constant for the F11 function key. */
public static final int VK_F11 = 0x7A;
/** Constant for the F12 function key. */
public static final int VK_F12 = 0x7B;
/**
* Constant for the F13 function key.
* @since 1.2
*/
/* F13 - F24 are used on IBM 3270 keyboard; use random range for constants. */
public static final int VK_F13 = 0xF000;
/**
* Constant for the F14 function key.
* @since 1.2
*/
public static final int VK_F14 = 0xF001;
/**
* Constant for the F15 function key.
* @since 1.2
*/
public static final int VK_F15 = 0xF002;
/**
* Constant for the F16 function key.
* @since 1.2
*/
public static final int VK_F16 = 0xF003;
/**
* Constant for the F17 function key.
* @since 1.2
*/
public static final int VK_F17 = 0xF004;
/**
* Constant for the F18 function key.
* @since 1.2
*/
public static final int VK_F18 = 0xF005;
/**
* Constant for the F19 function key.
* @since 1.2
*/
public static final int VK_F19 = 0xF006;
/**
* Constant for the F20 function key.
* @since 1.2
*/
public static final int VK_F20 = 0xF007;
/**
* Constant for the F21 function key.
* @since 1.2
*/
public static final int VK_F21 = 0xF008;
/**
* Constant for the F22 function key.
* @since 1.2
*/
public static final int VK_F22 = 0xF009;
/**
* Constant for the F23 function key.
* @since 1.2
*/
public static final int VK_F23 = 0xF00A;
/**
* Constant for the F24 function key.
* @since 1.2
*/
public static final int VK_F24 = 0xF00B;
public static final int VK_PRINTSCREEN = 0x9A;
public static final int VK_INSERT = 0x9B;
public static final int VK_HELP = 0x9C;
public static final int VK_META = 0x9D;
public static final int VK_BACK_QUOTE = 0xC0;
public static final int VK_QUOTE = 0xDE;
/**
* Constant for the numeric keypad <b>up</b> arrow key.
* @see #VK_UP
* @since 1.2
*/
public static final int VK_KP_UP = 0xE0;
/**
* Constant for the numeric keypad <b>down</b> arrow key.
* @see #VK_DOWN
* @since 1.2
*/
public static final int VK_KP_DOWN = 0xE1;
/**
* Constant for the numeric keypad <b>left</b> arrow key.
* @see #VK_LEFT
* @since 1.2
*/
public static final int VK_KP_LEFT = 0xE2;
/**
* Constant for the numeric keypad <b>right</b> arrow key.
* @see #VK_RIGHT
* @since 1.2
*/
public static final int VK_KP_RIGHT = 0xE3;
/* For European keyboards */
/** @since 1.2 */
public static final int VK_DEAD_GRAVE = 0x80;
/** @since 1.2 */
public static final int VK_DEAD_ACUTE = 0x81;
/** @since 1.2 */
public static final int VK_DEAD_CIRCUMFLEX = 0x82;
/** @since 1.2 */
public static final int VK_DEAD_TILDE = 0x83;
/** @since 1.2 */
public static final int VK_DEAD_MACRON = 0x84;
/** @since 1.2 */
public static final int VK_DEAD_BREVE = 0x85;
/** @since 1.2 */
public static final int VK_DEAD_ABOVEDOT = 0x86;
/** @since 1.2 */
public static final int VK_DEAD_DIAERESIS = 0x87;
/** @since 1.2 */
public static final int VK_DEAD_ABOVERING = 0x88;
/** @since 1.2 */
public static final int VK_DEAD_DOUBLEACUTE = 0x89;
/** @since 1.2 */
public static final int VK_DEAD_CARON = 0x8a;
/** @since 1.2 */
public static final int VK_DEAD_CEDILLA = 0x8b;
/** @since 1.2 */
public static final int VK_DEAD_OGONEK = 0x8c;
/** @since 1.2 */
public static final int VK_DEAD_IOTA = 0x8d;
/** @since 1.2 */
public static final int VK_DEAD_VOICED_SOUND = 0x8e;
/** @since 1.2 */
public static final int VK_DEAD_SEMIVOICED_SOUND = 0x8f;
/** @since 1.2 */
public static final int VK_AMPERSAND = 0x96;
/** @since 1.2 */
public static final int VK_ASTERISK = 0x97;
/** @since 1.2 */
public static final int VK_QUOTEDBL = 0x98;
/** @since 1.2 */
public static final int VK_LESS = 0x99;
/** @since 1.2 */
public static final int VK_GREATER = 0xa0;
/** @since 1.2 */
public static final int VK_BRACELEFT = 0xa1;
/** @since 1.2 */
public static final int VK_BRACERIGHT = 0xa2;
/**
* Constant for the "@" key.
* @since 1.2
*/
public static final int VK_AT = 0x0200;
/**
* Constant for the ":" key.
* @since 1.2
*/
public static final int VK_COLON = 0x0201;
/**
* Constant for the "^" key.
* @since 1.2
*/
public static final int VK_CIRCUMFLEX = 0x0202;
/**
* Constant for the "$" key.
* @since 1.2
*/
public static final int VK_DOLLAR = 0x0203;
/**
* Constant for the Euro currency sign key.
* @since 1.2
*/
public static final int VK_EURO_SIGN = 0x0204;
/**
* Constant for the "!" key.
* @since 1.2
*/
public static final int VK_EXCLAMATION_MARK = 0x0205;
/**
* Constant for the inverted exclamation mark key.
* @since 1.2
*/
public static final int VK_INVERTED_EXCLAMATION_MARK = 0x0206;
/**
* Constant for the "(" key.
* @since 1.2
*/
public static final int VK_LEFT_PARENTHESIS = 0x0207;
/**
* Constant for the "#" key.
* @since 1.2
*/
public static final int VK_NUMBER_SIGN = 0x0208;
/**
* Constant for the "+" key.
* @since 1.2
*/
public static final int VK_PLUS = 0x0209;
/**
* Constant for the ")" key.
* @since 1.2
*/
public static final int VK_RIGHT_PARENTHESIS = 0x020A;
/**
* Constant for the "_" key.
* @since 1.2
*/
public static final int VK_UNDERSCORE = 0x020B;
/**
* Constant for the Microsoft Windows "Windows" key.
* It is used for both the left and right version of the key.
* see getKeyLocation
* @since 1.5
*/
public static final int VK_WINDOWS = 0x020C;
/**
* Constant for the Microsoft Windows Context Menu key.
* @since 1.5
*/
public static final int VK_CONTEXT_MENU = 0x020D;
/* for input method support on Asian Keyboards */
/* not clear what this means - listed in Microsoft Windows API */
public static final int VK_FINAL = 0x0018;
/** Constant for the Convert function key. */
/* Japanese PC 106 keyboard, Japanese Solaris keyboard: henkan */
public static final int VK_CONVERT = 0x001C;
/** Constant for the Don't Convert function key. */
/* Japanese PC 106 keyboard: muhenkan */
public static final int VK_NONCONVERT = 0x001D;
/** Constant for the Accept or Commit function key. */
/* Japanese Solaris keyboard: kakutei */
public static final int VK_ACCEPT = 0x001E;
/* not clear what this means - listed in Microsoft Windows API */
public static final int VK_MODECHANGE = 0x001F;
/* replaced by VK_KANA_LOCK for Microsoft Windows and Solaris;
might still be used on other platforms */
public static final int VK_KANA = 0x0015;
/* replaced by VK_INPUT_METHOD_ON_OFF for Microsoft Windows and Solaris;
might still be used for other platforms */
public static final int VK_KANJI = 0x0019;
/**
* Constant for the Alphanumeric function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: eisuu */
public static final int VK_ALPHANUMERIC = 0x00F0;
/**
* Constant for the Katakana function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: katakana */
public static final int VK_KATAKANA = 0x00F1;
/**
* Constant for the Hiragana function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: hiragana */
public static final int VK_HIRAGANA = 0x00F2;
/**
* Constant for the Full-Width Characters function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: zenkaku */
public static final int VK_FULL_WIDTH = 0x00F3;
/**
* Constant for the Half-Width Characters function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: hankaku */
public static final int VK_HALF_WIDTH = 0x00F4;
/**
* Constant for the Roman Characters function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard: roumaji */
public static final int VK_ROMAN_CHARACTERS = 0x00F5;
/**
* Constant for the All Candidates function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard - VK_CONVERT + ALT: zenkouho */
public static final int VK_ALL_CANDIDATES = 0x0100;
/**
* Constant for the Previous Candidate function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard - VK_CONVERT + SHIFT: maekouho */
public static final int VK_PREVIOUS_CANDIDATE = 0x0101;
/**
* Constant for the Code Input function key.
* @since 1.2
*/
/* Japanese PC 106 keyboard - VK_ALPHANUMERIC + ALT: kanji bangou */
public static final int VK_CODE_INPUT = 0x0102;
/**
* Constant for the Japanese-Katakana function key.
* This key switches to a Japanese input method and selects its Katakana input mode.
* @since 1.2
*/
/* Japanese Macintosh keyboard - VK_JAPANESE_HIRAGANA + SHIFT */
public static final int VK_JAPANESE_KATAKANA = 0x0103;
/**
* Constant for the Japanese-Hiragana function key.
* This key switches to a Japanese input method and selects its Hiragana input mode.
* @since 1.2
*/
/* Japanese Macintosh keyboard */
public static final int VK_JAPANESE_HIRAGANA = 0x0104;
/**
* Constant for the Japanese-Roman function key.
* This key switches to a Japanese input method and selects its Roman-Direct input mode.
* @since 1.2
*/
/* Japanese Macintosh keyboard */
public static final int VK_JAPANESE_ROMAN = 0x0105;
/**
* Constant for the locking Kana function key.
* This key locks the keyboard into a Kana layout.
* @since 1.3
*/
/* Japanese PC 106 keyboard with special Windows driver - eisuu + Control; Japanese Solaris keyboard: kana */
public static final int VK_KANA_LOCK = 0x0106;
/**
* Constant for the input method on/off key.
* @since 1.3
*/
/* Japanese PC 106 keyboard: kanji. Japanese Solaris keyboard: nihongo */
public static final int VK_INPUT_METHOD_ON_OFF = 0x0107;
/* for Sun keyboards */
/** @since 1.2 */
public static final int VK_CUT = 0xFFD1;
/** @since 1.2 */
public static final int VK_COPY = 0xFFCD;
/** @since 1.2 */
public static final int VK_PASTE = 0xFFCF;
/** @since 1.2 */
public static final int VK_UNDO = 0xFFCB;
/** @since 1.2 */
public static final int VK_AGAIN = 0xFFC9;
/** @since 1.2 */
public static final int VK_FIND = 0xFFD0;
/** @since 1.2 */
public static final int VK_PROPS = 0xFFCA;
/** @since 1.2 */
public static final int VK_STOP = 0xFFC8;
/**
* Constant for the Compose function key.
* @since 1.2
*/
public static final int VK_COMPOSE = 0xFF20;
/**
* Constant for the AltGraph function key.
* @since 1.2
*/
public static final int VK_ALT_GRAPH = 0xFF7E;
/**
* Constant for the Begin key.
* @since 1.5
*/
public static final int VK_BEGIN = 0xFF58;
/**
* This value is used to indicate that the keyCode is unknown.
* KEY_TYPED events do not have a keyCode value; this value
* is used instead.
*/
public static final int VK_UNDEFINED = 0x0;
/**
* KEY_PRESSED and KEY_RELEASED events which do not map to a
* valid Unicode character use this for the keyChar value.
*/
public static final char CHAR_UNDEFINED = 0xFFFF;
/**
* A constant indicating that the keyLocation is indeterminate
* or not relevant.
* <code>KEY_TYPED</code> events do not have a keyLocation; this value
* is used instead.
* @since 1.4
*/
public static final int KEY_LOCATION_UNKNOWN = 0;
/**
* A constant indicating that the key pressed or released
* is not distinguished as the left or right version of a key,
* and did not originate on the numeric keypad (or did not
* originate with a virtual key corresponding to the numeric
* keypad).
* @since 1.4
*/
public static final int KEY_LOCATION_STANDARD = 1;
/**
* A constant indicating that the key pressed or released is in
* the left key location (there is more than one possible location
* for this key). Example: the left shift key.
* @since 1.4
*/
public static final int KEY_LOCATION_LEFT = 2;
/**
* A constant indicating that the key pressed or released is in
* the right key location (there is more than one possible location
* for this key). Example: the right shift key.
* @since 1.4
*/
public static final int KEY_LOCATION_RIGHT = 3;
/**
* A constant indicating that the key event originated on the
* numeric keypad or with a virtual key corresponding to the
* numeric keypad.
* @since 1.4
*/
public static final int KEY_LOCATION_NUMPAD = 4;
// MOUSE
/**
* The first number in the range of ids used for mouse events.
*/
public static final int MOUSE_FIRST = 500;
/**
* The last number in the range of ids used for mouse events.
*/
public static final int MOUSE_LAST = 507;
/**
* The "mouse clicked" event. This <code>MouseEvent</code>
* occurs when a mouse button is pressed and released.
*/
public static final int MOUSE_CLICKED = MOUSE_FIRST;
/**
* The "mouse pressed" event. This <code>MouseEvent</code>
* occurs when a mouse button is pushed down.
*/
public static final int MOUSE_PRESSED = 1 + MOUSE_FIRST; //Event.MOUSE_DOWN
/**
* The "mouse released" event. This <code>MouseEvent</code>
* occurs when a mouse button is let up.
*/
public static final int MOUSE_RELEASED = 2 + MOUSE_FIRST; //Event.MOUSE_UP
/**
* The "mouse moved" event. This <code>MouseEvent</code>
* occurs when the mouse position changes.
*/
public static final int MOUSE_MOVED = 3 + MOUSE_FIRST; //Event.MOUSE_MOVE
/**
* The "mouse entered" event. This <code>MouseEvent</code>
* occurs when the mouse cursor enters the unobscured part of component's
* geometry.
*/
public static final int MOUSE_ENTERED = 4 + MOUSE_FIRST; //Event.MOUSE_ENTER
/**
* The "mouse exited" event. This <code>MouseEvent</code>
* occurs when the mouse cursor exits the unobscured part of component's
* geometry.
*/
public static final int MOUSE_EXITED = 5 + MOUSE_FIRST; //Event.MOUSE_EXIT
/**
* The "mouse dragged" event. This <code>MouseEvent</code>
* occurs when the mouse position changes while a mouse button is pressed.
*/
public static final int MOUSE_DRAGGED = 6 + MOUSE_FIRST; //Event.MOUSE_DRAG
/**
* The "mouse wheel" event. This is the only <code>MouseWheelEvent</code>.
* It occurs when a mouse equipped with a wheel has its wheel rotated.
* @since 1.4
*/
public static final int MOUSE_WHEEL = 7 + MOUSE_FIRST;
/**
* Indicates no mouse buttons; used by getButton.
* @since 1.4
*/
public static final int NOBUTTON = 0;
/**
* Indicates mouse button #1; used by getButton.
* @since 1.4
*/
public static final int BUTTON1 = 1;
/**
* Indicates mouse button #2; used by getButton.
* @since 1.4
*/
public static final int BUTTON2 = 2;
/**
* Indicates mouse button #3; used by getButton.
* @since 1.4
*/
public static final int BUTTON3 = 3;
}
@@ -1,107 +0,0 @@
package net.kdt.pojavlaunch;
import android.os.Build;
/**
* This class aims at providing a simple and easy way to deal with the device architecture.
*/
public class Architecture {
public static final int UNSUPPORTED_ARCH = -1;
public static final int ARCH_ARM64 = 0x1;
public static final int ARCH_ARM = 0x2;
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
*/
public static boolean is64BitsDevice(){
return Build.SUPPORTED_64_BIT_ABIS.length != 0;
}
/**
* Tell us if the device supports 32 bits architecture
* Note, that a 64 bits device won't be reported as supporting 32 bits.
* @return If the device supports 32 bits architecture
*/
public static boolean is32BitsDevice(){
return !is64BitsDevice();
}
/**
* Tells the device supported architecture.
* Since mips(/64) has been phased out long ago, is isn't checked here.
*
* @return ARCH_ARM || ARCH_ARM64 || ARCH_X86 || ARCH_86_64
*/
public static int getDeviceArchitecture(){
if(isx86Device()){
return is64BitsDevice() ? ARCH_X86_64 : ARCH_X86;
}
return is64BitsDevice() ? ARCH_ARM64 : ARCH_ARM;
}
/**
* Tell is the device is based on an x86 processor.
* It doesn't tell if the device is 64 or 32 bits.
* @return Whether or not the device is x86 based.
*/
public static boolean isx86Device(){
//We check the whole range of supported ABIs,
//Since asus zenfones can place arm before their native instruction set.
String[] ABI = is64BitsDevice() ? Build.SUPPORTED_64_BIT_ABIS : Build.SUPPORTED_32_BIT_ABIS;
int comparedArch = is64BitsDevice() ? ARCH_X86_64 : ARCH_X86;
for (String str : ABI) {
if (archAsInt(str) == comparedArch) return true;
}
return false;
}
/**
* Convert an architecture from a String to an int.
* @param arch The architecture as a String
* @return The architecture as an int, can be UNSUPPORTED_ARCH if unknown.
*/
public static int archAsInt(String arch){
arch = arch.toLowerCase().trim().replace(" ", "");
if(arch.contains("arm64") || arch.equals("aarch64")) return ARCH_ARM64;
if(arch.contains("arm") || arch.equals("aarch32")) return ARCH_ARM;
if(arch.contains("x86_64") || arch.contains("amd64")) return ARCH_X86_64;
if(arch.contains("x86") || (arch.startsWith("i") && arch.endsWith("86"))) return ARCH_X86;
//Shouldn't happen
return UNSUPPORTED_ARCH;
}
/**
* Convert to a string an architecture.
* @param arch The architecture as an int.
* @return "arm64" || "arm" || "x86_64" || "x86" || "UNSUPPORTED_ARCH"
*/
public static String archAsString(int arch){
if(arch == ARCH_ARM64) return "arm64";
if(arch == ARCH_ARM) return "arm";
if(arch == ARCH_X86_64) return "x86_64";
if(arch == ARCH_X86) return "x86";
return "UNSUPPORTED_ARCH";
}
}
@@ -1,57 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.*;
import android.os.*;
import androidx.appcompat.app.*;
import net.kdt.pojavlaunch.utils.*;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_IGNORE_NOTCH;
public abstract class BaseActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocaleUtils.setLocale(newBase));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocaleUtils.setLocale(this);
Tools.setFullscreen(this, setFullscreen());
Tools.updateWindowSize(this);
}
/** @return Whether the activity should be set as a fullscreen one */
public boolean setFullscreen(){
return true;
}
@Override
public void startActivity(Intent i) {
super.startActivity(i);
//new Throwable("StartActivity").printStackTrace();
}
@Override
protected void onResume() {
super.onResume();
if(!Tools.checkStorageRoot(this)) {
startActivity(new Intent(this, MissingStorageActivity.class));
finish();
}
}
@Override
protected void onPostResume() {
super.onPostResume();
Tools.setFullscreen(this, setFullscreen());
Tools.ignoreNotch(shouldIgnoreNotch(),this);
}
/** @return Whether or not the notch should be ignored */
protected boolean shouldIgnoreNotch(){
return PREF_IGNORE_NOTCH;
}
}
@@ -1,14 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
import dalvik.annotation.optimization.CriticalNative;
@Keep
public class CriticalNativeTest {
@CriticalNative
public static native void testCriticalNative(int arg0, int arg1);
public static void invokeTest() {
testCriticalNative(0, 0);
}
}
@@ -1,88 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.drawerlayout.widget.DrawerLayout;
import net.kdt.pojavlaunch.customcontrols.ControlData;
import net.kdt.pojavlaunch.customcontrols.ControlDrawerData;
import net.kdt.pojavlaunch.customcontrols.ControlJoystickData;
import net.kdt.pojavlaunch.customcontrols.ControlLayout;
import net.kdt.pojavlaunch.customcontrols.EditorExitable;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import java.io.IOException;
public class CustomControlsActivity extends BaseActivity implements EditorExitable {
private DrawerLayout mDrawerLayout;
private ListView mDrawerNavigationView;
private ControlLayout mControlLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_controls);
mControlLayout = findViewById(R.id.customctrl_controllayout);
mDrawerLayout = findViewById(R.id.customctrl_drawerlayout);
mDrawerNavigationView = findViewById(R.id.customctrl_navigation_view);
View mPullDrawerButton = findViewById(R.id.drawer_button);
mPullDrawerButton.setOnClickListener(v -> mDrawerLayout.openDrawer(mDrawerNavigationView));
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerNavigationView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.menu_customcontrol_customactivity)));
mDrawerNavigationView.setOnItemClickListener((parent, view, position, id) -> {
switch(position) {
case 0: mControlLayout.addControlButton(new ControlData("New")); break;
case 1: mControlLayout.addDrawer(new ControlDrawerData()); break;
case 2: mControlLayout.addJoystickButton(new ControlJoystickData()); break;
case 3: mControlLayout.openLoadDialog(); break;
case 4: mControlLayout.openSaveDialog(this); break;
case 5: mControlLayout.openSetDefaultDialog(); break;
case 6: // Saving the currently shown control
try {
Uri contentUri = DocumentsContract.buildDocumentUri(getString(R.string.storageProviderAuthorities), mControlLayout.saveToDirectory(mControlLayout.mLayoutFileName));
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, contentUri);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("application/json");
startActivity(shareIntent);
Intent sendIntent = Intent.createChooser(shareIntent, mControlLayout.mLayoutFileName);
startActivity(sendIntent);
}catch (Exception e) {
Tools.showError(this, e);
}
break;
}
mDrawerLayout.closeDrawers();
});
mControlLayout.setModifiable(true);
try {
mControlLayout.loadLayout(LauncherPreferences.PREF_DEFAULTCTRL_PATH);
}catch (IOException e) {
Tools.showError(this, e);
}
}
@Override
public void onBackPressed() {
mControlLayout.askToExit(this);
}
@Override
public void exitEditor() {
super.onBackPressed();
}
}
@@ -1,223 +0,0 @@
package net.kdt.pojavlaunch;
import static org.lwjgl.glfw.CallbackBridge.sendKeyPress;
import android.view.KeyEvent;
import org.lwjgl.glfw.CallbackBridge;
import java.util.Arrays;
public class EfficientAndroidLWJGLKeycode {
//This old version of this class was using an ArrayMap, a generic Key -> Value data structure.
//The key being the android keycode from a KeyEvent
//The value its LWJGL equivalent.
private static final int KEYCODE_COUNT = 106;
private static final int[] sAndroidKeycodes = new int[KEYCODE_COUNT];
private static final short[] sLwjglKeycodes = new short[KEYCODE_COUNT];
private static String[] androidKeyNameArray; /* = new String[androidKeycodes.length]; */
private static int mTmpCount = 0;
static {
/* BINARY SEARCH IS PERFORMED ON THE androidKeycodes ARRAY !
WHEN ADDING A MAPPING, ADD IT SO THE androidKeycodes ARRAY STAYS SORTED ! */
// Mapping Android Keycodes to LWJGL Keycodes
add(KeyEvent.KEYCODE_UNKNOWN, LwjglGlfwKeycode.GLFW_KEY_UNKNOWN);
add(KeyEvent.KEYCODE_HOME, LwjglGlfwKeycode.GLFW_KEY_HOME);
// Escape key
add(KeyEvent.KEYCODE_BACK, LwjglGlfwKeycode.GLFW_KEY_ESCAPE);
// 0-9 keys
add(KeyEvent.KEYCODE_0, LwjglGlfwKeycode.GLFW_KEY_0); //7
add(KeyEvent.KEYCODE_1, LwjglGlfwKeycode.GLFW_KEY_1);
add(KeyEvent.KEYCODE_2, LwjglGlfwKeycode.GLFW_KEY_2);
add(KeyEvent.KEYCODE_3, LwjglGlfwKeycode.GLFW_KEY_3);
add(KeyEvent.KEYCODE_4, LwjglGlfwKeycode.GLFW_KEY_4);
add(KeyEvent.KEYCODE_5, LwjglGlfwKeycode.GLFW_KEY_5);
add(KeyEvent.KEYCODE_6, LwjglGlfwKeycode.GLFW_KEY_6);
add(KeyEvent.KEYCODE_7, LwjglGlfwKeycode.GLFW_KEY_7);
add(KeyEvent.KEYCODE_8, LwjglGlfwKeycode.GLFW_KEY_8);
add(KeyEvent.KEYCODE_9, LwjglGlfwKeycode.GLFW_KEY_9); //16
add(KeyEvent.KEYCODE_POUND, LwjglGlfwKeycode.GLFW_KEY_3);
// Arrow keys
add(KeyEvent.KEYCODE_DPAD_UP, LwjglGlfwKeycode.GLFW_KEY_UP); //19
add(KeyEvent.KEYCODE_DPAD_DOWN, LwjglGlfwKeycode.GLFW_KEY_DOWN);
add(KeyEvent.KEYCODE_DPAD_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT);
add(KeyEvent.KEYCODE_DPAD_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT); //22
// A-Z keys
add(KeyEvent.KEYCODE_A, LwjglGlfwKeycode.GLFW_KEY_A); //29
add(KeyEvent.KEYCODE_B, LwjglGlfwKeycode.GLFW_KEY_B);
add(KeyEvent.KEYCODE_C, LwjglGlfwKeycode.GLFW_KEY_C);
add(KeyEvent.KEYCODE_D, LwjglGlfwKeycode.GLFW_KEY_D);
add(KeyEvent.KEYCODE_E, LwjglGlfwKeycode.GLFW_KEY_E);
add(KeyEvent.KEYCODE_F, LwjglGlfwKeycode.GLFW_KEY_F);
add(KeyEvent.KEYCODE_G, LwjglGlfwKeycode.GLFW_KEY_G);
add(KeyEvent.KEYCODE_H, LwjglGlfwKeycode.GLFW_KEY_H);
add(KeyEvent.KEYCODE_I, LwjglGlfwKeycode.GLFW_KEY_I);
add(KeyEvent.KEYCODE_J, LwjglGlfwKeycode.GLFW_KEY_J);
add(KeyEvent.KEYCODE_K, LwjglGlfwKeycode.GLFW_KEY_K);
add(KeyEvent.KEYCODE_L, LwjglGlfwKeycode.GLFW_KEY_L);
add(KeyEvent.KEYCODE_M, LwjglGlfwKeycode.GLFW_KEY_M);
add(KeyEvent.KEYCODE_N, LwjglGlfwKeycode.GLFW_KEY_N);
add(KeyEvent.KEYCODE_O, LwjglGlfwKeycode.GLFW_KEY_O);
add(KeyEvent.KEYCODE_P, LwjglGlfwKeycode.GLFW_KEY_P);
add(KeyEvent.KEYCODE_Q, LwjglGlfwKeycode.GLFW_KEY_Q);
add(KeyEvent.KEYCODE_R, LwjglGlfwKeycode.GLFW_KEY_R);
add(KeyEvent.KEYCODE_S, LwjglGlfwKeycode.GLFW_KEY_S);
add(KeyEvent.KEYCODE_T, LwjglGlfwKeycode.GLFW_KEY_T);
add(KeyEvent.KEYCODE_U, LwjglGlfwKeycode.GLFW_KEY_U);
add(KeyEvent.KEYCODE_V, LwjglGlfwKeycode.GLFW_KEY_V);
add(KeyEvent.KEYCODE_W, LwjglGlfwKeycode.GLFW_KEY_W);
add(KeyEvent.KEYCODE_X, LwjglGlfwKeycode.GLFW_KEY_X);
add(KeyEvent.KEYCODE_Y, LwjglGlfwKeycode.GLFW_KEY_Y);
add(KeyEvent.KEYCODE_Z, LwjglGlfwKeycode.GLFW_KEY_Z); //54
add(KeyEvent.KEYCODE_COMMA, LwjglGlfwKeycode.GLFW_KEY_COMMA);
add(KeyEvent.KEYCODE_PERIOD, LwjglGlfwKeycode.GLFW_KEY_PERIOD);
// Alt keys
add(KeyEvent.KEYCODE_ALT_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT_ALT);
add(KeyEvent.KEYCODE_ALT_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT_ALT);
// Shift keys
add(KeyEvent.KEYCODE_SHIFT_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT_SHIFT);
add(KeyEvent.KEYCODE_SHIFT_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT_SHIFT);
add(KeyEvent.KEYCODE_TAB, LwjglGlfwKeycode.GLFW_KEY_TAB);
add(KeyEvent.KEYCODE_SPACE, LwjglGlfwKeycode.GLFW_KEY_SPACE);
add(KeyEvent.KEYCODE_ENTER, LwjglGlfwKeycode.GLFW_KEY_ENTER); //66
add(KeyEvent.KEYCODE_DEL, LwjglGlfwKeycode.GLFW_KEY_BACKSPACE); // Backspace
add(KeyEvent.KEYCODE_GRAVE, LwjglGlfwKeycode.GLFW_KEY_GRAVE_ACCENT);
add(KeyEvent.KEYCODE_MINUS, LwjglGlfwKeycode.GLFW_KEY_MINUS);
add(KeyEvent.KEYCODE_EQUALS, LwjglGlfwKeycode.GLFW_KEY_EQUAL);
add(KeyEvent.KEYCODE_LEFT_BRACKET, LwjglGlfwKeycode.GLFW_KEY_LEFT_BRACKET);
add(KeyEvent.KEYCODE_RIGHT_BRACKET, LwjglGlfwKeycode.GLFW_KEY_RIGHT_BRACKET);
add(KeyEvent.KEYCODE_BACKSLASH, LwjglGlfwKeycode.GLFW_KEY_BACKSLASH);
add(KeyEvent.KEYCODE_SEMICOLON, LwjglGlfwKeycode.GLFW_KEY_SEMICOLON); //74
add(KeyEvent.KEYCODE_APOSTROPHE, LwjglGlfwKeycode.GLFW_KEY_APOSTROPHE);
add(KeyEvent.KEYCODE_SLASH, LwjglGlfwKeycode.GLFW_KEY_SLASH); //76
add(KeyEvent.KEYCODE_AT, LwjglGlfwKeycode.GLFW_KEY_2);
add(KeyEvent.KEYCODE_PLUS, LwjglGlfwKeycode.GLFW_KEY_KP_ADD);
// Page keys
add(KeyEvent.KEYCODE_PAGE_UP, LwjglGlfwKeycode.GLFW_KEY_PAGE_UP); //92
add(KeyEvent.KEYCODE_PAGE_DOWN, LwjglGlfwKeycode.GLFW_KEY_PAGE_DOWN);
add(KeyEvent.KEYCODE_ESCAPE, LwjglGlfwKeycode.GLFW_KEY_ESCAPE);
// Control keys
add(KeyEvent.KEYCODE_CTRL_LEFT, LwjglGlfwKeycode.GLFW_KEY_LEFT_CONTROL);
add(KeyEvent.KEYCODE_CTRL_RIGHT, LwjglGlfwKeycode.GLFW_KEY_RIGHT_CONTROL);
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);
// Fn keys
add(KeyEvent.KEYCODE_F1, LwjglGlfwKeycode.GLFW_KEY_F1); //131
add(KeyEvent.KEYCODE_F2, LwjglGlfwKeycode.GLFW_KEY_F2);
add(KeyEvent.KEYCODE_F3, LwjglGlfwKeycode.GLFW_KEY_F3);
add(KeyEvent.KEYCODE_F4, LwjglGlfwKeycode.GLFW_KEY_F4);
add(KeyEvent.KEYCODE_F5, LwjglGlfwKeycode.GLFW_KEY_F5);
add(KeyEvent.KEYCODE_F6, LwjglGlfwKeycode.GLFW_KEY_F6);
add(KeyEvent.KEYCODE_F7, LwjglGlfwKeycode.GLFW_KEY_F7);
add(KeyEvent.KEYCODE_F8, LwjglGlfwKeycode.GLFW_KEY_F8);
add(KeyEvent.KEYCODE_F9, LwjglGlfwKeycode.GLFW_KEY_F9);
add(KeyEvent.KEYCODE_F10, LwjglGlfwKeycode.GLFW_KEY_F10);
add(KeyEvent.KEYCODE_F11, LwjglGlfwKeycode.GLFW_KEY_F11);
add(KeyEvent.KEYCODE_F12, LwjglGlfwKeycode.GLFW_KEY_F12); //142
// Num keys
add(KeyEvent.KEYCODE_NUM_LOCK, LwjglGlfwKeycode.GLFW_KEY_NUM_LOCK); //143
add(KeyEvent.KEYCODE_NUMPAD_0, LwjglGlfwKeycode.GLFW_KEY_KP_0);
add(KeyEvent.KEYCODE_NUMPAD_1, LwjglGlfwKeycode.GLFW_KEY_KP_1);
add(KeyEvent.KEYCODE_NUMPAD_2, LwjglGlfwKeycode.GLFW_KEY_KP_2);
add(KeyEvent.KEYCODE_NUMPAD_3, LwjglGlfwKeycode.GLFW_KEY_KP_3);
add(KeyEvent.KEYCODE_NUMPAD_4, LwjglGlfwKeycode.GLFW_KEY_KP_4);
add(KeyEvent.KEYCODE_NUMPAD_5, LwjglGlfwKeycode.GLFW_KEY_KP_5);
add(KeyEvent.KEYCODE_NUMPAD_6, LwjglGlfwKeycode.GLFW_KEY_KP_6);
add(KeyEvent.KEYCODE_NUMPAD_7, LwjglGlfwKeycode.GLFW_KEY_KP_7);
add(KeyEvent.KEYCODE_NUMPAD_8, LwjglGlfwKeycode.GLFW_KEY_KP_8);
add(KeyEvent.KEYCODE_NUMPAD_9, LwjglGlfwKeycode.GLFW_KEY_KP_9);
add(KeyEvent.KEYCODE_NUMPAD_DIVIDE, LwjglGlfwKeycode.GLFW_KEY_KP_DIVIDE);
add(KeyEvent.KEYCODE_NUMPAD_MULTIPLY, LwjglGlfwKeycode.GLFW_KEY_KP_MULTIPLY);
add(KeyEvent.KEYCODE_NUMPAD_SUBTRACT, LwjglGlfwKeycode.GLFW_KEY_KP_SUBTRACT);
add(KeyEvent.KEYCODE_NUMPAD_ADD, LwjglGlfwKeycode.GLFW_KEY_KP_ADD);
add(KeyEvent.KEYCODE_NUMPAD_DOT, LwjglGlfwKeycode.GLFW_KEY_KP_DECIMAL);
add(KeyEvent.KEYCODE_NUMPAD_COMMA, LwjglGlfwKeycode.GLFW_KEY_COMMA);
add(KeyEvent.KEYCODE_NUMPAD_ENTER, LwjglGlfwKeycode.GLFW_KEY_KP_ENTER);
add(KeyEvent.KEYCODE_NUMPAD_EQUALS, LwjglGlfwKeycode.GLFW_KEY_EQUAL); //161
}
public static boolean containsIndex(int index){
return index >= 0;
}
public static String[] generateKeyName() {
if (androidKeyNameArray == null) {
androidKeyNameArray = new String[sAndroidKeycodes.length];
for(int i=0; i < androidKeyNameArray.length; ++i){
androidKeyNameArray[i] = KeyEvent.keyCodeToString(sAndroidKeycodes[i]).replace("KEYCODE_", "");
}
}
return androidKeyNameArray;
}
public static void execKey(KeyEvent keyEvent, int valueIndex) {
//valueIndex points to where the value is stored in the array.
CallbackBridge.holdingAlt = keyEvent.isAltPressed();
CallbackBridge.holdingCapslock = keyEvent.isCapsLockOn();
CallbackBridge.holdingCtrl = keyEvent.isCtrlPressed();
CallbackBridge.holdingNumlock = keyEvent.isNumLockOn();
CallbackBridge.holdingShift = keyEvent.isShiftPressed();
System.out.println(keyEvent.getKeyCode() + " " +keyEvent.getDisplayLabel());
char key = (char)(keyEvent.getUnicodeChar() != 0 ? keyEvent.getUnicodeChar() : '\u0000');
sendKeyPress(
getValueByIndex(valueIndex),
key,
0,
CallbackBridge.getCurrentMods(),
keyEvent.getAction() == KeyEvent.ACTION_DOWN);
}
public static void execKeyIndex(int index){
//Send a quick key press.
sendKeyPress(getValueByIndex(index));
}
public static short getValueByIndex(int index) {
return sLwjglKeycodes[index];
}
public static int getIndexByKey(int key){
return Arrays.binarySearch(sAndroidKeycodes, key);
}
/** @return the index at which the key is in the array, searching linearly */
public static int getIndexByValue(int lwjglKey) {
//You should avoid using this function on performance critical areas
for (int i = 0; i < sLwjglKeycodes.length; i++) {
if(sLwjglKeycodes[i] == lwjglKey) return i;
}
return 0;
}
private static void add(int androidKeycode, short LWJGLKeycode){
sAndroidKeycodes[mTmpCount] = androidKeycode;
sLwjglKeycodes[mTmpCount] = LWJGLKeycode;
mTmpCount ++;
}
}
@@ -1,48 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Tools.shareLog;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Keep;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
@Keep
public class ExitActivity extends AppCompatActivity {
@SuppressLint("StringFormatInvalid") //invalid on some translations but valid on most, cant fix that atm
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int code = -1;
boolean isSignal = false;
Bundle extras = getIntent().getExtras();
if(extras != null) {
code = extras.getInt("code",-1);
isSignal = extras.getBoolean("isSignal", false);
}
int message = isSignal ? R.string.mcn_signal_title : R.string.mcn_exit_title;
new AlertDialog.Builder(this)
.setMessage(getString(message,code))
.setPositiveButton(R.string.main_share_logs, (dialog, which) -> shareLog(this))
.setOnDismissListener(dialog -> ExitActivity.this.finish())
.show();
}
public static void showExitMessage(Context ctx, int code, boolean isSignal) {
Intent i = new Intent(ctx,ExitActivity.class);
i.putExtra("code",code);
i.putExtra("isSignal", isSignal);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
}
}
@@ -1,55 +0,0 @@
package net.kdt.pojavlaunch;
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 {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
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 + "." :
"Storage permission is required to save crash stack trace!";
new AlertDialog.Builder(this)
.setTitle(R.string.error_fatal)
.setMessage(errHeader + "\n\n" + stackTrace)
.setPositiveButton(android.R.string.ok, (p1, p2) -> finish())
.setNegativeButton(R.string.global_restart, (p1, p2) -> startActivity(new Intent(FatalErrorActivity.this, LauncherActivity.class)))
.setNeutralButton(android.R.string.copy, (p1, p2) -> {
ClipboardManager mgr = (ClipboardManager) FatalErrorActivity.this.getSystemService(CLIPBOARD_SERVICE);
mgr.setPrimaryClip(ClipData.newPlainText("error", stackTrace));
finish();
})
.setCancelable(false)
.show();
}
public static void showError(Context ctx, String savePath, boolean storageAllow, Throwable th) {
Intent fatalErrorIntent = new Intent(ctx, FatalErrorActivity.class);
fatalErrorIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
fatalErrorIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
fatalErrorIntent.putExtra("throwable", th);
fatalErrorIntent.putExtra("savePath", savePath);
fatalErrorIntent.putExtra("storageAllow", storageAllow);
ctx.startActivity(fatalErrorIntent);
}
}
@@ -1,5 +0,0 @@
package net.kdt.pojavlaunch;
public interface GrabListener {
void onGrabState(boolean isGrabbing);
}
@@ -1,187 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.utils.FileUtils;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* An activity dedicated to importing control files.
*/
@SuppressWarnings("IOStreamConstructor")
public class ImportControlActivity extends Activity {
private Uri mUriData;
private boolean mHasIntentChanged = true;
private volatile boolean mIsFileVerified = false;
private EditText mEditText;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tools.initContextConstants(getApplicationContext());
setContentView(R.layout.activity_import_control);
mEditText = findViewById(R.id.editText_import_control_file_name);
}
/**
* Override the previous loaded intent
* @param intent the intent used to replace the old one.
*/
@Override
protected void onNewIntent(Intent intent) {
if(intent != null) setIntent(intent);
mHasIntentChanged = true;
}
/**
* Update all over again if the intent changed.
*/
@Override
protected void onPostResume() {
super.onPostResume();
if(!mHasIntentChanged) return;
mIsFileVerified = false;
getUriData();
if(mUriData == null) {
finishAndRemoveTask();
return;
}
mEditText.setText(trimFileName(Tools.getFileName(this, mUriData)));
mHasIntentChanged = false;
//Import and verify thread
//Kill the app if the file isn't valid.
new Thread(() -> {
importControlFile();
if(verify())mIsFileVerified = true;
else runOnUiThread(() -> {
Toast.makeText(
ImportControlActivity.this,
getText(R.string.import_control_invalid_file),
Toast.LENGTH_SHORT).show();
finishAndRemoveTask();
});
}).start();
//Auto show the keyboard
Tools.MAIN_HANDLER.postDelayed(() -> {
InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
mEditText.setSelection(mEditText.getText().length());
}, 100);
}
/**
* Start the import.
* @param view the view which called the function
*/
public void startImport(View view) {
String fileName = trimFileName(mEditText.getText().toString());
//Step 1 check for suffixes.
if(!isFileNameValid(fileName)){
Toast.makeText(this, getText(R.string.import_control_invalid_name), Toast.LENGTH_SHORT).show();
return;
}
if(!mIsFileVerified){
Toast.makeText(this, getText(R.string.import_control_verifying_file), Toast.LENGTH_LONG).show();
return;
}
new File(Tools.CTRLMAP_PATH + "/TMP_IMPORT_FILE.json").renameTo(new File(Tools.CTRLMAP_PATH + "/" + fileName + ".json"));
Toast.makeText(getApplicationContext(), getText(R.string.import_control_done), Toast.LENGTH_SHORT).show();
finishAndRemoveTask();
}
/**
* Copy a the file from the Intent data with a provided name into the controlmap folder.
*/
private void importControlFile(){
InputStream is;
try {
is = getContentResolver().openInputStream(mUriData);
OutputStream os = new FileOutputStream(Tools.CTRLMAP_PATH + "/" + "TMP_IMPORT_FILE" + ".json");
IOUtils.copy(is, os);
os.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Tell if the clean version of the filename is valid.
* @param fileName the string to test
* @return whether the filename is valid
*/
private static boolean isFileNameValid(String fileName){
fileName = trimFileName(fileName);
if(fileName.isEmpty()) return false;
return !FileUtils.exists(Tools.CTRLMAP_PATH + "/" + fileName + ".json");
}
/**
* Remove or undesirable chars from the string
* @param fileName The string to trim
* @return The trimmed string
*/
private static String trimFileName(String fileName){
return fileName
.replace(".json", "")
.replaceAll("%..", "/")
.replace("/", "")
.replace("\\", "")
.trim();
}
/**
* Tries to get an Uri from the various sources
*/
private void getUriData(){
mUriData = getIntent().getData();
if(mUriData != null) return;
try {
mUriData = getIntent().getClipData().getItemAt(0).getUri();
}catch (Exception ignored){}
}
/**
* Verify if the control file is valid
* @return Whether the control file is valid
*/
private static boolean verify(){
try{
String jsonLayoutData = Tools.read(Tools.CTRLMAP_PATH + "/TMP_IMPORT_FILE.json");
JSONObject layoutJobj = new JSONObject(jsonLayoutData);
return layoutJobj.has("version") && layoutJobj.has("mControlDataList");
}catch (JSONException | IOException e) {
e.printStackTrace();
return false;
}
}
}
@@ -1,10 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
@Keep
public class JAssetInfo
{
public String hash;
public int size;
}
@@ -1,18 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
@Keep
public class JAssets {
/* Used by older versions of mc, when the files were named and under .minecraft/resources */
@SerializedName("map_to_resources") public boolean mapToResources;
public Map<String, JAssetInfo> objects;
/* Used by the legacy.json (~1.6.X) asset file, used for paths at the root of the .minecraft/assets folder */
public boolean virtual;
}
@@ -1,88 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
import java.util.*;
import net.kdt.pojavlaunch.value.*;
@Keep
@SuppressWarnings("unused") // all unused fields here are parts of JSON structures
public class JMinecraftVersionList {
public Map<String, String> latest;
public Version[] versions;
@Keep
public static class FileProperties {
public String id, sha1, url;
public long size;
}
@Keep
public static class Version extends FileProperties {
// Since 1.13, so it's one of ways to check
public Arguments arguments;
public AssetIndex assetIndex;
public String assets;
public Map<String, MinecraftClientInfo> downloads;
public String inheritsFrom;
public JavaVersionInfo javaVersion;
public DependentLibrary[] libraries;
public LoggingConfig logging;
public String mainClass;
public String minecraftArguments;
public int minimumLauncherVersion;
public String releaseTime;
public String time;
public String type;
}
@Keep
public static class JavaVersionInfo {
public String component;
public int majorVersion;
public int version; // parameter used by LabyMod 4
}
@Keep
public static class LoggingConfig {
public LoggingClientConfig client;
@Keep
public static class LoggingClientConfig {
public String argument;
public FileProperties file;
public String type;
}
}
// Since 1.13
@Keep
public static class Arguments {
public Object[] game;
public Object[] jvm;
@Keep
public static class ArgValue {
public ArgRules[] rules;
public String value;
// TLauncher styled argument...
public String[] values;
@Keep
public static class ArgRules {
public String action;
public String features;
public ArgOS os;
@Keep
public static class ArgOS {
public String name;
public String version;
}
}
}
}
@Keep
public static class AssetIndex extends FileProperties {
public long totalSize;
}
}
@@ -1,434 +0,0 @@
package net.kdt.pojavlaunch;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AlertDialog;
import com.kdt.LoggerView;
import net.kdt.pojavlaunch.customcontrols.keyboard.AwtCharSender;
import net.kdt.pojavlaunch.customcontrols.keyboard.TouchCharInput;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.multirt.Runtime;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.JREUtils;
import net.kdt.pojavlaunch.utils.MathUtils;
import org.apache.commons.io.IOUtils;
import org.lwjgl.glfw.CallbackBridge;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouchListener {
private AWTCanvasView mTextureView;
private LoggerView mLoggerView;
private TouchCharInput mTouchCharInput;
private LinearLayout mTouchPad;
private ImageView mMousePointerImageView;
private GestureDetector mGestureDetector;
private boolean mIsVirtualMouseEnabled;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_gui_launcher);
try {
File latestLogFile = new File(Tools.DIR_GAME_HOME, "latestlog.txt");
if (!latestLogFile.exists() && !latestLogFile.createNewFile())
throw new IOException("Failed to create a new log file");
Logger.begin(latestLogFile.getAbsolutePath());
}catch (IOException e) {
Tools.showError(this, e, true);
}
MainActivity.GLOBAL_CLIPBOARD = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mTouchCharInput = findViewById(R.id.awt_touch_char);
mTouchCharInput.setCharacterSender(new AwtCharSender());
mTouchPad = findViewById(R.id.main_touchpad);
mLoggerView = findViewById(R.id.launcherLoggerView);
mMousePointerImageView = findViewById(R.id.main_mouse_pointer);
mTextureView = findViewById(R.id.installmod_surfaceview);
mGestureDetector = new GestureDetector(this, new SingleTapConfirm());
mTouchPad.setFocusable(false);
mTouchPad.setVisibility(View.GONE);
findViewById(R.id.installmod_mouse_pri).setOnTouchListener(this);
findViewById(R.id.installmod_mouse_sec).setOnTouchListener(this);
findViewById(R.id.installmod_window_moveup).setOnTouchListener(this);
findViewById(R.id.installmod_window_movedown).setOnTouchListener(this);
findViewById(R.id.installmod_window_moveleft).setOnTouchListener(this);
findViewById(R.id.installmod_window_moveright).setOnTouchListener(this);
mMousePointerImageView.post(() -> {
ViewGroup.LayoutParams params = mMousePointerImageView.getLayoutParams();
params.width = (int) (36 * LauncherPreferences.PREF_MOUSESCALE);
params.height = (int) (54 * LauncherPreferences.PREF_MOUSESCALE);
});
mTouchPad.setOnTouchListener(new View.OnTouchListener() {
float prevX = 0, prevY = 0;
@Override
public boolean onTouch(View v, 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();
int action = event.getActionMasked();
float x = event.getX();
float y = event.getY();
float mouseX, mouseY;
mouseX = mMousePointerImageView.getX();
mouseY = mMousePointerImageView.getY();
if (mGestureDetector.onTouchEvent(event)) {
sendScaledMousePosition(mouseX,mouseY);
AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON1_DOWN_MASK);
} else {
if (action == MotionEvent.ACTION_MOVE) { // 2
mouseX = Math.max(0, Math.min(CallbackBridge.physicalWidth, mouseX + x - prevX));
mouseY = Math.max(0, Math.min(CallbackBridge.physicalHeight, mouseY + y - prevY));
placeMouseAt(mouseX, mouseY);
sendScaledMousePosition(mouseX, mouseY);
}
}
prevY = y;
prevX = x;
return true;
}
});
mTextureView.setOnTouchListener((v, event) -> {
float x = event.getX();
float y = event.getY();
if (mGestureDetector.onTouchEvent(event)) {
sendScaledMousePosition(x + mTextureView.getX(), y);
AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON1_DOWN_MASK);
return true;
}
switch (event.getActionMasked()) {
case MotionEvent.ACTION_UP: // 1
case MotionEvent.ACTION_CANCEL: // 3
case MotionEvent.ACTION_POINTER_UP: // 6
break;
case MotionEvent.ACTION_MOVE: // 2
sendScaledMousePosition(x + mTextureView.getX(), y);
break;
}
return true;
});
try {
placeMouseAt(CallbackBridge.physicalWidth / 2f, CallbackBridge.physicalHeight / 2f);
Bundle extras = getIntent().getExtras();
if(extras == null) {
finish();
return;
}
final String javaArgs = extras.getString("javaArgs");
final Uri resourceUri = (Uri) extras.getParcelable("modUri");
if(extras.getBoolean("openLogOutput", false)) openLogOutput(null);
if (javaArgs != null) {
startModInstaller(null, javaArgs);
}else if(resourceUri != null) {
ProgressDialog barrierDialog = Tools.getWaitingDialog(this, R.string.multirt_progress_caching);
PojavApplication.sExecutorService.execute(()->{
startModInstallerWithUri(resourceUri);
runOnUiThread(barrierDialog::dismiss);
});
}
} catch (Throwable th) {
Tools.showError(this, th, true);
}
getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Tools.dialogForceClose(JavaGUILauncherActivity.this);
}
});
}
private void startModInstallerWithUri(Uri uri) {
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);
}
contentStream.close();
startModInstaller(cacheFile, null);
}catch (IOException e) {
Tools.showError(this, e, true);
}
}
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(() -> {
// 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 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
public void onResume() {
super.onResume();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouch(View v, MotionEvent e) {
boolean isDown;
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN: // 0
case MotionEvent.ACTION_POINTER_DOWN: // 5
isDown = true;
break;
case MotionEvent.ACTION_UP: // 1
case MotionEvent.ACTION_CANCEL: // 3
case MotionEvent.ACTION_POINTER_UP: // 6
isDown = false;
break;
default:
return false;
}
switch (v.getId()) {
case R.id.installmod_mouse_pri:
AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON1_DOWN_MASK, isDown);
break;
case R.id.installmod_mouse_sec:
AWTInputBridge.sendMousePress(AWTInputEvent.BUTTON3_DOWN_MASK, isDown);
break;
}
if(isDown) switch(v.getId()) {
case R.id.installmod_window_moveup:
AWTInputBridge.nativeMoveWindow(0, -10);
break;
case R.id.installmod_window_movedown:
AWTInputBridge.nativeMoveWindow(0, 10);
break;
case R.id.installmod_window_moveleft:
AWTInputBridge.nativeMoveWindow(-10, 0);
break;
case R.id.installmod_window_moveright:
AWTInputBridge.nativeMoveWindow(10, 0);
break;
}
return true;
}
public void placeMouseAt(float x, float y) {
mMousePointerImageView.setX(x);
mMousePointerImageView.setY(y);
}
@SuppressWarnings("SuspiciousNameCombination")
void sendScaledMousePosition(float x, float y){
// Clamp positions to the borders of the usable view, then scale them
x = androidx.core.math.MathUtils.clamp(x, mTextureView.getX(), mTextureView.getX() + mTextureView.getWidth());
y = androidx.core.math.MathUtils.clamp(y, mTextureView.getY(), mTextureView.getY() + mTextureView.getHeight());
AWTInputBridge.sendMousePos(
(int) MathUtils.map(x, mTextureView.getX(), mTextureView.getX() + mTextureView.getWidth(), 0, AWTCanvasView.AWT_CANVAS_WIDTH),
(int) MathUtils.map(y, mTextureView.getY(), mTextureView.getY() + mTextureView.getHeight(), 0, AWTCanvasView.AWT_CANVAS_HEIGHT)
);
}
public void forceClose(View v) {
Tools.dialogForceClose(this);
}
public void openLogOutput(View v) {
mLoggerView.setVisibility(View.VISIBLE);
}
public void toggleVirtualMouse(View v) {
mIsVirtualMouseEnabled = !mIsVirtualMouseEnabled;
mTouchPad.setVisibility(mIsVirtualMouseEnabled ? View.VISIBLE : View.GONE);
Toast.makeText(this,
mIsVirtualMouseEnabled ? R.string.control_mouseon : R.string.control_mouseoff,
Toast.LENGTH_SHORT).show();
}
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(javaArgs);
}
if(modFile != null) {
javaArgList.add("-jar");
javaArgList.add(modFile.getAbsolutePath());
}
if (LauncherPreferences.PREF_JAVA_SANDBOX) {
Collections.reverse(javaArgList);
javaArgList.add("-Xbootclasspath/a:" + Tools.DIR_DATA + "/security/pro-grade.jar");
javaArgList.add("-Djava.security.manager=net.sourceforge.prograde.sm.ProGradeJSM");
javaArgList.add("-Djava.security.policy=" + Tools.DIR_DATA + "/security/java_sandbox.policy");
Collections.reverse(javaArgList);
}
Logger.appendToLog("Info: Java arguments: " + Arrays.toString(javaArgList.toArray(new String[0])));
JREUtils.launchJavaVM(this, runtime,null,javaArgList, LauncherPreferences.PREF_CUSTOM_JAVA_ARGS);
} catch (Throwable th) {
Tools.showError(this, th, true);
}
}
public void toggleKeyboard(View view) {
mTouchCharInput.switchKeyboardState();
}
public void performCopy(View view) {
AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 1);
AWTInputBridge.sendKey(' ', AWTInputEvent.VK_C);
AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 0);
}
public void performPaste(View view) {
AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 1);
AWTInputBridge.sendKey(' ', AWTInputEvent.VK_V);
AWTInputBridge.sendKey(' ', AWTInputEvent.VK_CONTROL, 0);
}
public int getJavaVersion(File modFile) {
try (ZipFile zipFile = new ZipFile(modFile)){
ZipEntry manifest = zipFile.getEntry("META-INF/MANIFEST.MF");
if(manifest == null) return -1;
String manifestString = Tools.read(zipFile.getInputStream(manifest));
String mainClass = Tools.extractUntilCharacter(manifestString, "Main-Class:", '\n');
if(mainClass == null) return -1;
mainClass = mainClass.trim().replace('.', '/') + ".class";
ZipEntry mainClassFile = zipFile.getEntry(mainClass);
if(mainClassFile == null) return -1;
InputStream classStream = zipFile.getInputStream(mainClassFile);
byte[] bytesWeNeed = new byte[8];
int readCount = classStream.read(bytesWeNeed);
classStream.close();
if(readCount < 8) return -1;
ByteBuffer byteBuffer = ByteBuffer.wrap(bytesWeNeed);
if(byteBuffer.getInt() != 0xCAFEBABE) return -1;
short minorVersion = byteBuffer.getShort();
short majorVersion = byteBuffer.getShort();
Log.i("JavaGUILauncher", majorVersion+","+minorVersion);
return classVersionToJavaVersion(majorVersion);
}catch (Exception e) {
Log.e("JavaVersion", "Exception thrown", e);
return -1;
}
}
public static int classVersionToJavaVersion(int majorVersion) {
if(majorVersion < 46) return 2; // there isn't even an arm64 port of jre 1.1 (or anything before 1.8 in fact)
return majorVersion - 44;
}
}
@@ -1,350 +0,0 @@
package net.kdt.pojavlaunch;
import static android.content.res.Configuration.ORIENTATION_PORTRAIT;
import android.Manifest;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentContainerView;
import androidx.fragment.app.FragmentManager;
import com.kdt.mcgui.ProgressLayout;
import com.kdt.mcgui.mcAccountSpinner;
import net.kdt.pojavlaunch.contracts.OpenDocumentWithExtension;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.extra.ExtraCore;
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;
import net.kdt.pojavlaunch.prefs.screens.LauncherPreferenceFragment;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
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.tasks.MinecraftDownloader;
import net.kdt.pojavlaunch.utils.NotificationUtils;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import java.lang.ref.WeakReference;
public class LauncherActivity extends BaseActivity {
public static final String SETTING_FRAGMENT_TAG = "SETTINGS_FRAGMENT";
public final ActivityResultLauncher<Object> modInstallerLauncher =
registerForActivityResult(new OpenDocumentWithExtension("jar"), (data)->{
if(data != null) Tools.launchModInstaller(this, data);
});
private mcAccountSpinner mAccountSpinner;
private FragmentContainerView mFragmentView;
private ImageButton mSettingsButton, mDeleteAccountButton;
private ProgressLayout mProgressLayout;
private ProgressServiceKeeper mProgressServiceKeeper;
private ModloaderInstallTracker mInstallTracker;
private NotificationManager mNotificationManager;
/* Allows to switch from one button "type" to another */
private final FragmentManager.FragmentLifecycleCallbacks mFragmentCallbackListener = new FragmentManager.FragmentLifecycleCallbacks() {
@Override
public void onFragmentResumed(@NonNull FragmentManager fm, @NonNull Fragment f) {
mSettingsButton.setImageDrawable(ContextCompat.getDrawable(getBaseContext(), f instanceof MainMenuFragment
? R.drawable.ic_menu_settings : R.drawable.ic_menu_home));
}
};
/* Listener for the back button in settings */
private final ExtraListener<String> mBackPreferenceListener = (key, value) -> {
if(value.equals("true")) onBackPressed();
return false;
};
/* Listener for the auth method selection screen */
private final ExtraListener<Boolean> mSelectAuthMethod = (key, value) -> {
Fragment fragment = getSupportFragmentManager().findFragmentById(mFragmentView.getId());
// 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, null);
return false;
};
/* Listener for the settings fragment */
private final View.OnClickListener mSettingButtonListener = v -> {
Fragment fragment = getSupportFragmentManager().findFragmentById(mFragmentView.getId());
if(fragment instanceof MainMenuFragment){
Tools.swapFragment(this, LauncherPreferenceFragment.class, SETTING_FRAGMENT_TAG, null);
} else{
// The setting button doubles as a home button now
Tools.backToMainMenu(this);
}
};
/* Listener for account deletion */
private final View.OnClickListener mAccountDeleteButtonListener = v -> new AlertDialog.Builder(this)
.setMessage(R.string.warning_remove_account)
.setPositiveButton(android.R.string.cancel, null)
.setNeutralButton(R.string.global_delete, (dialog, which) -> mAccountSpinner.removeCurrentAccount())
.show();
private final ExtraListener<Boolean> mLaunchGameListener = (key, value) -> {
if(mProgressLayout.hasProcesses()){
Toast.makeText(this, R.string.tasks_ongoing, Toast.LENGTH_LONG).show();
return false;
}
String selectedProfile = LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,"");
if (LauncherProfiles.mainProfileJson == null || !LauncherProfiles.mainProfileJson.profiles.containsKey(selectedProfile)){
Toast.makeText(this, R.string.error_no_version, Toast.LENGTH_LONG).show();
return false;
}
MinecraftProfile prof = LauncherProfiles.mainProfileJson.profiles.get(selectedProfile);
if (prof == null || prof.lastVersionId == null || "Unknown".equals(prof.lastVersionId)){
Toast.makeText(this, R.string.error_no_version, Toast.LENGTH_LONG).show();
return false;
}
if(mAccountSpinner.getSelectedAccount() == null){
Toast.makeText(this, R.string.no_saved_accounts, Toast.LENGTH_LONG).show();
ExtraCore.setValue(ExtraConstants.SELECT_AUTH_METHOD, true);
return false;
}
String normalizedVersionId = AsyncMinecraftDownloader.normalizeVersionId(prof.lastVersionId);
JMinecraftVersionList.Version mcVersion = AsyncMinecraftDownloader.getListedVersion(normalizedVersionId);
new MinecraftDownloader().start(
this,
mcVersion,
normalizedVersionId,
new ContextAwareDoneListener(this, normalizedVersionId)
);
return false;
};
private final TaskCountListener mDoubleLaunchPreventionListener = taskCount -> {
// Hide the notification that starts the game if there are tasks executing.
// Prevents the user from trying to launch the game with tasks ongoing.
if(taskCount > 0) {
Tools.runOnUiThread(() ->
mNotificationManager.cancel(NotificationUtils.NOTIFICATION_ID_GAME_START)
);
}
};
private ActivityResultLauncher<String> mRequestNotificationPermissionLauncher;
private WeakReference<Runnable> mRequestNotificationPermissionRunnable;
@Override
protected boolean shouldIgnoreNotch() {
return getResources().getConfiguration().orientation == ORIENTATION_PORTRAIT;
}
@Override
public boolean setFullscreen() {
return false;
}
@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(),
isAllowed -> {
if(!isAllowed) handleNoNotificationPermission();
else {
Runnable runnable = Tools.getWeakReference(mRequestNotificationPermissionRunnable);
if(runnable != null) runnable.run();
}
}
);
getWindow().setBackgroundDrawable(null);
bindViews();
checkNotificationPermission();
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
ProgressKeeper.addTaskCountListener(mDoubleLaunchPreventionListener);
ProgressKeeper.addTaskCountListener((mProgressServiceKeeper = new ProgressServiceKeeper(this)));
mSettingsButton.setOnClickListener(mSettingButtonListener);
mDeleteAccountButton.setOnClickListener(mAccountDeleteButtonListener);
ProgressKeeper.addTaskCountListener(mProgressLayout);
ExtraCore.addExtraListener(ExtraConstants.BACK_PREFERENCE, mBackPreferenceListener);
ExtraCore.addExtraListener(ExtraConstants.SELECT_AUTH_METHOD, mSelectAuthMethod);
ExtraCore.addExtraListener(ExtraConstants.LAUNCH_GAME, mLaunchGameListener);
new AsyncVersionList().getVersionList(versions -> ExtraCore.setValue(ExtraConstants.RELEASE_TABLE, versions), false);
mInstallTracker = new ModloaderInstallTracker(this);
mProgressLayout.observe(ProgressLayout.DOWNLOAD_MINECRAFT);
mProgressLayout.observe(ProgressLayout.UNPACK_RUNTIME);
mProgressLayout.observe(ProgressLayout.INSTALL_MODPACK);
mProgressLayout.observe(ProgressLayout.AUTHENTICATE_MICROSOFT);
mProgressLayout.observe(ProgressLayout.DOWNLOAD_VERSION_LIST);
}
@Override
protected void onResume() {
super.onResume();
ContextExecutor.setActivity(this);
mInstallTracker.attach();
}
@Override
protected void onPause() {
super.onPause();
ContextExecutor.clearActivity();
mInstallTracker.detach();
}
@Override
protected void onStart() {
super.onStart();
getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentCallbackListener, true);
}
@Override
protected void onDestroy() {
super.onDestroy();
mProgressLayout.cleanUpObservers();
ProgressKeeper.removeTaskCountListener(mProgressLayout);
ProgressKeeper.removeTaskCountListener(mProgressServiceKeeper);
ExtraCore.removeExtraListenerFromValue(ExtraConstants.BACK_PREFERENCE, mBackPreferenceListener);
ExtraCore.removeExtraListenerFromValue(ExtraConstants.SELECT_AUTH_METHOD, mSelectAuthMethod);
ExtraCore.removeExtraListenerFromValue(ExtraConstants.LAUNCH_GAME, mLaunchGameListener);
getSupportFragmentManager().unregisterFragmentLifecycleCallbacks(mFragmentCallbackListener);
}
/** Custom implementation to feel more natural when a backstack isn't present */
@Override
public void onBackPressed() {
MicrosoftLoginFragment fragment = (MicrosoftLoginFragment) getVisibleFragment(MicrosoftLoginFragment.TAG);
if(fragment != null){
if(fragment.canGoBack()){
fragment.goBack();
return;
}
}
// Check if we are at the root then
if(getVisibleFragment("ROOT") != null){
finish();
}
super.onBackPressed();
}
@Override
public void onAttachedToWindow() {
LauncherPreferences.computeNotchSize(this);
}
@SuppressWarnings("SameParameterValue")
private Fragment getVisibleFragment(String tag){
Fragment fragment = getSupportFragmentManager().findFragmentByTag(tag);
if(fragment != null && fragment.isVisible()) {
return fragment;
}
return null;
}
@SuppressWarnings("unused")
private Fragment getVisibleFragment(int id){
Fragment fragment = getSupportFragmentManager().findFragmentById(id);
if(fragment != null && fragment.isVisible()) {
return fragment;
}
return null;
}
private void checkNotificationPermission() {
if(LauncherPreferences.PREF_SKIP_NOTIFICATION_PERMISSION_CHECK ||
checkForNotificationPermission()) {
return;
}
if(ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.POST_NOTIFICATIONS)) {
showNotificationPermissionReasoning();
return;
}
askForNotificationPermission(null);
}
private void showNotificationPermissionReasoning() {
new AlertDialog.Builder(this)
.setTitle(R.string.notification_permission_dialog_title)
.setMessage(R.string.notification_permission_dialog_text)
.setPositiveButton(android.R.string.ok, (d, w) -> askForNotificationPermission(null))
.setNegativeButton(android.R.string.cancel, (d, w)-> handleNoNotificationPermission())
.show();
}
private void handleNoNotificationPermission() {
LauncherPreferences.PREF_SKIP_NOTIFICATION_PERMISSION_CHECK = true;
LauncherPreferences.DEFAULT_PREF.edit()
.putBoolean(LauncherPreferences.PREF_KEY_SKIP_NOTIFICATION_CHECK, true)
.apply();
Toast.makeText(this, R.string.notification_permission_toast, Toast.LENGTH_LONG).show();
}
public boolean checkForNotificationPermission() {
return Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission(
this,
Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_DENIED;
}
public void askForNotificationPermission(Runnable onSuccessRunnable) {
if(Build.VERSION.SDK_INT < 33) return;
if(onSuccessRunnable != null) {
mRequestNotificationPermissionRunnable = new WeakReference<>(onSuccessRunnable);
}
mRequestNotificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS);
}
/** Stuff all the view boilerplate here */
private void bindViews(){
mFragmentView = findViewById(R.id.container_fragment);
mSettingsButton = findViewById(R.id.setting_button);
mDeleteAccountButton = findViewById(R.id.delete_account_button);
mAccountSpinner = findViewById(R.id.account_spinner);
mProgressLayout = findViewById(R.id.progress_layout);
}
}
@@ -1,25 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
/** Singleton class made to log on one file
* The singleton part can be removed but will require more implementation from the end-dev
*/
@Keep
public class Logger {
/** Print the text to the log file if not censored */
public static native void appendToLog(String text);
/** Reset the log file, effectively erasing any previous logs */
public static native void begin(String logFilePath);
/** Small listener for anything listening to the log */
@Keep
public interface eventLogListener {
void onEventLogged(String text);
}
/** Link a log listener to the logger */
public static native void setLogListener(eventLogListener logListener);
}
@@ -1,202 +0,0 @@
// Keycodes from https://github.com/glfw/glfw/blob/master/include/GLFW/glfw3.h
/*-************************************************************************
* GLFW 3.4 - www.glfw.org
* A library for OpenGL, window and input
*------------------------------------------------------------------------
* Copyright (c) 2002-2006 Marcus Geelnard
* Copyright (c) 2006-2019 Camilla Löwy <[email protected]>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*************************************************************************/
package net.kdt.pojavlaunch;
@SuppressWarnings("unused")
public class LwjglGlfwKeycode {
/** The unknown key. */
public static final short GLFW_KEY_UNKNOWN = 0; // should be -1
/** Printable keys. */
public static final short
GLFW_KEY_SPACE = 32,
GLFW_KEY_APOSTROPHE = 39,
GLFW_KEY_COMMA = 44,
GLFW_KEY_MINUS = 45,
GLFW_KEY_PERIOD = 46,
GLFW_KEY_SLASH = 47,
GLFW_KEY_0 = 48,
GLFW_KEY_1 = 49,
GLFW_KEY_2 = 50,
GLFW_KEY_3 = 51,
GLFW_KEY_4 = 52,
GLFW_KEY_5 = 53,
GLFW_KEY_6 = 54,
GLFW_KEY_7 = 55,
GLFW_KEY_8 = 56,
GLFW_KEY_9 = 57,
GLFW_KEY_SEMICOLON = 59,
GLFW_KEY_EQUAL = 61,
GLFW_KEY_A = 65,
GLFW_KEY_B = 66,
GLFW_KEY_C = 67,
GLFW_KEY_D = 68,
GLFW_KEY_E = 69,
GLFW_KEY_F = 70,
GLFW_KEY_G = 71,
GLFW_KEY_H = 72,
GLFW_KEY_I = 73,
GLFW_KEY_J = 74,
GLFW_KEY_K = 75,
GLFW_KEY_L = 76,
GLFW_KEY_M = 77,
GLFW_KEY_N = 78,
GLFW_KEY_O = 79,
GLFW_KEY_P = 80,
GLFW_KEY_Q = 81,
GLFW_KEY_R = 82,
GLFW_KEY_S = 83,
GLFW_KEY_T = 84,
GLFW_KEY_U = 85,
GLFW_KEY_V = 86,
GLFW_KEY_W = 87,
GLFW_KEY_X = 88,
GLFW_KEY_Y = 89,
GLFW_KEY_Z = 90,
GLFW_KEY_LEFT_BRACKET = 91,
GLFW_KEY_BACKSLASH = 92,
GLFW_KEY_RIGHT_BRACKET = 93,
GLFW_KEY_GRAVE_ACCENT = 96,
GLFW_KEY_WORLD_1 = 161,
GLFW_KEY_WORLD_2 = 162;
/** Function keys. */
public static final short
GLFW_KEY_ESCAPE = 256,
GLFW_KEY_ENTER = 257,
GLFW_KEY_TAB = 258,
GLFW_KEY_BACKSPACE = 259,
GLFW_KEY_INSERT = 260,
GLFW_KEY_DELETE = 261,
GLFW_KEY_RIGHT = 262,
GLFW_KEY_LEFT = 263,
GLFW_KEY_DOWN = 264,
GLFW_KEY_UP = 265,
GLFW_KEY_PAGE_UP = 266,
GLFW_KEY_PAGE_DOWN = 267,
GLFW_KEY_HOME = 268,
GLFW_KEY_END = 269,
GLFW_KEY_CAPS_LOCK = 280,
GLFW_KEY_SCROLL_LOCK = 281,
GLFW_KEY_NUM_LOCK = 282,
GLFW_KEY_PRINT_SCREEN = 283,
GLFW_KEY_PAUSE = 284,
GLFW_KEY_F1 = 290,
GLFW_KEY_F2 = 291,
GLFW_KEY_F3 = 292,
GLFW_KEY_F4 = 293,
GLFW_KEY_F5 = 294,
GLFW_KEY_F6 = 295,
GLFW_KEY_F7 = 296,
GLFW_KEY_F8 = 297,
GLFW_KEY_F9 = 298,
GLFW_KEY_F10 = 299,
GLFW_KEY_F11 = 300,
GLFW_KEY_F12 = 301,
GLFW_KEY_F13 = 302,
GLFW_KEY_F14 = 303,
GLFW_KEY_F15 = 304,
GLFW_KEY_F16 = 305,
GLFW_KEY_F17 = 306,
GLFW_KEY_F18 = 307,
GLFW_KEY_F19 = 308,
GLFW_KEY_F20 = 309,
GLFW_KEY_F21 = 310,
GLFW_KEY_F22 = 311,
GLFW_KEY_F23 = 312,
GLFW_KEY_F24 = 313,
GLFW_KEY_F25 = 314,
GLFW_KEY_KP_0 = 320,
GLFW_KEY_KP_1 = 321,
GLFW_KEY_KP_2 = 322,
GLFW_KEY_KP_3 = 323,
GLFW_KEY_KP_4 = 324,
GLFW_KEY_KP_5 = 325,
GLFW_KEY_KP_6 = 326,
GLFW_KEY_KP_7 = 327,
GLFW_KEY_KP_8 = 328,
GLFW_KEY_KP_9 = 329,
GLFW_KEY_KP_DECIMAL = 330,
GLFW_KEY_KP_DIVIDE = 331,
GLFW_KEY_KP_MULTIPLY = 332,
GLFW_KEY_KP_SUBTRACT = 333,
GLFW_KEY_KP_ADD = 334,
GLFW_KEY_KP_ENTER = 335,
GLFW_KEY_KP_EQUAL = 336,
GLFW_KEY_LEFT_SHIFT = 340,
GLFW_KEY_LEFT_CONTROL = 341,
GLFW_KEY_LEFT_ALT = 342,
GLFW_KEY_LEFT_SUPER = 343,
GLFW_KEY_RIGHT_SHIFT = 344,
GLFW_KEY_RIGHT_CONTROL = 345,
GLFW_KEY_RIGHT_ALT = 346,
GLFW_KEY_RIGHT_SUPER = 347,
GLFW_KEY_MENU = 348,
GLFW_KEY_LAST = GLFW_KEY_MENU;
/** If this bit is set one or more Shift keys were held down. */
public static final int GLFW_MOD_SHIFT = 0x1;
/** If this bit is set one or more Control keys were held down. */
public static final int GLFW_MOD_CONTROL = 0x2;
/** If this bit is set one or more Alt keys were held down. */
public static final int GLFW_MOD_ALT = 0x4;
/** If this bit is set one or more Super keys were held down. */
public static final int GLFW_MOD_SUPER = 0x8;
/** If this bit is set the Caps Lock key is enabled and the LOCK_KEY_MODS input mode is set. */
public static final int GLFW_MOD_CAPS_LOCK = 0x10;
/** If this bit is set the Num Lock key is enabled and the LOCK_KEY_MODS input mode is set. */
public static final int GLFW_MOD_NUM_LOCK = 0x20;
/** Mouse buttons. See <a target="_blank" href="http://www.glfw.org/docs/latest/input.html#input_mouse_button">mouse button input</a> for how these are used. */
public static final short
GLFW_MOUSE_BUTTON_1 = 0,
GLFW_MOUSE_BUTTON_2 = 1,
GLFW_MOUSE_BUTTON_3 = 2,
GLFW_MOUSE_BUTTON_4 = 3,
GLFW_MOUSE_BUTTON_5 = 4,
GLFW_MOUSE_BUTTON_6 = 5,
GLFW_MOUSE_BUTTON_7 = 6,
GLFW_MOUSE_BUTTON_8 = 7,
GLFW_MOUSE_BUTTON_LAST = GLFW_MOUSE_BUTTON_8,
GLFW_MOUSE_BUTTON_LEFT = GLFW_MOUSE_BUTTON_1,
GLFW_MOUSE_BUTTON_RIGHT = GLFW_MOUSE_BUTTON_2,
GLFW_MOUSE_BUTTON_MIDDLE = GLFW_MOUSE_BUTTON_3;
public static final int
GLFW_VISIBLE = 0x20004,
GLFW_HOVERED = 0x2000B;
}
@@ -1,573 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_ENABLE_GYRO;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_SUSTAINED_PERFORMANCE;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_USE_ALTERNATE_SURFACE;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_VIRTUAL_MOUSE_START;
import static org.lwjgl.glfw.CallbackBridge.sendKeyPress;
import static org.lwjgl.glfw.CallbackBridge.windowHeight;
import static org.lwjgl.glfw.CallbackBridge.windowWidth;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
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.MotionEvent;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.Keep;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.kdt.LoggerView;
import net.kdt.pojavlaunch.customcontrols.ControlButtonMenuListener;
import net.kdt.pojavlaunch.customcontrols.ControlData;
import net.kdt.pojavlaunch.customcontrols.ControlDrawerData;
import net.kdt.pojavlaunch.customcontrols.ControlJoystickData;
import net.kdt.pojavlaunch.customcontrols.ControlLayout;
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.HotbarView;
import net.kdt.pojavlaunch.customcontrols.mouse.Touchpad;
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.prefs.QuickSettingSideDialog;
import net.kdt.pojavlaunch.services.GameService;
import net.kdt.pojavlaunch.utils.JREUtils;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import org.lwjgl.glfw.CallbackBridge;
import java.io.File;
import java.io.IOException;
public class MainActivity extends BaseActivity implements ControlButtonMenuListener, EditorExitable, ServiceConnection {
public static volatile ClipboardManager GLOBAL_CLIPBOARD;
public static final String INTENT_MINECRAFT_VERSION = "intent_version";
volatile public static boolean isInputStackCall;
public static TouchCharInput touchCharInput;
private MinecraftGLSurface minecraftGLView;
private static Touchpad touchpad;
private LoggerView loggerView;
private DrawerLayout drawerLayout;
private ListView navDrawer;
private View mDrawerPullButton;
private GyroControl mGyroControl = null;
private ControlLayout mControlLayout;
private HotbarView mHotbarView;
MinecraftProfile minecraftProfile;
private ArrayAdapter<String> gameActionArrayAdapter;
private AdapterView.OnItemClickListener gameActionClickListener;
public ArrayAdapter<String> ingameControlsEditorArrayAdapter;
public AdapterView.OnItemClickListener ingameControlsEditorListener;
private GameService.LocalBinder mServiceBinder;
private QuickSettingSideDialog mQuickSettingSideDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
minecraftProfile = LauncherProfiles.getCurrentProfile();
MCOptionUtils.load(Tools.getGameDirPath(minecraftProfile).getAbsolutePath());
Intent gameServiceIntent = new Intent(this, GameService.class);
// Start the service a bit early
ContextCompat.startForegroundService(this, gameServiceIntent);
initLayout(R.layout.activity_basemain);
CallbackBridge.addGrabListener(touchpad);
CallbackBridge.addGrabListener(minecraftGLView);
mGyroControl = new GyroControl(this);
// Enabling this on TextureView results in a broken white result
if(PREF_USE_ALTERNATE_SURFACE) getWindow().setBackgroundDrawable(null);
else getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
// Set the sustained performance mode for available APIs
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
getWindow().setSustainedPerformanceMode(PREF_SUSTAINED_PERFORMANCE);
ingameControlsEditorArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.menu_customcontrol));
ingameControlsEditorListener = (parent, view, position, id) -> {
switch(position) {
case 0: mControlLayout.addControlButton(new ControlData("New")); break;
case 1: mControlLayout.addDrawer(new ControlDrawerData()); break;
case 2: mControlLayout.addJoystickButton(new ControlJoystickData()); break;
case 3: mControlLayout.openLoadDialog(); break;
case 4: mControlLayout.openSaveDialog(this); break;
case 5: mControlLayout.openSetDefaultDialog(); break;
case 6: mControlLayout.openExitDialog(this);
}
};
// Recompute the gui scale when options are changed
MCOptionUtils.MCOptionListener optionListener = MCOptionUtils::getMcScale;
MCOptionUtils.addMCOptionListener(optionListener);
mControlLayout.setModifiable(false);
// Set the activity for the executor. Must do this here, or else Tools.showErrorRemote() may not
// execute the correct method
ContextExecutor.setActivity(this);
//Now, attach to the service. The game will only start when this happens, to make sure that we know the right state.
bindService(gameServiceIntent, this, 0);
}
protected void initLayout(int resId) {
setContentView(resId);
bindValues();
mControlLayout.setMenuListener(this);
mDrawerPullButton.setOnClickListener(v -> onClickedMenu());
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
try {
File latestLogFile = new File(Tools.DIR_GAME_HOME, "latestlog.txt");
if(!latestLogFile.exists() && !latestLogFile.createNewFile())
throw new IOException("Failed to create a new log file");
Logger.begin(latestLogFile.getAbsolutePath());
// FIXME: is it safe for multi thread?
GLOBAL_CLIPBOARD = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
touchCharInput.setCharacterSender(new LwjglCharSender());
if(minecraftProfile.pojavRendererName != null) {
Log.i("RdrDebug","__P_renderer="+minecraftProfile.pojavRendererName);
Tools.LOCAL_RENDERER = minecraftProfile.pojavRendererName;
}
setTitle("Minecraft " + minecraftProfile.lastVersionId);
// Minecraft 1.13+
String version = getIntent().getStringExtra(INTENT_MINECRAFT_VERSION);
version = version == null ? minecraftProfile.lastVersionId : version;
JMinecraftVersionList.Version mVersionInfo = Tools.getVersionInfo(version);
isInputStackCall = mVersionInfo.arguments != null;
CallbackBridge.nativeSetUseInputStackQueue(isInputStackCall);
Tools.getDisplayMetrics(this);
windowWidth = Tools.getDisplayFriendlyRes(currentDisplayMetrics.widthPixels, 1f);
windowHeight = Tools.getDisplayFriendlyRes(currentDisplayMetrics.heightPixels, 1f);
// Menu
gameActionArrayAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.menu_ingame));
gameActionClickListener = (parent, view, position, id) -> {
switch(position) {
case 0: openLogOutput(); break;
case 1: dialogSendCustomKey(); break;
case 2: openQuickSettings(); break;
case 3: openCustomControls(); break;
}
drawerLayout.closeDrawers();
};
navDrawer.setAdapter(gameActionArrayAdapter);
navDrawer.setOnItemClickListener(gameActionClickListener);
drawerLayout.closeDrawers();
final String finalVersion = version;
minecraftGLView.setSurfaceReadyListener(() -> {
try {
// Setup virtual mouse right before launching
if (PREF_VIRTUAL_MOUSE_START) {
touchpad.post(() -> touchpad.switchState());
}
runCraft(finalVersion, mVersionInfo);
}catch (Throwable e){
Tools.showErrorRemote(e);
}
});
} catch (Throwable e) {
Tools.showError(this, e, true);
}
}
private void loadControls() {
try {
// Load keys
mControlLayout.loadLayout(
minecraftProfile.controlFile == null
? LauncherPreferences.PREF_DEFAULTCTRL_PATH
: Tools.CTRLMAP_PATH + "/" + minecraftProfile.controlFile);
} catch(IOException e) {
try {
Log.w("MainActivity", "Unable to load the control file, loading the default now", e);
mControlLayout.loadLayout(Tools.CTRLDEF_FILE);
} catch (IOException ioException) {
Tools.showError(this, ioException);
}
} catch (Throwable th) {
Tools.showError(this, th);
}
mDrawerPullButton.setVisibility(mControlLayout.hasMenuButton() ? View.GONE : View.VISIBLE);
mControlLayout.toggleControlVisible();
}
@Override
public void onAttachedToWindow() {
// Post to get the correct display dimensions after layout.
LauncherPreferences.computeNotchSize(this);
mControlLayout.post(()->{
Tools.getDisplayMetrics(this);
loadControls();
});
}
/** Boilerplate binding */
private void bindValues(){
mControlLayout = findViewById(R.id.main_control_layout);
minecraftGLView = findViewById(R.id.main_game_render_view);
touchpad = findViewById(R.id.main_touchpad);
drawerLayout = findViewById(R.id.main_drawer_options);
navDrawer = findViewById(R.id.main_navigation_view);
loggerView = findViewById(R.id.mainLoggerView);
mControlLayout = findViewById(R.id.main_control_layout);
touchCharInput = findViewById(R.id.mainTouchCharInput);
mDrawerPullButton = findViewById(R.id.drawer_button);
mHotbarView = findViewById(R.id.hotbar_view);
}
@Override
public void onResume() {
super.onResume();
if(PREF_ENABLE_GYRO) mGyroControl.enable();
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 1);
}
@Override
protected void onPause() {
mGyroControl.disable();
if (CallbackBridge.isGrabbing()){
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ESCAPE);
}
if(mQuickSettingSideDialog != null) {
mQuickSettingSideDialog.cancel();
}
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 0);
super.onPause();
}
@Override
protected void onStart() {
super.onStart();
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_VISIBLE, 1);
}
@Override
protected void onStop() {
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_VISIBLE, 0);
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
CallbackBridge.removeGrabListener(touchpad);
CallbackBridge.removeGrabListener(minecraftGLView);
ContextExecutor.clearActivity();
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(mGyroControl != null) mGyroControl.updateOrientation();
// Layout resize is practically guaranteed on a configuration change, and `onConfigurationChanged`
// does not implicitly start a layout. So, request a layout and expect the screen dimensions to be valid after the]
// post.
mControlLayout.requestLayout();
mControlLayout.post(()->{
// Child of mControlLayout, so refreshing size here is correct
minecraftGLView.refreshSize();
Tools.updateWindowSize(this);
mControlLayout.refreshControlButtonPositions();
});
}
@Override
protected void onPostResume() {
super.onPostResume();
if(minecraftGLView != null) // Useful when backing out of the app
Tools.MAIN_HANDLER.postDelayed(() -> minecraftGLView.refreshSize(), 500);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
// Reload PREF_DEFAULTCTRL_PATH
LauncherPreferences.loadPreferences(getApplicationContext());
try {
mControlLayout.loadLayout(LauncherPreferences.PREF_DEFAULTCTRL_PATH);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void runCraft(String versionId, JMinecraftVersionList.Version version) throws Throwable {
if(Tools.LOCAL_RENDERER == null) {
Tools.LOCAL_RENDERER = LauncherPreferences.PREF_RENDERER;
}
if(!Tools.checkRendererCompatible(this, Tools.LOCAL_RENDERER)) {
Tools.RenderersList renderersList = Tools.getCompatibleRenderers(this);
String firstCompatibleRenderer = renderersList.rendererIds.get(0);
Log.w("runCraft","Incompatible renderer "+Tools.LOCAL_RENDERER+ " will be replaced with "+firstCompatibleRenderer);
Tools.LOCAL_RENDERER = firstCompatibleRenderer;
Tools.releaseRenderersCache();
}
MinecraftAccount minecraftAccount = PojavProfile.getCurrentProfileContent(this, null);
Logger.appendToLog("--------- Starting game with Launcher Debug!");
Tools.printLauncherInfo(versionId, Tools.isValidString(minecraftProfile.javaArgs) ? minecraftProfile.javaArgs : LauncherPreferences.PREF_CUSTOM_JAVA_ARGS);
JREUtils.redirectAndPrintJRELog();
LauncherProfiles.load();
int requiredJavaVersion = 8;
if(version.javaVersion != null) requiredJavaVersion = version.javaVersion.majorVersion;
Tools.launchMinecraft(this, minecraftAccount, minecraftProfile, versionId, requiredJavaVersion);
//Note that we actually stall in the above function, even if the game crashes. But let's be safe.
Tools.runOnUiThread(()-> mServiceBinder.isActive = false);
}
private void dialogSendCustomKey() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.control_customkey);
dialog.setItems(EfficientAndroidLWJGLKeycode.generateKeyName(), (dInterface, position) -> EfficientAndroidLWJGLKeycode.execKeyIndex(position));
dialog.show();
}
boolean isInEditor;
private void openCustomControls() {
if(ingameControlsEditorListener == null || ingameControlsEditorArrayAdapter == null) return;
mControlLayout.setModifiable(true);
navDrawer.setAdapter(ingameControlsEditorArrayAdapter);
navDrawer.setOnItemClickListener(ingameControlsEditorListener);
mDrawerPullButton.setVisibility(View.VISIBLE);
isInEditor = true;
}
private void openLogOutput() {
loggerView.setVisibility(View.VISIBLE);
}
private void openQuickSettings() {
if(mQuickSettingSideDialog == null) {
mQuickSettingSideDialog = new QuickSettingSideDialog(this, mControlLayout) {
@Override
public void onResolutionChanged() {
minecraftGLView.refreshSize();
mHotbarView.onResolutionChanged();
}
@Override
public void onGyroStateChanged() {
mGyroControl.updateOrientation();
if (PREF_ENABLE_GYRO) {
mGyroControl.enable();
} else {
mGyroControl.disable();
}
}
};
}
mQuickSettingSideDialog.appear(true);
}
public static void toggleMouse(Context ctx) {
if (CallbackBridge.isGrabbing()) return;
Toast.makeText(ctx, touchpad.switchState()
? R.string.control_mouseon : R.string.control_mouseoff,
Toast.LENGTH_SHORT).show();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if(isInEditor) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if(event.getAction() == KeyEvent.ACTION_DOWN) mControlLayout.askToExit(this);
return true;
}
return super.dispatchKeyEvent(event);
}
boolean handleEvent;
if(!(handleEvent = minecraftGLView.processKeyEvent(event))) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && !touchCharInput.isEnabled()) {
if(event.getAction() != KeyEvent.ACTION_UP) return true; // We eat it anyway
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ESCAPE);
return true;
}
}
return handleEvent;
}
public static void switchKeyboardState() {
if(touchCharInput != null) touchCharInput.switchKeyboardState();
}
@Keep
public static void openLink(String link) {
Context ctx = touchpad.getContext(); // no more better way to obtain a context statically
((Activity)ctx).runOnUiThread(() -> {
try {
if(link.startsWith("file:")) {
int truncLength = 5;
if(link.startsWith("file://")) truncLength = 7;
String path = link.substring(truncLength);
Tools.openPath(ctx, new File(path), false);
}else {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(link), "*/*");
ctx.startActivity(intent);
}
} catch (Throwable th) {
Tools.showError(ctx, th);
}
});
}
@SuppressWarnings("unused") //TODO: actually use it
public static void openPath(String path) {
Context ctx = touchpad.getContext(); // no more better way to obtain a context statically
((Activity)ctx).runOnUiThread(() -> {
try {
Tools.openPath(ctx, new File(path), false);
} catch (Throwable th) {
Tools.showError(ctx, th);
}
});
}
@Keep
public static void querySystemClipboard() {
Tools.runOnUiThread(()->{
ClipData clipData = GLOBAL_CLIPBOARD.getPrimaryClip();
if(clipData == null) {
AWTInputBridge.nativeClipboardReceived(null, null);
return;
}
ClipData.Item firstClipItem = clipData.getItemAt(0);
//TODO: coerce to HTML if the clip item is styled
CharSequence clipItemText = firstClipItem.getText();
if(clipItemText == null) {
AWTInputBridge.nativeClipboardReceived(null, null);
return;
}
AWTInputBridge.nativeClipboardReceived(clipItemText.toString(), "plain");
});
}
@Keep
public static void putClipboardData(String data, String mimeType) {
Tools.runOnUiThread(()-> {
ClipData clipData = null;
switch(mimeType) {
case "text/plain":
clipData = ClipData.newPlainText("AWT Paste", data);
break;
case "text/html":
clipData = ClipData.newHtmlText("AWT Paste", data, data);
}
if(clipData != null) GLOBAL_CLIPBOARD.setPrimaryClip(clipData);
});
}
@Override
public void onClickedMenu() {
drawerLayout.openDrawer(navDrawer);
navDrawer.requestLayout();
}
@Override
public void exitEditor() {
try {
mControlLayout.loadLayout((CustomControls)null);
mControlLayout.setModifiable(false);
System.gc();
mControlLayout.loadLayout(
minecraftProfile.controlFile == null
? LauncherPreferences.PREF_DEFAULTCTRL_PATH
: Tools.CTRLMAP_PATH + "/" + minecraftProfile.controlFile);
mDrawerPullButton.setVisibility(mControlLayout.hasMenuButton() ? View.GONE : View.VISIBLE);
} catch (IOException e) {
Tools.showError(this,e);
}
navDrawer.setAdapter(gameActionArrayAdapter);
navDrawer.setOnItemClickListener(gameActionClickListener);
isInEditor = false;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
GameService.LocalBinder localBinder = (GameService.LocalBinder) service;
mServiceBinder = localBinder;
minecraftGLView.start(localBinder.isActive, touchpad);
localBinder.isActive = true;
}
@Override
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(Tools.isAndroid8OrHigher() && checkCaptureDispatchConditions(ev))
return minecraftGLView.dispatchCapturedPointerEvent(ev);
else return super.dispatchTrackballEvent(ev);
}
}
@@ -1,419 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.MainActivity.touchCharInput;
import static net.kdt.pojavlaunch.utils.MCOptionUtils.getMcScale;
import static org.lwjgl.glfw.CallbackBridge.sendMouseButton;
import static org.lwjgl.glfw.CallbackBridge.windowHeight;
import static org.lwjgl.glfw.CallbackBridge.windowWidth;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
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 org.lwjgl.glfw.CallbackBridge;
import fr.spse.gamepad_remapper.RemapperManager;
import fr.spse.gamepad_remapper.RemapperView;
/**
* Class dealing with showing minecraft surface and taking inputs to dispatch them to minecraft
*/
public class MinecraftGLSurface extends View implements GrabListener {
/* Gamepad object for gamepad inputs, instantiated on need */
private Gamepad mGamepad = null;
/* The RemapperView.Builder object allows you to set which buttons to remap */
private final RemapperManager mInputManager = new RemapperManager(getContext(), new RemapperView.Builder(null)
.remapA(true)
.remapB(true)
.remapX(true)
.remapY(true)
.remapLeftJoystick(true)
.remapRightJoystick(true)
.remapStart(true)
.remapSelect(true)
.remapLeftShoulder(true)
.remapRightShoulder(true)
.remapLeftTrigger(true)
.remapRightTrigger(true)
.remapDpad(true));
/* Sensitivity, adjusted according to screen size */
private final double mSensitivityFactor = (1.4 * (1080f/ Tools.getDisplayMetrics((Activity) getContext()).heightPixels));
/* 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;
private final InGameEventProcessor mIngameProcessor = new InGameEventProcessor(mSensitivityFactor);
private final InGUIEventProcessor mInGUIProcessor = new InGUIEventProcessor();
private TouchEventProcessor mCurrentTouchProcessor = mInGUIProcessor;
private AndroidPointerCapture mPointerCapture;
private boolean mLastGrabState = false;
public MinecraftGLSurface(Context context) {
this(context, null);
}
public MinecraftGLSurface(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setFocusable(true);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void setUpPointerCapture(AbstractTouchpad touchpad) {
if(mPointerCapture != null) mPointerCapture.detach();
mPointerCapture = new AndroidPointerCapture(touchpad, this);
}
/** 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, AbstractTouchpad touchpad){
if(Tools.isAndroid8OrHigher()) setUpPointerCapture(touchpad);
mInGUIProcessor.setAbstractTouchpad(touchpad);
if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){
SurfaceView surfaceView = new SurfaceView(getContext());
mSurface = surfaceView;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
private boolean isCalled = isAlreadyRunning;
@Override
public void surfaceCreated(@NonNull SurfaceHolder holder) {
if(isCalled) {
JREUtils.setupBridgeWindow(surfaceView.getHolder().getSurface());
return;
}
isCalled = true;
realStart(surfaceView.getHolder().getSurface());
}
@Override
public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
refreshSize();
}
@Override
public void surfaceDestroyed(@NonNull SurfaceHolder holder) {}
});
((ViewGroup)getParent()).addView(surfaceView);
}else{
TextureView textureView = new TextureView(getContext());
textureView.setOpaque(true);
textureView.setAlpha(1.0f);
mSurface = textureView;
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
private boolean isCalled = isAlreadyRunning;
@Override
public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
Surface tSurface = new Surface(surface);
if(isCalled) {
JREUtils.setupBridgeWindow(tSurface);
return;
}
isCalled = true;
realStart(tSurface);
}
@Override
public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
refreshSize();
}
@Override
public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
return true;
}
@Override
public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {}
});
((ViewGroup)getParent()).addView(textureView);
}
}
/**
* The touch event for both grabbed an non-grabbed mouse state on the touch screen
* Does not cover the virtual mouse touchpad
*/
@Override
@SuppressWarnings("accessibility")
public boolean onTouchEvent(MotionEvent e) {
// Kinda need to send this back to the layout
if(((ControlLayout)getParent()).getModifiable()) return false;
// Looking for a mouse to handle, won't have an effect if no mouse exists.
for (int i = 0; i < e.getPointerCount(); i++) {
int toolType = e.getToolType(i);
if(toolType == MotionEvent.TOOL_TYPE_MOUSE) {
if(Tools.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) * LauncherPreferences.PREF_SCALE_FACTOR, e.getY(i) * LauncherPreferences.PREF_SCALE_FACTOR);
return true; //mouse event handled successfully
}
if (mIngameProcessor == null || mInGUIProcessor == null) return true;
return mCurrentTouchProcessor.processTouchEvent(e);
}
private void createGamepad(View contextView, InputDevice inputDevice) {
mGamepad = new Gamepad(contextView, inputDevice, DefaultDataProvider.INSTANCE, true);
}
/**
* The event for mouse/joystick movements
*/
@SuppressLint("NewApi")
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
int mouseCursorIndex = -1;
if(Gamepad.isGamepadEvent(event)){
if(mGamepad == null) createGamepad(this, event.getDevice());
mInputManager.handleMotionEventInput(getContext(), event, mGamepad);
return true;
}
for(int i = 0; i < event.getPointerCount(); i++) {
if(event.getToolType(i) != MotionEvent.TOOL_TYPE_MOUSE && event.getToolType(i) != MotionEvent.TOOL_TYPE_STYLUS ) continue;
// Mouse found
mouseCursorIndex = i;
break;
}
if(mouseCursorIndex == -1) return false; // we cant consoom that, theres no mice!
// Make sure we grabbed the mouse if necessary
updateGrabState(CallbackBridge.isGrabbing());
switch(event.getActionMasked()) {
case MotionEvent.ACTION_HOVER_MOVE:
CallbackBridge.mouseX = (event.getX(mouseCursorIndex) * LauncherPreferences.PREF_SCALE_FACTOR);
CallbackBridge.mouseY = (event.getY(mouseCursorIndex) * LauncherPreferences.PREF_SCALE_FACTOR);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
return true;
case MotionEvent.ACTION_SCROLL:
CallbackBridge.sendScroll((double) event.getAxisValue(MotionEvent.AXIS_HSCROLL), (double) event.getAxisValue(MotionEvent.AXIS_VSCROLL));
return true;
case MotionEvent.ACTION_BUTTON_PRESS:
return sendMouseButtonUnconverted(event.getActionButton(),true);
case MotionEvent.ACTION_BUTTON_RELEASE:
return sendMouseButtonUnconverted(event.getActionButton(),false);
default:
return false;
}
}
/** The event for keyboard/ gamepad button inputs */
public boolean processKeyEvent(KeyEvent event) {
//Log.i("KeyEvent", event.toString());
//Filtering useless events by order of probability
int eventKeycode = event.getKeyCode();
if(eventKeycode == KeyEvent.KEYCODE_UNKNOWN) return true;
if(eventKeycode == KeyEvent.KEYCODE_VOLUME_DOWN) return false;
if(eventKeycode == KeyEvent.KEYCODE_VOLUME_UP) return false;
if(event.getRepeatCount() != 0) return true;
int action = event.getAction();
if(action == KeyEvent.ACTION_MULTIPLE) return true;
// Ignore the cancelled up events. They occur when the user switches layouts.
// In accordance with https://developer.android.com/reference/android/view/KeyEvent#FLAG_CANCELED
if(action == KeyEvent.ACTION_UP &&
(event.getFlags() & KeyEvent.FLAG_CANCELED) != 0) return true;
//Sometimes, key events comes from SOME keys of the software keyboard
//Even weirder, is is unknown why a key or another is selected to trigger a keyEvent
if((event.getFlags() & KeyEvent.FLAG_SOFT_KEYBOARD) == KeyEvent.FLAG_SOFT_KEYBOARD){
if(eventKeycode == KeyEvent.KEYCODE_ENTER) return true; //We already listen to it.
touchCharInput.dispatchKeyEvent(event);
return true;
}
//Sometimes, key events may come from the mouse
if(event.getDevice() != null
&& ( (event.getSource() & InputDevice.SOURCE_MOUSE_RELATIVE) == InputDevice.SOURCE_MOUSE_RELATIVE
|| (event.getSource() & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE) ){
if(eventKeycode == KeyEvent.KEYCODE_BACK){
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, event.getAction() == KeyEvent.ACTION_DOWN);
return true;
}
}
if(Gamepad.isGamepadEvent(event)){
if(mGamepad == null) createGamepad(this, event.getDevice());
mInputManager.handleKeyEventInput(getContext(), event, mGamepad);
return true;
}
int index = EfficientAndroidLWJGLKeycode.getIndexByKey(eventKeycode);
if(EfficientAndroidLWJGLKeycode.containsIndex(index)) {
EfficientAndroidLWJGLKeycode.execKey(event, index);
return true;
}
// Some events will be generated an infinite number of times when no consumed
return (event.getFlags() & KeyEvent.FLAG_FALLBACK) == KeyEvent.FLAG_FALLBACK;
}
/** Convert the mouse button, then send it
* @return Whether the event was processed
*/
public static boolean sendMouseButtonUnconverted(int button, boolean status) {
int glfwButton = -256;
switch (button) {
case MotionEvent.BUTTON_PRIMARY:
glfwButton = LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT;
break;
case MotionEvent.BUTTON_TERTIARY:
glfwButton = LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_MIDDLE;
break;
case MotionEvent.BUTTON_SECONDARY:
glfwButton = LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT;
break;
}
if(glfwButton == -256) return false;
sendMouseButton(glfwButton, status);
return true;
}
/** Called when the size need to be set at any point during the surface lifecycle **/
public void refreshSize(){
refreshSize(false);
}
/** Same as refreshSize, but allows you to force an immediate size update **/
public void refreshSize(boolean immediate) {
if(isInLayout() && !immediate) {
post(this::refreshSize);
return;
}
// Use the width and height of the View instead of display dimensions to avoid
// getting squiched/stretched due to inconsistencies between the layout and
// screen dimensions.
windowWidth = Tools.getDisplayFriendlyRes(getWidth(), LauncherPreferences.PREF_SCALE_FACTOR);
windowHeight = Tools.getDisplayFriendlyRes(getHeight(), LauncherPreferences.PREF_SCALE_FACTOR);
if(mSurface == null){
Log.w("MGLSurface", "Attempt to refresh size on null surface");
return;
}
if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){
SurfaceView view = (SurfaceView) mSurface;
if(view.getHolder() != null){
view.getHolder().setFixedSize(windowWidth, windowHeight);
}
}else{
TextureView view = (TextureView)mSurface;
if(view.getSurfaceTexture() != null){
view.getSurfaceTexture().setDefaultBufferSize(windowWidth, windowHeight);
}
}
CallbackBridge.sendUpdateWindowSize(windowWidth, windowHeight);
}
private void realStart(Surface surface){
// Initial size set. Request immedate refresh, otherwise the initial width and height for the game
// may be broken/unknown.
refreshSize(true);
//Load Minecraft options:
MCOptionUtils.set("fullscreen", "off");
MCOptionUtils.set("overrideWidth", String.valueOf(windowWidth));
MCOptionUtils.set("overrideHeight", String.valueOf(windowHeight));
MCOptionUtils.save();
getMcScale();
JREUtils.setupBridgeWindow(surface);
new Thread(() -> {
try {
// Wait until the listener is attached
synchronized(mSurfaceReadyListenerLock) {
if(mSurfaceReadyListener == null) mSurfaceReadyListenerLock.wait();
}
mSurfaceReadyListener.isReady();
} catch (Throwable e) {
Tools.showError(getContext(), e, true);
}
}, "JVM Main thread").start();
}
@Override
public void onGrabState(boolean isGrabbing) {
post(()->updateGrabState(isGrabbing));
}
private TouchEventProcessor pickEventProcessor(boolean isGrabbing) {
return isGrabbing ? mIngameProcessor : mInGUIProcessor;
}
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 */
public interface SurfaceReadyListener {
void isReady();
}
public void setSurfaceReadyListener(SurfaceReadyListener listener){
synchronized (mSurfaceReadyListenerLock) {
mSurfaceReadyListener = listener;
mSurfaceReadyListenerLock.notifyAll();
}
}
}
@@ -1,13 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MissingStorageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.storage_test_no_sdcard);
}
}
@@ -1,157 +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.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;
}
}
}
@@ -1,97 +0,0 @@
package net.kdt.pojavlaunch;
import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
import android.app.*;
import android.content.*;
import android.content.pm.*;
import android.content.res.*;
import android.os.*;
import androidx.core.app.*;
import android.util.*;
import java.io.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import net.kdt.pojavlaunch.lifecycle.ContextExecutor;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
import net.kdt.pojavlaunch.utils.*;
import net.kdt.pojavlaunch.utils.FileUtils;
public class PojavApplication extends Application {
public static final String CRASH_REPORT_TAG = "PojavCrashReport";
public static final ExecutorService sExecutorService = new ThreadPoolExecutor(4, 4, 500, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
@Override
public void onCreate() {
ContextExecutor.setApplication(this);
Thread.setDefaultUncaughtExceptionHandler((thread, th) -> {
boolean storagePermAllowed = (Build.VERSION.SDK_INT < 23 || Build.VERSION.SDK_INT >= 29 ||
ActivityCompat.checkSelfPermission(PojavApplication.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) && Tools.checkStorageRoot(PojavApplication.this);
File crashFile = new File(storagePermAllowed ? Tools.DIR_GAME_HOME : Tools.DIR_DATA, "latestcrash.txt");
try {
// Write to file, since some devices may not able to show error
FileUtils.ensureParentDirectory(crashFile);
PrintStream crashStream = new PrintStream(crashFile);
crashStream.append("PojavLauncher crash report\n");
crashStream.append(" - Time: ").append(DateFormat.getDateTimeInstance().format(new Date())).append("\n");
crashStream.append(" - Device: ").append(Build.PRODUCT).append(" ").append(Build.MODEL).append("\n");
crashStream.append(" - Android version: ").append(Build.VERSION.RELEASE).append("\n");
crashStream.append(" - Crash stack trace:\n");
crashStream.append(" - Launcher version: " + BuildConfig.VERSION_NAME + "\n");
crashStream.append(Log.getStackTraceString(th));
crashStream.close();
} catch (Throwable throwable) {
Log.e(CRASH_REPORT_TAG, " - Exception attempt saving crash stack trace:", throwable);
Log.e(CRASH_REPORT_TAG, " - The crash stack trace was:", th);
}
FatalErrorActivity.showError(PojavApplication.this, crashFile.getAbsolutePath(), storagePermAllowed, th);
Tools.fullyExit();
});
try {
super.onCreate();
Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent();
Tools.DIR_CACHE = getCacheDir();
Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts";
Tools.DEVICE_ARCHITECTURE = Architecture.getDeviceArchitecture();
//Force x86 lib directory for Asus x86 based zenfones
if(Architecture.isx86Device() && Architecture.is32BitsDevice()){
String originalJNIDirectory = getApplicationInfo().nativeLibraryDir;
getApplicationInfo().nativeLibraryDir = originalJNIDirectory.substring(0,
originalJNIDirectory.lastIndexOf("/"))
.concat("/x86");
}
AsyncAssetManager.unpackRuntime(getAssets());
} catch (Throwable throwable) {
Intent ferrorIntent = new Intent(this, FatalErrorActivity.class);
ferrorIntent.putExtra("throwable", throwable);
ferrorIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
startActivity(ferrorIntent);
}
}
@Override
public void onTerminate() {
super.onTerminate();
ContextExecutor.clearApplication();
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleUtils.setLocale(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.setLocale(this);
}
}
@@ -1,49 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.value.MinecraftAccount;
public class PojavProfile {
private static final String PROFILE_PREF = "pojav_profile";
private static final String PROFILE_PREF_FILE = "file";
public static SharedPreferences getPrefs(Context ctx) {
return ctx.getSharedPreferences(PROFILE_PREF, Context.MODE_PRIVATE);
}
public static MinecraftAccount getCurrentProfileContent(@NonNull Context ctx, @Nullable String profileName) {
return MinecraftAccount.load(profileName == null ? getCurrentProfileName(ctx) : profileName);
}
public static String getCurrentProfileName(Context ctx) {
String name = getPrefs(ctx).getString(PROFILE_PREF_FILE, "");
// A dirty fix
if (!name.isEmpty() && name.startsWith(Tools.DIR_ACCOUNT_NEW) && name.endsWith(".json")) {
name = name.substring(0, name.length() - 5).replace(Tools.DIR_ACCOUNT_NEW, "").replace(".json", "");
setCurrentProfile(ctx, name);
}
return name;
}
public static void setCurrentProfile(@NonNull Context ctx, @Nullable Object obj) {
SharedPreferences.Editor pref = getPrefs(ctx).edit();
try { if (obj instanceof String) {
String acc = (String) obj;
pref.putString(PROFILE_PREF_FILE, acc);
//MinecraftAccount.clearTempAccount();
} else if (obj == null) {
pref.putString(PROFILE_PREF_FILE, "");
} else {
throw new IllegalArgumentException("Profile must be String.class or null");
}
} finally {
pref.apply();
}
}
}
@@ -1,81 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.lifecycle.ContextExecutorTask;
import net.kdt.pojavlaunch.utils.NotificationUtils;
import java.io.Serializable;
public class ShowErrorActivity extends Activity {
private static final String ERROR_ACTIVITY_REMOTE_TASK = "remoteTask";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if(intent == null) {
finish();
return;
}
RemoteErrorTask remoteErrorTask = (RemoteErrorTask) intent.getSerializableExtra(ERROR_ACTIVITY_REMOTE_TASK);
if(remoteErrorTask == null) {
finish();
return;
}
remoteErrorTask.executeWithActivity(this);
}
public static class RemoteErrorTask implements ContextExecutorTask, Serializable {
private final Throwable mThrowable;
private final String mRolledMsg;
public RemoteErrorTask(Throwable mThrowable, String mRolledMsg) {
this.mThrowable = mThrowable;
this.mRolledMsg = mRolledMsg;
}
@Override
public void executeWithActivity(Activity activity) {
if(mThrowable instanceof ContextExecutorTask) {
((ContextExecutorTask)mThrowable).executeWithActivity(activity);
}else {
Tools.showError(activity, mRolledMsg, mThrowable, activity instanceof ShowErrorActivity);
}
}
@Override
public void executeWithApplication(Context context) {
Intent showErrorIntent = new Intent(context, ShowErrorActivity.class);
showErrorIntent.putExtra(ERROR_ACTIVITY_REMOTE_TASK, this);
NotificationUtils.sendBasicNotification(context,
R.string.notif_error_occured,
R.string.notif_error_occured_desc,
showErrorIntent,
NotificationUtils.PENDINGINTENT_CODE_SHOW_ERROR,
NotificationUtils.NOTIFICATION_ID_SHOW_ERROR
);
}
}
/**
* Install remote dialog handling onto a dialog. This should be used when the dialog is planned to be presented
* through Tools.showError or Tools.showErrorRemote as a Throwable implementing a ContextExecutorTask.
* @param callerActivity the activity provided by the ContextExecutorTask.executeWithActivity
* @param builder the alert dialog builder.
*/
public static void installRemoteDialogHandling(Activity callerActivity, @NonNull AlertDialog.Builder builder) {
if (callerActivity instanceof ShowErrorActivity) {
builder.setOnDismissListener(d -> callerActivity.finish());
}
}
}
@@ -1,13 +0,0 @@
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) {
return true;
}
}
@@ -1,71 +0,0 @@
package net.kdt.pojavlaunch;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import net.kdt.pojavlaunch.tasks.AsyncAssetManager;
public class TestStorageActivity extends Activity {
private final int REQUEST_STORAGE_REQUEST_CODE = 1;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(Build.VERSION.SDK_INT >= 23 && Build.VERSION.SDK_INT < 29 && !isStorageAllowed(this)) requestStoragePermission();
else exit();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == REQUEST_STORAGE_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
exit();
} else {
Toast.makeText(this, R.string.toast_permission_denied, Toast.LENGTH_LONG).show();
requestStoragePermission();
}
}
}
public static boolean isStorageAllowed(Context context) {
//Getting the permission status
int result1 = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int result2 = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
//If permission is granted returning true
return result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED;
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_REQUEST_CODE);
}
private void exit() {
if(!Tools.checkStorageRoot(this)) {
startActivity(new Intent(this, MissingStorageActivity.class));
return;
}
//Only run them once we get a definitive green light to use storage
AsyncAssetManager.unpackComponents(this);
AsyncAssetManager.unpackSingleFiles(this);
Intent intent = new Intent(this, LauncherActivity.class);
startActivity(intent);
finish();
}
}
File diff suppressed because it is too large. Load diff
@@ -1,8 +0,0 @@
package net.kdt.pojavlaunch.authenticator.listener;
import net.kdt.pojavlaunch.value.MinecraftAccount;
/** Called when the login is done and the account received. guaranteed to be on the UI Thread */
public interface DoneListener {
void onLoginDone(MinecraftAccount account);
}
@@ -1,7 +0,0 @@
package net.kdt.pojavlaunch.authenticator.listener;
/** Called when there is a complete failure, guaranteed to be on the UI Thread */
public interface ErrorListener {
void onLoginError(Throwable errorMessage);
}
@@ -1,7 +0,0 @@
package net.kdt.pojavlaunch.authenticator.listener;
/** Called when a step is started, guaranteed to be in the UI Thread */
public interface ProgressListener {
/** */
void onLoginProgress(int step);
}
@@ -1,353 +0,0 @@
package net.kdt.pojavlaunch.authenticator.microsoft;
import static net.kdt.pojavlaunch.PojavApplication.sExecutorService;
import android.util.ArrayMap;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.kdt.mcgui.ProgressLayout;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.Tools;
import net.kdt.pojavlaunch.authenticator.listener.DoneListener;
import net.kdt.pojavlaunch.authenticator.listener.ErrorListener;
import net.kdt.pojavlaunch.authenticator.listener.ProgressListener;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
/** Allow to perform a background login on a given account */
// TODO handle connection errors !
public class MicrosoftBackgroundLogin {
private static final String authTokenUrl = "https://login.live.com/oauth20_token.srf";
private static final String xblAuthUrl = "https://user.auth.xboxlive.com/user/authenticate";
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;
private static final Map<Long, Integer> XSTS_ERRORS;
static {
XSTS_ERRORS = new ArrayMap<>();
XSTS_ERRORS.put(2148916233L, R.string.xerr_no_account);
XSTS_ERRORS.put(2148916235L, R.string.xerr_not_available);
XSTS_ERRORS.put(2148916236L ,R.string.xerr_adult_verification);
XSTS_ERRORS.put(2148916237L ,R.string.xerr_adult_verification);
XSTS_ERRORS.put(2148916238L ,R.string.xerr_child);
}
/* Fields used to fill the account */
public String msRefreshToken;
public String mcName;
public String mcToken;
public String mcUuid;
public boolean doesOwnGame;
public long expiresAt;
public MicrosoftBackgroundLogin(boolean isRefresh, String authCode){
mIsRefresh = isRefresh;
mAuthCode = authCode;
}
/** Performs a full login, calling back listeners appropriately */
public void performLogin(@Nullable final ProgressListener progressListener,
@Nullable final DoneListener doneListener,
@Nullable final ErrorListener errorListener){
sExecutorService.execute(() -> {
try {
notifyProgress(progressListener, 1);
String accessToken = acquireAccessToken(mIsRefresh, mAuthCode);
notifyProgress(progressListener, 2);
String xboxLiveToken = acquireXBLToken(accessToken);
notifyProgress(progressListener, 3);
String[] xsts = acquireXsts(xboxLiveToken);
notifyProgress(progressListener, 4);
String mcToken = acquireMinecraftToken(xsts[0], xsts[1]);
notifyProgress(progressListener, 5);
fetchOwnedItems(mcToken);
checkMcProfile(mcToken);
MinecraftAccount acc = MinecraftAccount.load(mcName);
if(acc == null) acc = new MinecraftAccount();
if (doesOwnGame) {
acc.xuid = xsts[0];
acc.clientToken = "0"; /* FIXME */
acc.accessToken = mcToken;
acc.username = mcName;
acc.profileId = mcUuid;
acc.isMicrosoft = true;
acc.msaRefreshToken = msRefreshToken;
acc.expiresAt = expiresAt;
acc.updateSkinFace();
}
acc.save();
if(doneListener != null) {
MinecraftAccount finalAcc = acc;
Tools.runOnUiThread(() -> doneListener.onLoginDone(finalAcc));
}
}catch (Exception e){
Log.e("MicroAuth", "Exception thrown during authentication", e);
if(errorListener != null)
Tools.runOnUiThread(() -> errorListener.onLoginError(e));
}
ProgressLayout.clearProgress(ProgressLayout.AUTHENTICATE_MICROSOFT);
});
}
public String acquireAccessToken(boolean isRefresh, String authcode) throws IOException, JSONException {
URL url = new URL(authTokenUrl);
Log.i("MicrosoftLogin", "isRefresh=" + isRefresh + ", authCode= "+authcode);
String formData = convertToFormData(
"client_id", "00000000402b5328",
isRefresh ? "refresh_token" : "code", authcode,
"grant_type", isRefresh ? "refresh_token" : "authorization_code",
"redirect_url", "https://login.live.com/oauth20_desktop.srf",
"scope", "service::user.auth.xboxlive.com::MBI_SSL"
);
Log.i("MicroAuth", formData);
//да пошла yf[eq1 она ваша джава 11
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(formData.getBytes(StandardCharsets.UTF_8).length));
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(formData.getBytes(StandardCharsets.UTF_8));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
msRefreshToken = jo.getString("refresh_token");
conn.disconnect();
Log.i("MicrosoftLogin","Acess Token = " + jo.getString("access_token"));
return jo.getString("access_token");
//acquireXBLToken(jo.getString("access_token"));
}else{
throw getResponseThrowable(conn);
}
}
private String acquireXBLToken(String accessToken) throws IOException, JSONException {
URL url = new URL(xblAuthUrl);
JSONObject data = new JSONObject();
JSONObject properties = new JSONObject();
properties.put("AuthMethod", "RPS");
properties.put("SiteName", "user.auth.xboxlive.com");
properties.put("RpsTicket", accessToken);
data.put("Properties",properties);
data.put("RelyingParty", "http://auth.xboxlive.com");
data.put("TokenType", "JWT");
String req = data.toString();
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
setCommonProperties(conn, req);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes(StandardCharsets.UTF_8));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
conn.disconnect();
Log.i("MicrosoftLogin","Xbl Token = "+jo.getString("Token"));
return jo.getString("Token");
//acquireXsts(jo.getString("Token"));
}else{
throw getResponseThrowable(conn);
}
}
/** @return [uhs, token]*/
private @NonNull String[] acquireXsts(String xblToken) throws IOException, JSONException {
URL url = new URL(xstsAuthUrl);
JSONObject data = new JSONObject();
JSONObject properties = new JSONObject();
properties.put("SandboxId", "RETAIL");
properties.put("UserTokens", new JSONArray(Collections.singleton(xblToken)));
data.put("Properties", properties);
data.put("RelyingParty", "rp://api.minecraftservices.com/");
data.put("TokenType", "JWT");
String req = data.toString();
Log.i("MicroAuth", req);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
setCommonProperties(conn, req);
Log.i("MicroAuth", conn.getRequestMethod());
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes(StandardCharsets.UTF_8));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
String uhs = jo.getJSONObject("DisplayClaims").getJSONArray("xui").getJSONObject(0).getString("uhs");
String token = jo.getString("Token");
conn.disconnect();
Log.i("MicrosoftLogin","Xbl Xsts = " + token + "; Uhs = " + uhs);
return new String[]{uhs, token};
//acquireMinecraftToken(uhs,jo.getString("Token"));
}else if(conn.getResponseCode() == 401) {
String responseContents = Tools.read(conn.getErrorStream());
JSONObject jo = new JSONObject(responseContents);
long xerr = jo.optLong("XErr", -1);
Integer locale_id = XSTS_ERRORS.get(xerr);
if(locale_id != null) {
throw new PresentedException(new RuntimeException(responseContents), locale_id);
}
throw new PresentedException(new RuntimeException(responseContents), R.string.xerr_unknown, xerr);
}else{
throw getResponseThrowable(conn);
}
}
private String acquireMinecraftToken(String xblUhs, String xblXsts) throws IOException, JSONException {
URL url = new URL(mcLoginUrl);
JSONObject data = new JSONObject();
data.put("identityToken", "XBL3.0 x=" + xblUhs + ";" + xblXsts);
String req = data.toString();
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
setCommonProperties(conn, req);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes(StandardCharsets.UTF_8));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
expiresAt = System.currentTimeMillis() + 86400000;
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
conn.disconnect();
Log.i("MicrosoftLogin","MC token: "+jo.getString("access_token"));
mcToken = jo.getString("access_token");
//checkMcProfile(jo.getString("access_token"));
return jo.getString("access_token");
}else{
throw getResponseThrowable(conn);
}
}
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);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + mcAccessToken);
conn.setUseCaches(false);
conn.connect();
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
String s= Tools.read(conn.getInputStream());
conn.disconnect();
Log.i("MicrosoftLogin","profile:" + s);
JSONObject jsonObject = new JSONObject(s);
String name = (String) jsonObject.get("name");
String uuid = (String) jsonObject.get("id");
String uuidDashes = uuid.replaceFirst(
"(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5"
);
doesOwnGame = true;
Log.i("MicrosoftLogin","UserName = " + name);
Log.i("MicrosoftLogin","Uuid Minecraft = " + uuidDashes);
mcName=name;
mcUuid=uuidDashes;
}else{
Log.i("MicrosoftLogin","It seems that this Microsoft Account does not own the game.");
doesOwnGame = false;
throw new PresentedException(new RuntimeException(conn.getResponseMessage()), R.string.minecraft_not_owned);
//throwResponseError(conn);
}
}
/** Wrapper to ease notifying the listener */
private void notifyProgress(@Nullable ProgressListener listener, int step){
if(listener != null){
Tools.runOnUiThread(() -> listener.onLoginProgress(step));
}
ProgressLayout.setProgress(ProgressLayout.AUTHENTICATE_MICROSOFT, step*20);
}
/** Set common properties for the connection. Given that all requests are POST, interactivity is always enabled */
private static void setCommonProperties(HttpURLConnection conn, String formData) {
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("charset", "utf-8");
try {
conn.setRequestProperty("Content-Length", Integer.toString(formData.getBytes(StandardCharsets.UTF_8).length));
conn.setRequestMethod("POST");
}catch (ProtocolException e) {
Log.e("MicrosoftAuth", e.toString());
}
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
}
/**
* @param data A series a strings: key1, value1, key2, value2...
* @return the data converted as a form string for a POST request
*/
private static String convertToFormData(String... data) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
for(int i=0; i<data.length; i+=2){
if (builder.length() > 0) builder.append("&");
builder.append(URLEncoder.encode(data[i], "UTF-8"))
.append("=")
.append(URLEncoder.encode(data[i+1], "UTF-8"));
}
return builder.toString();
}
private RuntimeException getResponseThrowable(HttpURLConnection conn) throws IOException {
Log.i("MicrosoftLogin", "Error code: " + conn.getResponseCode() + ": " + conn.getResponseMessage());
if(conn.getResponseCode() == 429) {
return new PresentedException(R.string.microsoft_login_retry_later);
}
return new RuntimeException(conn.getResponseMessage());
}
}
@@ -1,23 +0,0 @@
package net.kdt.pojavlaunch.authenticator.microsoft;
import android.content.Context;
public class PresentedException extends RuntimeException {
final int localizationStringId;
final Object[] extraArgs;
public PresentedException(int localizationStringId, Object... extraArgs) {
this.localizationStringId = localizationStringId;
this.extraArgs = extraArgs;
}
public PresentedException(Throwable throwable, int localizationStringId, Object... extraArgs) {
super(throwable);
this.localizationStringId = localizationStringId;
this.extraArgs = extraArgs;
}
public String toString(Context context) {
return context.getString(localizationStringId, extraArgs);
}
}
@@ -1,5 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
public interface AlphaSelectionListener {
void onAlphaSelected(int alpha);
}
Loaded 100 of 633 files, more files were not shown because too many files have changed in this diff. Show more