Compare commits

..
Author SHA1 Message Date
khanhduytran0 c8dc36500b Update README.md 2020-04-02 06:07:42 +07:00
khanhduytran0 eefc94f7b8 Update README.md 2020-04-02 05:43:18 +07:00
khanhduytran0 57229ac99b Update README.md 2020-04-02 05:39:07 +07:00
khanhduytran0 c269c4758f Update OptiFine supported 2020-04-01 13:22:18 +07:00
khanhduytran0 ceefb281c6 Added OptiFine table 2020-04-01 13:21:37 +07:00
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
604 changed files with 104 additions and 109237 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
open_collective: pojavlauncher
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: Application exited with code 1'
validations:
required: true
- type: textarea
attributes:
label: The log file and images/videos
description: |
The log file called `latestlog.txt` is located under `Android/data/net.kdt.pojavlaunch/files`, `games/PojavLauncher/` or `games/PojavLauncher/.minecraft`. You may need to activate an option in your file explorer to see hidden files and folders. |
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.
validations:
required: true
- type: textarea
attributes:
label: Steps To Reproduce
description: Steps to reproduce the behavior.
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 the game to launches'
validations:
required: true
- type: textarea
attributes:
label: Platform
description: |
Examples:
- **Device model**: Mi 8 Pro 8/128G
- **CPU architecture**: aarch64
- **Android version**: 10
- **PojavLauncher version**: [Latest Release || version 3.3.1.1_rel_20210206 ]
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: false
- 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: false
- 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
-137
View File
@@ -1,137 +0,0 @@
name: Android CI
on:
pull_request:
branches-ignore:
- 'l10n_v3_openjdk2'
push:
branches-ignore:
- 'l10n_v3_openjdk2'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-20.04
env:
GPLAY_KEYSTORE_PASSWORD: ${{ secrets.GPLAY_KEYSTORE_PASSWORD }}
steps:
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Get gl4es latest commit hash
id: gl4es-sha
run: echo "::set-output name=sha::$(echo $(git ls-remote https://github.com/PojavLauncherTeam/gl4es-114-extra refs/heads/master | grep -io '^\S*'))"
shell: bash
- name: Cache gl4es
uses: actions/cache@v2
id: gl4es-cache
with:
path: gl4es/libs
key: gl4es-holy-android-shared-${{ steps.gl4es-sha.outputs.sha }}
- name: Get gl4es
if: steps.gl4es-cache.outputs.cache-hit != 'true'
uses: actions/checkout@v2
with:
repository: 'PojavLauncherTeam/gl4es-114-extra'
path: 'gl4es'
- name: Build gl4es
if: steps.gl4es-cache.outputs.cache-hit != 'true'
continue-on-error: true
run: |
cd gl4es
git config --global user.email "[email protected]"
git config --global user.name "github-actions"
$ANDROID_NDK_HOME/ndk-build NDK_PROJECT_PATH=. APP_BUILD_SCRIPT=./Android.mk
cp -R libs/* ../app_pojavlauncher/src/main/jniLibs/
- name: Push gl4es
if: github.event != 'pull_request' && steps.gl4es-cache.outputs.cache-hit != 'true'
continue-on-error: true
run: |
git add .
git commit -am "CI: Update gl4es"
git push
- name: Get JRE8
uses: dawidd6/action-download-artifact@v2
with:
github_token: ${{secrets.GITHUB_TOKEN}}
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:
github_token: ${{secrets.GITHUB_TOKEN}}
workflow: build.yml
path: app_pojavlauncher/src/main/assets/components/jre-new
workflow_conclusion: success
repo: PojavLauncherTeam/android-openjdk-build-multiarch
branch: buildjre17
name: jre17-pojav
- name: Build JRE JAR files
run: |
cp -R gl4es/libs/* app_pojavlauncher/src/main/jniLibs/
chmod +x scripts/languagelist_updater.sh
bash scripts/languagelist_updater.sh
mkdir -p out
chmod +x gradlew
./gradlew clean
# Build JRE JAR files (security manager, etc...)
./gradlew :jre_lwjgl3glfw:build
- name: Build Google Play .aab
if: github.repository_owner == 'PojavLauncherTeam' && github.ref_name == 'v3_openjdk'
run: |
./gradlew :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
./gradlew :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
./gradlew assembleDebug
mv app_pojavlauncher/build/outputs/apk/debug/app_pojavlauncher-debug.apk out/app-debug-noruntime.apk
- name: Upload APK
uses: actions/upload-artifact@v2
with:
name: app-debug
path: out/app-debug.apk
- name: Upload onto the Google Play testing track
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@v2
with:
name: app-debug-noruntime
path: out/app-debug-noruntime.apk
-8
View File
@@ -1,8 +0,0 @@
/.gradle
/build
/*/build
app_pojavlauncher/src/main/assets/components/jre
local.properties
.idea/
app_pojavlauncher/.cxx/
.vs/
-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.
-674
View File
@@ -1,674 +0,0 @@
GNU 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.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
PojavLauncher - A Minecraft: Java Edition Launcher for Android and iOS
Copyright (C) 2021 Tran Hoang Khanh Duy and contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
PojavLauncher Copyright (C) 2021 Tran Hoang Khanh Duy
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
-1
View File
@@ -1 +0,0 @@
Данное приложения не отправляет какие либо данные пользователя в сеть "Интернет", и не собирает никакой информации о пользователе при использовании.
+104 -101
View File
@@ -1,108 +1,111 @@
[![Android CI](https://github.com/PojavLauncherTeam/PojavLauncher/workflows/Android%20CI/badge.svg)](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.gg/6RpEJda)
[![Reddit](https://img.shields.io/badge/dynamic/json.svg?label=r/PojavLauncher%20member%20count&query=$.data.subscribers&url=https://www.reddit.com/r/PojavLauncher/about.json)](https://reddit.com/r/PojavLauncher)
[![Google Play](https://gist.githubusercontent.com/meefik/54a54afa7cc1dc600bdb855cb7895a4a/raw/ad617c006a1ac28d067c9a87cec60199ca8fef7c/get-it-on-google-play.png)](https://play.google.com/store/apps/details?id=net.kdt.pojavlaunch)
# PojavLauncher
A Minecraft: Java Edition launcher for Android based from Boardwalk. Support up-to Minecraft 1.12
# PojavLauncher
# Source code
Not yet, this repository currently for bug tracking.
## Note
- We do not exist on TikTok. 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, please report them to Twitter's moderation team.
# 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)
## Navigation
- [Introduction](#introduction)
- [Building](#building)
- [Current status](#current-status)
- [License](#license)
- [Contributing](#contributing)
- [Credits & Third party components and their licenses](#credits--third-party-components-and-their-licenses)
## 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 (from rd-132211 to 1.18 snapshots (kinda)), including Combat Test versions. Modding via Forge (up to 1.16.5) 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).
# Minecraft versions worked in PojavLauncher 2.4.2
## Building
To get started, you can just get prebuilt app from [stable release](https://github.com/PojavLauncherTeam/PojavLauncher/releases) or [automatic builds](https://github.com/PojavLauncherTeam/PojavLauncher/actions). If you want to build after launcher code changes, follow steps below.
<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>
Will be moved to **BUILDING.md**
### Java Runtime Environment (JRE)
- JRE for Android is [here](https://github.com/PojavLauncherTeam/openjdk-multiarch-jdk8u), also the build script [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).
- Either get `jre8-pojav` artifact from auto builds, or do splitting 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>
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 `assets/components/jre/` folder</br>
- (If needed) update the Version file with the current date</br>
### LWJGL
- **Coming soon**
### The Launcher
- Because languages are auto added by Crowdin, so need to run language list generator before building. In this 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 ~~build use Android Studio~~.
```
# Build GLFW stub
./gradlew :jre_lwjgl3glfw:build
# Build the launcher
./gradlew :app_pojavlauncher:assembleDebug
```
(Replace `gradlew` to `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] Mod installer headless
- [x] Mod installer with GUI. Used `Caciocavallo` project for AWT without X11.
- [x] OpenGL in OpenJDK environment
- [x] OpenAL (work on most devices)
- [x] Support Minecraft 1.12.2 and below. Used [lwjglx](https://github.com/PojavLauncherTeam/lwjglx), a LWJGL2 compatibility layer for LWJGL3.
- [x] Support Minecraft 1.13 and above. Used [GLFW stub](https://github.com/PojavLauncherTeam/lwjgl3-glfw-java).
- [x] Game surface zooming.
- [x] New input pipe rewritten to native code to boost performance.
- [ ] More...
## Known Issues
- Minecraft `21w10a` or newer are currently not yet supported due to the new GLSL usage. Fortunately, a workaround is provided and built into the launcher.
- In 1.16 and up, spawn eggs banners are white (you can fix this by switching renderer
to `gl4es 1.1.5`, only works on 1.16 and up, do not use under this version, as the texture
will bug out when hit a mob)
- Controller mods aren't working.
- Random crashes could happen very often on Android 5.x during game load or join 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 GPLv3](https://github.com/khanhduytran0/PojavLauncher/blob/master/LICENSE).
## Contributing
Contributions are welcome! We welcome any type of contribution, not only code.
Any code change should be submitted as a pull request. The description should explain what the code does and give steps to execute it.
## 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).
- [xHook](https://github.com/iqiyi/xHook) (Used for exit code trapping): [MIT and BSD-style licenses](https://github.com/iqiyi/xHook/blob/master/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.
# OptiFine worked in PojavLauncher 2.4.2
|Android version | 9.0 |???|???|Tested in Android 10| ??? |
|-----------------|------|---|---|-----|-----|
|Minecraft version|1.7.10|1.8|1.9| 1.10| 1.11|
|OptiFine |OptiFine 1.7.10 HD U E7|???|???|OptiFine_1.10_HD_U_H5| ??? |
|Status |[Worked](https://youtu.be/In_EPebQG7Q)|???|???|[Worked (manually)](https://youtu.be/TJeJcPFgzcI)|???
-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>
-143
View File
@@ -1,143 +0,0 @@
apply plugin: 'com.android.application'
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()
exec {
try{
commandLine 'git', 'describe', '--tags'
ignoreExitValue true
standardOutput = TAG
}catch(Exception e){}
}
exec{
try{
commandLine 'git', 'branch', '--show-current'
ignoreExitValue true
standardOutput = BRANCH
}catch(Exception e){}
}
if(TAG.toString() == ""){
return ("LOCAL-" + "${getDate()}")
}
return TAG.toString().trim().replace("-g","-") + "-" + BRANCH.toString().trim();
}
android {
compileSdkVersion 31
dexOptions {
javaMaxHeapSize "4g"
}
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 31
versionCode getDateSeconds()
versionName getVersionName()
multiDexEnabled true //important
}
buildTypes {
debug {
applicationIdSuffix '.debug'
minifyEnabled false
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.customDebug
resValue 'string', 'storageProviderAuthorities', 'net.kdt.pojavlaunch.scoped.gamefolder.debug'
}
proguard {
initWith debug
minifyEnabled true
shrinkResources true
}
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'
}
gplay {
initWith release
signingConfig signingConfigs.googlePlayBuild
}
}
externalNativeBuild {
ndkBuild {
path file('src/main/jni/Android.mk')
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
bundle {
language {
enableSplit = false
}
}
buildToolsVersion '30.0.2'
}
dependencies {
implementation 'javax.annotation:javax.annotation-api:1.3.2'
implementation 'commons-codec:commons-codec:1.14'
// implementation 'com.wu-man:android-bsf-api:3.1.3'
implementation 'androidx.preference:preference:1.1.1'
//implementation 'androidx.core:core:1.7.0'
implementation 'androidx.drawerlayout:drawerlayout:1.1.1'
implementation 'androidx.viewpager2:viewpager2:1.0.0'
implementation 'androidx.annotation:annotation:1.3.0'
implementation "androidx.constraintlayout:constraintlayout:2.1.2"
implementation 'com.github.duanhong169:checkerboarddrawable:1.0.2'
// implementation 'com.intuit.sdp:sdp-android:1.0.5'
// implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'org.tukaani:xz:1.8'
implementation 'com.github.PojavLauncherTeam:exp4j:master-SNAPSHOT'
// 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.
-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,109 +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"
package="net.kdt.pojavlaunch">
<uses-feature android:glEsVersion="0x00020000"/>
<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" />
<application
android:allowBackup="true"
android:name=".PojavApplication"
android:theme="@style/AppTheme"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:resizeableActivity="true"
android:hasFragileUserData="true"
android:allowNativeHeapPointerTagging="false">
<meta-data
android:name="android.max_aspect"
android:value="ratio_float"/>
<activity
android:exported="true"
android:launchMode="singleTop"
android:screenOrientation="sensorLandscape"
android:label="@string/app_short_name"
android:name=".PojavLoginActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ImportControlActivity"
android:exported="true"
android:windowSoftInputMode="stateVisible"
android:launchMode="singleInstance"
android:configChanges="keyboard|keyboardHidden"
>
<intent-filter android:scheme="content"
android:label="@string/import_control_label"
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:theme="@style/Theme.AppCompat.DayNight.Dialog"
android:screenOrientation="sensorLandscape"
android:name=".FatalErrorActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"/>
<activity
android:theme="@style/Theme.AppCompat.DayNight.Dialog"
android:screenOrientation="sensorLandscape"
android:name=".ExitActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"/>
<activity
android:screenOrientation="sensorLandscape"
android:name=".PojavLauncherActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"/>
<activity
android:screenOrientation="sensorLandscape"
android:name=".JavaGUILauncherActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"/>
<activity
android:screenOrientation="sensorLandscape"
android:name=".CustomControlsActivity"
android:configChanges="keyboardHidden|orientation|screenSize|keyboard|navigation"/>
<activity
android:screenOrientation="sensorLandscape"
android:name=".authenticator.microsoft.ui.MicrosoftLoginGUIActivity"/>
<activity
android:launchMode="standard"
android:multiprocess="true"
android:screenOrientation="sensorLandscape"
android:name=".MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|keyboard|navigation"/>
<provider
android:name=".scoped.GameFolderProvider"
android:authorities="@string/storageProviderAuthorities"
android:exported="true"
android:grantUriPermissions="true"
android:permission="android.permission.MANAGE_DOCUMENTS"
android:enabled="true">
<intent-filter>
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
</intent-filter>
</provider>
</application>
</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>
Binary file not shown.
@@ -1 +0,0 @@
HEllo People
@@ -1 +0,0 @@
1652206097040
@@ -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,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": "Unknown"
}
},
"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
@@ -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,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,86 +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.ScrollView;
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 mToggleButton;
private ScrollView 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
mToggleButton.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
mToggleButton = findViewById(R.id.content_log_toggle_log);
mToggleButton.setOnCheckedChangeListener(
(compoundButton, isChecked) -> {
mLogTextView.setVisibility(isChecked ? VISIBLE : GONE);
if(!isChecked) mLogTextView.setText("");
});
mToggleButton.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);
// Listen to logs
mLogListener = text -> {
if(mLogTextView.getVisibility() != VISIBLE) return;
post(() -> {
mLogTextView.append(text + '\n');
mScrollView.fullScroll(View.FOCUS_DOWN);
});
};
Logger.getInstance().setLogListener(mLogListener);
}
}
@@ -1,26 +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));
}
}
@@ -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,173 +0,0 @@
package com.kdt.pickafile;
import androidx.appcompat.app.*;
import android.content.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.*;
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 String fullPath;
private ListView mainLv;
private Context context;
//For File selected listener:
private FileSelectedListener listener;
private AlertDialog build;
private String lockPath = "/";
//For filtering by file types:
private final String[] fileSuffixes;
public FileListView(AlertDialog build) {
this(build.getContext(), null, new String[0]);
this.build = build;
}
public FileListView(AlertDialog build, String fileSuffix) {
this(build.getContext(), null, new String[]{fileSuffix});
this.build = build;
}
public FileListView(AlertDialog build, String[] fileSuffixes){
this(build.getContext(), null, fileSuffixes);
this.build = build;
}
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);
}
public void init(final Context context) {
//Main setup:
this.context = context;
LayoutParams layParam = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
setOrientation(VERTICAL);
mainLv = new ListView(context);
mainLv.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> p1, View p2, int p3, long p4)
{
// TODO: Implement this method
File mainFile = new File(p1.getItemAtPosition(p3).toString());
if (p3 == 0 && !lockPath.equals(fullPath)) {
parentDir();
} else {
listFileAt(mainFile.getAbsolutePath());
}
}
});
mainLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> p1, View p2, int p3, long p4)
{
// TODO: Implement this method
File mainFile = new File(p1.getItemAtPosition(p3).toString());
if (mainFile.isFile()) {
listener.onFileLongClick(mainFile, mainFile.getAbsolutePath());
return true;
}
return false;
}
});
addView(mainLv, layParam);
try {
listFileAt(Environment.getExternalStorageDirectory().getAbsolutePath());
} catch (NullPointerException e) {} // Android 10+ disallows access to sdcard
}
public void setFileSelectedListener(FileSelectedListener listener)
{
this.listener = listener;
}
public void listFileAt(final String path)
{
try{
final File mainPath = new File(path);
if(mainPath.exists()){
if(mainPath.isDirectory()){
fullPath = path;
File[] listFile = mainPath.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());
if(fileSuffixes.length > 0){ //Meaning we want only specific files
for(File file : listFile){
if(file.isDirectory()){
if((!file.getName().startsWith(".")) || file.getName().equals(".minecraft"))
fileAdapter.add(file);
continue;
}
for(String suffix : fileSuffixes){
if(file.getName().endsWith("." + suffix)){
fileAdapter.add(file);
break;
}
}
}
}else{ //We get every file
for(File file : listFile){
fileAdapter.add(file);
}
}
}
mainLv.setAdapter(fileAdapter);
if (build != null) build.setTitle(new File(path).getName());
} else {
listener.onFileSelected(mainPath, path);
}
} else {
Toast.makeText(context, "This folder (or file) doesn't exist", Toast.LENGTH_SHORT).show();
refreshPath();
}
} catch (Exception e){
Tools.showError(context, e);
}
}
public String getFullPath(){
return fullPath;
}
public void refreshPath() {
listFileAt(getFullPath());
}
public void parentDir() {
File pathFile = new File(fullPath);
if(!pathFile.getAbsolutePath().equals("/")){
listFileAt(pathFile.getParent());
}
}
public void lockPathAt(String path) {
lockPath = path;
listFileAt(path);
}
}
@@ -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,131 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.*;
import android.graphics.*;
import android.text.*;
import android.util.*;
import android.view.*;
import android.widget.RelativeLayout;
import java.util.*;
import net.kdt.pojavlaunch.utils.*;
import org.lwjgl.glfw.*;
public class AWTCanvasView extends TextureView implements TextureView.SurfaceTextureListener, Runnable {
public static final int AWT_CANVAS_WIDTH = 600;
public static final int AWT_CANVAS_HEIGHT = 420;
private final int MAX_SIZE = 100;
private final double NANOS = 1000000000.0;
private int mWidth, mHeight;
private boolean mIsDestroyed = false;
private final TextPaint mFpsPaint;
private boolean mAttached = false;
private boolean mDrawing;
// 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);
mWidth = w;
mHeight = h;
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);
mWidth = w;
mHeight = h;
}
@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());
try {
while (!mIsDestroyed && surface.isValid()) {
canvas = surface.lockCanvas(null);
canvas.drawRGB(0, 0, 0);
if (!mAttached) {
mAttached = CallbackBridge.nativeAttachThreadToOther(true, BaseMainActivity.isInputStackCall);
} else {
int[] rgbArray = JREUtils.renderAWTScreenFrame(/* canvas, mWidth, mHeight */);
mDrawing = rgbArray != null;
if (rgbArray != null) {
canvas.save();
canvas.drawBitmap(rgbArray, 0, AWT_CANVAS_WIDTH, 0, 0, AWT_CANVAS_WIDTH, AWT_CANVAS_HEIGHT, true, null);
canvas.restore();
}
}
canvas.drawText("FPS: " + (Math.round(fps() * 10) / 10) + ", attached=" + mAttached + ", drawing=" + mDrawing, 0, 20, mFpsPaint);
surface.unlockCanvasAndPost(canvas);
}
} catch (Throwable throwable) {
Tools.showError(getContext(), throwable);
}
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,42 +0,0 @@
package net.kdt.pojavlaunch;
public class AWTInputBridge {
public static final int EVENT_TYPE_CHAR = 1000;
// public static final int EVENT_TYPE_CHAR_MODS = 1001;
// public static final int EVENT_TYPE_CURSOR_ENTER = 1002;
public static final int EVENT_TYPE_CURSOR_POS = 1003;
// public static final int EVENT_TYPE_FRAMEBUFFER_SIZE = 1004;
public static final int EVENT_TYPE_KEY = 1005;
public static final int EVENT_TYPE_MOUSE_BUTTON = 1006;
public static final int EVENT_TYPE_SCROLL = 1007;
// public static final int EVENT_TYPE_WINDOW_SIZE = 1008;
public static void sendKey(char keychar, int keycode) {
// TODO: Android -> AWT keycode mapping
nativeSendData(EVENT_TYPE_KEY, (int) keychar, keycode, 0, 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 nativePutClipboard(String data);
}
@@ -1,912 +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.
*/
public class AWTInputEvent {
// InputEvent
/**
* This flag indicates that the Shift key was down when the event
* occurred.
*/
public static final int SHIFT_MASK = 1 << 0;
/**
* 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 {@link #getButton}.
* @since 1.4
*/
public static final int NOBUTTON = 0;
/**
* Indicates mouse button #1; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON1 = 1;
/**
* Indicates mouse button #2; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON2 = 2;
/**
* Indicates mouse button #3; used by {@link #getButton}.
* @since 1.4
*/
public static final int BUTTON3 = 3;
}
@@ -1,101 +0,0 @@
package net.kdt.pojavlaunch;
import android.os.Build;
import java.util.Locale;
/**
* This class aims at providing a simple and easy way to deal with the device architecture.
*/
public class Architecture {
public static int UNSUPPORTED_ARCH = -1;
public static int ARCH_ARM64 = 0x1;
public static int ARCH_ARM = 0x2;
public static int ARCH_X86 = 0x4;
public static int ARCH_X86_64 = 0x8;
/**
* 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;
}
/**
* Tell is the device is based on an arm processor.
* It doesn't tell if the device is 64 or 32 bits.
* @return Whether or not the device is arm based.
*/
public static boolean isArmDevice(){
return !isx86Device();
}
/**
* 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,34 +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 onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tools.setFullscreen(this);
Tools.updateWindowSize(this);
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleUtils.setLocale(base));
}
@Override
public void startActivity(Intent i) {
super.startActivity(i);
//new Throwable("StartActivity").printStackTrace();
}
@Override
protected void onPostResume() {
super.onPostResume();
Tools.ignoreNotch(PREF_IGNORE_NOTCH,this);
}
}
@@ -1,274 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Tools.ENABLE_DEV_FEATURES;
import static net.kdt.pojavlaunch.Tools.getFileName;
import android.app.*;
import android.content.*;
import android.net.Uri;
import android.view.*;
import android.webkit.MimeTypeMap;
import android.widget.*;
import androidx.annotation.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.Map;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.multirt.MultiRTConfigDialog;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.tasks.*;
import androidx.appcompat.app.AlertDialog;
import net.kdt.pojavlaunch.value.*;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import org.apache.commons.io.IOUtils;
public abstract class BaseLauncherActivity extends BaseActivity {
public Button mPlayButton;
public ProgressBar mLaunchProgress;
public Spinner mVersionSelector;
public MultiRTConfigDialog mRuntimeConfigDialog;
public TextView mLaunchTextStatus;
public JMinecraftVersionList mVersionList;
public MinecraftDownloaderTask mTask;
public MinecraftAccount mProfile;
//public String[] mAvailableVersions;
public boolean mIsAssetsProcessing = false;
protected boolean canBack = false;
public abstract void statusIsLaunching(boolean isLaunching);
/**
* Used by the custom control button from the layout_main_v4
* @param view The view triggering the function
*/
public void launchCustomControlsActivity(View view){
startActivity(new Intent(BaseLauncherActivity.this, CustomControlsActivity.class));
}
/**
* Used by the install button from the layout_main_v4
* @param view The view triggering the function
*/
public void installJarFile(View view){
installMod(false);
}
public static final int RUN_MOD_INSTALLER = 2050;
private void installMod(boolean customJavaArgs) {
if (MultiRTUtils.getExactJreName(8) == null) {
Toast.makeText(this, R.string.multirt_nojava8rt, Toast.LENGTH_LONG).show();
return;
}
if (customJavaArgs) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.alerttitle_installmod);
builder.setNegativeButton(android.R.string.cancel, null);
final AlertDialog dialog;
final EditText edit = new EditText(this);
edit.setSingleLine();
edit.setHint("-jar/-cp /path/to/file.jar ...");
builder.setPositiveButton(android.R.string.ok, (di, i) -> {
Intent intent = new Intent(BaseLauncherActivity.this, JavaGUILauncherActivity.class);
intent.putExtra("skipDetectMod", true);
intent.putExtra("javaArgs", edit.getText().toString());
startActivity(intent);
});
dialog = builder.create();
dialog.setView(edit);
dialog.show();
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jar");
if(mimeType == null) mimeType = "*/*";
intent.setType(mimeType);
startActivityForResult(intent,RUN_MOD_INSTALLER);
}
}
public void launchGame(View v) {
if (!canBack && mIsAssetsProcessing && ENABLE_DEV_FEATURES) {
mIsAssetsProcessing = false;
statusIsLaunching(false);
} else if (canBack) {
v.setEnabled(false);
mTask = new MinecraftDownloaderTask(this);
LauncherProfiles.update();
String selectedProfile = LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,"");
if (LauncherProfiles.mainProfileJson != null && LauncherProfiles.mainProfileJson.profiles != null && LauncherProfiles.mainProfileJson.profiles.containsKey(selectedProfile)) {
MinecraftProfile prof = LauncherProfiles.mainProfileJson.profiles.get(selectedProfile);
if (prof != null && prof.lastVersionId != null) {
if (mProfile.accessToken.equals("0")) {
String versionId = getVersionId(prof.lastVersionId);
File verJsonFile = new File(Tools.DIR_HOME_VERSION,
versionId + "/" + versionId + ".json");
if (verJsonFile.exists()) {
mTask.onPostExecute(null);
return;
}
Tools.dialogOnUiThread(this,
getString(R.string.global_error),
getString(R.string.mcl_launch_error_localmode)
);
}else {
mTask.execute(getVersionId(prof.lastVersionId));
}
}
}
}
}
public static String getVersionId(String input) {
Map<String,String> releaseTable = (Map<String,String>)ExtraCore.getValue(ExtraConstants.RELEASE_TABLE);
if(releaseTable == null || releaseTable.isEmpty()) return input;
if("latest-release".equals(input)) return releaseTable.get("release");
if("latest-snapshot".equals(input)) return releaseTable.get("snapshot");
return input;
}
@Override
public void onBackPressed() {
if (canBack) {
super.onBackPressed();
}
}
@Override
protected void onPostResume() {
super.onPostResume();
System.out.println("call to onPostResume");
Tools.updateWindowSize(this);
System.out.println("call to onPostResume; E");
}
public static void updateVersionSpinner(Context ctx, ArrayList<String> value, Spinner mVersionSelector, String defaultSelection) {
if(value != null && value.size() > 0) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_spinner_item, value);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
mVersionSelector.setAdapter(adapter);
mVersionSelector.setSelection(RefreshVersionListTask.selectAt(value, defaultSelection));
return;
}
mVersionSelector.setSelection(RefreshVersionListTask.selectAt(PojavLauncherActivity.basicVersionList, defaultSelection));
}
@Override
protected void onResume(){
super.onResume();
new RefreshVersionListTask(this).execute();
if(listRefreshListener != null) {
LauncherPreferences.DEFAULT_PREF.unregisterOnSharedPreferenceChangeListener(listRefreshListener);
}
listRefreshListener = (sharedPreferences, key) -> {
if(key.startsWith("vertype_")) {
System.out.println("Verlist update needed!");
LauncherPreferences.PREF_VERTYPE_RELEASE = sharedPreferences.getBoolean("vertype_release",true);
LauncherPreferences.PREF_VERTYPE_SNAPSHOT = sharedPreferences.getBoolean("vertype_snapshot",false);
LauncherPreferences.PREF_VERTYPE_OLDALPHA = sharedPreferences.getBoolean("vertype_oldalpha",false);
LauncherPreferences.PREF_VERTYPE_OLDBETA = sharedPreferences.getBoolean("vertype_oldbeta",false);
new RefreshVersionListTask(this).execute();
}
};
LauncherPreferences.DEFAULT_PREF.registerOnSharedPreferenceChangeListener(listRefreshListener);
System.out.println("call to onResume");
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
System.out.println("call to onResume; E");
}
SharedPreferences.OnSharedPreferenceChangeListener listRefreshListener = null;
SharedPreferences.OnSharedPreferenceChangeListener profileEnableListener = null;
@Override
protected void onResumeFragments() {
super.onResumeFragments();
System.out.println("call to onResumeFragments");
mRuntimeConfigDialog = new MultiRTConfigDialog();
mRuntimeConfigDialog.prepare(this);
((Button)findViewById(R.id.installJarButton)).setOnLongClickListener(view -> {
installMod(true);
return true;
});
//TODO ADD CRASH CHECK AND FOCUS
System.out.println("call to onResumeFragments; E");
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == Activity.RESULT_OK) {
final ProgressDialog barrier = new ProgressDialog(this);
barrier.setMessage(getString(R.string.global_waiting));
barrier.setProgressStyle(barrier.STYLE_SPINNER);
barrier.setCancelable(false);
barrier.show();
// Install the runtime
if (requestCode == MultiRTConfigDialog.MULTIRT_PICK_RUNTIME) {
if (data == null) return;
final Uri uri = data.getData();
Thread t = new Thread(() -> {
try {
String name = getFileName(this, uri);
MultiRTUtils.installRuntimeNamed(getApplicationContext().getApplicationInfo().nativeLibraryDir, getContentResolver().openInputStream(uri), name,
(resid, stuff) -> BaseLauncherActivity.this.runOnUiThread(
() -> barrier.setMessage(BaseLauncherActivity.this.getString(resid, stuff))));
MultiRTUtils.postPrepare(BaseLauncherActivity.this, name);
} catch (IOException e) {
Tools.showError(BaseLauncherActivity.this, e);
}
BaseLauncherActivity.this.runOnUiThread(() -> {
barrier.dismiss();
mRuntimeConfigDialog.refresh();
mRuntimeConfigDialog.mDialog.show();
});
});
t.start();
}
// Run a mod installer
if (requestCode == RUN_MOD_INSTALLER) {
if (data == null) return;
final Uri uri = data.getData();
barrier.setMessage(BaseLauncherActivity.this.getString(R.string.multirt_progress_caching));
Thread t = new Thread(()->{
try {
final String name = getFileName(this, uri);
final File modInstallerFile = new File(getCacheDir(), name);
FileOutputStream fos = new FileOutputStream(modInstallerFile);
IOUtils.copy(getContentResolver().openInputStream(uri), fos);
fos.close();
BaseLauncherActivity.this.runOnUiThread(() -> {
barrier.dismiss();
Intent intent = new Intent(BaseLauncherActivity.this, JavaGUILauncherActivity.class);
intent.putExtra("modFile", modInstallerFile);
startActivity(intent);
});
}catch(IOException e) {
Tools.showError(BaseLauncherActivity.this,e);
}
});
t.start();
}
}
}
protected abstract void initTabs(int pageIndex);
}
@@ -1,421 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Architecture.ARCH_X86;
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_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.*;
import android.content.*;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.drawerlayout.widget.*;
import com.kdt.LoggerView;
import java.io.*;
import java.util.*;
import net.kdt.pojavlaunch.customcontrols.*;
import net.kdt.pojavlaunch.customcontrols.keyboard.LwjglCharSender;
import net.kdt.pojavlaunch.customcontrols.keyboard.TouchCharInput;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.utils.*;
import net.kdt.pojavlaunch.value.*;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import org.lwjgl.glfw.*;
public class BaseMainActivity extends BaseActivity {
public static volatile ClipboardManager GLOBAL_CLIPBOARD;
public static TouchCharInput touchCharInput;
volatile public static boolean isInputStackCall;
public float scaleFactor = 1;
private boolean mIsResuming = false;
ControlLayout mControlLayout;
private MinecraftGLSurface minecraftGLView;
private static Touchpad touchpad;
private LoggerView loggerView;
MinecraftAccount mProfile;
MinecraftProfile minecraftProfile;
private DrawerLayout drawerLayout;
private ListView navDrawer;
private ArrayAdapter<String> gameActionArrayAdapter;
private AdapterView.OnItemClickListener gameActionClickListener;
public ArrayAdapter<String> ingameControlsEditorArrayAdapter;
public AdapterView.OnItemClickListener ingameControlsEditorListener;
//public NavigationView.OnNavigationItemSelectedListener ingameControlsEditorListener;
protected volatile JMinecraftVersionList.Version mVersionInfo;
//private PerVersionConfig.VersionConfig config;
protected void initLayout(int resId) {
setContentView(resId);
try {
Logger.getInstance().reset();
// FIXME: is it safe fot multi thread?
GLOBAL_CLIPBOARD = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
touchCharInput = findViewById(R.id.mainTouchCharInput);
touchCharInput.setCharacterSender(new LwjglCharSender());
loggerView = findViewById(R.id.mainLoggerView);
mControlLayout = findViewById(R.id.main_control_layout);
mProfile = PojavProfile.getCurrentProfileContent(this);
LauncherProfiles.update();
minecraftProfile = LauncherProfiles.mainProfileJson.profiles.get(LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,""));
if(minecraftProfile == null) {
Toast.makeText(this,"Attempted to launch nonexistent profile",Toast.LENGTH_SHORT).show();
finish();
return;
}
String runtime = LauncherPreferences.PREF_DEFAULT_RUNTIME;
mVersionInfo = Tools.getVersionInfo(null, BaseLauncherActivity.getVersionId(
minecraftProfile.lastVersionId));
if(minecraftProfile.javaDir != null && minecraftProfile.javaDir.startsWith(Tools.LAUNCHERPROFILES_RTPREFIX)) {
String runtimeName = minecraftProfile.javaDir.substring(Tools.LAUNCHERPROFILES_RTPREFIX.length());
if(MultiRTUtils.forceReread(runtimeName).versionString != null) {
runtime = runtimeName;
}
}
if(minecraftProfile.pojavRendererName != null) {
Log.i("RdrDebug","__P_renderer="+minecraftProfile.pojavRendererName);
Tools.LOCAL_RENDERER = minecraftProfile.pojavRendererName;
}
setTitle("Minecraft " + minecraftProfile.lastVersionId);
MultiRTUtils.setRuntimeNamed(this,runtime);
// Minecraft 1.13+
isInputStackCall = mVersionInfo.arguments != null;
Tools.getDisplayMetrics(this);
windowWidth = Tools.getDisplayFriendlyRes(currentDisplayMetrics.widthPixels, scaleFactor);
windowHeight = Tools.getDisplayFriendlyRes(currentDisplayMetrics.heightPixels, scaleFactor);
System.out.println("WidthHeight: " + windowWidth + ":" + windowHeight);
// Menu
drawerLayout = findViewById(R.id.main_drawer_options);
navDrawer = findViewById(R.id.main_navigation_view);
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:
dialogForceClose(BaseMainActivity.this);
break;
case 1:
openLogOutput();
break;
case 2:
minecraftGLView.togglepointerDebugging();
break;
case 3:
dialogSendCustomKey();
break;
case 4:
adjustMouseSpeedLive();
break;
case 5:
openCustomControls();
}
drawerLayout.closeDrawers();
};
navDrawer.setAdapter(gameActionArrayAdapter);
navDrawer.setOnItemClickListener(gameActionClickListener);
touchpad = findViewById(R.id.main_touchpad);
this.minecraftGLView = findViewById(R.id.main_game_render_view);
this.drawerLayout.closeDrawers();
minecraftGLView.setSurfaceReadyListener(() -> {
try {
// Setup virtual mouse right before launching
if (PREF_VIRTUAL_MOUSE_START)
touchpad.switchState();
runCraft();
}catch (Throwable e){
Tools.showError(getApplicationContext(), e, true);
}
});
minecraftGLView.start();
} catch (Throwable e) {
Tools.showError(this, e, true);
}
}
@Override
public void onResume() {
super.onResume();
mIsResuming = true;
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 1);
}
@Override
protected void onPause() {
if (CallbackBridge.isGrabbing()){
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_ESCAPE);
}
CallbackBridge.nativeSetWindowAttrib(LwjglGlfwKeycode.GLFW_HOVERED, 0);
mIsResuming = false;
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
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Tools.updateWindowSize(this);
minecraftGLView.refreshSize();
runOnUiThread(() -> mControlLayout.refreshControlButtonPositions());
}
@Override
protected void onPostResume() {
super.onPostResume();
if(minecraftGLView != null) // Useful when backing out of the app
new Handler(Looper.getMainLooper()).postDelayed(() -> minecraftGLView.refreshSize(), 500);
}
public static void fullyExit() {
android.os.Process.killProcess(android.os.Process.myPid());
}
public static boolean isAndroid8OrHigher() {
return Build.VERSION.SDK_INT >= 26;
}
private void runCraft() throws Throwable {
if(Tools.LOCAL_RENDERER == null) {
Tools.LOCAL_RENDERER = LauncherPreferences.PREF_RENDERER;
}
Logger.getInstance().appendToLog("--------- beggining with launcher debug");
Logger.getInstance().appendToLog("Info: Launcher version: " + BuildConfig.VERSION_NAME);
if (Tools.LOCAL_RENDERER.equals("vulkan_zink")) {
checkVulkanZinkIsSupported();
}
checkLWJGL3Installed();
JREUtils.jreReleaseList = JREUtils.readJREReleaseProperties();
Logger.getInstance().appendToLog("Architecture: " + Architecture.archAsString(Tools.DEVICE_ARCHITECTURE));
checkJavaArgsIsLaunchable(JREUtils.jreReleaseList.get("JAVA_VERSION"));
// appendlnToLog("Info: Custom Java arguments: \"" + LauncherPreferences.PREF_CUSTOM_JAVA_ARGS + "\"");
Logger.getInstance().appendToLog("Info: Selected Minecraft version: " + mVersionInfo.id +
((mVersionInfo.inheritsFrom == null || mVersionInfo.inheritsFrom.equals(mVersionInfo.id)) ?
"" : " (" + mVersionInfo.inheritsFrom + ")"));
JREUtils.redirectAndPrintJRELog();
LauncherProfiles.update();
Tools.launchMinecraft(this, mProfile, BaseLauncherActivity.getVersionId(
minecraftProfile.lastVersionId));
}
private void checkJavaArgsIsLaunchable(String jreVersion) throws Throwable {
Logger.getInstance().appendToLog("Info: Custom Java arguments: \"" + LauncherPreferences.PREF_CUSTOM_JAVA_ARGS + "\"");
}
private void checkLWJGL3Installed() {
File lwjgl3dir = new File(Tools.DIR_GAME_HOME, "lwjgl3");
if (!lwjgl3dir.exists() || lwjgl3dir.isFile() || lwjgl3dir.list().length == 0) {
Logger.getInstance().appendToLog("Error: LWJGL3 was not installed!");
throw new RuntimeException(getString(R.string.mcn_check_fail_lwjgl));
} else {
Logger.getInstance().appendToLog("Info: LWJGL3 directory: " + Arrays.toString(lwjgl3dir.list()));
}
}
private void checkVulkanZinkIsSupported() {
if (Tools.DEVICE_ARCHITECTURE == ARCH_X86
|| Build.VERSION.SDK_INT < 25
|| !getPackageManager().hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_LEVEL)
|| !getPackageManager().hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION)) {
Logger.getInstance().appendToLog("Error: Vulkan Zink renderer is not supported!");
throw new RuntimeException(getString(R.string. mcn_check_fail_vulkan_support));
}
}
public void printStream(InputStream stream) {
try {
BufferedReader buffStream = new BufferedReader(new InputStreamReader(stream));
String line = null;
while ((line = buffStream.readLine()) != null) {
Logger.getInstance().appendToLog(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String fromArray(List<String> arr) {
StringBuilder s = new StringBuilder();
for (String exec : arr) {
s.append(" ").append(exec);
}
return s.toString();
}
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;
((MainActivity)this).mControlLayout.setModifiable(true);
navDrawer.setAdapter(ingameControlsEditorArrayAdapter);
navDrawer.setOnItemClickListener(ingameControlsEditorListener);
isInEditor = true;
}
public void leaveCustomControls() {
if(this instanceof MainActivity) {
try {
MainActivity.mControlLayout.hideAllHandleViews();
MainActivity.mControlLayout.loadLayout((CustomControls)null);
MainActivity.mControlLayout.setModifiable(false);
System.gc();
MainActivity.mControlLayout.loadLayout(LauncherPreferences.DEFAULT_PREF.getString("defaultCtrl",Tools.CTRLDEF_FILE));
} catch (IOException e) {
Tools.showError(this,e);
}
//((MainActivity) this).mControlLayout.loadLayout((CustomControls)null);
}
navDrawer.setAdapter(gameActionArrayAdapter);
navDrawer.setOnItemClickListener(gameActionClickListener);
isInEditor = false;
}
private void openLogOutput() {
loggerView.setVisibility(View.VISIBLE);
mIsResuming = false;
}
public void closeLogOutput(View view) {
loggerView.setVisibility(View.GONE);
mIsResuming = true;
}
public void toggleMenu(View v) {
drawerLayout.openDrawer(Gravity.RIGHT);
}
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();
}
public static void dialogForceClose(Context ctx) {
new AlertDialog.Builder(ctx)
.setMessage(R.string.mcn_exit_confirm)
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok, (p1, p2) -> {
try {
fullyExit();
} catch (Throwable th) {
Log.w(Tools.APP_NAME, "Could not enable System.exit() method!", th);
}
}).show();
}
@Override
public boolean dispatchKeyEvent(KeyEvent 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 super.dispatchKeyEvent(event);
}
public static void switchKeyboardState() {
if(touchCharInput != null) touchCharInput.switchKeyboardState();
}
int tmpMouseSpeed;
public void adjustMouseSpeedLive() {
AlertDialog.Builder b = new AlertDialog.Builder(this);
b.setTitle(R.string.mcl_setting_title_mousespeed);
View v = LayoutInflater.from(this).inflate(R.layout.dialog_live_mouse_speed_editor,null);
final SeekBar sb = v.findViewById(R.id.mouseSpeed);
final TextView tv = v.findViewById(R.id.mouseSpeedTV);
sb.setMax(275);
tmpMouseSpeed = (int) ((LauncherPreferences.PREF_MOUSESPEED*100));
sb.setProgress(tmpMouseSpeed-25);
tv.setText(tmpMouseSpeed +" %");
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
tmpMouseSpeed = i+25;
tv.setText(tmpMouseSpeed +" %");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
b.setView(v);
b.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> {
LauncherPreferences.PREF_MOUSESPEED = ((float)tmpMouseSpeed)/100f;
LauncherPreferences.DEFAULT_PREF.edit().putInt("mousespeed",tmpMouseSpeed).commit();
dialogInterface.dismiss();
System.gc();
});
b.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> {
dialogInterface.dismiss();
System.gc();
});
b.show();
}
}
@@ -1,236 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.*;
import android.os.*;
import androidx.appcompat.app.*;
import android.widget.*;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.gson.JsonSyntaxException;
import com.kdt.pickafile.*;
import java.io.*;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.customcontrols.*;
public class CustomControlsActivity extends BaseActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerNavigationView;
private ControlLayout mControlLayout;
public boolean isModified = false;
private static String sSelectedName = "new_control";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean("fromMainActivity", false)) {
// TODO translucent!
// setTheme(androidx.appcompat.R.style.Theme_AppCompat_Translucent);
}
setContentView(R.layout.activity_custom_controls);
mControlLayout = (ControlLayout) findViewById(R.id.customctrl_controllayout);
mDrawerLayout = (DrawerLayout) findViewById(R.id.customctrl_drawerlayout);
mDrawerNavigationView = (ListView) findViewById(R.id.customctrl_navigation_view);
mDrawerNavigationView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.menu_customcontrol)));
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:
load(mControlLayout);
break;
case 3:
save(false, mControlLayout);
break;
case 4:
dialogSelectDefaultCtrl(mControlLayout);
break;
}
mDrawerLayout.closeDrawers();
});
/*mDrawerNavigationView.setNavigationItemSelectedListener(
menuItem -> {
switch (menuItem.getItemId()) {
case R.id.menu_ctrl_load:
load(mControlLayout);
break;
case R.id.menu_ctrl_add:
mControlLayout.addControlButton(new ControlData("New"));
break;
case R.id.menu_ctrl_add_drawer:
mControlLayout.addDrawer(new ControlDrawerData());
break;
case R.id.menu_ctrl_selectdefault:
dialogSelectDefaultCtrl(mControlLayout);
break;
case R.id.menu_ctrl_save:
save(false, mControlLayout);
break;
}
//Toast.makeText(MainActivity.this, menuItem.getTitle() + ":" + menuItem.getItemId(), Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawers();
return true;
});
*/
mControlLayout.setActivity(this);
mControlLayout.setModifiable(true);
loadControl(LauncherPreferences.PREF_DEFAULTCTRL_PATH, mControlLayout);
}
@Override
public void onBackPressed() {
if (!isModified) {
setResult(Activity.RESULT_OK, new Intent());
super.onBackPressed();
return;
}
save(true, mControlLayout);
}
public static void dialogSelectDefaultCtrl(final ControlLayout layout) {
AlertDialog.Builder builder = new AlertDialog.Builder(layout.getContext());
builder.setTitle(R.string.customctrl_selectdefault);
builder.setPositiveButton(android.R.string.cancel, null);
final AlertDialog dialog = builder.create();
FileListView flv = new FileListView(dialog, "json");
flv.lockPathAt(Tools.CTRLMAP_PATH);
flv.setFileSelectedListener(new FileSelectedListener(){
@Override
public void onFileSelected(File file, String path) {
setDefaultControlJson(path,layout);
dialog.dismiss();
}
});
dialog.setView(flv);
dialog.show();
}
public static void save(final boolean exit, final ControlLayout layout) {
final Context ctx = layout.getContext();
final EditText edit = new EditText(ctx);
edit.setSingleLine();
edit.setText(sSelectedName);
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle(R.string.global_save);
builder.setView(edit);
builder.setPositiveButton(android.R.string.ok, null);
builder.setNegativeButton(android.R.string.cancel, null);
if (exit) {
builder.setNeutralButton(R.string.mcn_exit_call, new AlertDialog.OnClickListener(){
@Override
public void onClick(DialogInterface p1, int p2) {
layout.setModifiable(false);
if(ctx instanceof MainActivity) {
((MainActivity) ctx).leaveCustomControls();
}else{
((CustomControlsActivity) ctx).isModified = false;
((Activity)ctx).onBackPressed();
}
// setResult(Activity.RESULT_OK, new Intent());
// CustomControlsActivity.super.onBackPressed();
}
});
}
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(dialogInterface -> {
Button button = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
if (edit.getText().toString().isEmpty()) {
edit.setError(ctx.getResources().getString(R.string.global_error_field_empty));
return;
}
try {
String jsonPath = doSaveCtrl(edit.getText().toString(),layout);
Toast.makeText(ctx, ctx.getString(R.string.global_save) + ": " + jsonPath, Toast.LENGTH_SHORT).show();
dialog.dismiss();
if (!exit) return;
if(ctx instanceof MainActivity) {
((MainActivity) ctx).leaveCustomControls();
}else{
((Activity)ctx).onBackPressed();
}
} catch (Throwable th) {
Tools.showError(ctx, th, exit);
}
});
});
dialog.show();
}
public static void load(final ControlLayout layout) {
AlertDialog.Builder builder = new AlertDialog.Builder(layout.getContext());
builder.setTitle(R.string.global_load);
builder.setPositiveButton(android.R.string.cancel, null);
final AlertDialog dialog = builder.create();
FileListView flv = new FileListView(dialog, "json");
if(Build.VERSION.SDK_INT < 29)flv.listFileAt(Tools.CTRLMAP_PATH);
else flv.lockPathAt(Tools.CTRLMAP_PATH);
flv.setFileSelectedListener(new FileSelectedListener(){
@Override
public void onFileSelected(File file, String path) {
loadControl(path,layout);
dialog.dismiss();
}
});
dialog.setView(flv);
dialog.show();
}
private static void setDefaultControlJson(String path,ControlLayout ctrlLayout) {
// Load before save to make sure control is not error
try {
ctrlLayout.loadLayout(Tools.GLOBAL_GSON.fromJson(Tools.read(path), CustomControls.class));
LauncherPreferences.DEFAULT_PREF.edit().putString("defaultCtrl", path).apply();
LauncherPreferences.PREF_DEFAULTCTRL_PATH = path;
} catch (IOException| JsonSyntaxException exception) {
Tools.showError(ctrlLayout.getContext(), exception);
}
}
private static String doSaveCtrl(String name, final ControlLayout layout) throws Exception {
String jsonPath = Tools.CTRLMAP_PATH + "/" + name + ".json";
layout.saveLayout(jsonPath);
return jsonPath;
}
private static void loadControl(String path,ControlLayout layout) {
try {
layout.loadLayout(path);
sSelectedName = new File(path).getName();
// Remove `.json`
sSelectedName = sSelectedName.substring(0, sSelectedName.length() - 5);
} catch (Exception e) {
Tools.showError(layout.getContext(), e);
}
}
}
@@ -1,38 +0,0 @@
package net.kdt.pojavlaunch;
import java.util.*;
public class DisplayableLocale {
public final Locale mLocale;
public final CharSequence mName;
private static Locale processStringLocale(String locale) {
if (locale.contains("-")) {
String[] split = locale.split("-");
return new Locale(split[0], split[1]);
} else {
return new Locale(locale);
}
}
public DisplayableLocale(String locale) {
this(processStringLocale(locale));
}
public DisplayableLocale(Locale locale) {
this(locale, locale.getDisplayName(locale));
}
public DisplayableLocale(Locale locale, CharSequence name) {
mLocale = locale;
mName = name;
}
public Locale toLocale() {
return mLocale;
}
@Override
public String toString() {
return mName.toString();
}
}
@@ -1,227 +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 = 103;
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_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_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_0);
add(KeyEvent.KEYCODE_NUMPAD_1, LwjglGlfwKeycode.GLFW_KEY_1);
add(KeyEvent.KEYCODE_NUMPAD_2, LwjglGlfwKeycode.GLFW_KEY_2);
add(KeyEvent.KEYCODE_NUMPAD_3, LwjglGlfwKeycode.GLFW_KEY_3);
add(KeyEvent.KEYCODE_NUMPAD_4, LwjglGlfwKeycode.GLFW_KEY_4);
add(KeyEvent.KEYCODE_NUMPAD_5, LwjglGlfwKeycode.GLFW_KEY_5);
add(KeyEvent.KEYCODE_NUMPAD_6, LwjglGlfwKeycode.GLFW_KEY_6);
add(KeyEvent.KEYCODE_NUMPAD_7, LwjglGlfwKeycode.GLFW_KEY_7);
add(KeyEvent.KEYCODE_NUMPAD_8, LwjglGlfwKeycode.GLFW_KEY_8);
add(KeyEvent.KEYCODE_NUMPAD_9, LwjglGlfwKeycode.GLFW_KEY_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_PERIOD);
add(KeyEvent.KEYCODE_NUMPAD_COMMA, LwjglGlfwKeycode.GLFW_KEY_COMMA);
add(KeyEvent.KEYCODE_NUMPAD_ENTER, LwjglGlfwKeycode.GLFW_KEY_ENTER);
add(KeyEvent.KEYCODE_NUMPAD_EQUALS, LwjglGlfwKeycode.GLFW_KEY_EQUAL); //161
}
public static boolean containsKey(int keycode){
return getIndexByKey(keycode) >= 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) {
execKey(keyEvent, getIndexByKey(keyEvent.getKeyCode()));
}
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 int getValueByIndex(int index) {
return sLwjglKeycodes[index];
}
public static int getIndexByKey(int key){
return Arrays.binarySearch(sAndroidKeycodes, key);
}
public static short getValue(int key){
return sLwjglKeycodes[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,40 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.Context;
import android.content.DialogInterface;
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 {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int code = -1;
Bundle extras = getIntent().getExtras();
if(extras != null) {
code = extras.getInt("code",-1);
}
new AlertDialog.Builder(this)
.setMessage(getString(R.string.mcn_exit_title,code))
.setPositiveButton(android.R.string.ok, null)
.setOnDismissListener(dialog -> ExitActivity.this.finish())
.show();
}
public static void showExitMessage(Context ctx, int code) {
Intent i = new Intent(ctx,ExitActivity.class);
i.putExtra("code",code);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
}
}
@@ -1,47 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.*;
import android.os.*;
import androidx.appcompat.app.*;
import android.util.*;
import androidx.appcompat.app.AlertDialog;
public class FatalErrorActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
boolean storageAllow = extras.getBoolean("storageAllow");
final String stackTrace = Log.getStackTraceString((Throwable) extras.getSerializable("throwable"));
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, PojavLoginActivity.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 ferrorIntent = new Intent(ctx, FatalErrorActivity.class);
ferrorIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
ferrorIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ferrorIntent.putExtra("throwable", th);
ferrorIntent.putExtra("savePath", savePath);
ferrorIntent.putExtra("storageAllow", storageAllow);
ctx.startActivity(ferrorIntent);
}
}
@@ -1,202 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.OpenableColumns;
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.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.
*/
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();
mEditText.setText(getNameFromURI(mUriData));
mHasIntentChanged = false;
//Import and verify thread
//Kill the app if the file isn't valid.
new Thread(() -> {
importControlFile("TMP_IMPORT_FILE");
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
new Handler(Looper.getMainLooper()).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.
* @param fileName The file name to use.
* @return whether the file was successfully imported
*/
private boolean importControlFile(String fileName){
InputStream is;
try {
is = getContentResolver().openInputStream(mUriData);
OutputStream os = new FileOutputStream(Tools.CTRLMAP_PATH + "/" + fileName + ".json");
byte[] buffer = new byte[1024];
while(is.read(buffer) != -1)
os.write(buffer);
os.close();
is.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 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;
if (FileUtils.exists(Tools.CTRLMAP_PATH + "/" + fileName + ".json")) return false;
return true;
}
/**
* 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;
}
}
public String getNameFromURI(Uri uri) {
Cursor c = getContentResolver().query(uri, null, null, null, null);
c.moveToFirst();
String fileName = c.getString(c.getColumnIndex(OpenableColumns.DISPLAY_NAME));
c.close();
return trimFileName(fileName);
}
}
@@ -1,7 +0,0 @@
package net.kdt.pojavlaunch;
public class JAssetInfo
{
public String hash;
public int size;
}
@@ -1,11 +0,0 @@
package net.kdt.pojavlaunch;
import com.google.gson.annotations.SerializedName;
import java.util.Map;
public class JAssets {
@SerializedName("map_to_resources") public boolean mapToResources;
public Map<String, JAssetInfo> objects;
}
@@ -1,90 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
import java.util.*;
import net.kdt.pojavlaunch.value.*;
@Keep
public class JMinecraftVersionList {
public static final String TYPE_OLD_ALPHA = "old_alpha";
public static final String TYPE_OLD_BETA = "old_beta";
public static final String TYPE_RELEASE = "release";
public static final String TYPE_SNAPSHOT = "snapshot";
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 DependentLibrary optifineLib;
public String releaseTime;
public String time;
public String type;
}
@Keep
public static class JavaVersionInfo {
public String component;
public int majorVersion;
}
@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;
public static class ArgOS {
public String name;
public String version;
}
}
}
}
@Keep
public static class AssetIndex extends FileProperties {
public long totalSize;
}
}
@@ -1,49 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Architecture.archAsString;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.multirt.Runtime;
import java.io.IOException;
public class JRE17Util {
public static final String NEW_JRE_NAME = "Internal-17";
public static boolean checkInternalNewJre(Context context, MultiRTUtils.RuntimeProgressReporter reporter) {
AssetManager assetManager = context.getAssets();
String launcher_jre17_version;
String installed_jre17_version = MultiRTUtils.__internal__readBinpackVersion(NEW_JRE_NAME);
try {
launcher_jre17_version = Tools.read(assetManager.open("components/jre-new/version"));
}catch (IOException exc) {
//we don't have a runtime included!
return installed_jre17_version != null; //if we have one installed -> return true -> proceed (no updates but the current one should be functional)
//if we don't -> return false -> Cannot find compatible Java runtime
}
if(!launcher_jre17_version.equals(installed_jre17_version)) // this implicitly checks for null, so it will unpack the runtime even if we don't have one installed
return unpackJre17(context, assetManager, launcher_jre17_version, reporter);
else return true;
}
private static boolean unpackJre17(Context context, AssetManager assetManager, String rt_version, MultiRTUtils.RuntimeProgressReporter feedback) {
try {
MultiRTUtils.installRuntimeNamedBinpack(context.getApplicationInfo().nativeLibraryDir,
assetManager.open("components/jre-new/universal.tar.xz"),
assetManager.open("components/jre-new/bin-" + archAsString(Tools.DEVICE_ARCHITECTURE) + ".tar.xz"),
"Internal-17", rt_version, feedback);
MultiRTUtils.postPrepare(context,"Internal-17");
return true;
}catch (IOException e) {
Log.e("JRE17Auto", "Internal JRE unpack failed", e);
return false;
}
}
public static boolean isInternalNewJRE(String s_runtime) {
Runtime runtime = MultiRTUtils.read(s_runtime);
if(runtime == null) return false;
return NEW_JRE_NAME.equals(runtime.name);
}
}
@@ -1,285 +0,0 @@
package net.kdt.pojavlaunch;
import android.annotation.SuppressLint;
import android.os.*;
import android.util.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.util.*;
import net.kdt.pojavlaunch.customcontrols.keyboard.AwtCharSender;
import net.kdt.pojavlaunch.customcontrols.keyboard.TouchCharInput;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.utils.*;
import org.lwjgl.glfw.*;
import com.kdt.LoggerView;
public class JavaGUILauncherActivity extends BaseActivity implements View.OnTouchListener {
private static final int MSG_LEFT_MOUSE_BUTTON_CHECK = 1028;
private AWTCanvasView mTextureView;
private LoggerView mLoggerView;
private TouchCharInput mTouchCharInput;
private LinearLayout mTouchPad;
private ImageView mMousePointerImageView;
private GestureDetector mGestureDetector;
private boolean mSkipDetectMod, mIsVirtualMouseEnabled;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_java_gui_launcher);
Logger.getInstance().reset();
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);
mMousePointerImageView.post(() -> {
ViewGroup.LayoutParams params = mMousePointerImageView.getLayoutParams();
params.width = (int) (36 / 100f * LauncherPreferences.PREF_MOUSESCALE);
params.height = (int) (54 / 100f * 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);
}
}
// debugText.setText(CallbackBridge.DEBUG_STRING.toString());
CallbackBridge.DEBUG_STRING.setLength(0);
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 {
JREUtils.jreReleaseList = JREUtils.readJREReleaseProperties(LauncherPreferences.PREF_DEFAULT_RUNTIME);
if (JREUtils.jreReleaseList.get("JAVA_VERSION").equals("1.8.0")) {
MultiRTUtils.setRuntimeNamed(this,LauncherPreferences.PREF_DEFAULT_RUNTIME);
} else {
MultiRTUtils.setRuntimeNamed(this,MultiRTUtils.getExactJreName(8));
JREUtils.jreReleaseList = JREUtils.readJREReleaseProperties();
}
placeMouseAt(CallbackBridge.physicalWidth / 2, CallbackBridge.physicalHeight / 2);
final File modFile = (File) getIntent().getExtras().getSerializable("modFile");
final String javaArgs = getIntent().getExtras().getString("javaArgs");
mSkipDetectMod = getIntent().getExtras().getBoolean("skipDetectMod", false);
if (mSkipDetectMod) {
new Thread(() -> launchJavaRuntime(modFile, javaArgs), "JREMainThread").start();
return;
}
// No skip detection
openLogOutput(null);
new Thread(() -> {
try {
final int exit = doCustomInstall(modFile, javaArgs);
Logger.getInstance().appendToLog(getString(R.string.toast_optifine_success));
if (exit != 0) return;
runOnUiThread(() -> {
Toast.makeText(JavaGUILauncherActivity.this, R.string.toast_optifine_success, Toast.LENGTH_SHORT).show();
MainActivity.fullyExit();
});
} catch (Throwable e) {
Logger.getInstance().appendToLog("Install failed:");
Logger.getInstance().appendToLog(Log.getStackTraceString(e));
Tools.showError(JavaGUILauncherActivity.this, e);
}
}, "Installer").start();
} catch (Throwable th) {
Tools.showError(this, th, true);
}
}
@Override
public void onResume() {
super.onResume();
final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
final View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(uiOptions);
}
@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;
}
return true;
}
public void placeMouseAdd(float x, float y) {
mMousePointerImageView.setX(mMousePointerImageView.getX() + x);
mMousePointerImageView.setY(mMousePointerImageView.getY() + y);
}
public void placeMouseAt(float x, float y) {
mMousePointerImageView.setX(x);
mMousePointerImageView.setY(y);
}
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) {
BaseMainActivity.dialogForceClose(this);
}
public void openLogOutput(View v) {
mLoggerView.setVisibility(View.VISIBLE);
}
public void closeLogOutput(View view) {
if (mSkipDetectMod) {
mLoggerView.setVisibility(View.GONE);
} else {
forceClose(null);
}
}
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 int launchJavaRuntime(File modFile, String javaArgs) {
JREUtils.redirectAndPrintJRELog();
try {
List<String> javaArgList = new ArrayList<String>();
// Enable Caciocavallo
Tools.getCacioJavaArgs(javaArgList,false);
if (javaArgs != null) {
javaArgList.addAll(Arrays.asList(javaArgs.split(" ")));
} else {
javaArgList.add("-jar");
javaArgList.add(modFile.getAbsolutePath());
}
Logger.getInstance().appendToLog("Info: Java arguments: " + Arrays.toString(javaArgList.toArray(new String[0])));
// Run java on sandbox, non-overrideable.
Collections.reverse(javaArgList);
javaArgList.add("-Xbootclasspath/a:" + Tools.DIR_DATA + "/pro-grade.jar");
javaArgList.add("-Djava.security.manager=net.sourceforge.prograde.sm.ProGradeJSM");
javaArgList.add("-Djava.security.policy=" + Tools.DIR_DATA + "/java_sandbox.policy");
Collections.reverse(javaArgList);
return JREUtils.launchJavaVM(this, javaArgList);
} catch (Throwable th) {
Tools.showError(this, th, true);
return -1;
}
}
private int doCustomInstall(File modFile, String javaArgs) throws IOException {
mSkipDetectMod = true;
return launchJavaRuntime(modFile, javaArgs);
}
public void toggleKeyboard(View view) {
mTouchCharInput.switchKeyboardState();
}
}
@@ -1,107 +0,0 @@
package net.kdt.pojavlaunch;
import androidx.annotation.Keep;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
/** 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 {
private static Logger sLoggerSingleton = null;
/* Instance variables */
private final File mLogFile;
private PrintStream mLogStream;
private WeakReference<eventLogListener> mLogListenerWeakReference = null;
/* No public construction */
private Logger(){
this("latestlog.txt");
}
private Logger(String fileName){
mLogFile = new File(Tools.DIR_GAME_HOME, fileName);
// Make a new instance of the log file
mLogFile.delete();
try {
mLogFile.createNewFile();
mLogStream = new PrintStream(mLogFile.getAbsolutePath());
}catch (IOException e){e.printStackTrace();}
}
public static Logger getInstance(){
if(sLoggerSingleton == null){
synchronized(Logger.class){
if(sLoggerSingleton == null){
sLoggerSingleton = new Logger();
}
}
}
return sLoggerSingleton;
}
/** Print the text to the log file if not censored */
public void appendToLog(String text){
if(shouldCensorLog(text)) return;
appendToLogUnchecked(text);
}
/** Print the text to the log file, no china censoring there */
public void appendToLogUnchecked(String text){
mLogStream.println(text);
notifyLogListener(text);
}
/** Reset the log file, effectively erasing any previous logs */
public void reset(){
try{
mLogFile.delete();
mLogFile.createNewFile();
mLogStream = new PrintStream(mLogFile.getAbsolutePath());
}catch (IOException e){ e.printStackTrace();}
}
/** Disables the printing */
public void shutdown(){
mLogStream.close();
}
/**
* Perform various checks to see if the log is safe to print
* Subclasses may want to override this behavior
* @param text The text to check
* @return Whether the log should be censored
*/
private static boolean shouldCensorLog(String text){
if(text.contains("Session ID is")) return true;
return false;
}
/** Small listener for anything listening to the log */
public interface eventLogListener {
void onEventLogged(String text);
}
/** Link a log listener to the logger */
public void setLogListener(eventLogListener logListener){
this.mLogListenerWeakReference = new WeakReference<>(logListener);
}
/** Notifies the event listener, if it exists */
private void notifyLogListener(String text){
if(mLogListenerWeakReference == null) return;
eventLogListener logListener = mLogListenerWeakReference.get();
if(logListener == null){
mLogListenerWeakReference = null;
return;
}
logListener.onEventLogged(text);
}
}
@@ -1,201 +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;
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 {@link #GLFW_LOCK_KEY_MODS 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 {@link #GLFW_LOCK_KEY_MODS 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,143 +0,0 @@
package net.kdt.pojavlaunch;
import java.io.*;;
/**
* This account data format is deprecated.
* The current account data format is JSON on net.kdt.pojavlaunch.value.MinecraftAccount.
* This class remain for account data migrator only.
* Methods for saving/exporting on this format are no longer available.
*/
@Deprecated
public class MCProfile
{
private static String[] emptyBuilder = new String[]{
"1.9", //Version
"ProfileIDEmpty",
"AccessToken",
"AccessTokenEmpty",
"Steve"
};
public static MCProfile.Builder load(String pofFilePath) {
try {
String pofContent = Tools.read(pofFilePath);
return parse(pofContent);
} catch (Exception e) {
throw new RuntimeException("Unable to load Profile " + pofFilePath, e);
}
}
public static MCProfile.Builder parse(String content) {
if (content == null || content.isEmpty()) {
return null;
}
MCProfile.Builder builder = new MCProfile.Builder();
String[] profileInfos = content.split(":");
String cltk = profileInfos[0];
String prtk = profileInfos[1];
String acct = profileInfos[2];
String name = profileInfos[3];
String vers = profileInfos[4];
String isAc = profileInfos[5];
//System.out.println("parse THE VER = " + vers);
builder.setClientID(cltk);
builder.setProfileID(prtk);
builder.setAccessToken(acct);
builder.setUsername(name);
builder.setVersion(vers);
builder.setIsMojangAccount(Boolean.parseBoolean(isAc));
return builder;
}
public static MCProfile.Builder loadSafety(String pofFilePath) {
try {
return load(pofFilePath);
} catch (Exception e) {
e.printStackTrace();
// return new MCProfile.Builder();
return null;
}
}
public static class Builder implements Serializable
{
private String[] fullArgs = new String[6];
private boolean isMojangAccount = true;
public Builder()
{
fullArgs = emptyBuilder;
setClientID("0");
setProfileID("00000000-0000-0000-0000-000000000000");
setAccessToken("0");
}
public boolean isMojangAccount()
{
return isMojangAccount;
}
public String getVersion()
{
return fullArgs[0];
}
public String getClientID()
{
return fullArgs[1];
}
public String getProfileID()
{
return fullArgs[2];
}
public String getAccessToken()
{
return fullArgs[3];
}
public String getUsername()
{
return fullArgs[4];
}
public void setIsMojangAccount(boolean value)
{
isMojangAccount = value;
}
public void setVersion(String value)
{
fullArgs[0] = value;
}
public void setClientID(String value)
{
fullArgs[1] = value;
}
public void setProfileID(String value)
{
fullArgs[2] = value;
}
public void setAccessToken(String value)
{
fullArgs[3] = value;
}
public void setUsername(String value)
{
fullArgs[4] = value;
}
}
}
@@ -1,96 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.Intent;
import android.os.*;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import net.kdt.pojavlaunch.customcontrols.*;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import java.io.*;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_SUSTAINED_PERFORMANCE;
public class MainActivity extends BaseMainActivity {
public static ControlLayout mControlLayout;
private MCOptionUtils.MCOptionListener optionListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initLayout(R.layout.activity_basemain);
// 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<String>(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:
CustomControlsActivity.load(mControlLayout);
break;
case 3:
CustomControlsActivity.save(true,mControlLayout);
break;
case 4:
CustomControlsActivity.dialogSelectDefaultCtrl(mControlLayout);
break;
}
};
// Recompute the gui scale when options are changed
optionListener = MCOptionUtils::getMcScale;
MCOptionUtils.addMCOptionListener(optionListener);
mControlLayout = findViewById(R.id.main_control_layout);
mControlLayout.setModifiable(false);
try {
mControlLayout.loadLayout(LauncherPreferences.PREF_DEFAULTCTRL_PATH);
} catch(IOException e) {
try {
mControlLayout.loadLayout(Tools.CTRLDEF_FILE);
DEFAULT_PREF.edit().putString("defaultCtrl",Tools.CTRLDEF_FILE).commit();
} catch (IOException ioException) {
Tools.showError(this, ioException);
}
} catch (Throwable th) {
Tools.showError(this, th);
}
// toggleGui(null);
mControlLayout.toggleControlVisible();
}
@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();
}
}
}
@Override
public void onBackPressed() {
//if(isInEditor) CustomControlsActivity.save(true,mControlLayout);
}
}
@@ -1,649 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.BaseMainActivity.touchCharInput;
import static net.kdt.pojavlaunch.utils.MCOptionUtils.getMcScale;
import static org.lwjgl.glfw.CallbackBridge.sendKeyPress;
import static org.lwjgl.glfw.CallbackBridge.sendMouseButton;
import static org.lwjgl.glfw.CallbackBridge.windowHeight;
import static org.lwjgl.glfw.CallbackBridge.windowWidth;
import android.app.Activity;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.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 android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import net.kdt.pojavlaunch.utils.MathUtils;
import net.kdt.pojavlaunch.customcontrols.gamepad.Gamepad;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.JREUtils;
import net.kdt.pojavlaunch.utils.MCOptionUtils;
import org.lwjgl.glfw.CallbackBridge;
/**
* Class dealing with showing minecraft surface and taking inputs to dispatch them to minecraft
*/
public class MinecraftGLSurface extends View {
/* Gamepad object for gamepad inputs, instantiated on need */
private Gamepad mGamepad = null;
/* Pointer Debug textview, used to show info about the pointer state */
private TextView mPointerDebugTextView;
/* Resolution scaler option, allow downsizing a window */
private final float mScaleFactor = LauncherPreferences.PREF_SCALE_FACTOR/100f;
/* Sensitivity, adjusted according to screen size */
private final double mSensitivityFactor = (1.4 * (1080f/ Tools.getDisplayMetrics((Activity) getContext()).heightPixels));
/* Use to detect simple and double taps */
private final TapDetector mSingleTapDetector = new TapDetector(1, TapDetector.DETECTION_METHOD_BOTH);
private final TapDetector mDoubleTapDetector = new TapDetector(2, TapDetector.DETECTION_METHOD_DOWN);
/* MC GUI scale, listened by MCOptionUtils */
private int mGuiScale = getMcScale();
private final MCOptionUtils.MCOptionListener mGuiScaleListener = () -> mGuiScale = getMcScale();
/* Surface ready listener, used by the activity to launch minecraft */
SurfaceReadyListener mSurfaceReadyListener = null;
/* View holding the surface, either a SurfaceView or a TextureView */
View mSurface;
/* List of hotbarKeys, used when clicking on the hotbar */
private static final int[] HOTBAR_KEYS = {
LwjglGlfwKeycode.GLFW_KEY_1, LwjglGlfwKeycode.GLFW_KEY_2, LwjglGlfwKeycode.GLFW_KEY_3,
LwjglGlfwKeycode.GLFW_KEY_4, LwjglGlfwKeycode.GLFW_KEY_5, LwjglGlfwKeycode.GLFW_KEY_6,
LwjglGlfwKeycode.GLFW_KEY_7, LwjglGlfwKeycode.GLFW_KEY_8, LwjglGlfwKeycode.GLFW_KEY_9};
/* Last hotbar button (0-9) registered */
private int mLastHotbarKey = -1;
/* Events can start with only a move instead of an pointerDown due to mouse passthrough */
private boolean mShouldBeDown = false;
/* When fingers are really near to each other, it tends to either swap or remove a pointer ! */
private int mLastPointerCount = 0;
/* Previous MotionEvent position, not scale */
private float mPrevX, mPrevY;
/* PointerID used for the moving camera */
private int mCurrentPointerID = -1000;
/* Initial first pointer positions non-scaled, used to test touch sloppiness */
private float mInitialX, mInitialY;
/* Last first pointer positions non-scaled, used to scroll distance */
private float mScrollLastInitialX, mScrollLastInitialY;
/* How much distance a finger has to go for touch sloppiness to be disabled */
public static final int FINGER_STILL_THRESHOLD = (int) Tools.dpToPx(9);
/* How much distance a finger has to go to scroll */
public static final int FINGER_SCROLL_THRESHOLD = (int) Tools.dpToPx(6);
/* Whether the button was triggered, used by the handler */
private static boolean triggeredLeftMouseButton = false;
/* Handle hotbar throw button and mouse mining button */
public static final int MSG_LEFT_MOUSE_BUTTON_CHECK = 1028;
public static final int MSG_DROP_ITEM_BUTTON_CHECK = 1029;
private final Handler mHandler = new Handler(Looper.getMainLooper()) {
public void handleMessage(Message msg) {
if(msg.what == MSG_LEFT_MOUSE_BUTTON_CHECK) {
if (LauncherPreferences.PREF_DISABLE_GESTURES) return;
float x = CallbackBridge.mouseX;
float y = CallbackBridge.mouseY;
if (CallbackBridge.isGrabbing() &&
MathUtils.dist(x, y, mInitialX, mInitialY) < FINGER_STILL_THRESHOLD) {
triggeredLeftMouseButton = true;
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, true);
}
return;
}
if(msg.what == MSG_DROP_ITEM_BUTTON_CHECK) {
if(CallbackBridge.isGrabbing()){
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q);
mHandler.sendEmptyMessageDelayed(MSG_DROP_ITEM_BUTTON_CHECK, 600);
}
return;
}
}
};
public MinecraftGLSurface(Context context) {
this(context, null);
}
public MinecraftGLSurface(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setFocusable(true);
MCOptionUtils.addMCOptionListener(mGuiScaleListener);
}
/** Initialize the view and all its settings */
public void start(){
// Add the pointer debug textview
mPointerDebugTextView = new TextView(getContext());
mPointerDebugTextView.setX(0);
mPointerDebugTextView.setY(0);
mPointerDebugTextView.setVisibility(GONE);
((ViewGroup)getParent()).addView(mPointerDebugTextView);
if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){
SurfaceView surfaceView = new SurfaceView(getContext());
mSurface = surfaceView;
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
private boolean isCalled = false;
@Override
public void surfaceCreated(@NonNull SurfaceHolder holder) {
if(isCalled) 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);
mSurface = textureView;
textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
private boolean isCalled = false;
@Override
public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
if(isCalled) return;
isCalled = true;
realStart(new Surface(textureView.getSurfaceTexture()));
}
@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
public boolean onTouchEvent(MotionEvent e) {
// Looking for a mouse to handle, won't have an effect if no mouse exists.
for (int i = 0; i < e.getPointerCount(); i++) {
if (e.getToolType(i) != MotionEvent.TOOL_TYPE_MOUSE) continue;
// Mouse found
if(CallbackBridge.isGrabbing()) return false;
CallbackBridge.sendCursorPos( e.getX(i) * mScaleFactor, e.getY(i) * mScaleFactor);
return true; //mouse event handled successfully
}
// System.out.println("Pre touch, isTouchInHotbar=" + Boolean.toString(isTouchInHotbar) + ", action=" + MotionEvent.actionToString(e.getActionMasked()));
//Getting scaled position from the event
/* Tells if a double tap happened [MOUSE GRAB ONLY]. Doesn't tell where though. */
if(!CallbackBridge.isGrabbing()) {
CallbackBridge.mouseX = (e.getX() * mScaleFactor);
CallbackBridge.mouseY = (e.getY() * mScaleFactor);
//One android click = one MC click
if(mSingleTapDetector.onTouchEvent(e)){
CallbackBridge.putMouseEventWithCoords(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, CallbackBridge.mouseX, CallbackBridge.mouseY);
return true;
}
}
// Check double tap state, used for the hotbar
boolean hasDoubleTapped = mDoubleTapDetector.onTouchEvent(e);
switch (e.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
int pointerCount = e.getPointerCount();
// In-menu interactions
if(!CallbackBridge.isGrabbing()){
// Touch hover
if(pointerCount == 1){
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
mPrevX = e.getX();
mPrevY = e.getY();
break;
}
// Scrolling feature
if(LauncherPreferences.PREF_DISABLE_GESTURES) break;
// The pointer count can never be 0, and it is not 1, therefore it is >= 2
int hScroll = ((int) (e.getX() - mScrollLastInitialX)) / FINGER_SCROLL_THRESHOLD;
int vScroll = ((int) (e.getY() - mScrollLastInitialY)) / FINGER_SCROLL_THRESHOLD;
if(vScroll != 0 || hScroll != 0){
CallbackBridge.sendScroll(hScroll, vScroll);
mScrollLastInitialX = e.getX();
mScrollLastInitialY = e.getY();
}
break;
}
// Camera movement
int pointerIndex = e.findPointerIndex(mCurrentPointerID);
int hudKeyHandled = handleGuiBar((int)e.getX(), (int) e.getY());
// Start movement, due to new pointer or loss of pointer
if (pointerIndex == -1 || mLastPointerCount != pointerCount || !mShouldBeDown) {
if(hudKeyHandled != -1) break; //No pointer attribution on hotbar
mShouldBeDown = true;
mCurrentPointerID = e.getPointerId(0);
mPrevX = e.getX();
mPrevY = e.getY();
break;
}
// Continue movement as usual
if(hudKeyHandled == -1){ //No camera on hotbar
CallbackBridge.mouseX += (e.getX(pointerIndex) - mPrevX) * mSensitivityFactor;
CallbackBridge.mouseY += (e.getY(pointerIndex) - mPrevY) * mSensitivityFactor;
}
mPrevX = e.getX(pointerIndex);
mPrevY = e.getY(pointerIndex);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
break;
case MotionEvent.ACTION_DOWN: // 0
CallbackBridge.sendPrepareGrabInitialPos();
hudKeyHandled = handleGuiBar((int)e.getX(), (int) e.getY());
boolean isTouchInHotbar = hudKeyHandled != -1;
if (isTouchInHotbar) {
sendKeyPress(hudKeyHandled);
if(hasDoubleTapped && hudKeyHandled == mLastHotbarKey){
//Prevent double tapping Event on two different slots
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_F);
}
mHandler.sendEmptyMessageDelayed(MSG_DROP_ITEM_BUTTON_CHECK, 350);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
mLastHotbarKey = hudKeyHandled;
break;
}
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
mPrevX = e.getX();
mPrevY = e.getY();
if (CallbackBridge.isGrabbing()) {
mCurrentPointerID = e.getPointerId(0);
// It cause hold left mouse while moving camera
mInitialX = CallbackBridge.mouseX;
mInitialY = CallbackBridge.mouseY;
mHandler.sendEmptyMessageDelayed(MSG_LEFT_MOUSE_BUTTON_CHECK, LauncherPreferences.PREF_LONGPRESS_TRIGGER);
}
mLastHotbarKey = hudKeyHandled;
break;
case MotionEvent.ACTION_UP: // 1
case MotionEvent.ACTION_CANCEL: // 3
mShouldBeDown = false;
mCurrentPointerID = -1;
hudKeyHandled = handleGuiBar((int)e.getX(), (int) e.getY());
isTouchInHotbar = hudKeyHandled != -1;
// We only treat in world events
if (!CallbackBridge.isGrabbing()) break;
// Stop the dropping of items
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_Q, 0, false);
mHandler.removeMessages(MSG_DROP_ITEM_BUTTON_CHECK);
// Remove the mouse left button
if(triggeredLeftMouseButton){
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT, false);
triggeredLeftMouseButton = false;
break;
}
mHandler.removeMessages(MSG_LEFT_MOUSE_BUTTON_CHECK);
// In case of a short click, just send a quick right click
if(!LauncherPreferences.PREF_DISABLE_GESTURES &&
MathUtils.dist(mInitialX, mInitialY, CallbackBridge.mouseX, CallbackBridge.mouseY) < FINGER_STILL_THRESHOLD){
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, true);
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, false);
}
break;
case MotionEvent.ACTION_POINTER_DOWN: // 5
//TODO Hey we could have some sort of middle click detection ?
mScrollLastInitialX = e.getX();
mScrollLastInitialY = e.getY();
//Checking if we are pressing the hotbar to select the item
hudKeyHandled = handleGuiBar((int)e.getX(e.getPointerCount()-1), (int) e.getY(e.getPointerCount()-1));
if(hudKeyHandled != -1){
sendKeyPress(hudKeyHandled);
if(hasDoubleTapped && hudKeyHandled == mLastHotbarKey){
//Prevent double tapping Event on two different slots
sendKeyPress(LwjglGlfwKeycode.GLFW_KEY_F);
}
}
mLastHotbarKey = hudKeyHandled;
break;
}
// Actualise the pointer count
mLastPointerCount = e.getPointerCount();
//debugText.setText(CallbackBridge.DEBUG_STRING.toString());
CallbackBridge.DEBUG_STRING.setLength(0);
return true;
}
/**
* The event for mouse/joystick movements
* We don't do the gamepad right now.
*/
@Override
public boolean dispatchGenericMotionEvent(MotionEvent event) {
int mouseCursorIndex = -1;
if(Gamepad.isGamepadEvent(event)){
if(mGamepad == null){
mGamepad = new Gamepad(this, event.getDevice());
}
mGamepad.update(event);
return true;
}
for(int i = 0; i < event.getPointerCount(); i++) {
if(event.getToolType(i) != MotionEvent.TOOL_TYPE_MOUSE) continue;
// Mouse found
mouseCursorIndex = i;
break;
}
if(mouseCursorIndex == -1) return false; // we cant consoom that, theres no mice!
if(CallbackBridge.isGrabbing()) {
if(BaseMainActivity.isAndroid8OrHigher()){
requestFocus();
requestPointerCapture();
}
}
switch(event.getActionMasked()) {
case MotionEvent.ACTION_HOVER_MOVE:
CallbackBridge.mouseX = (event.getX(mouseCursorIndex) * mScaleFactor);
CallbackBridge.mouseY = (event.getY(mouseCursorIndex) * mScaleFactor);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
//debugText.setText(CallbackBridge.DEBUG_STRING.toString());
CallbackBridge.DEBUG_STRING.setLength(0);
return true;
case MotionEvent.ACTION_SCROLL:
CallbackBridge.sendScroll((double) event.getAxisValue(MotionEvent.AXIS_VSCROLL), (double) event.getAxisValue(MotionEvent.AXIS_HSCROLL));
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;
}
}
//TODO MOVE THIS SOMEWHERE ELSE
private boolean debugErrored = false;
/** The input event for mouse with a captured pointer */
@RequiresApi(26)
@Override
public boolean dispatchCapturedPointerEvent(MotionEvent e) {
CallbackBridge.mouseX += (e.getX()* mScaleFactor);
CallbackBridge.mouseY += (e.getY()* mScaleFactor);
if(!CallbackBridge.isGrabbing()){
releasePointerCapture();
clearFocus();
}
if (mPointerDebugTextView.getVisibility() == View.VISIBLE && !debugErrored) {
StringBuilder builder = new StringBuilder();
try {
builder.append("PointerCapture debug\n");
builder.append("MotionEvent=").append(e.getActionMasked()).append("\n");
builder.append("PressingBtn=").append(MotionEvent.class.getDeclaredMethod("buttonStateToString").invoke(null, e.getButtonState())).append("\n\n");
builder.append("PointerX=").append(e.getX()).append("\n");
builder.append("PointerY=").append(e.getY()).append("\n");
builder.append("RawX=").append(e.getRawX()).append("\n");
builder.append("RawY=").append(e.getRawY()).append("\n\n");
builder.append("XPos=").append(CallbackBridge.mouseX).append("\n");
builder.append("YPos=").append(CallbackBridge.mouseY).append("\n\n");
builder.append("MovingX=").append(getMoving(e.getX(), true)).append("\n");
builder.append("MovingY=").append(getMoving(e.getY(), false)).append("\n");
} catch (Throwable th) {
debugErrored = true;
builder.append("Error getting debug. The debug will be stopped!\n").append(Log.getStackTraceString(th));
} finally {
mPointerDebugTextView.setText(builder.toString());
builder.setLength(0);
}
}
mPointerDebugTextView.setText(CallbackBridge.DEBUG_STRING.toString());
CallbackBridge.DEBUG_STRING.setLength(0);
switch (e.getActionMasked()) {
case MotionEvent.ACTION_MOVE:
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
return true;
case MotionEvent.ACTION_BUTTON_PRESS:
return sendMouseButtonUnconverted(e.getActionButton(), true);
case MotionEvent.ACTION_BUTTON_RELEASE:
return sendMouseButtonUnconverted(e.getActionButton(), false);
case MotionEvent.ACTION_SCROLL:
CallbackBridge.sendScroll(e.getAxisValue(MotionEvent.AXIS_HSCROLL), e.getAxisValue(MotionEvent.AXIS_VSCROLL));
return true;
default:
return false;
}
}
/** The event for keyboard/ gamepad button inputs */
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
//Toast.makeText(this, event.toString(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this, event.getDevice().toString(), Toast.LENGTH_SHORT).show();
//Filtering useless events by order of probability
if((event.getFlags() & KeyEvent.FLAG_FALLBACK) == KeyEvent.FLAG_FALLBACK) return true;
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;
if(event.getAction() == KeyEvent.ACTION_MULTIPLE) return true;
//Toast.makeText(this, "FIRST VERIF PASSED", Toast.LENGTH_SHORT).show();
//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;
}
//Toast.makeText(this, "SECOND VERIF PASSED", Toast.LENGTH_SHORT).show();
//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) ){
//Toast.makeText(this, "THE EVENT COMES FROM A MOUSE", Toast.LENGTH_SHORT).show();
if(eventKeycode == KeyEvent.KEYCODE_BACK){
sendMouseButton(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_RIGHT, event.getAction() == KeyEvent.ACTION_DOWN);
return true;
}
}
//System.out.println(event);
if(Gamepad.isGamepadEvent(event)){
if(mGamepad == null){
mGamepad = new Gamepad(this, event.getDevice());
}
mGamepad.update(event);
return true;
}
int index = EfficientAndroidLWJGLKeycode.getIndexByKey(eventKeycode);
if(index >= 0) {
//Toast.makeText(this,"THIS IS A KEYBOARD EVENT !", Toast.LENGTH_SHORT).show();
EfficientAndroidLWJGLKeycode.execKey(event, index);
return true;
}
return false;
}
/** Get the mouse direction as a string */
private String getMoving(float pos, boolean xOrY) {
if (pos == 0) return "STOPPED";
if (pos > 0) return xOrY ? "RIGHT" : "DOWN";
return xOrY ? "LEFT" : "UP";
}
/** 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;
}
/** @return the hotbar key, given the position. -1 if no key are pressed */
public int handleGuiBar(int x, int y) {
if (!CallbackBridge.isGrabbing()) return -1;
int barHeight = mcscale(20);
int barY = CallbackBridge.physicalHeight - barHeight;
if(y < barY) return -1;
int barWidth = mcscale(180);
int barX = (CallbackBridge.physicalWidth / 2) - (barWidth / 2);
if(x < barX || x >= barX + barWidth) return -1;
return HOTBAR_KEYS[(int) net.kdt.pojavlaunch.utils.MathUtils.map(x, barX, barX + barWidth, 0, 9)];
}
/** Return the size, given the UI scale size */
private int mcscale(int input) {
return (int)((mGuiScale * input)/ mScaleFactor);
}
/** Toggle the pointerDebugText visibility state */
public void togglepointerDebugging() {
mPointerDebugTextView.setVisibility(mPointerDebugTextView.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);
}
/** Called when the size need to be set at any point during the surface lifecycle **/
public void refreshSize(){
windowWidth = Tools.getDisplayFriendlyRes(Tools.currentDisplayMetrics.widthPixels, mScaleFactor);
windowHeight = Tools.getDisplayFriendlyRes(Tools.currentDisplayMetrics.heightPixels, mScaleFactor);
if(LauncherPreferences.PREF_USE_ALTERNATE_SURFACE){
((SurfaceView)mSurface).getHolder().setFixedSize(windowWidth, windowHeight);
}else{
((TextureView)mSurface).getSurfaceTexture().setDefaultBufferSize(windowWidth, windowHeight);
}
CallbackBridge.sendUpdateWindowSize(windowWidth, windowHeight);
//getMcScale();
//Toast.makeText(getContext(), "width: " + width, Toast.LENGTH_SHORT).show();
//Toast.makeText(getContext(), "height: " + height, Toast.LENGTH_SHORT).show();
}
private void realStart(Surface surface){
// Initial size set
refreshSize();
//Load Minecraft options:
MCOptionUtils.load();
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 {
Thread.sleep(200);
if(mSurfaceReadyListener != null){
mSurfaceReadyListener.isReady();
}
} catch (Throwable e) {
Tools.showError(getContext(), e, true);
}
}, "JVM Main thread").start();
}
/** A small interface called when the listener is ready for the first time */
public interface SurfaceReadyListener {
void isReady();
}
public void setSurfaceReadyListener(SurfaceReadyListener listener){
mSurfaceReadyListener = listener;
}
}
@@ -1,87 +0,0 @@
package net.kdt.pojavlaunch;
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 net.kdt.pojavlaunch.utils.*;
public class PojavApplication extends Application {
public static String CRASH_REPORT_TAG = "PojavCrashReport";
@Override
public void onCreate() {
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;
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
crashFile.getParentFile().mkdirs();
crashFile.createNewFile();
PrintStream crashStream = new PrintStream(crashFile);
crashStream.append("PojavLauncher crash report\n");
crashStream.append(" - Time: " + DateFormat.getDateTimeInstance().format(new Date()) + "\n");
crashStream.append(" - Device: " + Build.PRODUCT + " " + Build.MODEL + "\n");
crashStream.append(" - Android version: " + Build.VERSION.RELEASE + "\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);
// android.os.Process.killProcess(android.os.Process.myPid());
BaseMainActivity.fullyExit();
});
try {
super.onCreate();
Tools.APP_NAME = getResources().getString(R.string.app_short_name);
Tools.DIR_DATA = getDir("files", MODE_PRIVATE).getParent();
//Tools.DIR_HOME_JRE = Tools.DIR_DATA + "/jre_runtime".replace("/data/user/0", "/data/data");
Tools.DIR_ACCOUNT_OLD = Tools.DIR_DATA + "/Users";
Tools.DIR_ACCOUNT_NEW = Tools.DIR_DATA + "/accounts";
// Tools.FILE_ACCOUNT_JSON = getFilesDir().getAbsolutePath() + "/account_profiles.json";
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");
}
} catch (Throwable throwable) {
Intent ferrorIntent = new Intent(this, FatalErrorActivity.class);
ferrorIntent.putExtra("throwable", throwable);
startActivity(ferrorIntent);
}
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(LocaleUtils.setLocale(base));
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.setLocale(this);
}
}
@@ -1,401 +0,0 @@
package net.kdt.pojavlaunch;
import static android.os.Build.VERSION_CODES.P;
import static net.kdt.pojavlaunch.Tools.ignoreNotch;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_HIDE_SIDEBAR;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_NOTCH_SIZE;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.Guideline;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.extra.ExtraListener;
import net.kdt.pojavlaunch.fragments.ConsoleFragment;
import net.kdt.pojavlaunch.fragments.CrashFragment;
import net.kdt.pojavlaunch.fragments.LauncherFragment;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.prefs.screens.LauncherPreferenceFragment;
import net.kdt.pojavlaunch.profiles.ProfileAdapter;
import net.kdt.pojavlaunch.extra.ExtraConstants;
import net.kdt.pojavlaunch.profiles.ProfileEditor;
import net.kdt.pojavlaunch.profiles.ProfileIconCache;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PojavLauncherActivity extends BaseLauncherActivity
{
// An equivalent ViewPager2 adapter class
private static class ScreenSlidePagerAdapter extends FragmentStateAdapter {
public ScreenSlidePagerAdapter(FragmentActivity fa) {
super(fa);
}
@Override
public Fragment createFragment(int position) {
if (position == 0) return new LauncherFragment();
if (position == 1) return new ConsoleFragment();
if (position == 2) return new CrashFragment();
if (position == 3) return new LauncherPreferenceFragment();
return null;
}
@Override
public int getItemCount() {
return 4;
}
}
private TextView tvConnectStatus;
private Spinner accountSelector;
private ViewPager2 viewPager;
private final Button[] Tabs = new Button[4];
private View selectedTab;
private ImageView accountFaceImageView;
private Button logoutBtn; // MineButtons
private ExtraListener backPreferenceListener;
public PojavLauncherActivity() {
}
@Override
protected void onDestroy() {
ExtraCore.removeExtraListenerFromValue(ExtraConstants.BACK_PREFERENCE, backPreferenceListener);
super.onDestroy();
ProfileIconCache.clearIconCache();
Log.i("LauncherActivity","Destroyed!");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pojav_launcher);
//Boilerplate linking/initialisation
viewPager = findViewById(R.id.launchermainTabPager);
selectedTab = findViewById(R.id.viewTabSelected);
tvConnectStatus = findViewById(R.id.launchermain_text_accountstatus);
accountFaceImageView = findViewById(R.id.launchermain_account_image);
accountSelector = findViewById(R.id.launchermain_spinner_account);
mVersionSelector = findViewById(R.id.launchermain_spinner_version);
mLaunchProgress = findViewById(R.id.progressDownloadBar);
mLaunchTextStatus = findViewById(R.id.progressDownloadText);
logoutBtn = findViewById(R.id.installJarButton);
mPlayButton = findViewById(R.id.launchermainPlayButton);
Tabs[0] = findViewById(R.id.btnTab1);
Tabs[1] = findViewById(R.id.btnTab2);
Tabs[2] = findViewById(R.id.btnTab3);
Tabs[3] = findViewById(R.id.btnTab4);
if (BuildConfig.DEBUG) {
Toast.makeText(this, "Launcher process id: " + android.os.Process.myPid(), Toast.LENGTH_LONG).show();
}
// Setup the viewPager to slide across fragments
viewPager.setAdapter(new ScreenSlidePagerAdapter(this));
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
@Override
public void onPageSelected(int position) {
setTabActive(position);
}
});
//Setup listener to the backPreference system
backPreferenceListener = (key, value) -> {
if(value.equals("true")){
onBackPressed();
ExtraCore.setValue(key, "false");
}
return false;
};
ExtraCore.addExtraListener(ExtraConstants.BACK_PREFERENCE, backPreferenceListener);
// Try to load the temporary account
final List<String> accountList = new ArrayList<>();
final MinecraftAccount tempProfile = PojavProfile.getTempProfileContent();
if (tempProfile != null) {
accountList.add(tempProfile.username);
}
for (String s : new File(Tools.DIR_ACCOUNT_NEW).list()) {
accountList.add(s.substring(0, s.length() - 5));
}
// Setup account spinner
pickAccount();
ArrayAdapter<String> adapterAcc = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, accountList);
adapterAcc.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
accountSelector.setAdapter(adapterAcc);
if (tempProfile != null) {
accountSelector.setSelection(0);
} else {
for (int i = 0; i < accountList.size(); i++) {
String account = accountList.get(i);
if (account.equals(mProfile.username)) {
accountSelector.setSelection(i);
}
}
}
accountSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> p1, View p2, int position, long p4) {
if (tempProfile != null && position == 0) {
PojavProfile.setCurrentProfile(PojavLauncherActivity.this, tempProfile);
} else {
PojavProfile.setCurrentProfile(PojavLauncherActivity.this,
accountList.get(position + (tempProfile != null ? 1 : 0)));
}
pickAccount();
}
@Override
public void onNothingSelected(AdapterView<?> p1) {
// TODO: Implement this method
}
});
// Setup the minecraft version list
setupBasicList(this);
//mAvailableVersions;
ProfileAdapter profileAdapter = new ProfileAdapter(this, true);
ProfileEditor profileEditor = new ProfileEditor(this,(name, isNew, deleting)->{
LauncherProfiles.update();
profileAdapter.notifyDataSetChanged();
if(isNew) {
mVersionSelector.setSelection(profileAdapter.resolveProfileIndex(name));
}
if(deleting) {
mVersionSelector.setSelection(0);
}
});
mVersionSelector.setOnLongClickListener((v)->profileEditor.show(LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,"")));
mVersionSelector.setAdapter(profileAdapter);
mVersionSelector.setSelection(profileAdapter.resolveProfileIndex(LauncherPreferences.DEFAULT_PREF.getString(LauncherPreferences.PREF_KEY_CURRENT_PROFILE,"")));
mVersionSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> p1, View p2, int p3, long p4)
{
String profileName = p1.getItemAtPosition(p3).toString();
if(profileName.equals(ProfileAdapter.CREATE_PROFILE_MAGIC)) {
profileEditor.show(profileName);
mVersionSelector.setSelection(0);
return;
}
LauncherPreferences.DEFAULT_PREF.edit()
.putString(
LauncherPreferences.PREF_KEY_CURRENT_PROFILE,
p1.getItemAtPosition(p3).toString())
.commit();
}
@Override
public void onNothingSelected(AdapterView<?> p1)
{
// TODO: Implement this method
}
});
//
statusIsLaunching(false);
//Add the preference changed listener
LauncherPreferences.DEFAULT_PREF.registerOnSharedPreferenceChangeListener((sharedPreferences, key) -> {
if(key.equals("hideSidebar")){
changeLookAndFeel(sharedPreferences.getBoolean("hideSidebar",false));
return;
}
if(key.equals("ignoreNotch")){
ignoreNotch(sharedPreferences.getBoolean("ignoreNotch", true), PojavLauncherActivity.this);
return;
}
});
changeLookAndFeel(PREF_HIDE_SIDEBAR);
initTabs(0);
}
private void selectTabPage(int pageIndex){
viewPager.setCurrentItem(pageIndex);
setTabActive(pageIndex);
}
public static String[] basicVersionList;
public static void setupBasicList(Context ctx) {
List<String> versions = new ArrayList<>();
final File fVers = new File(Tools.DIR_HOME_VERSION);
try {
if (fVers.listFiles().length < 1) {
throw new Exception(ctx.getString(R.string.error_no_version));
}
for (File fVer : fVers.listFiles()) {
if (fVer.isDirectory())
versions.add(fVer.getName());
}
} catch (Exception e) {
versions.add(ctx.getString(R.string.global_error) + ":");
versions.add(e.getMessage());
} finally {
basicVersionList = versions.toArray(new String[0]);
ExtraCore.setValue(ExtraConstants.VERSION_LIST,versions);
}
}
private void pickAccount() {
try {
mProfile = PojavProfile.getCurrentProfileContent(this);
accountFaceImageView.setImageBitmap(mProfile.getSkinFace());
//TODO FULL BACKGROUND LOGIN
tvConnectStatus.setText(mProfile.accessToken.equals("0") ? R.string.mcl_account_local : R.string.mcl_account_connected);
} catch(Exception e) {
mProfile = new MinecraftAccount();
Tools.showError(this, e, true);
}
}
public void statusIsLaunching(boolean isLaunching) {
int launchVisibility = isLaunching ? View.VISIBLE : View.GONE;
mLaunchProgress.setVisibility(launchVisibility);
mLaunchTextStatus.setVisibility(launchVisibility);
logoutBtn.setEnabled(!isLaunching);
mVersionSelector.setEnabled(!isLaunching);
canBack = !isLaunching;
}
public void onTabClicked(View view) {
for(int i=0; i<Tabs.length;i++){
if(view.getId() == Tabs[i].getId()) {
selectTabPage(i);
return;
}
}
}
private void setTabActive(int index){
for (Button tab : Tabs) {
tab.setTypeface(null, Typeface.NORMAL);
tab.setTextColor(Color.rgb(220,220,220)); //Slightly less bright white.
}
Tabs[index].setTypeface(Tabs[index].getTypeface(), Typeface.BOLD);
Tabs[index].setTextColor(Color.WHITE);
//Animating the white bar on the left
ValueAnimator animation = ValueAnimator.ofFloat(selectedTab.getY(), Tabs[index].getY()+(Tabs[index].getHeight()- selectedTab.getHeight())/2f);
animation.setDuration(250);
animation.addUpdateListener(animation1 -> selectedTab.setY((float) animation1.getAnimatedValue()));
animation.start();
}
protected void initTabs(int activeTab){
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(() -> {
//Do something after 100ms
selectTabPage(activeTab);
}, 100);
}
private void changeLookAndFeel(boolean useOldLook){
Guideline guideLine = findViewById(R.id.guidelineLeft);
ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) guideLine.getLayoutParams();
if(useOldLook || getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
//UI v1 Style
//Hide the sidebar
params.guidePercent = 0; // 0%, range: 0 <-> 1
guideLine.setLayoutParams(params);
//Remove the selected Tab and the head image
selectedTab.setVisibility(View.GONE);
accountFaceImageView.setVisibility(View.GONE);
//Enlarge the button, but just a bit.
params = (ConstraintLayout.LayoutParams) mPlayButton.getLayoutParams();
params.matchConstraintPercentWidth = 0.35f;
}else{
//UI v2 Style
//Show the sidebar back
params.guidePercent = 0.23f; // 23%, range: 0 <-> 1
guideLine.setLayoutParams(params);
//Show the selected Tab
selectedTab.setVisibility(View.VISIBLE);
accountFaceImageView.setVisibility(View.VISIBLE);
//Set the default button size
params = (ConstraintLayout.LayoutParams) mPlayButton.getLayoutParams();
params.matchConstraintPercentWidth = 0.25f;
}
mPlayButton.setLayoutParams(params);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
//Try to get the notch so it can be taken into account in settings
if (Build.VERSION.SDK_INT >= P){
try {
PREF_NOTCH_SIZE = getWindow().getDecorView().getRootWindowInsets().getDisplayCutout().getBoundingRects().get(0).width();
}catch (Exception e){
Log.i("NOTCH DETECTION", "No notch detected, or the device if in split screen mode");
PREF_NOTCH_SIZE = -1;
}
Tools.updateWindowSize(this);
}
}
/**
* Custom back stack system. Use the classic backstack when the focus is on the setting screen,
* finish the activity and remove the back_preference listener otherwise
*/
@Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if(count > 0 && viewPager.getCurrentItem() == 3){
getSupportFragmentManager().popBackStack();
}else{
super.onBackPressed();
//additional code
ExtraCore.removeExtraListenerFromValue(ExtraConstants.BACK_PREFERENCE, backPreferenceListener);
finish();
}
}
}
@@ -1,765 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.Architecture.archAsString;
import static net.kdt.pojavlaunch.Tools.getFileName;
import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import net.kdt.pojavlaunch.authenticator.microsoft.MicrosoftAuthTask;
import net.kdt.pojavlaunch.authenticator.microsoft.ui.MicrosoftLoginGUIActivity;
import net.kdt.pojavlaunch.authenticator.mojang.InvalidateTokenTask;
import net.kdt.pojavlaunch.authenticator.mojang.LoginListener;
import net.kdt.pojavlaunch.authenticator.mojang.LoginTask;
import net.kdt.pojavlaunch.authenticator.mojang.RefreshListener;
import net.kdt.pojavlaunch.colorselector.ColorSelector;
import net.kdt.pojavlaunch.customcontrols.CustomControls;
import net.kdt.pojavlaunch.multirt.MultiRTConfigDialog;
import net.kdt.pojavlaunch.multirt.MultiRTUtils;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import net.kdt.pojavlaunch.utils.LocaleUtils;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import net.kdt.pojavlaunch.value.PerVersionConfig;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Locale;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
public class PojavLoginActivity extends BaseActivity {
private final Object mLockStoragePerm = new Object();
private final Object mLockSelectJRE = new Object();
private EditText edit2, edit3;
private final int REQUEST_STORAGE_REQUEST_CODE = 1;
private CheckBox sRemember, sLocal;
private TextView startupTextView;
private SharedPreferences firstLaunchPrefs;
private MinecraftAccount mProfile = null;
private boolean isSkipInit = false;
private boolean isStarting = false;
public static final String PREF_IS_INSTALLED_JAVARUNTIME = "isJavaRuntimeInstalled";
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState); // false;
if(savedInstanceState != null) {
isStarting = savedInstanceState.getBoolean("isStarting");
isSkipInit = savedInstanceState.getBoolean("isSkipInit");
}
Tools.updateWindowSize(this);
firstLaunchPrefs = getSharedPreferences("pojav_extract", MODE_PRIVATE);
new Thread(new InitRunnable()).start();
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("isStarting",isStarting);
outState.putBoolean("isSkipInit",isSkipInit);
}
public class InitRunnable implements Runnable{
private int revokeCount = -1;
private int proceedState = 0;
private ProgressBar progress;
public InitRunnable() {
}
public void initLocalUi() {
LinearLayout startScr = new LinearLayout(PojavLoginActivity.this);
LayoutInflater.from(PojavLoginActivity.this).inflate(R.layout.start_screen,startScr);
PojavLoginActivity.this.setContentView(startScr);
progress = (ProgressBar) findViewById(R.id.startscreenProgress);
if(isStarting) progress.setVisibility(View.VISIBLE);
startupTextView = (TextView) findViewById(R.id.startscreen_text);
}
public int _start() {
Log.i("UITest","START initialization");
if(!isStarting) {
//try { Thread.sleep(2000); } catch (InterruptedException e) { }
runOnUiThread(() -> progress.setVisibility(View.VISIBLE));
while (Build.VERSION.SDK_INT >= 23 && Build.VERSION.SDK_INT < 29 && !isStorageAllowed()) { //Do not ask for storage at all on Android 10+
try {
revokeCount++;
if (revokeCount >= 3) {
Toast.makeText(PojavLoginActivity.this, R.string.toast_permission_denied, Toast.LENGTH_LONG).show();
return 2;
}
requestStoragePermission();
synchronized (mLockStoragePerm) {
mLockStoragePerm.wait();
}
} catch (InterruptedException e) {
}
}
isStarting = true;
}
try {
initMain();
} catch (Throwable th) {
Tools.showError(PojavLoginActivity.this, th, true);
return 1;
}
return 0;
}
public void proceed() {
isStarting = false;
switch(proceedState) {
case 2:
finish();
break;
case 0:
uiInit();
break;
}
}
@Override
public void run() {
if(!isSkipInit) {
PojavLoginActivity.this.runOnUiThread(this::initLocalUi);
proceedState = _start();
}
PojavLoginActivity.this.runOnUiThread(this::proceed);
}
}
private void uiInit() {
setContentView(R.layout.activity_pojav_login);
Spinner spinnerChgLang = findViewById(R.id.login_spinner_language);
String defaultLang = LocaleUtils.DEFAULT_LOCALE.getDisplayName();
SpannableString defaultLangChar = new SpannableString(defaultLang);
defaultLangChar.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, defaultLang.length(), 0);
final ArrayAdapter<DisplayableLocale> langAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
langAdapter.add(new DisplayableLocale(LocaleUtils.DEFAULT_LOCALE, defaultLangChar));
langAdapter.add(new DisplayableLocale(Locale.ENGLISH));
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getAssets().open("language_list.txt")));
String line;
while ((line = reader.readLine()) != null) {
File currFile = new File("/" + line);
// System.out.println(currFile.getAbsolutePath());
if (currFile.getAbsolutePath().contains("/values-") || currFile.getName().startsWith("values-")) {
// TODO use regex(?)
langAdapter.add(new DisplayableLocale(currFile.getName().replace("values-", "").replace("-r", "-")));
}
}
} catch (IOException e) {
Tools.showError(this, e);
}
langAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
int selectedLang = 0;
for (int i = 0; i < langAdapter.getCount(); i++) {
if (Locale.getDefault().getDisplayLanguage().equals(langAdapter.getItem(i).mLocale.getDisplayLanguage())) {
selectedLang = i;
break;
}
}
spinnerChgLang.setAdapter(langAdapter);
spinnerChgLang.setSelection(selectedLang);
spinnerChgLang.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
private boolean isInitCalled;
@Override
public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {
if (!isInitCalled) {
isInitCalled = true;
return;
}
Locale locale;
if (position == 0) {
locale = LocaleUtils.DEFAULT_LOCALE;
} else if (position == 1) {
locale = Locale.ENGLISH;
} else {
locale = langAdapter.getItem(position).mLocale;
}
LauncherPreferences.PREF_LANGUAGE = locale.getLanguage();
LauncherPreferences.DEFAULT_PREF.edit().putString("language", LauncherPreferences.PREF_LANGUAGE).apply();
// Restart to apply language change
finish();
startActivity(getIntent());
}
@Override
public void onNothingSelected(AdapterView<?> adapter) {}
});
edit2 = findViewById(R.id.login_edit_email);
edit3 = findViewById(R.id.login_edit_password);
sRemember = findViewById(R.id.login_switch_remember);
sLocal = findViewById(R.id.login_switch_local);
sLocal.setOnCheckedChangeListener((p1, p2) -> {
// May delete later
edit3.setEnabled(!p2);
});
isSkipInit = true;
}
@Override
public void onResume() {
super.onResume();
Tools.updateWindowSize(this);
// Clear current profile
PojavProfile.setCurrentProfile(this, null);
}
private boolean unpackComponent(AssetManager am, String component) throws IOException {
File versionFile = new File(Tools.DIR_GAME_HOME + "/" + component + "/version");
InputStream is = am.open("components/" + component + "/version");
if(!versionFile.exists()) {
if (versionFile.getParentFile().exists() && versionFile.getParentFile().isDirectory()) {
FileUtils.deleteDirectory(versionFile.getParentFile());
}
versionFile.getParentFile().mkdir();
Log.i("UnpackPrep", component + ": Pack was installed manually, or does not exist, unpacking new...");
String[] fileList = am.list("components/" + component);
for(String s : fileList) {
Tools.copyAssetFile(this, "components/" + component + "/" + s, Tools.DIR_GAME_HOME + "/" + component, true);
}
} else {
FileInputStream fis = new FileInputStream(versionFile);
String release1 = Tools.read(is);
String release2 = Tools.read(fis);
if (!release1.equals(release2)) {
if (versionFile.getParentFile().exists() && versionFile.getParentFile().isDirectory()) {
FileUtils.deleteDirectory(versionFile.getParentFile());
}
versionFile.getParentFile().mkdir();
String[] fileList = am.list("components/" + component);
for (String s : fileList) {
Tools.copyAssetFile(this, "components/" + component + "/" + s, Tools.DIR_GAME_HOME + "/" + component, true);
}
} else {
Log.i("UnpackPrep", component + ": Pack is up-to-date with the launcher, continuing...");
return false;
}
}
return true;
}
public static void disableSplash(String dir) {
mkdirs(dir + "/config");
File forgeSplashFile = new File(dir, "config/splash.properties");
String forgeSplashContent = "enabled=true";
try {
if (forgeSplashFile.exists()) {
forgeSplashContent = Tools.read(forgeSplashFile.getAbsolutePath());
}
if (forgeSplashContent.contains("enabled=true")) {
Tools.write(forgeSplashFile.getAbsolutePath(),
forgeSplashContent.replace("enabled=true", "enabled=false"));
}
} catch (IOException e) {
Log.w(Tools.APP_NAME, "Could not disable Forge 1.12.2 and below splash screen!", e);
}
}
private void initMain() throws Throwable {
mkdirs(Tools.DIR_ACCOUNT_NEW);
PojavMigrator.migrateAccountData(this);
mkdirs(Tools.DIR_GAME_HOME);
mkdirs(Tools.DIR_GAME_HOME + "/lwjgl3");
mkdirs(Tools.DIR_GAME_HOME + "/config");
if (!PojavMigrator.migrateGameDir()) {
mkdirs(Tools.DIR_GAME_NEW);
mkdirs(Tools.DIR_GAME_NEW + "/mods");
mkdirs(Tools.DIR_HOME_VERSION);
mkdirs(Tools.DIR_HOME_LIBRARY);
}
mkdirs(Tools.CTRLMAP_PATH);
try {
new CustomControls(this).save(Tools.CTRLDEF_FILE);
Tools.copyAssetFile(this, "components/security/pro-grade.jar", Tools.DIR_DATA, true);
Tools.copyAssetFile(this, "components/security/java_sandbox.policy", Tools.DIR_DATA, true);
Tools.copyAssetFile(this, "options.txt", Tools.DIR_GAME_NEW, false);
// TODO: Remove after implement.
Tools.copyAssetFile(this, "launcher_profiles.json", Tools.DIR_GAME_NEW, false);
Tools.copyAssetFile(this,"resolv.conf",Tools.DIR_DATA, true);
Tools.copyAssetFile(this,"arc_dns_injector.jar",Tools.DIR_DATA, true);
AssetManager am = this.getAssets();
unpackComponent(am, "caciocavallo");
// Since the Java module system doesn't allow multiple JARs to declare the same module,
// we repack them to a single file here
unpackComponent(am, "lwjgl3");
if(!installRuntimeAutomatically(am,MultiRTUtils.getRuntimes().size() > 0)) {
MultiRTConfigDialog.openRuntimeSelector(this, MultiRTConfigDialog.MULTIRT_PICK_RUNTIME_STARTUP);
synchronized (mLockSelectJRE) {
mLockSelectJRE.wait();
}
}
migrateToProfiles();
if(Build.VERSION.SDK_INT > 28) runOnUiThread(this::showStorageDialog);
LauncherPreferences.loadPreferences(getApplicationContext());
}
catch(Throwable e){
Tools.showError(this, e);
}
}
private void showStorageDialog() {
if(!firstLaunchPrefs.getBoolean("storageDialogShown",false)) {
AlertDialog.Builder bldr = new AlertDialog.Builder(this);
bldr.setTitle(R.string.storage_warning_title);
Spanned sp = Html.fromHtml(getString(R.string.storage_warning_text,BuildConfig.APPLICATION_ID));
bldr.setMessage(sp);
bldr.setCancelable(false);
bldr.setPositiveButton(android.R.string.ok, (dialog, which)->{
firstLaunchPrefs.edit().putBoolean("storageDialogShown",true).apply();
dialog.dismiss();
});
bldr.show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK) {
if (requestCode == MultiRTConfigDialog.MULTIRT_PICK_RUNTIME_STARTUP) {
if (data != null) {
final Uri uri = data.getData();
Thread t = new Thread(() -> {
try {
MultiRTUtils.installRuntimeNamed(getApplicationContext().getApplicationInfo().nativeLibraryDir, getContentResolver().openInputStream(uri), getFileName(this, uri),
(resid, stuff) -> PojavLoginActivity.this.runOnUiThread(
() -> {
if (startupTextView != null)
startupTextView.setText(PojavLoginActivity.this.getString(resid, stuff));
}));
synchronized (mLockSelectJRE) {
mLockSelectJRE.notifyAll();
}
} catch (IOException e) {
Tools.showError(PojavLoginActivity.this
, e);
}
});
t.start();
}
}else if(requestCode == MicrosoftLoginGUIActivity.AUTHENTICATE_MICROSOFT_REQUEST) {
//Log.i("MicroLoginWrap","Got microsoft login result:" + data);
performMicroLogin(data);
}
}
}
private void migrateToProfiles() {
try {
if(!PerVersionConfig.exists()) return;
LauncherProfiles.update();
PerVersionConfig.update();
if(PerVersionConfig.erase()) {
for (String version : PerVersionConfig.configMap.keySet()) {
PerVersionConfig.VersionConfig config = PerVersionConfig.configMap.get(version);
if(config == null) continue; // Skip the version
// Replaced by gl4es_extra
if(config.renderer != null) {
if (config.renderer.contains("zink")) config.renderer = "opengles3_virgl";
if (!config.renderer.contains("virgl")) config.renderer = null;
}
if(config.renderer == null && config.gamePath == null &&
config.jvmArgs == null && config.selectedRuntime == null){
continue; // Empty pvc, skip it.
}
MinecraftProfile profile = new MinecraftProfile();
profile.lastVersionId = version;
profile.name = getString(R.string.migrated_profile_str, version);
profile.pojavRendererName = config.renderer;
profile.gameDir = config.gamePath;
profile.javaDir = Tools.LAUNCHERPROFILES_RTPREFIX + config.selectedRuntime;
profile.javaArgs = config.jvmArgs;
LauncherProfiles.mainProfileJson.profiles.put("pvc-migrated-" + version, profile);
}
LauncherProfiles.update();
}else{
Log.e("ProfileMigrator"," Unable to remove Per Version Config files.");
}
}catch (IOException e) {
Log.e("ProfileMigrator","Failed to migrate!",e);
}
}
private boolean installRuntimeAutomatically(AssetManager am, boolean otherRuntimesAvailable) {
/* Check if JRE is included */
String rt_version = null;
String current_rt_version = MultiRTUtils.__internal__readBinpackVersion("Internal");
try {
rt_version = Tools.read(am.open("components/jre/version"));
} catch (IOException e) {
Log.e("JREAuto", "JRE was not included on this APK.", e);
}
if(current_rt_version == null && MultiRTUtils.getExactJreName(8) != null) return true; //Assume user maintains his own runtime
if(rt_version == null) return otherRuntimesAvailable; // On noruntime builds, skip if there is at least 1 runtime installed (no matter if it is 8 or not)
if(!rt_version.equals(current_rt_version)) { //If we already have an integrated one installed, check if it's up-to-date
try {
MultiRTUtils.installRuntimeNamedBinpack(getApplicationInfo().nativeLibraryDir, am.open("components/jre/universal.tar.xz"), am.open("components/jre/bin-" + archAsString(Tools.DEVICE_ARCHITECTURE) + ".tar.xz"), "Internal", rt_version,
(resid, vararg) -> runOnUiThread(()->{if(startupTextView!=null)startupTextView.setText(getString(resid,vararg));}));
MultiRTUtils.postPrepare(PojavLoginActivity.this,"Internal");
return true;
}catch (IOException e) {
Log.e("JREAuto", "Internal JRE unpack failed", e);
return false;
}
}else return true; // we have at least one runtime, and it's compartible, good to go
}
private static boolean mkdirs(String path)
{
File file = new File(path);
// check necessary???
if(file.getParentFile().exists())
return file.mkdir();
else return file.mkdirs();
}
public void loginMicrosoft(View view) {
Intent i = new Intent(this,MicrosoftLoginGUIActivity.class);
startActivityForResult(i,MicrosoftLoginGUIActivity.AUTHENTICATE_MICROSOFT_REQUEST);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
public void performMicroLogin(Intent intent) {
Uri data = intent.getData();
//Log.i("MicroAuth", data.toString());
if (data != null && data.getScheme().equals("ms-xal-00000000402b5328") && data.getHost().equals("auth")) {
String error = data.getQueryParameter("error");
String error_description = data.getQueryParameter("error_description");
if (error != null) {
// "The user has denied access to the scope requested by the client application": user pressed Cancel button, skip it
if (!error_description.startsWith("The user has denied access to the scope requested by the client application")) {
Toast.makeText(this, "Error: " + error + ": " + error_description, Toast.LENGTH_LONG).show();
}
} else {
String code = data.getQueryParameter("code");
new MicrosoftAuthTask(this, new RefreshListener(){
@Override
public void onFailed(Throwable e) {
Tools.showError(PojavLoginActivity.this, e);
}
@Override
public void onSuccess(MinecraftAccount b) {
mProfile = b;
playProfile(false);
}
}).execute("false", code);
// Toast.makeText(this, "Logged in to Microsoft account, but NYI", Toast.LENGTH_LONG).show();
}
}
}
private View getViewFromList(int pos, ListView listView) {
final int firstItemPos = listView.getFirstVisiblePosition();
final int lastItemPos = firstItemPos + listView.getChildCount() - 1;
if (pos < firstItemPos || pos > lastItemPos ) {
return listView.getAdapter().getView(pos, null, listView);
} else {
final int childIndex = pos - firstItemPos;
return listView.getChildAt(childIndex);
}
}
public void loginSavedAcc(View view) {
String[] accountArr = new File(Tools.DIR_ACCOUNT_NEW).list();
if(accountArr.length == 0){
showNoAccountDialog();
return;
}
final Dialog accountDialog = new Dialog(PojavLoginActivity.this);
accountDialog.setContentView(R.layout.dialog_select_account);
LinearLayout accountListLayout = accountDialog.findViewById(R.id.accountListLayout);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
for (int accountIndex = 0; accountIndex < accountArr.length; accountIndex++) {
String s = accountArr[accountIndex];
View child = inflater.inflate(R.layout.item_minecraft_account, accountListLayout,false);
TextView accountName = child.findViewById(R.id.accountitem_text_name);
ImageButton removeButton = child.findViewById(R.id.accountitem_button_remove);
ImageView imageView = child.findViewById(R.id.account_head);
String accNameStr = s.substring(0, s.length() - 5);
MinecraftAccount minecraftAccount = MinecraftAccount.load(accNameStr);
if(minecraftAccount != null) {
imageView.setImageBitmap(minecraftAccount.getSkinFace());
}else{
imageView.setImageBitmap(null);
}
accountName.setText(accNameStr);
accountListLayout.addView(child);
accountName.setOnClickListener(new View.OnClickListener() {
final String selectedAccName = accountName.getText().toString();
@Override
public void onClick(View v) {
try {
RefreshListener authListener = new RefreshListener(){
@Override
public void onFailed(Throwable e) {
Tools.showError(PojavLoginActivity.this, e);
}
@Override
public void onSuccess(MinecraftAccount out) {
accountDialog.dismiss();
mProfile = out;
playProfile(true);
}
};
MinecraftAccount acc = MinecraftAccount.load(selectedAccName);
if(acc == null) {
Log.e("Account","Stop torturing me sempai");
return;
}
if (acc.isMicrosoft){
new MicrosoftAuthTask(PojavLoginActivity.this, authListener)
.execute("true", acc.msaRefreshToken);
} else {
accountDialog.dismiss();
PojavProfile.launch(PojavLoginActivity.this, selectedAccName);
}
} catch (Exception e) {
Tools.showError(PojavLoginActivity.this, e);
}
}
});
final int accountIndex_final = accountIndex;
removeButton.setOnClickListener(new View.OnClickListener() {
final String selectedAccName = accountName.getText().toString();
@Override
public void onClick(View v) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(PojavLoginActivity.this);
builder2.setTitle(selectedAccName);
builder2.setMessage(R.string.warning_remove_account);
builder2.setPositiveButton(android.R.string.ok, (p1, p2) -> {
new InvalidateTokenTask(PojavLoginActivity.this).execute(selectedAccName);
accountListLayout.removeViewsInLayout(accountIndex_final, 1);
if (accountListLayout.getChildCount() == 0) {
accountDialog.dismiss(); //No need to keep it, since there is no account
return;
}
//Refreshes the layout with the same settings so it take the missing child into account.
accountListLayout.setLayoutParams(accountListLayout.getLayoutParams());
});
builder2.setNegativeButton(android.R.string.cancel, null);
builder2.show();
}
});
}
accountDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
accountDialog.show();
}
private MinecraftAccount loginLocal() {
new File(Tools.DIR_ACCOUNT_OLD).mkdir();
String text = edit2.getText().toString();
if (text.isEmpty()) {
edit2.setError(getString(R.string.global_error_field_empty));
} else if (text.length() < 3 || text.length() > 16 || !text.matches("\\w+")) {
edit2.setError(getString(R.string.login_error_invalid_username));
} else if (new File(Tools.DIR_ACCOUNT_NEW + "/" + text + ".json").exists()) {
edit2.setError(getString(R.string.login_error_exist_username));
} else {
MinecraftAccount builder = new MinecraftAccount();
builder.isMicrosoft = false;
builder.username = text;
return builder;
}
return null;
}
public void loginMC(final View v)
{
if (sLocal.isChecked()) {
mProfile = loginLocal();
playProfile(false);
} else {
ProgressBar prb = findViewById(R.id.launcherAccProgress);
new LoginTask().setLoginListener(new LoginListener(){
@Override
public void onBeforeLogin() {
v.setEnabled(false);
prb.setVisibility(View.VISIBLE);
}
@Override
public void onLoginDone(String[] result) {
if(result[0].equals("ERROR")){
Tools.dialogOnUiThread(PojavLoginActivity.this,
getResources().getString(R.string.global_error), strArrToString(result));
} else{
MinecraftAccount builder = new MinecraftAccount();
builder.accessToken = result[1];
builder.clientToken = result[2];
builder.profileId = result[3];
builder.username = result[4];
builder.updateSkinFace();
mProfile = builder;
}
runOnUiThread(() -> {
v.setEnabled(true);
prb.setVisibility(View.GONE);
playProfile(false);
});
}
}).execute(edit2.getText().toString(), edit3.getText().toString());
}
}
private void playProfile(boolean notOnLogin) {
if (mProfile != null) {
try {
String profileName = null;
if (sRemember.isChecked() || notOnLogin) {
profileName = mProfile.save();
}
PojavProfile.launch(PojavLoginActivity.this, profileName == null ? mProfile : profileName);
} catch (IOException e) {
Tools.showError(this, e);
}
}
}
public static String strArrToString(String[] strArr)
{
String[] strArrEdit = strArr.clone();
strArrEdit[0] = "";
String str = Arrays.toString(strArrEdit);
str = str.substring(1, str.length() - 1).replace(",", "\n");
return str;
}
//We are calling this method to check the permission status
private boolean isStorageAllowed() {
//Getting the permission status
int result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int result2 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
//If permission is granted returning true
return result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED;
}
//Requesting permission
private void requestStoragePermission()
{
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_REQUEST_CODE);
}
// This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_STORAGE_REQUEST_CODE){
synchronized (mLockStoragePerm) {
mLockStoragePerm.notifyAll();
}
}
}
//When the user have no saved account, you can show him this dialog
private void showNoAccountDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(PojavLoginActivity.this);
builder.setMessage(R.string.login_dialog_no_saved_account)
.setTitle(R.string.login_title_no_saved_account)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
@@ -1,60 +0,0 @@
package net.kdt.pojavlaunch;
import android.content.*;
import java.io.*;
import net.kdt.pojavlaunch.value.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
public class PojavMigrator {
public static void migrateAccountData(Context ctx) {
File oldAccDir = new File(Tools.DIR_ACCOUNT_OLD);
if (oldAccDir.exists() && oldAccDir.isDirectory()) {
for (String account : oldAccDir.list()) {
File oldAccFile = new File(oldAccDir, account);
try {
MCProfile.Builder oldAccStruct = MCProfile.load(oldAccFile.getAbsolutePath());
MinecraftAccount newAccStruct = new MinecraftAccount();
newAccStruct.accessToken = oldAccStruct.getAccessToken();
newAccStruct.clientToken = oldAccStruct.getClientID();
newAccStruct.isMicrosoft = false;
newAccStruct.profileId = oldAccStruct.getProfileID();
newAccStruct.selectedVersion = oldAccStruct.getVersion();
newAccStruct.username = oldAccStruct.getUsername();
newAccStruct.save();
} catch (IOException e) {
Tools.showError(ctx, e);
}
oldAccFile.delete();
}
}
}
public static boolean migrateGameDir() throws IOException {
File oldGameDir = new File(Tools.DIR_GAME_OLD);
boolean moved = oldGameDir.exists() && oldGameDir.isDirectory();
/*
if (!migrateBugFix20201217() && moved) {
command("mv " + Tools.DIR_GAME_OLD + " " + Tools.DIR_GAME_HOME + "/");
}
*/
if(moved) {
oldGameDir.renameTo(new File(Tools.DIR_GAME_NEW + "/"));
FileUtils.deleteDirectory(new File(Tools.DIR_GAME_NEW + "/lwjgl3"));
}
return moved;
}
private static void command(String cmd) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
if (exitCode != 0) {
throw new IOException("Exit code " + exitCode +
", message:\n" + Tools.read(p.getErrorStream()));
}
}
}
@@ -1,121 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import com.google.gson.JsonSyntaxException;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import net.kdt.pojavlaunch.authenticator.mojang.RefreshListener;
import net.kdt.pojavlaunch.authenticator.mojang.RefreshTokenTask;
import net.kdt.pojavlaunch.value.MinecraftAccount;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
public class PojavProfile {
private static final String PROFILE_PREF = "pojav_profile";
private static final String PROFILE_PREF_FILE = "file";
public static String PROFILE_PREF_TEMP_CONTENT = "tempContent";
public static SharedPreferences getPrefs(Context ctx) {
return ctx.getSharedPreferences(PROFILE_PREF, Context.MODE_PRIVATE);
}
public static MinecraftAccount getCurrentProfileContent(Context ctx) throws JsonSyntaxException {
MinecraftAccount build = MinecraftAccount.load(getCurrentProfileName(ctx));
if (build == null) {
System.out.println("isTempProfile null? " + (getTempProfileContent() == null));
return getTempProfileContent();
}
return build;
}
public static MinecraftAccount getTempProfileContent() {
try {
MinecraftAccount account = MinecraftAccount.parse(Tools.read(Tools.DIR_DATA+"/cache/tempacc.json"));
if (account.accessToken == null) {
account.accessToken = "0";
}
if (account.clientToken == null) {
account.clientToken = "0";
}
if (account.profileId == null) {
account.profileId = "00000000-0000-0000-0000-000000000000";
}
if (account.username == null) {
account.username = "0";
}
if (account.selectedVersion == null) {
account.selectedVersion = "1.7.10";
}
if (account.msaRefreshToken == null) {
account.msaRefreshToken = "0";
}
return account;
}catch (IOException e) {
Log.e(MinecraftAccount.class.getName(), "Caught an exception while loading the temporary profile",e);
return null;
}
}
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 boolean setCurrentProfile(Context ctx, Object obj) {
SharedPreferences.Editor pref = getPrefs(ctx).edit();
try {
if (obj instanceof MinecraftAccount) {
try {
MinecraftAccount.saveTempAccount((MinecraftAccount) obj);
} catch (IOException e) {
Tools.showError(ctx, e);
}
} else 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 MinecraftAccount.class, String.class or null");
}
} finally {
return pref.commit();
}
}
public static boolean isFileType(Context ctx) {
return new File(Tools.DIR_ACCOUNT_NEW + "/" + PojavProfile.getCurrentProfileName(ctx) + ".json").exists();
}
public static void launch(Activity ctx, Object o) {
PojavProfile.setCurrentProfile(ctx, o);
LauncherProfiles.update();
if(!LauncherProfiles.mainProfileJson.profilesWereMigrated && LauncherProfiles.mainProfileJson.profiles != null) {
MinecraftProfile defaultProfile = LauncherProfiles.mainProfileJson.profiles.get("(Default)");
if(defaultProfile != null) {
defaultProfile.lastVersionId = PojavProfile.getCurrentProfileContent(ctx).selectedVersion;
}
LauncherProfiles.mainProfileJson.profilesWereMigrated = true;
LauncherProfiles.update();
}
Intent intent = new Intent(ctx, PojavLauncherActivity.class); //MCLauncherActivity.class);
ctx.startActivity(intent);
}
public static void updateTokens(final Activity ctx, final String name, RefreshListener listen) throws Exception {
new RefreshTokenTask(ctx, listen).execute(name);
}
}
@@ -1,11 +0,0 @@
package net.kdt.pojavlaunch;
import android.view.*;
import android.view.GestureDetector.*;
public class SingleTapConfirm extends SimpleOnGestureListener {
@Override
public boolean onSingleTapUp(MotionEvent event) {
return true;
}
}
@@ -1,121 +0,0 @@
package net.kdt.pojavlaunch;
import android.view.MotionEvent;
import static android.view.MotionEvent.ACTION_DOWN;
import static android.view.MotionEvent.ACTION_POINTER_DOWN;
import static android.view.MotionEvent.ACTION_POINTER_UP;
import static android.view.MotionEvent.ACTION_UP;
/**
* Class aiming at better detecting X-tap events regardless of the POINTERS
* Only uses the least amount of events possible,
* since we aren't guaranteed to have all events in order
*/
public class TapDetector {
public final static int DETECTION_METHOD_DOWN = 0x1;
public final static int DETECTION_METHOD_UP = 0x2;
public final static int DETECTION_METHOD_BOTH = 0x3; //Unused for now
private final static int TAP_MIN_DELTA_MS = 10;
private final static int TAP_MAX_DELTA_MS = 300;
private final static int TAP_SLOP_SQUARE_PX = (int) Math.pow(Tools.dpToPx(100), 2);
private final int mTapNumberToDetect;
private int mCurrentTapNumber = 0;
private final int mDetectionMethod;
private long mLastEventTime = 0;
private float mLastX = 9999;
private float mLastY = 9999;
/**
* @param tapNumberToDetect How many taps are needed before onTouchEvent returns True.
* @param detectionMethod Method used to detect touches. See DETECTION_METHOD constants above.
*/
public TapDetector(int tapNumberToDetect, int detectionMethod){
this.mDetectionMethod = detectionMethod;
//We expect both ACTION_DOWN and ACTION_UP for the DETECTION_METHOD_BOTH
this.mTapNumberToDetect = detectBothTouch() ? 2*tapNumberToDetect : tapNumberToDetect;
}
/**
* A function to call when you have a touch event.
* @param e The MotionEvent to inspect
* @return whether or not a X-tap happened for a pointer
*/
public boolean onTouchEvent(MotionEvent e){
int eventAction = e.getActionMasked();
int pointerIndex = -1;
//Get the event to look forward
if(detectDownTouch()){
if(eventAction == ACTION_DOWN) pointerIndex = 0;
else if(eventAction == ACTION_POINTER_DOWN) pointerIndex = e.getActionIndex();
}
if(detectUpTouch()){
if(eventAction == ACTION_UP) pointerIndex = 0;
else if(eventAction == ACTION_POINTER_UP) pointerIndex = e.getActionIndex();
}
if(pointerIndex == -1) return false; // Useless event
//Store current event info
float eventX = e.getX(pointerIndex);
float eventY = e.getY(pointerIndex);
long eventTime = e.getEventTime();
//Compute deltas
long deltaTime = eventTime - mLastEventTime;
int deltaX = (int) mLastX - (int) eventX;
int deltaY = (int) mLastY - (int) eventY;
//Store current event info to persist on next event
mLastEventTime = eventTime;
mLastX = eventX;
mLastY = eventY;
//Check for high enough speed and precision
if(mCurrentTapNumber > 0){
if ((deltaTime < TAP_MIN_DELTA_MS || deltaTime > TAP_MAX_DELTA_MS) ||
((deltaX*deltaX + deltaY*deltaY) > TAP_SLOP_SQUARE_PX)) {
// We invalidate previous taps, not this one though
mCurrentTapNumber = 0;
}
}
//A worthy tap happened
mCurrentTapNumber += 1;
if(mCurrentTapNumber >= mTapNumberToDetect){
resetTapDetectionState();
return true;
}
//If not enough taps are reached
return false;
}
/**
* Reset the double tap values.
*/
private void resetTapDetectionState(){
mCurrentTapNumber = 0;
mLastEventTime = 0;
mLastX = 9999;
mLastY = 9999;
}
private boolean detectDownTouch(){
return (mDetectionMethod & DETECTION_METHOD_DOWN) == DETECTION_METHOD_DOWN;
}
private boolean detectUpTouch(){
return (mDetectionMethod & DETECTION_METHOD_UP) == DETECTION_METHOD_UP;
}
private boolean detectBothTouch(){
return mDetectionMethod == DETECTION_METHOD_BOTH;
}
}
@@ -1,890 +0,0 @@
package net.kdt.pojavlaunch;
import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.net.*;
import android.os.*;
import android.provider.OpenableColumns;
import android.system.*;
import android.util.*;
import com.google.gson.*;
import com.oracle.dalvik.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.zip.*;
import net.kdt.pojavlaunch.prefs.*;
import net.kdt.pojavlaunch.utils.*;
import net.kdt.pojavlaunch.value.*;
import net.kdt.pojavlaunch.value.launcherprofiles.LauncherProfiles;
import net.kdt.pojavlaunch.value.launcherprofiles.MinecraftProfile;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.lwjgl.glfw.*;
import android.view.*;
import android.widget.Toast;
import static android.os.Build.VERSION.SDK_INT;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_IGNORE_NOTCH;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.PREF_NOTCH_SIZE;
public final class Tools {
public static final boolean ENABLE_DEV_FEATURES = BuildConfig.DEBUG;
public static String APP_NAME = "null";
public static final Gson GLOBAL_GSON = new GsonBuilder().setPrettyPrinting().create();
public static final String URL_HOME = "https://pojavlauncherteam.github.io/PojavLauncher";
public static String DIR_DATA; //Initialized later to get context
public static String MULTIRT_HOME;
public static String LOCAL_RENDERER = null;
public static int DEVICE_ARCHITECTURE;
public static String LAUNCHERPROFILES_RTPREFIX = "pojav://";
// New since 3.3.1
public static String DIR_ACCOUNT_NEW;
public static String DIR_ACCOUNT_OLD;
public static String DIR_GAME_HOME = Environment.getExternalStorageDirectory().getAbsolutePath() + "/games/PojavLauncher";
public static String DIR_GAME_NEW;
public static String DIR_GAME_OLD = Environment.getExternalStorageDirectory().getAbsolutePath() + "/games/.minecraft";
// New since 3.0.0
public static String DIR_HOME_JRE;
public static String DIRNAME_HOME_JRE = "lib";
// New since 2.4.2
public static String DIR_HOME_VERSION;
public static String DIR_HOME_LIBRARY;
public static String DIR_HOME_CRASH;
public static String ASSETS_PATH;
public static String OBSOLETE_RESOURCES_PATH;
public static String CTRLMAP_PATH;
public static String CTRLDEF_FILE;
public static final String LIBNAME_OPTIFINE = "optifine:OptiFine";
/**
* Since some constant requires the use of the Context object
* You can call this function to initialize them.
* Any value (in)directly dependant on DIR_DATA should be set only here.
*/
public static void initContextConstants(Context ctx){
DIR_DATA = ctx.getFilesDir().getParent();
MULTIRT_HOME = DIR_DATA+"/runtimes";
if(SDK_INT >= 29) {
DIR_GAME_HOME = ctx.getExternalFilesDir(null).getAbsolutePath();
}else{
DIR_GAME_HOME = new File(Environment.getExternalStorageDirectory(),"games/PojavLauncher").getAbsolutePath();
}
DIR_GAME_NEW = DIR_GAME_HOME + "/.minecraft";
DIR_HOME_VERSION = DIR_GAME_NEW + "/versions";
DIR_HOME_LIBRARY = DIR_GAME_NEW + "/libraries";
DIR_HOME_CRASH = DIR_GAME_NEW + "/crash-reports";
ASSETS_PATH = DIR_GAME_NEW + "/assets";
OBSOLETE_RESOURCES_PATH= DIR_GAME_NEW + "/resources";
CTRLMAP_PATH = DIR_GAME_HOME + "/controlmap";
CTRLDEF_FILE = DIR_GAME_HOME + "/controlmap/default.json";
}
public static void launchMinecraft(final Activity activity, MinecraftAccount profile, String versionName) throws Throwable {
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
((ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryInfo(mi);
if(LauncherPreferences.PREF_RAM_ALLOCATION > (mi.availMem/1048576L)) {
Object memoryErrorLock = new Object();
activity.runOnUiThread(() -> {
androidx.appcompat.app.AlertDialog.Builder b = new androidx.appcompat.app.AlertDialog.Builder(activity)
.setMessage(activity.getString(R.string.memory_warning_msg,(mi.availMem/1048576L),LauncherPreferences.PREF_RAM_ALLOCATION))
.setPositiveButton(android.R.string.ok, (dialogInterface, i) -> {synchronized(memoryErrorLock){memoryErrorLock.notifyAll();}})
.setOnCancelListener((i) -> {synchronized(memoryErrorLock){memoryErrorLock.notifyAll();}});
b.show();
});
synchronized (memoryErrorLock) {
memoryErrorLock.wait();
}
}
JMinecraftVersionList.Version versionInfo = Tools.getVersionInfo(null,versionName);
String gamedirPath = Tools.DIR_GAME_NEW;
if(activity instanceof BaseMainActivity) {
LauncherProfiles.update();
MinecraftProfile minecraftProfile = ((BaseMainActivity)activity).minecraftProfile;
if(minecraftProfile == null) throw new Exception("Launching empty Profile");
if(minecraftProfile.gameDir != null && minecraftProfile.gameDir.startsWith(Tools.LAUNCHERPROFILES_RTPREFIX))
gamedirPath = minecraftProfile.gameDir.replace(Tools.LAUNCHERPROFILES_RTPREFIX,Tools.DIR_GAME_HOME+"/");
if(minecraftProfile.javaArgs != null && !minecraftProfile.javaArgs.isEmpty())
LauncherPreferences.PREF_CUSTOM_JAVA_ARGS = minecraftProfile.javaArgs;
}
PojavLoginActivity.disableSplash(gamedirPath);
String[] launchArgs = getMinecraftClientArgs(profile, versionInfo, gamedirPath);
// Select the appropriate openGL version
OldVersionsUtils.selectOpenGlVersion(versionInfo);
// ctx.appendlnToLog("Minecraft Args: " + Arrays.toString(launchArgs));
String launchClassPath = generateLaunchClassPath(versionInfo,versionName);
List<String> javaArgList = new ArrayList<String>();
// Only Java 8 supports headful AWT for now
if (JREUtils.jreReleaseList.get("JAVA_VERSION").equals("1.8.0")) {
getCacioJavaArgs(javaArgList, false);
} else if (LauncherPreferences.PREF_ARC_CAPES) {
// Opens the java.net package to Arc DNS injector on Java 9+
javaArgList.add("--add-opens=java.base/java.net=ALL-UNNAMED");
}
/*
int mcReleaseDate = Integer.parseInt(versionInfo.releaseTime.substring(0, 10).replace("-", ""));
// 13w17a: 20130425
// 13w18a: 20130502
if (mcReleaseDate < 20130502 && versionInfo.minimumLauncherVersion < 9){
ctx.appendlnToLog("AWT-enabled version detected! ("+mcReleaseDate+")");
getCacioJavaArgs(javaArgList,false);
}else{
getCacioJavaArgs(javaArgList,false); // true
ctx.appendlnToLog("Headless version detected! ("+mcReleaseDate+")");
}
*/
if (versionInfo.logging != null) {
javaArgList.add("-Dlog4j.configurationFile=" + Tools.DIR_GAME_NEW + "/" + versionInfo.logging.client.file.id);
}
javaArgList.addAll(Arrays.asList(getMinecraftJVMArgs(versionName, gamedirPath)));
javaArgList.add("-cp");
javaArgList.add(getLWJGL3ClassPath() + ":" + launchClassPath);
javaArgList.add(versionInfo.mainClass);
javaArgList.addAll(Arrays.asList(launchArgs));
// ctx.appendlnToLog("full args: "+javaArgList.toString());
JREUtils.launchJavaVM(activity, javaArgList);
}
public static void getCacioJavaArgs(List<String> javaArgList, boolean isHeadless) {
javaArgList.add("-Djava.awt.headless="+isHeadless);
// Caciocavallo config AWT-enabled version
javaArgList.add("-Dcacio.managed.screensize=" + AWTCanvasView.AWT_CANVAS_WIDTH + "x" + AWTCanvasView.AWT_CANVAS_HEIGHT);
// javaArgList.add("-Dcacio.font.fontmanager=net.java.openjdk.cacio.ctc.CTCFontManager");
javaArgList.add("-Dcacio.font.fontmanager=sun.awt.X11FontManager");
javaArgList.add("-Dcacio.font.fontscaler=sun.font.FreetypeFontScaler");
javaArgList.add("-Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel");
javaArgList.add("-Dawt.toolkit=net.java.openjdk.cacio.ctc.CTCToolkit");
javaArgList.add("-Djava.awt.graphicsenv=net.java.openjdk.cacio.ctc.CTCGraphicsEnvironment");
StringBuilder cacioClasspath = new StringBuilder();
cacioClasspath.append("-Xbootclasspath/p");
File cacioDir = new File(DIR_GAME_HOME + "/caciocavallo");
if (cacioDir.exists() && cacioDir.isDirectory()) {
for (File file : cacioDir.listFiles()) {
if (file.getName().endsWith(".jar")) {
cacioClasspath.append(":" + file.getAbsolutePath());
}
}
}
javaArgList.add(cacioClasspath.toString());
}
public static String[] getMinecraftJVMArgs(String versionName, String strGameDir) {
JMinecraftVersionList.Version versionInfo = Tools.getVersionInfo(null, versionName, true);
// Parse Forge 1.17+ additional JVM Arguments
if (versionInfo.inheritsFrom == null || versionInfo.arguments == null || versionInfo.arguments.jvm == null) {
return new String[0];
}
Map<String, String> varArgMap = new ArrayMap<>();
varArgMap.put("classpath_separator", ":");
varArgMap.put("library_directory", strGameDir + "/libraries");
varArgMap.put("version_name", versionInfo.id);
List<String> minecraftArgs = new ArrayList<String>();
if (versionInfo.arguments != null) {
for (Object arg : versionInfo.arguments.jvm) {
if (arg instanceof String) {
minecraftArgs.add((String) arg);
} else {
/*
JMinecraftVersionList.Arguments.ArgValue argv = (JMinecraftVersionList.Arguments.ArgValue) arg;
if (argv.values != null) {
minecraftArgs.add(argv.values[0]);
} else {
for (JMinecraftVersionList.Arguments.ArgValue.ArgRules rule : arg.rules) {
// rule.action = allow
// TODO implement this
}
}
*/
}
}
}
String[] argsFromJson = JSONUtils.insertJSONValueList(minecraftArgs.toArray(new String[0]), varArgMap);
// Tools.dialogOnUiThread(this, "Result args", Arrays.asList(argsFromJson).toString());
return argsFromJson;
}
public static String[] getMinecraftClientArgs(MinecraftAccount profile, JMinecraftVersionList.Version versionInfo, String strGameDir) {
String username = profile.username;
String versionName = versionInfo.id;
if (versionInfo.inheritsFrom != null) {
versionName = versionInfo.inheritsFrom;
}
String userType = "mojang";
File gameDir = new File(strGameDir);
gameDir.mkdirs();
Map<String, String> varArgMap = new ArrayMap<>();
varArgMap.put("auth_access_token", profile.accessToken);
varArgMap.put("auth_player_name", username);
varArgMap.put("auth_uuid", profile.profileId);
varArgMap.put("assets_root", Tools.ASSETS_PATH);
varArgMap.put("assets_index_name", versionInfo.assets);
varArgMap.put("game_assets", Tools.ASSETS_PATH);
varArgMap.put("game_directory", gameDir.getAbsolutePath());
varArgMap.put("user_properties", "{}");
varArgMap.put("user_type", userType);
varArgMap.put("version_name", versionName);
varArgMap.put("version_type", versionInfo.type);
List<String> minecraftArgs = new ArrayList<String>();
if (versionInfo.arguments != null) {
// Support Minecraft 1.13+
for (Object arg : versionInfo.arguments.game) {
if (arg instanceof String) {
minecraftArgs.add((String) arg);
} else {
/*
JMinecraftVersionList.Arguments.ArgValue argv = (JMinecraftVersionList.Arguments.ArgValue) arg;
if (argv.values != null) {
minecraftArgs.add(argv.values[0]);
} else {
for (JMinecraftVersionList.Arguments.ArgValue.ArgRules rule : arg.rules) {
// rule.action = allow
// TODO implement this
}
}
*/
}
}
}
/*
minecraftArgs.add("--width");
minecraftArgs.add(Integer.toString(CallbackBridge.windowWidth));
minecraftArgs.add("--height");
minecraftArgs.add(Integer.toString(CallbackBridge.windowHeight));
minecraftArgs.add("--fullscreenWidth");
minecraftArgs.add(Integer.toString(CallbackBridge.windowWidth));
minecraftArgs.add("--fullscreenHeight");
minecraftArgs.add(Integer.toString(CallbackBridge.windowHeight));
*/
String[] argsFromJson = JSONUtils.insertJSONValueList(
splitAndFilterEmpty(
versionInfo.minecraftArguments == null ?
fromStringArray(minecraftArgs.toArray(new String[0])):
versionInfo.minecraftArguments
), varArgMap
);
// Tools.dialogOnUiThread(this, "Result args", Arrays.asList(argsFromJson).toString());
return argsFromJson;
}
public static String fromStringArray(String[] strArr) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < strArr.length; i++) {
if (i > 0) builder.append(" ");
builder.append(strArr[i]);
}
return builder.toString();
}
private static String[] splitAndFilterEmpty(String argStr) {
List<String> strList = new ArrayList<String>();
for (String arg : argStr.split(" ")) {
if (!arg.isEmpty()) {
strList.add(arg);
}
}
//strList.add("--fullscreen");
return strList.toArray(new String[0]);
}
public static String artifactToPath(String name) {
int idx = name.indexOf(":");
assert idx != -1;
int idx2 = name.indexOf(":", idx+1);
assert idx2 != -1;
String group = name.substring(0, idx);
String artifact = name.substring(idx+1, idx2);
String version = name.substring(idx2+1).replace(':','-');
return group.replaceAll("\\.", "/") + "/" + artifact + "/" + version + "/" + artifact + "-" + version + ".jar";
}
public static String getPatchedFile(String version) {
return DIR_HOME_VERSION + "/" + version + "/" + version + ".jar";
}
private static String getLWJGL3ClassPath() {
StringBuilder libStr = new StringBuilder();
File lwjgl3Folder = new File(Tools.DIR_GAME_HOME, "lwjgl3");
if (/* info.arguments != null && */ lwjgl3Folder.exists()) {
for (File file: lwjgl3Folder.listFiles()) {
if (file.getName().endsWith(".jar")) {
libStr.append(file.getAbsolutePath() + ":");
}
}
}
// Remove the ':' at the end
libStr.setLength(libStr.length() - 1);
return libStr.toString();
}
private static boolean isClientFirst = false;
public static String generateLaunchClassPath(JMinecraftVersionList.Version info,String actualname) {
StringBuilder libStr = new StringBuilder(); //versnDir + "/" + version + "/" + version + ".jar:";
String[] classpath = generateLibClasspath(info);
// Debug: LWJGL 3 override
// File lwjgl2Folder = new File(Tools.MAIN_PATH, "lwjgl2");
/*
File lwjgl3Folder = new File(Tools.MAIN_PATH, "lwjgl3");
if (lwjgl3Folder.exists()) {
for (File file: lwjgl3Folder.listFiles()) {
if (file.getName().endsWith(".jar")) {
libStr.append(file.getAbsolutePath() + ":");
}
}
} else if (lwjgl2Folder.exists()) {
for (File file: lwjgl2Folder.listFiles()) {
if (file.getName().endsWith(".jar")) {
libStr.append(file.getAbsolutePath() + ":");
}
}
}
*/
if (isClientFirst) {
libStr.append(getPatchedFile(actualname));
}
for (String perJar : classpath) {
if (!new File(perJar).exists()) {
Log.d(APP_NAME, "Ignored non-exists file: " + perJar);
continue;
}
libStr.append((isClientFirst ? ":" : "") + perJar + (!isClientFirst ? ":" : ""));
}
if (!isClientFirst) {
libStr.append(getPatchedFile(actualname));
}
return libStr.toString();
}
public static DisplayMetrics getDisplayMetrics(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
if(SDK_INT >= Build.VERSION_CODES.N && (activity.isInMultiWindowMode() || activity.isInPictureInPictureMode())){
//For devices with free form/split screen, we need window size, not screen size.
displayMetrics = activity.getResources().getDisplayMetrics();
}else{
if (SDK_INT >= Build.VERSION_CODES.R) {
activity.getDisplay().getRealMetrics(displayMetrics);
} else {
activity.getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
}
if(!PREF_IGNORE_NOTCH){
//Remove notch width when it isn't ignored.
displayMetrics.widthPixels -= PREF_NOTCH_SIZE;
}
}
currentDisplayMetrics = displayMetrics;
return displayMetrics;
}
public static void setFullscreen(Activity activity) {
final View decorView = activity.getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener (visibility -> {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
});
}
public static DisplayMetrics currentDisplayMetrics;
public static void updateWindowSize(Activity activity) {
currentDisplayMetrics = getDisplayMetrics(activity);
CallbackBridge.physicalWidth = currentDisplayMetrics.widthPixels;
CallbackBridge.physicalHeight = currentDisplayMetrics.heightPixels;
}
public static float dpToPx(float dp) {
//Better hope for the currentDisplayMetrics to be good
return dp * currentDisplayMetrics.density;
}
public static float pxToDp(float px){
//Better hope for the currentDisplayMetrics to be good
return px / currentDisplayMetrics.density;
}
public static void copyAssetFile(Context ctx, String fileName, String output, boolean overwrite) throws IOException {
copyAssetFile(ctx, fileName, output, new File(fileName).getName(), overwrite);
}
public static void copyAssetFile(Context ctx, String fileName, String output, String outputName, boolean overwrite) throws IOException
{
File file = new File(output);
if(!file.exists()) {
file.mkdirs();
}
File file2 = new File(output, outputName);
if(!file2.exists() || overwrite){
write(file2.getAbsolutePath(), loadFromAssetToByte(ctx, fileName));
}
}
public static void showError(Context ctx, Throwable e) {
showError(ctx, e, false);
}
public static void showError(final Context ctx, final Throwable e, final boolean exitIfOk) {
showError(ctx, R.string.global_error, e, exitIfOk, false);
}
public static void showError(final Context ctx, final int titleId, final Throwable e, final boolean exitIfOk) {
showError(ctx, titleId, e, exitIfOk, false);
}
private static void showError(final Context ctx, final int titleId, final Throwable e, final boolean exitIfOk, final boolean showMore) {
e.printStackTrace();
Runnable runnable = () -> {
final String errMsg = showMore ? Log.getStackTraceString(e): e.getMessage();
AlertDialog.Builder builder = new AlertDialog.Builder((Context) ctx)
.setTitle(titleId)
.setMessage(errMsg)
.setPositiveButton(android.R.string.ok, (DialogInterface.OnClickListener) (p1, p2) -> {
if(exitIfOk) {
if (ctx instanceof BaseMainActivity) {
BaseMainActivity.fullyExit();
} else if (ctx instanceof Activity) {
((Activity) ctx).finish();
}
}
})
.setNegativeButton(showMore ? R.string.error_show_less : R.string.error_show_more, (DialogInterface.OnClickListener) (p1, p2) -> showError(ctx, titleId, e, exitIfOk, !showMore))
.setNeutralButton(android.R.string.copy, (DialogInterface.OnClickListener) (p1, p2) -> {
ClipboardManager mgr = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
mgr.setPrimaryClip(ClipData.newPlainText("error", Log.getStackTraceString(e)));
if(exitIfOk) {
if (ctx instanceof BaseMainActivity) {
BaseMainActivity.fullyExit();
} else {
((Activity) ctx).finish();
}
}
})
.setCancelable(!exitIfOk);
try {
builder.show();
} catch (Throwable th) {
th.printStackTrace();
}
};
if (ctx instanceof Activity) {
((Activity) ctx).runOnUiThread(runnable);
} else {
runnable.run();
}
}
public static void dialogOnUiThread(final Activity activity, final CharSequence title, final CharSequence message) {
activity.runOnUiThread(() -> new AlertDialog.Builder(activity)
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, null)
.show());
}
public static void moveInside(String from, String to) {
File fromFile = new File(from);
for (File fromInside : fromFile.listFiles()) {
moveRecursive(fromInside.getAbsolutePath(), to);
}
fromFile.delete();
}
public static void moveRecursive(String from, String to) {
moveRecursive(new File(from), new File(to));
}
public static void moveRecursive(File from, File to) {
File toFrom = new File(to, from.getName());
try {
if (from.isDirectory()) {
for (File child : from.listFiles()) {
moveRecursive(child, toFrom);
}
}
} finally {
from.getParentFile().mkdirs();
from.renameTo(toFrom);
}
}
public static void openURL(Activity act, String url) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
act.startActivity(browserIntent);
}
private static boolean checkRules(JMinecraftVersionList.Arguments.ArgValue.ArgRules[] rules) {
if(rules == null) return true; // always allow
for (JMinecraftVersionList.Arguments.ArgValue.ArgRules rule : rules) {
if (rule.action.equals("allow") && rule.os != null && rule.os.name.equals("osx")) {
return false; //disallow
}
}
return true; // allow if none match
}
public static String[] generateLibClasspath(JMinecraftVersionList.Version info) {
List<String> libDir = new ArrayList<String>();
for (DependentLibrary libItem: info.libraries) {
if(!checkRules(libItem.rules)) continue;
libDir.add(Tools.DIR_HOME_LIBRARY + "/" + Tools.artifactToPath(libItem.name));
}
return libDir.toArray(new String[0]);
}
public static JMinecraftVersionList.Version getVersionInfo(BaseLauncherActivity bla, String versionName) {
return getVersionInfo(bla, versionName, false);
}
public static JMinecraftVersionList.Version getVersionInfo(BaseLauncherActivity bla, String versionName, boolean skipInheriting) {
try {
JMinecraftVersionList.Version customVer = Tools.GLOBAL_GSON.fromJson(read(DIR_HOME_VERSION + "/" + versionName + "/" + versionName + ".json"), JMinecraftVersionList.Version.class);
for (DependentLibrary lib : customVer.libraries) {
if (lib.name.startsWith(LIBNAME_OPTIFINE)) {
customVer.optifineLib = lib;
}
}
if (skipInheriting || customVer.inheritsFrom == null || customVer.inheritsFrom.equals(customVer.id)) {
return customVer;
} else {
JMinecraftVersionList.Version inheritsVer = null;
if(bla != null) if (bla.mVersionList != null) {
for (JMinecraftVersionList.Version valueVer : bla.mVersionList.versions) {
if (valueVer.id.equals(customVer.inheritsFrom) && (!new File(DIR_HOME_VERSION + "/" + customVer.inheritsFrom + "/" + customVer.inheritsFrom + ".json").exists()) && (valueVer.url != null)) {
Tools.downloadFile(valueVer.url,DIR_HOME_VERSION + "/" + customVer.inheritsFrom + "/" + customVer.inheritsFrom + ".json");
}
}
}//If it won't download, just search for it
try{
inheritsVer = Tools.GLOBAL_GSON.fromJson(read(DIR_HOME_VERSION + "/" + customVer.inheritsFrom + "/" + customVer.inheritsFrom + ".json"), JMinecraftVersionList.Version.class);
}catch(IOException e) {
throw new RuntimeException("Can't find the source version for "+ versionName +" (req version="+customVer.inheritsFrom+")");
}
//inheritsVer.inheritsFrom = inheritsVer.id;
insertSafety(inheritsVer, customVer,
"assetIndex", "assets", "id",
"mainClass", "minecraftArguments",
"optifineLib", "releaseTime", "time", "type"
);
List<DependentLibrary> libList = new ArrayList<DependentLibrary>(Arrays.asList(inheritsVer.libraries));
try {
loop_1:
for (DependentLibrary lib : customVer.libraries) {
String libName = lib.name.substring(0, lib.name.lastIndexOf(":"));
for (int i = 0; i < libList.size(); i++) {
DependentLibrary libAdded = libList.get(i);
String libAddedName = libAdded.name.substring(0, libAdded.name.lastIndexOf(":"));
if (libAddedName.equals(libName)) {
Log.d(APP_NAME, "Library " + libName + ": Replaced version " +
libName.substring(libName.lastIndexOf(":") + 1) + " with " +
libAddedName.substring(libAddedName.lastIndexOf(":") + 1));
libList.set(i, lib);
continue loop_1;
}
}
libList.add(lib);
}
} finally {
inheritsVer.libraries = libList.toArray(new DependentLibrary[0]);
}
// Inheriting Minecraft 1.13+ with append custom args
if (inheritsVer.arguments != null && customVer.arguments != null) {
List totalArgList = new ArrayList();
totalArgList.addAll(Arrays.asList(inheritsVer.arguments.game));
int nskip = 0;
for (int i = 0; i < customVer.arguments.game.length; i++) {
if (nskip > 0) {
nskip--;
continue;
}
Object perCustomArg = customVer.arguments.game[i];
if (perCustomArg instanceof String) {
String perCustomArgStr = (String) perCustomArg;
// Check if there is a duplicate argument on combine
if (perCustomArgStr.startsWith("--") && totalArgList.contains(perCustomArgStr)) {
perCustomArg = customVer.arguments.game[i + 1];
if (perCustomArg instanceof String) {
perCustomArgStr = (String) perCustomArg;
// If the next is argument value, skip it
if (!perCustomArgStr.startsWith("--")) {
nskip++;
}
}
} else {
totalArgList.add(perCustomArgStr);
}
} else if (!totalArgList.contains(perCustomArg)) {
totalArgList.add(perCustomArg);
}
}
inheritsVer.arguments.game = totalArgList.toArray(new Object[0]);
}
return inheritsVer;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Prevent NullPointerException
private static void insertSafety(JMinecraftVersionList.Version targetVer, JMinecraftVersionList.Version fromVer, String... keyArr) {
for (String key : keyArr) {
Object value = null;
try {
Field fieldA = fromVer.getClass().getDeclaredField(key);
value = fieldA.get(fromVer);
if (((value instanceof String) && !((String) value).isEmpty()) || value != null) {
Field fieldB = targetVer.getClass().getDeclaredField(key);
fieldB.set(targetVer, value);
}
} catch (Throwable th) {
Log.w(Tools.APP_NAME, "Unable to insert " + key + "=" + value, th);
}
}
}
public static String convertStream(InputStream inputStream) throws IOException {
return convertStream(inputStream, Charset.forName("UTF-8"));
}
public static String convertStream(InputStream inputStream, Charset charset) throws IOException {
StringBuilder out = new StringBuilder();
int len;
byte[] buf = new byte[512];
while((len = inputStream.read(buf))!=-1) {
out.append(new String(buf, 0, len, charset));
}
return out.toString();
}
public static File lastFileModified(String dir) {
File fl = new File(dir);
File[] files = fl.listFiles(File::isFile);
if(files == null) {
return null;
// The patch was a bit wrong...
// So, this may be null, why? Because this folder may not exist yet
// Or it may not have any files...
// Doesn't matter. We must check for that in the crash fragment.
}
long lastMod = Long.MIN_VALUE;
File choice = null;
for (File file : files) {
if (file.lastModified() > lastMod) {
choice = file;
lastMod = file.lastModified();
}
}
return choice;
}
public static String read(InputStream is) throws IOException {
StringBuilder out = new StringBuilder();
int len;
byte[] buf = new byte[512];
while((len = is.read(buf))!=-1) {
out.append(new String(buf, 0, len));
}
return out.toString();
}
public static String read(String path) throws IOException {
return read(new FileInputStream(path));
}
public static void write(String path, byte[] content) throws IOException
{
File outPath = new File(path);
outPath.getParentFile().mkdirs();
outPath.createNewFile();
BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path));
fos.write(content, 0, content.length);
fos.close();
}
public static void write(String path, String content) throws IOException {
write(path, content.getBytes());
}
public static byte[] loadFromAssetToByte(Context ctx, String inFile) {
byte[] buffer = null;
try {
InputStream stream = ctx.getAssets().open(inFile);
int size = stream.available();
buffer = new byte[size];
stream.read(buffer);
stream.close();
} catch (IOException e) {
// Handle exceptions here
e.printStackTrace();
}
return buffer;
}
public static void downloadFile(String urlInput, String nameOutput) throws IOException {
File file = new File(nameOutput);
DownloadUtils.downloadFile(urlInput, file);
}
public abstract static class DownloaderFeedback {
public abstract void updateProgress(int curr, int max);
}
public static void downloadFileMonitored(String urlInput,String nameOutput, DownloaderFeedback monitor) throws IOException {
File nameOutputFile = new File(nameOutput);
if (!nameOutputFile.exists()) {
nameOutputFile.getParentFile().mkdirs();
}
HttpURLConnection conn = (HttpURLConnection) new URL(urlInput).openConnection();
InputStream readStr = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(nameOutputFile);
int cur = 0;
int oval = 0;
int len = conn.getContentLength();
byte[] buf = new byte[65535];
while ((cur = readStr.read(buf)) != -1) {
oval += cur;
fos.write(buf, 0, cur);
monitor.updateProgress(oval, len);
}
fos.close();
conn.disconnect();
}
public static boolean compareSHA1(File f, String sourceSHA) {
try {
String sha1_dst;
try (InputStream is = new FileInputStream(f)) {
sha1_dst = new String(Hex.encodeHex(org.apache.commons.codec.digest.DigestUtils.sha1(is)));
}
if(sha1_dst != null && sourceSHA != null) {
return sha1_dst.equalsIgnoreCase(sourceSHA);
} else{
return true; // fake match
}
}catch (IOException e) {
Log.i("SHA1","Fake-matching a hash due to a read error",e);
return true;
}
}
public static void ignoreNotch(boolean shouldIgnore, Activity ctx){
if (SDK_INT >= P) {
if (shouldIgnore) {
ctx.getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
} else {
ctx.getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
}
ctx.getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
Tools.updateWindowSize(ctx);
}
}
public static int getTotalDeviceMemory(Context ctx){
ActivityManager actManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
return (int) (memInfo.totalMem / 1048576L);
}
public static int getFreeDeviceMemory(Context ctx){
ActivityManager actManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
return (int) (memInfo.availMem / 1048576L);
}
public static int getDisplayFriendlyRes(int displaySideRes, float scaling){
displaySideRes *= scaling;
if(displaySideRes % 2 != 0) displaySideRes ++;
return displaySideRes;
}
public static String getFileName(Context ctx, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = ctx.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
}
@@ -1,189 +0,0 @@
package net.kdt.pojavlaunch;
import static net.kdt.pojavlaunch.MinecraftGLSurface.FINGER_SCROLL_THRESHOLD;
import static net.kdt.pojavlaunch.Tools.currentDisplayMetrics;
import static net.kdt.pojavlaunch.prefs.LauncherPreferences.DEFAULT_PREF;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.res.ResourcesCompat;
import net.kdt.pojavlaunch.prefs.LauncherPreferences;
import org.lwjgl.glfw.CallbackBridge;
/**
* Class dealing with the virtual mouse
*/
public class Touchpad extends FrameLayout {
/* Whether the Touchpad should be displayed */
private boolean mDisplayState;
/* Mouse pointer icon used by the touchpad */
private final ImageView mMousePointerImageView = new ImageView(getContext());
/* Detect a classic android Tap */
private final GestureDetector mSingleTapDetector = new GestureDetector(getContext(), new SingleTapConfirm());
/* Resolution scaler option, allow downsizing a window */
private final float mScaleFactor = DEFAULT_PREF.getInt("resolutionRatio",100)/100f;
/* Current pointer ID to move the mouse */
private int mCurrentPointerID = -1000;
/* Previous MotionEvent position, not scale */
private float mPrevX, mPrevY;
/* Last first pointer positions non-scaled, used to scroll distance */
private float mScrollLastInitialX, mScrollLastInitialY;
public Touchpad(@NonNull Context context) {
this(context, null);
}
public Touchpad(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// MotionEvent reports input details from the touch screen
// and other input controls. In this case, you are only
// interested in events where the touch position changed.
// int index = event.getActionIndex();
if(CallbackBridge.isGrabbing()) {
disable();
return false;
}
int action = event.getActionMasked();
float x = event.getX();
float y = event.getY();
float mouseX = mMousePointerImageView.getX();
float mouseY = mMousePointerImageView.getY();
if (mSingleTapDetector.onTouchEvent(event)) {
CallbackBridge.mouseX = (mouseX * mScaleFactor);
CallbackBridge.mouseY = (mouseY * mScaleFactor);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
CallbackBridge.sendMouseKeycode(LwjglGlfwKeycode.GLFW_MOUSE_BUTTON_LEFT);
return true;
}
switch (action) {
case MotionEvent.ACTION_POINTER_DOWN: // 5
mScrollLastInitialX = event.getX();
mScrollLastInitialY = event.getY();
break;
case MotionEvent.ACTION_DOWN:
mPrevX = x;
mPrevY = y;
mCurrentPointerID = event.getPointerId(0);
break;
case MotionEvent.ACTION_MOVE: // 2
//Scrolling feature
if (!LauncherPreferences.PREF_DISABLE_GESTURES && !CallbackBridge.isGrabbing() && event.getPointerCount() >= 2) {
int hScroll = ((int) (event.getX() - mScrollLastInitialX)) / FINGER_SCROLL_THRESHOLD;
int vScroll = ((int) (event.getY() - mScrollLastInitialY)) / FINGER_SCROLL_THRESHOLD;
if(vScroll != 0 || hScroll != 0){
CallbackBridge.sendScroll(hScroll, vScroll);
mScrollLastInitialX = event.getX();
mScrollLastInitialY = event.getY();
}
break;
}
// Mouse movement
if(mCurrentPointerID == event.getPointerId(0)) {
mouseX = Math.max(0, Math.min(currentDisplayMetrics.widthPixels, mouseX + (x - mPrevX) * LauncherPreferences.PREF_MOUSESPEED));
mouseY = Math.max(0, Math.min(currentDisplayMetrics.heightPixels, mouseY + (y - mPrevY) * LauncherPreferences.PREF_MOUSESPEED));
placeMouseAt(mouseX, mouseY);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
}else mCurrentPointerID = event.getPointerId(0);
mPrevX = x;
mPrevY = y;
break;
case MotionEvent.ACTION_UP:
mPrevX = x;
mPrevY = y;
mCurrentPointerID = -1000;
break;
}
//debugText.setText(CallbackBridge.DEBUG_STRING.toString());
CallbackBridge.DEBUG_STRING.setLength(0);
return true;
}
/** Enable the touchpad */
public void enable(){
setVisibility(VISIBLE);
placeMouseAt(currentDisplayMetrics.widthPixels / 2, currentDisplayMetrics.heightPixels / 2);
}
/** Disable the touchpad and hides the mouse */
public void disable(){
setVisibility(GONE);
}
/** @return The new state, enabled or disabled */
public boolean switchState(){
mDisplayState = !mDisplayState;
return mDisplayState;
}
public void placeMouseAt(float x, float y) {
mMousePointerImageView.setX(x);
mMousePointerImageView.setY(y);
CallbackBridge.mouseX = (x * mScaleFactor);
CallbackBridge.mouseY = (y * mScaleFactor);
CallbackBridge.sendCursorPos(CallbackBridge.mouseX, CallbackBridge.mouseY);
}
private void init(){
// Setup mouse pointer
mMousePointerImageView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_mouse_pointer, getContext().getTheme()));
mMousePointerImageView.post(() -> {
ViewGroup.LayoutParams params = mMousePointerImageView.getLayoutParams();
params.width = (int) (36 / 100f * LauncherPreferences.PREF_MOUSESCALE);
params.height = (int) (54 / 100f * LauncherPreferences.PREF_MOUSESCALE);
});
addView(mMousePointerImageView);
setFocusable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
setDefaultFocusHighlightEnabled(false);
}
// When the game is grabbing, we should not display the mouse
disable();
mDisplayState = false;
Thread virtualMouseGrabThread = new Thread(() -> {
while (true) {
if (!CallbackBridge.isGrabbing() && mDisplayState && getVisibility() != VISIBLE) {
post(this::enable);
}else{
if ((CallbackBridge.isGrabbing() && getVisibility() != View.GONE) || !mDisplayState && getVisibility() == VISIBLE) {
post(this::disable);
}
}
}
}, "VirtualMouseGrabThread");
virtualMouseGrabThread.setPriority(Thread.MIN_PRIORITY);
virtualMouseGrabThread.start();
}
}
@@ -1,113 +0,0 @@
package net.kdt.pojavlaunch.authenticator.microsoft;
import android.app.*;
import android.content.*;
import android.os.*;
import android.util.*;
import java.lang.ref.WeakReference;
import java.net.*;
import java.text.*;
import java.util.*;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.authenticator.mojang.*;
import net.kdt.pojavlaunch.authenticator.microsoft.*;
import org.json.*;
import java.text.ParseException;
import java.io.*;
import net.kdt.pojavlaunch.value.launcherprofiles.*;
import net.kdt.pojavlaunch.value.*;
public class MicrosoftAuthTask extends AsyncTask<String, Void, Object> {
/*
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 mcStoreUrl = "https://api.minecraftservices.com/entitlements/mcstore";
private static final String mcProfileUrl = "https://api.minecraftservices.com/minecraft/profile";
*/
//private Gson gson = new Gson();
private final RefreshListener listener;
private final WeakReference<Context> ctx;
private ProgressDialog build;
public MicrosoftAuthTask(Context ctx, RefreshListener listener) {
this.ctx = new WeakReference<>(ctx);
this.listener = listener;
}
@Override
public void onPreExecute() {
build = new ProgressDialog(ctx.get());
build.setMessage(ctx.get().getString(R.string.global_waiting));
build.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
build.setCancelable(false);
build.setMax(6);
build.show();
}
@Override
public Object doInBackground(String... args) {
try {
/*
publishProgress();
String msaAccessToken = acquireAccessToken(args[0]);
publishProgress();
String xblToken = acquireXBLToken(msaAccessToken);
publishProgress();
String[] xstsData = acquireXsts(xblToken);
publishProgress();
String mcAccessToken = acquireMinecraftToken(xstsData[0], xstsData[1]);
publishProgress();
*/
Msa msa = new Msa(this, Boolean.parseBoolean(args[0]), args[1]);
MinecraftAccount acc = MinecraftAccount.load(msa.mcName);
if(acc == null) acc = new MinecraftAccount();
if (msa.doesOwnGame) {
acc.clientToken = "0"; /* FIXME */
acc.accessToken = msa.mcToken;
acc.username = msa.mcName;
acc.profileId = msa.mcUuid;
acc.isMicrosoft = true;
acc.msaRefreshToken = msa.msRefreshToken;
acc.updateSkinFace();
}
acc.save();
return acc;
} catch (Throwable e) {
return e;
}
}
public void publishProgressPublic() {
super.publishProgress();
}
@Override
protected void onProgressUpdate(Void[] p1) {
super.onProgressUpdate(p1);
build.setProgress(build.getProgress() + 1);
}
@Override
public void onPostExecute(Object result) {
build.dismiss();
if (result instanceof MinecraftAccount) {
listener.onSuccess((MinecraftAccount) result);
} else {
listener.onFailed((Throwable) result);
}
}
}
@@ -1,296 +0,0 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net.kdt.pojavlaunch.authenticator.microsoft;
import android.util.*;
import java.io.*;
import java.net.*;
import java.util.*;
import net.kdt.pojavlaunch.*;
import org.json.*;
public class Msa {
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 mcStoreUrl = "https://api.minecraftservices.com/entitlements/mcstore";
private static final String mcProfileUrl = "https://api.minecraftservices.com/minecraft/profile";
private MicrosoftAuthTask task;
public boolean isRefresh;
public String msRefreshToken;
public String mcName;
public String mcToken;
public String mcUuid;
public boolean doesOwnGame;
public Msa(MicrosoftAuthTask task, boolean isRefresh, String authCode) throws IOException, JSONException {
this.task = task;
acquireAccessToken(isRefresh, authCode);
}
public void acquireAccessToken(boolean isRefresh, String authcode) throws IOException, JSONException {
task.publishProgressPublic();
URL url = new URL(authTokenUrl);
Log.i("MicroAuth", "isRefresh=" + isRefresh + ", authCode= "+authcode);
Map<Object, Object> data = new HashMap<>();
/*Map.of(
"client_id", "00000000402b5328",
"code", authcode,
"grant_type", "authorization_code",
"redirect_uri", "https://login.live.com/oauth20_desktop.srf",
"scope", "service::user.auth.xboxlive.com::MBI_SSL"
);*/
data.put("client_id", "00000000402b5328");
data.put(isRefresh ? "refresh_token" : "code", authcode);
data.put("grant_type", isRefresh ? "refresh_token" : "authorization_code");
data.put("redirect_url", "https://login.live.com/oauth20_desktop.srf");
data.put("scope", "service::user.auth.xboxlive.com::MBI_SSL");
//да пошла yf[eq1 она ваша джава 11
String req = ofFormData(data);
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(req.getBytes("UTF-8").length));
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes("UTF-8"));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
msRefreshToken = jo.getString("refresh_token");
Log.i("MicroAuth","Acess Token = "+jo.getString("access_token"));
acquireXBLToken(jo.getString("access_token"));
}else{
throwResponseError(conn);
}
}
private void acquireXBLToken(String accessToken) throws IOException, JSONException {
task.publishProgressPublic();
URL url = new URL(xblAuthUrl);
Map<Object, Object> data = new HashMap<>();
Map<Object, Object> properties = new HashMap<>();
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");
/*Map.of(
"Properties", Map.of(
"AuthMethod", "RPS",
"SiteName", "user.auth.xboxlive.com",
"RpsTicket", accessToken
),
"RelyingParty", "http://auth.xboxlive.com",
"TokenType", "JWT"
);*/
String req = ofJSONData(data);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(req.getBytes("UTF-8").length));
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes("UTF-8"));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
Log.i("MicroAuth","Xbl Token = "+jo.getString("Token"));
acquireXsts(jo.getString("Token"));
}else{
throwResponseError(conn);
}
}
private void acquireXsts(String xblToken) throws IOException, JSONException {
task.publishProgressPublic();
URL url = new URL(xstsAuthUrl);
Map<Object, Object> data = new HashMap<>();
Map<Object, Object> properties = new HashMap<>();
properties.put("SandboxId", "RETAIL");
properties.put("UserTokens",Collections.singleton(xblToken));
data.put("Properties",properties);
data.put("RelyingParty", "rp://api.minecraftservices.com/");
data.put("TokenType", "JWT");
/*Map<Object, Object> data = Map.of(
"Properties", Map.of(
"SandboxId", "RETAIL",
"UserTokens", List.of(xblToken)
),
"RelyingParty", "rp://api.minecraftservices.com/",
"TokenType", "JWT"
);
*/
String req = ofJSONData(data);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(req.getBytes("UTF-8").length));
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes("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");
Log.i("MicroAuth","Xbl Xsts = "+jo.getString("Token")+"; Uhs = " + uhs);
acquireMinecraftToken(uhs,jo.getString("Token"));
}else{
throwResponseError(conn);
}
}
private void acquireMinecraftToken(String xblUhs, String xblXsts) throws IOException, JSONException {
task.publishProgressPublic();
URL url = new URL(mcLoginUrl);
Map<Object, Object> data = new HashMap<>();
data.put("identityToken", "XBL3.0 x=" + xblUhs + ";" + xblXsts);
String req = ofJSONData(data);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(req.getBytes("UTF-8").length));
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
try(OutputStream wr = conn.getOutputStream()) {
wr.write(req.getBytes("UTF-8"));
}
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
Log.i("MicroAuth","MC token: "+jo.getString("access_token"));
mcToken = jo.getString("access_token");
checkMcProfile(jo.getString("access_token"));
checkMcStore(jo.getString("access_token"));
}else{
throwResponseError(conn);
}
}
private void checkMcStore(String mcAccessToken) throws IOException, JSONException {
task.publishProgressPublic();
URL url = new URL(mcStoreUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestProperty("Authorization", "Bearer " + mcAccessToken);
conn.setRequestMethod("GET");
conn.setUseCaches(false);
conn.connect();
if(conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
JSONObject jo = new JSONObject(Tools.read(conn.getInputStream()));
JSONArray ja = jo.getJSONArray("items");
Log.i("MicroAuth","Store Len = " + ja.length());
for(int i = 0; i < ja.length(); i++) {
String prod = ja.getJSONObject(i).getString("name");
Log.i("MicroAuth","Product " + i +": " +prod);
}
}else{
throwResponseError(conn);
}
}
private void checkMcProfile(String mcAccessToken) throws IOException, JSONException {
task.publishProgressPublic();
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());
Log.i("MicroAuth","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("MicroAuth","UserName = " + name);
Log.i("MicroAuth","Uuid Minecraft = " + uuidDashes);
mcName=name;
mcUuid=uuidDashes;
}else{
Log.i("MicroAuth","It seems that this Microsoft Account does not own the game.");
doesOwnGame = false;
throwResponseError(conn);
}
}
public static String ofJSONData(Map<Object, Object> data) {
return new JSONObject(data).toString();
}
public static String ofFormData(Map<Object, Object> data) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if (builder.length() > 0) {
builder.append("&");
}
try {
builder.append(URLEncoder.encode(entry.getKey().toString(), "UTF-8"));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
//Should not happen
}
}
return builder.toString();
}
private static void throwResponseError(HttpURLConnection conn) throws IOException {
String otherErrStr = "";
String errStr = Tools.read(conn.getErrorStream());
Log.i("MicroAuth","Error code: " + conn.getResponseCode() + ": " + conn.getResponseMessage() + "\n" + errStr);
if (errStr.contains("NOT_FOUND") &&
errStr.contains("The server has not found anything matching the request URI"))
{
// TODO localize this
otherErrStr = "It seems that this Microsoft Account does not own the game. Make sure that you have bought/migrated to your Microsoft account.";
}
throw new RuntimeException(otherErrStr + "\n\nMSA Error: " + conn.getResponseCode() + ": " + conn.getResponseMessage() + ", error stream:\n" + errStr);
}
}
@@ -1,71 +0,0 @@
package net.kdt.pojavlaunch.authenticator.microsoft.ui;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
import net.kdt.pojavlaunch.R;
public class MicrosoftLoginGUIActivity extends AppCompatActivity {
public static final int AUTHENTICATE_MICROSOFT_REQUEST = 60;
WebView webView;
ProgressDialog waitDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CookieManager.getInstance().removeAllCookie();
waitDialog = new ProgressDialog(this);
waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
waitDialog.setIndeterminate(true);
waitDialog.setMessage(getString(R.string.global_waiting));
webView = new WebView(this);
webView.setWebViewClient(new WebViewTrackClient());
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.loadUrl("https://login.live.com/oauth20_authorize.srf" +
"?client_id=00000000402b5328" +
"&response_type=code" +
"&scope=service%3A%3Auser.auth.xboxlive.com%3A%3AMBI_SSL" +
"&redirect_url=https%3A%2F%2Flogin.live.com%2Foauth20_desktop.srf");
setContentView(webView);
}
class WebViewTrackClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("ms-xal-00000000402b5328")) {
Intent data = new Intent();
data.setData(Uri.parse(url));
if(waitDialog.isShowing()) waitDialog.dismiss();
setResult(Activity.RESULT_OK,data);
finish();
return true;
}else{
return super.shouldOverrideUrlLoading(view, url);
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//super.onPageStarted(view, url, favicon);
if(!waitDialog.isShowing()) waitDialog.show();
}
@Override
public void onPageFinished(WebView view, String url) {
waitDialog.hide();
}
}
}
@@ -1,24 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
import java.util.UUID;
public class AuthenticateRequest {
public AgentInfo agent = new AgentInfo();
public UUID clientToken;
public String password;
public String username;
public static class AgentInfo {
public String name;
public int version;
}
public AuthenticateRequest(String username, String password, UUID clientToken, String clientName, int clientVersion) {
this.username = username;
this.password = password;
this.clientToken = clientToken;
this.agent.name = clientName;
this.agent.version = clientVersion;
}
}
@@ -1,53 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang;
import android.content.*;
import android.os.*;
import net.kdt.pojavlaunch.authenticator.mojang.yggdrasil.*;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.value.*;
public class InvalidateTokenTask extends AsyncTask<String, Void, Throwable> {
private YggdrasilAuthenticator authenticator = new YggdrasilAuthenticator();
//private Gson gson = new Gson();
private MinecraftAccount profilePath;
private final WeakReference<Context> ctx;
private String path;
public InvalidateTokenTask(Context ctx) {
this.ctx = new WeakReference<>(ctx);
}
@Override
public Throwable doInBackground(String... args) {
path = args[0];
try {
this.profilePath = MinecraftAccount.load(args[0]);
if(profilePath == null) {
return null;
}
if (profilePath.accessToken.equals("0")) {
return null;
}
this.authenticator.invalidate(profilePath.accessToken,
UUID.fromString(profilePath.isMicrosoft ? profilePath.profileId : profilePath.clientToken /* should be? */));
return null;
} catch (Throwable e) {
return e;
}
}
@Override
public void onPostExecute(Throwable result) {
if (result != null) {
Tools.showError(ctx.get(), result);
}
new File(Tools.DIR_ACCOUNT_NEW + "/" + path + ".json").delete();
}
}
@@ -1,7 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang;
public interface LoginListener
{
public void onBeforeLogin();
public void onLoginDone(String[] result);
}
@@ -1,71 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang;
import android.os.*;
import net.kdt.pojavlaunch.authenticator.mojang.yggdrasil.*;
import java.io.*;
import java.util.*;
import net.kdt.pojavlaunch.*;
public class LoginTask extends AsyncTask<String, Void, Void>
{
private YggdrasilAuthenticator authenticator = new YggdrasilAuthenticator();
//private String TAG = "MojangAuth-login";
private LoginListener listener;
public LoginTask setLoginListener(LoginListener listener) {
this.listener = listener;
return this;
}
private UUID getRandomUUID() {
return UUID.randomUUID();
}
@Override
protected void onPreExecute() {
listener.onBeforeLogin();
super.onPreExecute();
}
@Override
protected Void doInBackground(String[] args) {
ArrayList<String> str = new ArrayList<String>();
str.add("ERROR");
try{
try{
AuthenticateResponse response = authenticator.authenticate(args[0], args[1], getRandomUUID());
if (response.selectedProfile == null) {
str.add("Can't login a demo account!\n");
} else {
if (new File(Tools.DIR_ACCOUNT_NEW + "/" + response.selectedProfile.name + ".json").exists()) {
str.add("This account already exist!\n");
} else {
str.add(response.accessToken); // Access token
str.add(response.clientToken.toString()); // Client token
str.add(response.selectedProfile.id); // Profile ID
str.add(response.selectedProfile.name); // Username
str.set(0, "NORMAL");
}
}
}
//MainActivity.updateStatus(804);
catch(Throwable e){
str.add(e.getMessage());
}
}
catch(Exception e){
str.add(e.getMessage());
}
listener.onLoginDone(str.toArray(new String[0]));
return null;
}
@Override
protected void onPostExecute(Void result) {
// listener.onLoginDone(result);
super.onPostExecute(result);
}
}
@@ -1,10 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.value.*;
public interface RefreshListener
{
public void onFailed(Throwable e);
public void onSuccess(MinecraftAccount profile);
}
@@ -1,81 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang;
import android.content.*;
import android.os.*;
import com.google.gson.*;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.*;
import net.kdt.pojavlaunch.*;
import net.kdt.pojavlaunch.authenticator.mojang.yggdrasil.*;
import android.app.*;
import net.kdt.pojavlaunch.value.*;
public class RefreshTokenTask extends AsyncTask<String, Void, Throwable> {
private YggdrasilAuthenticator authenticator = new YggdrasilAuthenticator();
//private Gson gson = new Gson();
private RefreshListener listener;
private MinecraftAccount profilePath;
private final WeakReference<Context> ctx;
private ProgressDialog build;
public RefreshTokenTask(Context ctx, RefreshListener listener) {
this.ctx = new WeakReference<>(ctx);
this.listener = listener;
}
@Override
public void onPreExecute() {
build = new ProgressDialog(ctx.get());
build.setMessage(ctx.get().getString(R.string.global_waiting));
build.setProgressStyle(ProgressDialog.STYLE_SPINNER);
build.setCancelable(false);
build.show();
}
@Override
public Throwable doInBackground(String... args) {
try {
this.profilePath = MinecraftAccount.load(args[0]);
if(profilePath == null) {
return new NullPointerException();
}
int responseCode = 400;
try {
responseCode = this.authenticator.validate(profilePath.accessToken).statusCode;
}catch(RuntimeException e) {}
if (responseCode == 403) {
RefreshResponse response = this.authenticator.refresh(profilePath.accessToken, UUID.fromString(profilePath.clientToken));
if (response == null) {
// Refresh when offline?
return null;
} else if (response.selectedProfile == null) {
throw new IllegalArgumentException("Can't refresh a demo account!");
}
profilePath.clientToken = response.clientToken.toString();
profilePath.accessToken = response.accessToken;
profilePath.username = response.selectedProfile.name;
profilePath.profileId = response.selectedProfile.id;
}
profilePath.updateSkinFace();
profilePath.save();
return null;
} catch (Throwable e) {
return e;
}
}
@Override
public void onPostExecute(Throwable result) {
build.dismiss();
if (result == null) {
listener.onSuccess(profilePath);
} else {
listener.onFailed(result);
}
}
}
@@ -1,10 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
import java.util.UUID;
public class AuthenticateResponse {
public String accessToken;
public Profile[] availableProfiles;
public UUID clientToken;
public Profile selectedProfile;
}
@@ -1,8 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
public class ErrorResponse {
public String cause;
public String error;
public String errorMessage;
}
@@ -1,23 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
import java.util.*;
public class NetworkResponse
{
public final int statusCode;
public final Object response;
public NetworkResponse(int statusCode, Object response) {
this.statusCode = statusCode;
this.response = response;
}
public void throwExceptionIfNeed(String msg) {
if (statusCode < 200 || statusCode >= 300) {
throw new RuntimeException(msg);
}
}
public void throwExceptionIfNeed() {
throwExceptionIfNeed("Respone error, code: " + statusCode + ", message: " + response);
}
}
@@ -1,8 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
public class Profile {
public String id;
public boolean legacy;
public String name;
}
@@ -1,14 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
import java.util.UUID;
public class RefreshRequest {
public String accessToken;
public UUID clientToken;
public RefreshRequest(String accessToken, UUID clientToken) {
this.accessToken = accessToken;
this.clientToken = clientToken;
}
}
@@ -1,9 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
import java.util.UUID;
public class RefreshResponse {
public String accessToken;
public UUID clientToken;
public Profile selectedProfile;
}
@@ -1,122 +0,0 @@
package net.kdt.pojavlaunch.authenticator.mojang.yggdrasil;
import android.util.*;
import java.io.*;
import java.net.*;
import java.nio.charset.*;
import java.util.*;
import net.kdt.pojavlaunch.*;
import org.apache.commons.io.*;
public class YggdrasilAuthenticator {
private static final String API_URL = "https://authserver.mojang.com/";
private String clientName = "Minecraft";
private int clientVersion = 1;
private NetworkResponse makeRequest(String endpoint, Object inputObject, Class<?> responseClass) throws IOException, Throwable {
Throwable th;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String requestJson = Tools.GLOBAL_GSON.toJson(inputObject);
try {
URL url = new URL(API_URL + endpoint);
OutputStream os;
try {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "Minecraft");
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
os = null;
os = conn.getOutputStream();
os.write(requestJson.getBytes(Charset.forName("UTF-8")));
if (os != null) {
os.close();
}
int statusCode = conn.getResponseCode();
if (statusCode != 200) {
is = conn.getErrorStream();
} else {
is = conn.getInputStream();
}
if (is != null) {
IOUtils.copy(is, bos);
try {
is.close();
} catch (Exception e) {
throw e;
}
}
String outString = new String(bos.toByteArray(), Charset.forName("UTF-8"));
if (statusCode == 200 || statusCode == 204){
Log.i("Result", "Task " + endpoint + " successful");
if (responseClass != null) {
return new NetworkResponse(statusCode, Tools.GLOBAL_GSON.fromJson(outString, responseClass));
}
} else {
Log.i("Result", "Task " + endpoint + " failure");
}
return new NetworkResponse(statusCode, outString);
} catch (UnknownHostException e) {
if (endpoint.equals("refresh")) {
return null;
} else {
throw new RuntimeException("Can't connect to the server", e);
}
} catch (Throwable th2) {
th = th2;
if (is != null) {
try {
is.close();
} catch (Exception e2) {
e2.addSuppressed(th2);
throw e2;
}
}
throw th;
}
} catch (Throwable th3) {
th = th3;
if (is != null) {
is.close();
}
throw th;
}
}
public AuthenticateResponse authenticate(String username, String password, UUID clientId) throws IOException, Throwable {
NetworkResponse obj = makeRequest("authenticate", new net.kdt.pojavlaunch.authenticator.mojang.yggdrasil.AuthenticateRequest(username, password, clientId, this.clientName, this.clientVersion), AuthenticateResponse.class);
/*
if (obj.statusCode != 200) {
throw new RuntimeException("Invalid username or password, status code: " + obj.statusCode);
}
*/
obj.throwExceptionIfNeed();
return (AuthenticateResponse) obj.response;
}
public RefreshResponse refresh(String authToken, UUID clientId) throws IOException, Throwable {
NetworkResponse obj = makeRequest("refresh", new RefreshRequest(authToken, clientId), RefreshResponse.class);
if (obj == null) {
return null;
} else {
obj.throwExceptionIfNeed(); // "Invalid username or password, status code: " + obj.statusCode);
return (RefreshResponse) obj.response;
}
}
public NetworkResponse validate(String authToken) throws Throwable {
return makeRequest("validate", new RefreshRequest(authToken, null), null);
}
public NetworkResponse invalidate(String authToken, UUID clientId) throws Throwable {
return makeRequest("invalidate", new RefreshRequest(authToken, clientId), null);
}
}
@@ -1,5 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
public interface AlphaSelectionListener {
void onAlphaSelected(int alpha);
}
@@ -1,76 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import net.kdt.pojavlaunch.Tools;
import top.defaults.checkerboarddrawable.CheckerboardDrawable;
public class AlphaView extends View {
private final Drawable mCheckerboardDrawable = CheckerboardDrawable.create();
private final Paint mShaderPaint = new Paint();
private final Paint mBlackPaint;
private final RectF mViewSize = new RectF(0,0,0,0);
private AlphaSelectionListener mAlphaSelectionListener;
private int mSelectedAlpha;
private float mAlphaDiv; // for quick pos->alpha multiplication
private float mScreenDiv; // for quick alpha->pos multiplication
private float mHeightThird; // 1/3 of the view size for cursor
public AlphaView(Context ctx, AttributeSet attrs) {
super(ctx,attrs);
mBlackPaint = new Paint();
mBlackPaint.setStrokeWidth(Tools.dpToPx(3));
mBlackPaint.setColor(Color.BLACK);
}
public void setAlphaSelectionListener(AlphaSelectionListener alphaSelectionListener) {
mAlphaSelectionListener = alphaSelectionListener;
}
public void setAlpha(int alpha) {
mSelectedAlpha = alpha;
invalidate();
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
mSelectedAlpha = (int) (mAlphaDiv * event.getX());
if(mSelectedAlpha < 0) mSelectedAlpha = 0;
if(mSelectedAlpha > 0xff) mSelectedAlpha = 0xff;
if(mAlphaSelectionListener != null) mAlphaSelectionListener.onAlphaSelected(mSelectedAlpha);
invalidate();
return true;
}
@Override
protected void onSizeChanged(int w, int h, int old_w, int old_h) {
mViewSize.right = w;
mViewSize.bottom = h;
float h2 = mViewSize.bottom / 2f;
mShaderPaint.setShader(new LinearGradient(0,h2,w,h2, 0, Color.BLACK, Shader.TileMode.REPEAT));
mAlphaDiv = 255f / mViewSize.right;
mScreenDiv = mViewSize.right / 255f;
mHeightThird = mViewSize.bottom / 3f;
}
@Override
protected void onDraw(Canvas canvas) {
mCheckerboardDrawable.draw(canvas);
canvas.drawRect(mViewSize, mShaderPaint);
float linePos = mSelectedAlpha * mScreenDiv;
canvas.drawLine(linePos, 0 ,linePos, mHeightThird, mBlackPaint);
canvas.drawLine(linePos, mHeightThird * 2 ,linePos, mViewSize.bottom, mBlackPaint);
}
}
@@ -1,9 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
public interface ColorSelectionListener {
/**
* This method gets called by the ColorSelector when the color is selected
* @param color the selected color
*/
void onColorSelected(int color);
}
@@ -1,150 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import net.kdt.pojavlaunch.R;
public class ColorSelector implements HueSelectionListener, RectangleSelectionListener, AlphaSelectionListener, TextWatcher{
private static final int ALPHA_MASK = ~(0xFF << 24);
private final HueView mHueView;
private final SVRectangleView mLuminosityIntensityView;
private final AlphaView mAlphaView;
private final ColorSideBySideView mColorView;
private final EditText mTextView;
private final AlertDialog mDialog;
private ColorSelectionListener mColorSelectionListener;
private float[] mHueTemplate = new float[] {0,1,1};
private float[] mHsvSelected = new float[] {360,1,1};
private int mAlphaSelected = 0xff;
private ColorStateList mTextColors;
private boolean mWatch = true;
/**
* Creates a color selector dialog for this Context.
* @param context Context used for this ColorSelector dialog
* @param colorSelectionListener Color selection listener to which the events will be sent to. Can be null.
*/
public ColorSelector(Context context, ColorSelectionListener colorSelectionListener) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_color_selector,null);
mHueView = view.findViewById(R.id.color_selector_hue_view);
mLuminosityIntensityView = view.findViewById(R.id.color_selector_rectangle_view);
mAlphaView = view.findViewById(R.id.color_selector_alpha_view);
mColorView = view.findViewById(R.id.color_selector_color_view);
mTextView = view.findViewById(R.id.color_selector_hex_edit);
runColor(Color.RED);
mHueView.setHueSelectionListener(this);
mLuminosityIntensityView.setRectSelectionListener(this);
mAlphaView.setAlphaSelectionListener(this);
mTextView.addTextChangedListener(this);
mTextColors = mTextView.getTextColors();
builder.setView(view);
builder.setPositiveButton(android.R.string.ok,(dialog,which)->{
if (mColorSelectionListener != null) {
mColorSelectionListener.onColorSelected(Color.HSVToColor(mAlphaSelected, mHsvSelected));
}
});
builder.setNegativeButton(android.R.string.cancel, ((dialog, which) -> {}));
mColorSelectionListener = colorSelectionListener;
mDialog = builder.create();
}
/**
* Shows the color selector with the default (red) color selected.
*/
public void show() {
runColor(Color.RED);
dispatchColorChange();
mDialog.show();
}
/**
* Shows the color selector with the desired ARGB color selected
* @param previousColor the desired ARGB color
*/
public void show(int previousColor) {
runColor(previousColor); // initialize
dispatchColorChange(); // set the hex text
mDialog.show();
}
@Override
public void onHueSelected(float hue) {
mHsvSelected[0] = mHueTemplate[0] = hue;
mLuminosityIntensityView.setColor(Color.HSVToColor(mHueTemplate), true);
dispatchColorChange();
}
@Override
public void onLuminosityIntensityChanged(float luminosity, float intensity) {
mHsvSelected[1] = intensity;
mHsvSelected[2] = luminosity;
dispatchColorChange();
}
@Override
public void onAlphaSelected(int alpha) {
mAlphaSelected = alpha;
dispatchColorChange();
}
/**
* Replaces the alpha value of the color passed in, and returns the result.
* @param color the color to replace the alpha of
* @param alpha the alpha to use
* @return the new color
*/
public static int setAlpha(int color, int alpha) {
return color & ALPHA_MASK | ((alpha & 0xFF) << 24);
}
//IUO: called on all color changes
protected void dispatchColorChange() {
int color = Color.HSVToColor(mAlphaSelected, mHsvSelected);
mColorView.setColor(color);
mWatch = false;
mTextView.setText(String.format("%08X",color));
}
//IUO: sets all Views to render the desired color. Used for initilaization and HEX color input
protected void runColor(int color) {
Color.RGBToHSV(Color.red(color), Color.green(color), Color.blue(color), mHsvSelected);
mHueTemplate[0] = mHsvSelected[0];
mHueView.setHue(mHsvSelected[0]);
mLuminosityIntensityView.setColor(Color.HSVToColor(mHueTemplate), false);
mLuminosityIntensityView.setLuminosityIntensity(mHsvSelected[2], mHsvSelected[1]);
mAlphaSelected = Color.alpha(color);
mAlphaView.setAlpha(mAlphaSelected);
mColorView.setColor(color);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if(mWatch) {
try {
int color = Integer.parseInt(s.toString(), 16);
mTextView.setTextColor(mTextColors);
runColor(color);
}catch (NumberFormatException exception) {
mTextView.setTextColor(Color.RED);
}
}else{
mWatch = true;
}
}
}
@@ -1,47 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
import top.defaults.checkerboarddrawable.CheckerboardDrawable;
public class ColorSideBySideView extends View {
private final Paint mPaint;
private final CheckerboardDrawable mCheckerboardDrawable = CheckerboardDrawable.create();
private int mColor;
private int mAlphaColor;
private float mWidth;
private float mHeight;
private float mHalfHeight;
public ColorSideBySideView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
}
public void setColor(int color) {
mColor = ColorSelector.setAlpha(color, 0xff);
mAlphaColor = color;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
mCheckerboardDrawable.draw(canvas);
mPaint.setColor(mColor);
canvas.drawRect(0,0,mWidth, mHalfHeight, mPaint);
mPaint.setColor(mAlphaColor);
canvas.drawRect(0,mHalfHeight,mWidth,mHeight, mPaint);
}
@Override
protected void onSizeChanged(int w, int h, int old_w, int old_h) {
mHalfHeight = h/2f;
mWidth = w;
mHeight = h;
}
}
@@ -1,5 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
public interface HueSelectionListener {
void onHueSelected(float hue);
}
@@ -1,83 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
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.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.Tools;
public class HueView extends View {
private final Paint blackPaint = new Paint();
private Bitmap mGamma;
private HueSelectionListener mHueSelectionListener;
private float mSelectionHue;
private float mWidthHueRatio;
private float mHueWidthRatio;
private float mWidth;
private float mHeight;
private float mHeightThird;
public HueView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
blackPaint.setColor(Color.BLACK);
blackPaint.setStrokeWidth(Tools.dpToPx(3));
}
public void setHueSelectionListener(HueSelectionListener listener) {
mHueSelectionListener = listener;
}
public void setHue(float hue) {
mSelectionHue = hue;
invalidate();
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
mSelectionHue = event.getX() * mWidthHueRatio;
invalidate();
if(mHueSelectionListener != null) mHueSelectionListener.onHueSelected(mSelectionHue);
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(mGamma, 0, 0 ,null);
float linePos = mSelectionHue * mHueWidthRatio;
canvas.drawLine(linePos, 0 ,linePos, mHeightThird, blackPaint);
canvas.drawLine(linePos, mHeightThird * 2 ,linePos, mHeight, blackPaint);
}
@Override
protected void onSizeChanged(int w, int h, int old_w, int old_h) {
mWidth = w;
mHeight = h;
mHeightThird = mHeight / 3;
regenerateGammaBitmap();
}
protected void regenerateGammaBitmap() {
if(mGamma != null)
mGamma.recycle();
mGamma = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
Canvas canvas = new Canvas(mGamma);
mWidthHueRatio = 360/ mWidth;
mHueWidthRatio = mWidth / 360;
float[] hsvFiller = new float[] {0, 1, 1};
for(float i = 0; i < mWidth; i++) {
hsvFiller[0] = i * mWidthHueRatio;
paint.setColor(Color.HSVToColor(hsvFiller));
canvas.drawLine(i,0,i, mHeight,paint);
}
}
}
@@ -1,5 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
public interface RectangleSelectionListener {
void onLuminosityIntensityChanged(float luminosity, float intensity);
}
@@ -1,113 +0,0 @@
package net.kdt.pojavlaunch.colorselector;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import net.kdt.pojavlaunch.Tools;
public class SVRectangleView extends View {
private final Paint mColorPaint = new Paint();
private final Paint mPointerPaint = new Paint();
private final float mPointerSize;
private Bitmap mSvRectangle;
private RectF mViewSize;
private float mHeightInverted;
private float mWidthInverted;
private float mFingerPosX;
private float mFingerPosY;
RectangleSelectionListener mRectSelectionListener;
public SVRectangleView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mColorPaint.setColor(Color.BLACK);
mColorPaint.setStyle(Paint.Style.FILL);
mPointerSize = Tools.dpToPx(6);
mPointerPaint.setColor(Color.BLACK);
mPointerPaint.setStrokeWidth(Tools.dpToPx(3));
}
@SuppressLint("ClickableViewAccessibility")
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
mFingerPosX = x * mWidthInverted;
mFingerPosY = y * mHeightInverted;
if(mFingerPosX < 0) mFingerPosX = 0;
else if(mFingerPosX > 1) mFingerPosX = 1;
if(mFingerPosY < 0) mFingerPosY = 0;
else if(mFingerPosY > 1) mFingerPosY = 1;
if(mRectSelectionListener != null) mRectSelectionListener.onLuminosityIntensityChanged(mFingerPosY,mFingerPosX);
invalidate();
return true;
}
public void setLuminosityIntensity(float luminosity, float intensity) {
mFingerPosX = intensity;
mFingerPosY = luminosity;
invalidate();
}
public void setColor(int color, boolean invalidate) {
mColorPaint.setColor(color);
if(invalidate) invalidate();
}
public void setRectSelectionListener(RectangleSelectionListener listener) {
mRectSelectionListener = listener;
}
protected void drawPointer(Canvas canvas, float x, float y) {
canvas.drawLine(mPointerSize * 2 + x, y, mPointerSize + x, y, mPointerPaint);
canvas.drawLine(x - mPointerSize * 2, y, x - mPointerSize, y, mPointerPaint);
canvas.drawLine(x, mPointerSize * 2 + y, x, mPointerSize + y, mPointerPaint);
canvas.drawLine(x, y - mPointerSize * 2, x, y - mPointerSize, mPointerPaint);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(mViewSize, mColorPaint);
canvas.drawBitmap(mSvRectangle, 0,0, null);
drawPointer(canvas, mViewSize.right * mFingerPosX, mViewSize.bottom * mFingerPosY);
}
@Override
protected void onSizeChanged(int w, int h, int old_w, int old_h) {
mViewSize = new RectF(0,0, w,h);
mWidthInverted = 1/mViewSize.right;
mHeightInverted = 1/mViewSize.bottom;
if(w > 0 && h > 0)
regenerateRectangle();
}
protected void regenerateRectangle() {
int w = getWidth();
int h = getHeight();
if(mSvRectangle != null)
mSvRectangle.recycle();
mSvRectangle = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Paint rectPaint = new Paint();
Canvas canvas = new Canvas(mSvRectangle);
float h2f = h/2f;
float w2f = w/2f;
rectPaint.setShader(new LinearGradient(0,h2f, w, h2f, Color.WHITE,0, Shader.TileMode.CLAMP));
canvas.drawRect(mViewSize, rectPaint);
rectPaint.setShader(new LinearGradient(w2f,0, w2f, h, Color.BLACK,0, Shader.TileMode.CLAMP));
canvas.drawRect(mViewSize, rectPaint);
}
}
Loaded 100 of 604 files, more files were not shown because too many files have changed in this diff. Show more