First commit

This commit is contained in:
Maschell 2022-11-11 12:02:22 +01:00
commit 7e84b9fa95
47 changed files with 40680 additions and 0 deletions

67
.clang-format Normal file
View File

@ -0,0 +1,67 @@
# Generated from CLion C/C++ Code Style settings
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: Consecutive
AlignConsecutiveMacros: AcrossEmptyLinesAndComments
AlignOperands: Align
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Always
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterReturnType: None
AlwaysBreakTemplateDeclarations: Yes
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: true
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
ColumnLimit: 0
CompactNamespaces: false
ContinuationIndentWidth: 8
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 4
KeepEmptyLinesAtTheStartOfBlocks: true
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PointerAlignment: Right
ReflowComments: false
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
TabWidth: 4
UseTab: Never

59
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,59 @@
name: CI-Release
on:
push:
branches:
- main
jobs:
clang-format:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: clang-format
run: |
docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./source --exclude ./source/utils/json.hpp
build-binary:
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v3
- name: create version.h
run: |
git_hash=$(git rev-parse --short "$GITHUB_SHA")
cat <<EOF > ./source/version.h
#pragma once
#define UPDATER_VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary
run: |
docker build . -t builder
docker run --rm -v ${PWD}:/project builder make
- uses: actions/upload-artifact@master
with:
name: binary
path: "*.wuhb"
deploy-binary:
needs: build-binary
runs-on: ubuntu-22.04
steps:
- name: Get environment variables
id: get_repository_name
run: |
echo REPOSITORY_NAME=$(echo "$GITHUB_REPOSITORY" | awk -F / '{print $2}' | sed -e "s/:refs//") >> $GITHUB_ENV
echo DATETIME=$(echo $(date '+%Y%m%d-%H%M%S')) >> $GITHUB_ENV
- uses: actions/download-artifact@master
with:
name: binary
- name: zip artifact
run: zip -r ${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip *.wuhb
- name: Create Release
uses: "softprops/action-gh-release@v1"
with:
tag_name: ${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
draft: false
prerelease: true
generate_release_notes: true
name: Nightly-${{ env.REPOSITORY_NAME }}-${{ env.DATETIME }}
files: |
./${{ env.REPOSITORY_NAME }}_${{ env.DATETIME }}.zip

43
.github/workflows/pr.yml vendored Normal file
View File

@ -0,0 +1,43 @@
name: CI-PR
on: [pull_request]
jobs:
clang-format:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- name: clang-format
run: |
docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./source --exclude ./source/utils/json.hpp
check-build-with-logging:
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v3
- name: build binary with logging
run: |
docker build . -t builder
docker run --rm -v ${PWD}:/project builder make DEBUG=VERBOSE
docker run --rm -v ${PWD}:/project builder make clean
docker run --rm -v ${PWD}:/project builder make DEBUG=1
build-binary:
runs-on: ubuntu-22.04
needs: clang-format
steps:
- uses: actions/checkout@v3
- name: create version.h
run: |
git_hash=$(git rev-parse --short "${{ github.event.pull_request.head.sha }}")
cat <<EOF > ./source/version.h
#pragma once
#define UPDATER_VERSION_EXTRA " (nightly-$git_hash)"
EOF
- name: build binary
run: |
docker build . -t builder
docker run --rm -v ${PWD}:/project builder make
- uses: actions/upload-artifact@master
with:
name: binary
path: "*.wuhb"

5
.gitignore vendored Normal file
View File

@ -0,0 +1,5 @@
build/
.idea/
*.rpx
*.elf
*.wuhb

3
Dockerfile Normal file
View File

@ -0,0 +1,3 @@
FROM wiiuenv/devkitppc:20221228
WORKDIR /project

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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:
<program> Copyright (C) <year> <name of author>
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>.

189
Makefile Normal file
View File

@ -0,0 +1,189 @@
#-------------------------------------------------------------------------------
.SUFFIXES:
#-------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPRO)),)
$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=<path to>/devkitpro")
endif
TOPDIR ?= $(CURDIR)
#-------------------------------------------------------------------------------
# APP_NAME sets the long name of the application
# APP_SHORTNAME sets the short name of the application
# APP_AUTHOR sets the author of the application
#-------------------------------------------------------------------------------
APP_NAME := Aroma Updater
APP_SHORTNAME := Aroma Updater
APP_AUTHOR := Maschell
include $(DEVKITPRO)/wut/share/wut_rules
#-------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# DATA is a list of directories containing data files
# INCLUDES is a list of directories containing header files
# CONTENT is the path to the bundled folder that will be mounted as /vol/content/
# ICON is the game icon, leave blank to use default rule
# TV_SPLASH is the image displayed during bootup on the TV, leave blank to use default rule
# DRC_SPLASH is the image displayed during bootup on the DRC, leave blank to use default rule
#-------------------------------------------------------------------------------
TARGET := AromaUpdater
BUILD := build
SOURCES := source \
source/utils
INCLUDES := include
CONTENT := data
ICON := meta/icon.png
#-------------------------------------------------------------------------------
# options for code generation
#-------------------------------------------------------------------------------
CFLAGS := -g -Wall -O2 -ffunction-sections \
$(MACHDEP)
CFLAGS += $(INCLUDE) -D__WIIU__ -D__WUT__
CXXFLAGS := $(CFLAGS) -std=c++20
ASFLAGS := -g $(ARCH)
LDFLAGS = -g $(ARCH) $(RPXSPECS) -Wl,-Map,$(notdir $*.map)
ifeq ($(DEBUG),1)
CXXFLAGS += -DDEBUG -g
CFLAGS += -DDEBUG -g
endif
ifeq ($(DEBUG),VERBOSE)
CXXFLAGS += -DDEBUG -DVERBOSE_DEBUG -g
CFLAGS += -DDEBUG -DVERBOSE_DEBUG -g
endif
LIBS :=-lcurl -lmbedtls -lmbedx509 -lmbedcrypto -lz -lwut
#-------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level
# containing include and lib
#-------------------------------------------------------------------------------
LIBDIRS := $(PORTLIBS) $(WUT_ROOT)
#-------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#-------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#-------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export TOPDIR := $(CURDIR)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
#-------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#-------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
#-------------------------------------------------------------------------------
export LD := $(CC)
#-------------------------------------------------------------------------------
else
#-------------------------------------------------------------------------------
export LD := $(CXX)
#-------------------------------------------------------------------------------
endif
#-------------------------------------------------------------------------------
export OFILES_BIN := $(addsuffix .o,$(BINFILES))
export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.S=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SRC)
export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES)))
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD)
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib)
ifneq (,$(strip $(CONTENT)))
export APP_CONTENT := $(TOPDIR)/$(CONTENT)
endif
ifneq (,$(strip $(ICON)))
export APP_ICON := $(TOPDIR)/$(ICON)
else ifneq (,$(wildcard $(TOPDIR)/$(TARGET).png))
export APP_ICON := $(TOPDIR)/$(TARGET).png
else ifneq (,$(wildcard $(TOPDIR)/icon.png))
export APP_ICON := $(TOPDIR)/icon.png
endif
ifneq (,$(strip $(TV_SPLASH)))
export APP_TV_SPLASH := $(TOPDIR)/$(TV_SPLASH)
else ifneq (,$(wildcard $(TOPDIR)/tv-splash.png))
export APP_TV_SPLASH := $(TOPDIR)/tv-splash.png
else ifneq (,$(wildcard $(TOPDIR)/splash.png))
export APP_TV_SPLASH := $(TOPDIR)/splash.png
endif
ifneq (,$(strip $(DRC_SPLASH)))
export APP_DRC_SPLASH := $(TOPDIR)/$(DRC_SPLASH)
else ifneq (,$(wildcard $(TOPDIR)/drc-splash.png))
export APP_DRC_SPLASH := $(TOPDIR)/drc-splash.png
else ifneq (,$(wildcard $(TOPDIR)/splash.png))
export APP_DRC_SPLASH := $(TOPDIR)/splash.png
endif
.PHONY: $(BUILD) clean all
#-------------------------------------------------------------------------------
all: $(BUILD)
$(BUILD):
@$(shell [ ! -d $(BUILD) ] && mkdir -p $(BUILD))
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#-------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(TARGET).wuhb $(TARGET).rpx $(TARGET).elf
#-------------------------------------------------------------------------------
else
.PHONY: all
DEPENDS := $(OFILES:.o=.d)
#-------------------------------------------------------------------------------
# main targets
#-------------------------------------------------------------------------------
all : $(OUTPUT).wuhb
$(OUTPUT).wuhb : $(OUTPUT).rpx
$(OUTPUT).rpx : $(OUTPUT).elf
$(OUTPUT).elf : $(OFILES)
$(OFILES_SRC) : $(HFILES_BIN)
#-------------------------------------------------------------------------------
# you need a rule like this for each extension you use as binary data
#-------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#-------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPENDS)
#-------------------------------------------------------------------------------
endif
#-------------------------------------------------------------------------------

39
README.md Normal file
View File

@ -0,0 +1,39 @@
[![CI-Release](https://github.com/wiiu-env/AromaUpdater/actions/workflows/ci.yml/badge.svg)](https://github.com/wiiu-env/AromaUpdater/actions/workflows/ci.yml)
# Aroma Updater
## Usage
(`[ENVIRONMENT]` is a placeholder for the actual environment name.)
1. Copy the file `AromaUpdater.wuhb` into `sd:/wiiu/apps/updater/AromaUpdater.wuhb`.
2. Run the Updater via Aroma (e.g. from the Wii U Menu).
## Buildflags
### Logging
Building via `make` only logs errors (via OSReport). To enable logging via the [LoggingModule](https://github.com/wiiu-env/LoggingModule) set `DEBUG` to `1` or `VERBOSE`.
`make` Logs errors only (via OSReport).
`make DEBUG=1` Enables information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule).
`make DEBUG=VERBOSE` Enables verbose information and error logging via [LoggingModule](https://github.com/wiiu-env/LoggingModule).
If the [LoggingModule](https://github.com/wiiu-env/LoggingModule) is not present, it'll fallback to UDP (Port 4405) and [CafeOS](https://github.com/wiiu-env/USBSerialLoggingModule) logging.
## Building using the Dockerfile
It's possible to use a docker image for building. This way you don't need anything installed on your host system.
```
# Build docker image (only needed once)
docker build . -t aromaupdater-builder
# make
docker run -it --rm -v ${PWD}:/project aromaupdater-builder make
# make clean
docker run -it --rm -v ${PWD}:/project aromaupdater-builder make clean
```
## Format the code via docker
`docker run --rm -v ${PWD}:/src wiiuenv/clang-format:13.0.0-2 -r ./source --exclude ./source/utils/json.hpp -i`

3372
data/cacert.pem Normal file

File diff suppressed because it is too large Load Diff

BIN
meta/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

75
source/ApplicationState.h Normal file
View File

@ -0,0 +1,75 @@
#pragma once
#include "common.h"
#include "input/Input.h"
#include "utils/DrawUtils.h"
#include "version.h"
#include <cstdint>
class ApplicationState {
public:
enum eSubState {
SUBSTATE_RUNNING,
SUBSTATE_RETURN,
SUBSTATE_SHUTDOWN,
};
virtual ~ApplicationState() = default;
virtual void render() = 0;
virtual eSubState update(Input *input) = 0;
virtual void proccessMenuNavigationY(Input *input, int32_t maxOptionValue) {
if (input->data.buttons_d & Input::BUTTON_UP) {
this->selectedOptionY--;
} else if (input->data.buttons_d & Input::BUTTON_DOWN) {
this->selectedOptionY++;
}
if (this->selectedOptionY < 0) {
this->selectedOptionY = maxOptionValue - 1;
} else if (this->selectedOptionY >= maxOptionValue) {
this->selectedOptionY = 0;
}
}
virtual void proccessMenuNavigationX(Input *input, int32_t maxOptionValue) {
if ((input->data.buttons_d & Input::BUTTON_LEFT) || (input->data.buttons_d & Input::BUTTON_L)) {
this->selectedOptionX--;
} else if ((input->data.buttons_d & Input::BUTTON_RIGHT) || (input->data.buttons_d & Input::BUTTON_R)) {
this->selectedOptionX++;
}
if (this->selectedOptionX < 0) {
this->selectedOptionX = maxOptionValue - 1;
} else if (this->selectedOptionX >= maxOptionValue) {
this->selectedOptionX = 0;
}
}
virtual bool buttonPressed(Input *input, Input::eButtons button) {
return input->data.buttons_d & button;
}
virtual bool entrySelected(Input *input) {
return input->data.buttons_d & Input::BUTTON_A;
}
virtual void printHeader() {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 4, COLOR_WHITE);
DrawUtils::setFontSize(24);
DrawUtils::print(16, 34, "Aroma Updater " UPDATER_VERSION_FULL);
DrawUtils::setFontSize(20);
DrawUtils::drawRectFilled(0, 44, SCREEN_WIDTH, 2, COLOR_WHITE);
DrawUtils::drawRectFilled(0, SCREEN_HEIGHT - 40, SCREEN_WIDTH, 2, COLOR_WHITE);
}
virtual void printFooter() {
}
int selectedOptionY = 0;
int selectedOptionX = 0;
};

View File

@ -0,0 +1,83 @@
/****************************************************************************
* Copyright (C) 2021 Maschell
*
* 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 <http://www.gnu.org/licenses/>.
****************************************************************************/
#include "MainApplicationState.h"
#include "UpdaterState.h"
#include "common.h"
#include "utils/DrawUtils.h"
#include "utils/logger.h"
MainApplicationState::MainApplicationState() {
this->state = STATE_WELCOME_SCREEN;
}
MainApplicationState::~MainApplicationState() = default;
void MainApplicationState::render() {
if (this->state == STATE_DO_SUBSTATE) {
if (this->subState == nullptr) {
OSFatal("SubState was null");
}
this->subState->render();
return;
}
DrawUtils::beginDraw();
DrawUtils::clear(BACKGROUND_COLOR);
if (this->state == STATE_WELCOME_SCREEN) {
printHeader();
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(30);
const char *text = "Welcome to the Aroma Updater";
DrawUtils::print(SCREEN_WIDTH / 2 - DrawUtils::getTextWidth(text) / 2, SCREEN_HEIGHT / 2 - 15, text);
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Check for updates", true);
const char *exitHint = "\ue044 Exit";
DrawUtils::print(SCREEN_WIDTH / 2 + DrawUtils::getTextWidth(exitHint) / 2, SCREEN_HEIGHT - 14, exitHint, true);
printFooter();
}
DrawUtils::endDraw();
}
ApplicationState::eSubState MainApplicationState::update(Input *input) {
if (this->state == STATE_WELCOME_SCREEN) {
proccessMenuNavigationY(input, 1);
if (entrySelected(input)) {
if (this->selectedOptionY == 0) {
this->state = STATE_DO_SUBSTATE;
this->subState = std::make_unique<UpdaterState>();
}
this->selectedOptionY = 0;
}
} else if (this->state == STATE_DO_SUBSTATE) {
auto retSubState = this->subState->update(input);
if (retSubState == SUBSTATE_RUNNING) {
// keep running.
return SUBSTATE_RUNNING;
} else if (retSubState == SUBSTATE_RETURN) {
this->subState.reset();
this->state = STATE_WELCOME_SCREEN;
} else if (retSubState == SUBSTATE_SHUTDOWN) {
this->subState.reset();
this->state = STATE_SHUTDOWN;
}
}
return SUBSTATE_RUNNING;
}

View File

@ -0,0 +1,48 @@
/****************************************************************************
* Copyright (C) 2021 Maschell
*
* 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 <http://www.gnu.org/licenses/>.
****************************************************************************/
#pragma once
#include "ApplicationState.h"
#include "input/Input.h"
#include <ctime>
#include <map>
#include <memory>
#include <optional>
#include <queue>
#include <string>
class MainApplicationState : public ApplicationState {
public:
enum eGameState {
STATE_WELCOME_SCREEN,
STATE_DO_SUBSTATE,
STATE_SHUTDOWN,
};
MainApplicationState();
~MainApplicationState() override;
void render() override;
ApplicationState::eSubState update(Input *input) override;
private:
std::unique_ptr<ApplicationState> subState{};
eGameState state = STATE_WELCOME_SCREEN;
};

View File

@ -0,0 +1,180 @@
#include "UpdaterState.h"
#include "utils/DownloadUtils.h"
#include "utils/FSUtils.h"
#include "utils/logger.h"
#include "utils/zip_file.hpp"
#include <coreinit/cache.h>
#include <coreinit/thread.h>
#include <mutex>
int DownloadFilesThreadEntry(UpdaterState *updater) {
std::lock_guard<std::mutex> lock(updater->mFilesDownloadListLock);
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos = DownloadInfos(updater->mFilesDownloadList.size());
}
for (auto &curFile : updater->mFilesDownloadList) {
DEBUG_FUNCTION_LINE("Download and extract %s", curFile.getPath().c_str());
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->curFile = curFile;
updater->mDownloadInfos->processStep = DownloadInfos::STEP_DOWNLOAD;
}
OSMemoryBarrier();
auto &curURL = curFile.getAsset().getBrowserDownloadUrl();
DEBUG_FUNCTION_LINE("Check if %s is in cache", curURL.c_str());
if (!updater->mZipDownloadCache.contains(curURL)) {
std::string downloadedZIP;
int responseCode;
updater->mProgress = 0.0f;
DEBUG_FUNCTION_LINE("Download %s", curURL.c_str());
if (DownloadUtils::DownloadFileToBuffer(curURL.c_str(), downloadedZIP, responseCode, &updater->mProgress) < 0 || responseCode != 200) {
DEBUG_FUNCTION_LINE_ERR("Download failed");
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->state = DownloadInfos::DOWNLOAD_FAILED;
OSMemoryBarrier();
return 0;
}
}
updater->mZipDownloadCache[curURL] = downloadedZIP;
} else {
DEBUG_FUNCTION_LINE("Use cached version.");
}
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->processStep = DownloadInfos::STEP_EXTRACT;
}
auto &curBuffer = updater->mZipDownloadCache[curURL];
std::istringstream iss(curBuffer);
miniz_cpp::zip_file zip(iss);
bool found = false;
// find asset
for (auto &assetFile : curFile.getAsset().getFiles()) {
if (assetFile.getSha1() == curFile.getSha1()) {
for (auto &member : zip.infolist()) {
if (member.filename == assetFile.getPath()) {
found = true;
auto fullPath = SD_PATH + curFile.getPath() + UPDATE_TEMP_SUFFIX;
std::filesystem::path path = fullPath;
if (CreateSubfolder(path.remove_filename().c_str()) == 0) {
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->state = DownloadInfos::DOWNLOAD_CREATE_DIR_FAILED;
OSMemoryBarrier();
return 0;
}
DEBUG_FUNCTION_LINE("Extract %s to %s", member.filename.c_str(), fullPath.c_str());
std::string ss = zip.read(member);
if (saveBufferToFile(fullPath.c_str(), (void *) ss.c_str(), ss.length()) < 0) {
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->state = DownloadInfos::DOWNLOAD_EXTRACT_FAILED;
OSMemoryBarrier();
return 0;
}
}
DEBUG_FUNCTION_LINE("Extract done");
break;
}
}
break;
}
}
if (!found) {
DEBUG_FUNCTION_LINE_ERR("Failed to find file in zip");
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->state = DownloadInfos::DOWNLOAD_NOT_FOUND_IN_ZIP;
OSMemoryBarrier();
}
return 0;
}
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->filesDone++;
OSMemoryBarrier();
}
}
{
std::lock_guard<std::mutex> lockInfo(updater->mDownloadInfosLock);
updater->mDownloadInfos->state = DownloadInfos::DOWNLOAD_SUCCESS;
OSMemoryBarrier();
}
return 0;
}
ApplicationState::eSubState UpdaterState::UpdateProcessDownloadFiles(Input *input) {
if (mDownloadFilesThread == nullptr) {
OSMemoryBarrier();
mDownloadFilesThread = new (std::nothrow) std::thread(DownloadFilesThreadEntry, this);
if (mDownloadFilesThread == nullptr) {
setError(ERROR_FAILED_TO_CREATE_THREAD);
return ApplicationState::SUBSTATE_RUNNING;
}
auto nativeHandle = (OSThread *) mDownloadFilesThread->native_handle();
OSSetThreadName(nativeHandle, "DownloadFilesThread");
return ApplicationState::SUBSTATE_RUNNING;
}
{
std::lock_guard<std::mutex> lockInfo(this->mDownloadInfosLock);
if (!this->mDownloadInfos.has_value() || mDownloadInfos->state == DownloadInfos::DOWNLOAD_RUNNING) {
return ApplicationState::SUBSTATE_RUNNING;
}
}
mDownloadFilesThread->join();
delete mDownloadFilesThread;
mDownloadFilesThread = nullptr;
OSMemoryBarrier();
switch (mDownloadInfos->state) {
case DownloadInfos::DOWNLOAD_RUNNING:
setError(ERROR_UNKNOWN);
break;
case DownloadInfos::DOWNLOAD_SUCCESS:
this->mState = STATE_UPDATE_PROCESS_DOWNLOAD_FILES_FINISHED;
break;
case DownloadInfos::DOWNLOAD_FAILED:
setError(ERROR_DOWNLOAD_FAILED);
break;
case DownloadInfos::DOWNLOAD_EXTRACT_FAILED:
setError(ERROR_EXTRACT_FAILED);
break;
case DownloadInfos::DOWNLOAD_NOT_FOUND_IN_ZIP:
setError(ERROR_FAILED_TO_FIND_FILE_IN_ZIP);
break;
case DownloadInfos::DOWNLOAD_CREATE_DIR_FAILED:
setError(ERROR_FAILED_TO_CREATE_DIR);
break;
}
return ApplicationState::SUBSTATE_RUNNING;
}
void UpdaterState::RenderProcessDownloadFiles() {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
{
std::lock_guard<std::mutex> lock(mDownloadInfosLock);
if (mDownloadInfos.has_value()) {
DrawUtils::printf(16, 80, false, "Downloading and extracting files... %s", this->mLoadAnimation[mAnimationTick++ % this->mLoadAnimation.size()].c_str());
if (mDownloadInfos->curFile.has_value()) {
DrawUtils::printf(16, 100, false, "File: %s", mDownloadInfos->curFile->getPath().c_str());
if (mDownloadInfos->processStep == DownloadInfos::STEP_DOWNLOAD) {
if (this->mProgress > 0.0f) {
DrawUtils::printf(16, 120, false, "Downloading... %.0f%%", this->mProgress * 100.0f);
} else {
DrawUtils::printf(16, 120, false, "Downloading...");
}
} else {
DrawUtils::printf(16, 120, false, "Extracting...", mDownloadInfos->curFile->getPath().c_str());
}
}
DrawUtils::printf(16, 160, false, "%d of %d files done.", mDownloadInfos->filesDone, mDownloadInfos->totalFiles);
} else {
DrawUtils::printf(16, 80, false, "Preparing download of files...");
}
}
}

View File

@ -0,0 +1,79 @@
#include "UpdaterState.h"
#include "common.h"
#include "utils/UpdateUtils.h"
#include <coreinit/cache.h>
void UpdaterState::RenderError() {
DrawUtils::setFontColor(COLOR_RED);
DrawUtils::setFontSize(30);
DrawUtils::print(16, 90, "An error has happened:");
DrawUtils::setFontSize(20);
DrawUtils::print(16, 120, ErrorMessage());
if (this->mErrorState == ERROR_FAILED_COPY_FILES) {
DrawUtils::print(16, 160, "Your Aroma installation might has been corrupted. Please re-download Aroma");
DrawUtils::print(16, 180, "from " AROMA_DOWNLOAD_URL " and replace the files on the sd card.");
}
DrawUtils::setFontSize(18);
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Continue", true);
}
void UpdaterState::RenderConfirmPackages() {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::printf(16, 80, false, "The following packages will be updated or installed:");
uint32_t y = 120;
for (auto &base : this->mVersionInfo) {
for (auto &cat : base.getCategory()) {
for (auto &package : cat.getPackages()) {
if (package.getRequired() || package.getIsSelected()) {
if (package.getStatus() != VersionCheck::PackageStatus::Latest) {
DrawUtils::printf(16, y, false, "- %s", package.getName().c_str());
y += 20;
}
}
}
}
}
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Confirm", true);
DrawUtils::print(16, SCREEN_HEIGHT - 14, "\ue001 Return");
}
void UpdaterState::RenderCheckIndividualFile() {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
if (mCurFile.has_value()) {
DrawUtils::print(16, 80, "###### WARNING ######");
DrawUtils::printf(16, 100, false, "File: %s", mCurFile->getPath().c_str());
uint32_t y = 140;
if (mCurFile->getStatus() == VersionCheck::FileStatus::Newer) {
DrawUtils::print(16, y, "This version of this file is known, but is newer than expected.");
y += 20;
DrawUtils::print(16, y, "(Possibly from a nightly release?)");
y += 20;
DrawUtils::print(16, y, "Do you want to downgrade the file?");
y += 40;
} else if (mCurFile->getStatus() == VersionCheck::FileStatus::Error) {
DrawUtils::print(16, y, "Failed to check if this version of this file is known.");
y += 20;
DrawUtils::print(16, y, "Do you want to overwrite the file?");
y += 40;
} else {
DrawUtils::print(16, y, "This version of this file is unknown. Probably a custom build?");
y += 20;
DrawUtils::print(16, y, "Do you want to overwrite the file?");
y += 40;
}
DrawUtils::print(16, y, "Press A to confirm");
y += 20;
DrawUtils::print(16, y, "Press B to skip this file");
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Confirm", true);
DrawUtils::print(16, SCREEN_HEIGHT - 14, "\ue001 Skip");
}
}

325
source/UpdaterState.cpp Normal file
View File

@ -0,0 +1,325 @@
/****************************************************************************
* Copyright (C) 2021 Maschell
*
* 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 <http://www.gnu.org/licenses/>.
****************************************************************************/
#include "UpdaterState.h"
#include "utils/UpdateUtils.h"
UpdaterState::UpdaterState() {
this->mState = STATE_DOWNLOAD_VERSIONS;
this->mErrorState = ERROR_NONE;
this->mLoadAnimation = {"\ue020", "\ue021", "\ue022", "\ue023", "\ue024", "\ue025", "\ue026", "\ue027"};
}
UpdaterState::~UpdaterState() = default;
void UpdaterState::setError(UpdaterState::eErrorState err) {
this->mState = STATE_ERROR;
this->mErrorState = err;
}
extern "C" void OSShutdown();
ApplicationState::eSubState UpdaterState::update(Input *input) {
switch (this->mState) {
case STATE_ERROR: {
if (entrySelected(input)) {
return ApplicationState::SUBSTATE_RETURN;
}
return ApplicationState::SUBSTATE_RUNNING;
}
case STATE_DOWNLOAD_VERSIONS: {
return UpdaterState::UpdateDownloadVersions(input);
}
case STATE_PARSE_VERSIONS: {
return UpdaterState::UpdateParseVersions(input);
}
case STATE_CHECK_VERSIONS: {
return UpdaterState::UpdateCheckVersions(input);
}
case STATE_SHOW_VERSIONS: {
return UpdateShowVersionsMenu(input);
}
case STATE_SELECTED_PACKAGES_EMPTY: {
if (buttonPressed(input, Input::BUTTON_A)) {
mState = STATE_SHOW_VERSIONS;
} else if (buttonPressed(input, Input::BUTTON_B)) {
mState = STATE_SHOW_VERSIONS;
}
break;
}
case STATE_CONFIRM_PACKAGES: {
if (buttonPressed(input, Input::BUTTON_A)) {
mState = STATE_UPDATE_CHECK_FILES;
} else if (buttonPressed(input, Input::BUTTON_B)) {
mState = STATE_SHOW_VERSIONS;
}
break;
}
case STATE_UPDATE_CHECK_FILES: {
mFilesToUpdateAll = UpdateUtils::GetNonLatestFilesFromVersionInfo(mVersionInfo, mOnlyRequired);
mFilesToUpdateAllSize = mFilesToUpdateAll.size();
mState = STATE_UPDATE_GET_INDIVIDUAL_FILE;
break;
}
case STATE_UPDATE_GET_INDIVIDUAL_FILE: {
bool fullBreak = false;
while (!mFilesToUpdateAll.empty()) {
mCurFile = mFilesToUpdateAll.front();
mFilesToUpdateAll.erase(mFilesToUpdateAll.begin() + 0);
if (mCurFile->getStatus() == VersionCheck::FileStatus::Outdated ||
mCurFile->getStatus() == VersionCheck::FileStatus::Missing) {
mFilesToUpdateConfirmed.push_back(mCurFile.value());
mCurFile = {};
} else {
mState = STATE_UPDATE_CHECK_INDIVIDUAL_FILE;
fullBreak = true;
break;
}
}
if (fullBreak) {
break;
}
mCurFile = {};
if (!mFilesToUpdateConfirmed.empty() && (mFilesToUpdateConfirmed.size() == mFilesToUpdateAllSize)) {
mFilesDownloadList = mFilesToUpdateConfirmed;
mState = STATE_UPDATE_PROCESS_DOWNLOAD_FILES;
} else {
mState = STATE_UPDATE_PROCESS_FILES;
}
break;
}
case STATE_UPDATE_CHECK_INDIVIDUAL_FILE: {
if (!mCurFile.has_value()) {
setError(ERROR_UNKNOWN);
break;
} else {
if (buttonPressed(input, Input::BUTTON_A)) {
mFilesToUpdateConfirmed.push_back(mCurFile.value());
mState = STATE_UPDATE_GET_INDIVIDUAL_FILE;
} else if (buttonPressed(input, Input::BUTTON_B)) {
mState = STATE_UPDATE_GET_INDIVIDUAL_FILE;
} else {
break;
}
mCurFile = {};
}
break;
}
case STATE_UPDATE_PROCESS_FILES: {
if (!mFilesToUpdateConfirmed.empty()) {
if (buttonPressed(input, Input::BUTTON_A)) {
mFilesDownloadList = mFilesToUpdateConfirmed;
mState = STATE_UPDATE_PROCESS_DOWNLOAD_FILES;
break;
} else if (buttonPressed(input, Input::BUTTON_B)) {
return SUBSTATE_RETURN;
}
} else {
mState = STATE_UPDATE_PROCESS_FILES_EMPTY;
}
break;
}
case STATE_UPDATE_PROCESS_FILES_EMPTY: {
if (buttonPressed(input, Input::BUTTON_A)) {
return SUBSTATE_RETURN;
}
break;
}
case STATE_UPDATE_PROCESS_DOWNLOAD_FILES: {
return UpdaterState::UpdateProcessDownloadFiles(input);
}
case STATE_UPDATE_PROCESS_DOWNLOAD_FILES_FINISHED: {
return UpdaterState::UpdateDownloadFilesFinished(input);
}
case STATE_UPDATE_SUCCESS: {
if (buttonPressed(input, Input::BUTTON_A)) {
OSShutdown();
return SUBSTATE_SHUTDOWN;
}
break;
}
}
return ApplicationState::SUBSTATE_RUNNING;
}
void UpdaterState::render() {
DrawUtils::beginDraw();
DrawUtils::clear(BACKGROUND_COLOR);
ApplicationState::printHeader();
switch (mState) {
case STATE_ERROR: {
UpdaterState::RenderError();
break;
}
case STATE_DOWNLOAD_VERSIONS: {
UpdaterState::RenderDownloadVersions();
break;
}
case STATE_PARSE_VERSIONS: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::print(16, 80, "Parsing the latest versions...");
break;
}
case STATE_CHECK_VERSIONS: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
if (this->mProgress > 0.0f) {
DrawUtils::printf(16, 80, false, "Checking the version of each file, this might take a bit... %.0f%%. %s", this->mProgress * 100.0f, this->mLoadAnimation[mAnimationTick++ % this->mLoadAnimation.size()].c_str());
} else {
DrawUtils::printf(16, 80, false, "Checking the version of each file, this might take a bit... %s", this->mLoadAnimation[mAnimationTick++ % this->mLoadAnimation.size()].c_str());
}
break;
}
case STATE_SHOW_VERSIONS: {
UpdaterState::RenderShowVersions();
break;
}
case STATE_SELECTED_PACKAGES_EMPTY: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::printf(16, 80, false, "The selected packages are already up to date");
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Return", true);
break;
}
case STATE_CONFIRM_PACKAGES: {
UpdaterState::RenderConfirmPackages();
break;
}
case STATE_UPDATE_CHECK_FILES: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::print(16, 80, "Checking files..");
break;
}
case STATE_UPDATE_GET_INDIVIDUAL_FILE: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::print(16, 80, "Checking files...");
break;
}
case STATE_UPDATE_CHECK_INDIVIDUAL_FILE: {
UpdaterState::RenderCheckIndividualFile();
break;
}
case STATE_UPDATE_PROCESS_FILES: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::printf(16, 80, false, "You have skipped %d files.", mFilesToUpdateAllSize - mFilesToUpdateConfirmed.size());
DrawUtils::printf(16, 100, false, "Do you want to continue?");
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Confirm", true);
DrawUtils::print(16, SCREEN_HEIGHT - 14, "\ue001 Abort");
break;
}
case STATE_UPDATE_PROCESS_FILES_EMPTY:
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::print(16, 80, "All files that could be updated have been skipped.");
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Return", true);
break;
case STATE_UPDATE_PROCESS_DOWNLOAD_FILES: {
UpdaterState::RenderProcessDownloadFiles();
break;
}
case STATE_UPDATE_PROCESS_DOWNLOAD_FILES_FINISHED: {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
DrawUtils::print(16, 80, "Copy files...");
break;
}
case STATE_UPDATE_SUCCESS: {
DrawUtils::setFontSize(20);
DrawUtils::print(16, 80, "All files have been updated successfully.");
DrawUtils::print(16, 100, "The console will now shutdown.");
DrawUtils::setFontSize(18);
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, "\ue000 Shutdown", true);
break;
}
}
ApplicationState::printFooter();
DrawUtils::endDraw();
}
const char *UpdaterState::ErrorMessage() const {
switch (this->mErrorState) {
case ERROR_NONE:
return "ERROR_NONE";
case ERROR_FAILED_TO_DOWNLOAD_VERSIONS:
return "Failed to download the latest version information.";
case ERROR_FAILED_TO_PARSE_VERSIONS:
return "Failed to parse the latest version information.";
case ERROR_FAILED_TO_SAVE_FILE:
return "Failed to write a file to the sd card.";
case ERROR_FAILED_TO_FIND_FILE_IN_ZIP:
return "Failed to find the file in the zip.";
case ERROR_UNKNOWN:
return "Something unexpected has happened.";
case ERROR_DOWNLOAD_FAILED:
return "The download has failed";
case ERROR_EXTRACT_FAILED:
return "Extracting a file to the sd card has failed.";
case ERROR_FAILED_TO_CREATE_THREAD:
return "Creating a thread has failed.";
case ERROR_DOWNLOADED_FILES_INVALID:
return "The downloaded files were corrupt.";
case ERROR_FAILED_COPY_FILES:
return "Failed to finalize the update.";
case ERROR_FAILED_TO_CREATE_DIR:
return "Failed to create a directory.";
}
return "Something unexpected has happened.";
}
const char *UpdaterState::ErrorDescription() const {
switch (this->mErrorState) {
case ERROR_NONE:
return "ERROR_NONE";
case ERROR_FAILED_TO_DOWNLOAD_VERSIONS:
return "ERROR_FAILED_TO_DOWNLOAD_VERSIONS";
case ERROR_FAILED_TO_PARSE_VERSIONS:
return "ERROR_FAILED_TO_PARSE_VERSIONS";
case ERROR_FAILED_TO_SAVE_FILE:
return "ERROR_FAILED_TO_SAVE_FILE";
case ERROR_FAILED_TO_FIND_FILE_IN_ZIP:
return "ERROR_FAILED_TO_FIND_FILE_IN_ZIP";
case ERROR_UNKNOWN:
return "ERROR_UNKNOWN";
case ERROR_DOWNLOAD_FAILED:
return "ERROR_DOWNLOAD_FAILED";
case ERROR_EXTRACT_FAILED:
return "ERROR_EXTRACT_FAILED";
case ERROR_FAILED_TO_CREATE_THREAD:
return "ERROR_FAILED_TO_CREATE_THREAD";
case ERROR_DOWNLOADED_FILES_INVALID:
return "ERROR_DOWNLOADED_FILES_INVALID";
case ERROR_FAILED_COPY_FILES:
return "ERROR_FAILED_COPY_FILES";
case ERROR_FAILED_TO_CREATE_DIR:
return "ERROR_FAILED_TO_CREATE_DIR";
}
return "UNKNOWN_ERROR";
}

159
source/UpdaterState.h Normal file
View File

@ -0,0 +1,159 @@
/****************************************************************************
* Copyright (C) 2021 Maschell
*
* 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 <http://www.gnu.org/licenses/>.
****************************************************************************/
#pragma once
#include "ApplicationState.h"
#include "input/Input.h"
#include "utils/VersionCheck.h"
#include <array>
#include <map>
#include <memory>
#include <queue>
#include <string>
#include <thread>
class DownloadInfos {
public:
explicit DownloadInfos(uint32_t totalFiles) : totalFiles(totalFiles) {
this->state = DOWNLOAD_RUNNING;
}
enum eDownloadFileState {
DOWNLOAD_RUNNING,
DOWNLOAD_SUCCESS,
DOWNLOAD_FAILED,
DOWNLOAD_EXTRACT_FAILED,
DOWNLOAD_CREATE_DIR_FAILED,
DOWNLOAD_NOT_FOUND_IN_ZIP,
};
enum eProcessStep {
STEP_DOWNLOAD,
STEP_EXTRACT,
};
uint32_t filesDone = 0;
uint32_t totalFiles = 0;
std::optional<VersionCheck::RepositoryFile> curFile;
eProcessStep processStep = STEP_DOWNLOAD;
eDownloadFileState state = DOWNLOAD_RUNNING;
};
class UpdaterState : public ApplicationState {
public:
enum eDumpState {
STATE_ERROR,
STATE_DOWNLOAD_VERSIONS,
STATE_PARSE_VERSIONS,
STATE_CHECK_VERSIONS,
STATE_SHOW_VERSIONS,
STATE_SELECTED_PACKAGES_EMPTY,
STATE_CONFIRM_PACKAGES,
STATE_UPDATE_CHECK_FILES,
STATE_UPDATE_GET_INDIVIDUAL_FILE,
STATE_UPDATE_CHECK_INDIVIDUAL_FILE,
STATE_UPDATE_PROCESS_FILES,
STATE_UPDATE_PROCESS_FILES_EMPTY,
STATE_UPDATE_PROCESS_DOWNLOAD_FILES,
STATE_UPDATE_PROCESS_DOWNLOAD_FILES_FINISHED,
STATE_UPDATE_SUCCESS
};
enum eErrorState {
ERROR_NONE,
ERROR_DOWNLOAD_FAILED,
ERROR_EXTRACT_FAILED,
ERROR_FAILED_TO_DOWNLOAD_VERSIONS,
ERROR_FAILED_TO_PARSE_VERSIONS,
ERROR_FAILED_TO_SAVE_FILE,
ERROR_FAILED_TO_FIND_FILE_IN_ZIP,
ERROR_FAILED_TO_CREATE_THREAD,
ERROR_DOWNLOADED_FILES_INVALID,
ERROR_FAILED_COPY_FILES,
ERROR_FAILED_TO_CREATE_DIR,
ERROR_UNKNOWN
};
enum eDownloadState {
DOWNLOAD_RUNNING,
DOWNLOAD_SUCCESS,
DOWNLOAD_FAILED,
};
explicit UpdaterState();
~UpdaterState() override;
void setError(eErrorState err);
void render() override;
void RenderError();
void RenderDownloadVersions();
void RenderShowVersions();
void RenderConfirmPackages();
void RenderCheckIndividualFile();
void RenderProcessDownloadFiles();
ApplicationState::eSubState UpdateProcessDownloadFiles(Input *input);
ApplicationState::eSubState UpdateDownloadVersions(Input *input);
ApplicationState::eSubState UpdateParseVersions(Input *input);
ApplicationState::eSubState UpdateCheckVersions(Input *input);
ApplicationState::eSubState UpdateShowVersionsMenu(Input *input);
eSubState update(Input *input) override;
[[nodiscard]] const char *ErrorMessage() const;
[[nodiscard]] const char *ErrorDescription() const;
eDumpState mState;
std::map<std::string, std::string> mZipDownloadCache;
std::mutex mVersionBufferLock;
std::string mVersionBuffer;
eErrorState mErrorState;
VersionCheck::VersionInfo mVersionInfo;
bool mOnlyRequired = false;
int32_t mTotalPackageCount = 0;
std::vector<VersionCheck::RepositoryFile> mFilesToUpdateAll;
uint32_t mFilesToUpdateAllSize = 0;
std::vector<VersionCheck::RepositoryFile> mFilesToUpdateConfirmed;
std::mutex mFilesDownloadListLock;
std::vector<VersionCheck::RepositoryFile> mFilesDownloadList;
std::mutex mDownloadInfosLock;
std::optional<DownloadInfos> mDownloadInfos;
std::optional<VersionCheck::RepositoryFile> mCurFile = {};
std::mutex mVersionInfoLock;
std::thread *mCheckFilesThread = nullptr;
std::thread *mDownloadInfoThread = nullptr;
std::thread *mDownloadFilesThread = nullptr;
bool mCheckFilesDone = false;
uint8_t mAnimationTick = 0;
eDownloadState mDownloadInfoResult = DOWNLOAD_RUNNING;
std::vector<std::string> mLoadAnimation;
float mProgress{};
ApplicationState::eSubState UpdateDownloadFilesFinished(Input *pInput);
};

View File

@ -0,0 +1,170 @@
#include "UpdaterState.h"
#include "common.h"
#include "utils/DownloadUtils.h"
#include "utils/UpdateUtils.h"
#include "utils/logger.h"
#include "utils/utils.h"
#include <coreinit/cache.h>
#include <coreinit/thread.h>
int DownloadVersionInfoThreadEntry(UpdaterState *updater) {
std::lock_guard<std::mutex> lock(updater->mVersionBufferLock);
int responseCode;
updater->mProgress = 0.0f;
if (DownloadUtils::DownloadFileToBuffer(UPDATE_SERVER_URL "/api/check_versions", updater->mVersionBuffer, responseCode, &updater->mProgress) < 0 || responseCode != 200) {
DEBUG_FUNCTION_LINE_ERR("Error while downloading");
updater->mDownloadInfoResult = UpdaterState::DOWNLOAD_FAILED;
} else {
updater->mDownloadInfoResult = UpdaterState::DOWNLOAD_SUCCESS;
}
OSMemoryBarrier();
return 0;
}
ApplicationState::eSubState UpdaterState::UpdateDownloadVersions(Input *input) {
if (mDownloadInfoThread == nullptr) {
mDownloadInfoResult = DOWNLOAD_RUNNING;
mDownloadInfoThread = new (std::nothrow) std::thread(DownloadVersionInfoThreadEntry, this);
if (mDownloadInfoThread == nullptr) {
mDownloadInfoResult = DOWNLOAD_FAILED;
setError(ERROR_FAILED_TO_CREATE_THREAD);
return ApplicationState::SUBSTATE_RUNNING;
}
auto nativeHandle = (OSThread *) mDownloadInfoThread->native_handle();
OSSetThreadName(nativeHandle, "DownloadVersionInfoThread");
OSMemoryBarrier();
return ApplicationState::SUBSTATE_RUNNING;
}
if (mDownloadInfoResult == DOWNLOAD_RUNNING) {
return ApplicationState::SUBSTATE_RUNNING;
}
mDownloadInfoThread->join();
delete mDownloadInfoThread;
mDownloadInfoThread = nullptr;
OSMemoryBarrier();
if (mDownloadInfoResult == DOWNLOAD_SUCCESS) {
this->mState = STATE_PARSE_VERSIONS;
} else {
setError(ERROR_FAILED_TO_DOWNLOAD_VERSIONS);
}
return ApplicationState::SUBSTATE_RUNNING;
}
ApplicationState::eSubState UpdaterState::UpdateParseVersions(Input *input) {
try {
std::lock_guard<std::mutex> lock(mVersionInfoLock);
std::lock_guard<std::mutex> lock1(mVersionBufferLock);
mVersionInfo = nlohmann::json::parse(mVersionBuffer.c_str());
mVersionBuffer.clear();
} catch (std::exception &e) {
this->setError(ERROR_FAILED_TO_PARSE_VERSIONS);
return SUBSTATE_RUNNING;
}
this->mState = STATE_CHECK_VERSIONS;
return SUBSTATE_RUNNING;
}
int CheckIndividualFileVersions(UpdaterState *updater) {
std::lock_guard<std::mutex> lock(updater->mVersionInfoLock);
UpdateUtils::CheckFilesOfVersionInfo(updater->mVersionInfo, updater->mOnlyRequired, &updater->mProgress);
updater->mCheckFilesDone = true;
OSMemoryBarrier();
return 0;
}
ApplicationState::eSubState UpdaterState::UpdateCheckVersions(Input *input) {
if (mCheckFilesThread == nullptr) {
OSMemoryBarrier();
mCheckFilesThread = new (std::nothrow) std::thread(CheckIndividualFileVersions, this);
if (mCheckFilesThread == nullptr) {
setError(ERROR_FAILED_TO_CREATE_THREAD);
return SUBSTATE_RUNNING;
}
auto nativeHandle = (OSThread *) mCheckFilesThread->native_handle();
OSSetThreadName(nativeHandle, "CheckFilesOfVersionInfoThread");
return SUBSTATE_RUNNING;
}
if (!mCheckFilesDone) {
return SUBSTATE_RUNNING;
}
mCheckFilesThread->join();
delete mCheckFilesThread;
mCheckFilesThread = nullptr;
OSMemoryBarrier();
std::lock_guard<std::mutex> lock(mVersionInfoLock);
int32_t packageCount = 0;
for (auto &base : mVersionInfo) {
for (auto &cat : base.getCategory()) {
packageCount += cat.getPackagesCount(mOnlyRequired);
}
}
mTotalPackageCount = packageCount;
// Use a one Base Category per page.
std::vector<VersionCheck::BaseCategory> mPages;
constexpr float maxHeightForPage = 15.0f;
VersionCheck::BaseCategory curPage;
auto curPageName = string_format("Page %d", 1);
curPage.setName(curPageName);
float curHeight = 0.0f;
bool isFirstCat = true;
for (auto &baseCategory : mVersionInfo) {
for (auto &category : baseCategory.getCategory()) {
if (category.getPackagesCount(mOnlyRequired) == 0) {
continue;
}
if (!isFirstCat) {
curHeight += 1.5f;
}
curHeight++;
auto curPackageCount = (float) category.getPackagesCount(mOnlyRequired);
if (curHeight + curPackageCount <= maxHeightForPage) {
curPage.getMutableCategory().push_back(category);
curHeight += curPackageCount;
isFirstCat = false;
} else {
mPages.push_back(curPage);
curPage = {};
auto curPageNameIn = string_format("Page %d", mPages.size() + 1);
curPage.setName(curPageNameIn);
curPage.getMutableCategory().push_back(category);
curHeight = 1.0f + curPackageCount;
isFirstCat = false;
}
}
}
mPages.push_back(curPage);
mVersionInfo = mPages;
mState = STATE_SHOW_VERSIONS;
return SUBSTATE_RUNNING;
}
void UpdaterState::RenderDownloadVersions() {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
if (mDownloadInfoThread == nullptr || this->mProgress == 0.0f) {
DrawUtils::printf(16, 80, false, "Getting the latest versions... %s", this->mLoadAnimation[mAnimationTick++ % this->mLoadAnimation.size()].c_str());
} else {
DrawUtils::printf(16, 80, false, "Getting the latest versions... %.0f%% %s", this->mProgress * 100.0f, this->mLoadAnimation[mAnimationTick++ % this->mLoadAnimation.size()].c_str());
}
}

View File

@ -0,0 +1,166 @@
#include "UpdaterState.h"
#include "common.h"
#include "utils/logger.h"
#include "utils/utils.h"
#include <sys/stat.h>
bool CheckTempFilesValid(const std::vector<VersionCheck::RepositoryFile> &filesToCheck,
const std::string &base_path = SD_PATH,
const std::string &suffix = UPDATE_TEMP_SUFFIX);
bool CopyFilesFinal(const std::vector<VersionCheck::RepositoryFile> &filesToCheck,
const std::string &base_path = SD_PATH,
const std::string &suffix_temp = UPDATE_TEMP_SUFFIX,
const std::string &suffix_old = UPDATE_OLD_SUFFIX);
bool RenameCurrentToOld(const std::vector<VersionCheck::RepositoryFile> &filesToCheck,
const std::string &base_path = SD_PATH,
const std::string &suffix_old = UPDATE_OLD_SUFFIX);
bool RestoreOldToCurrent(const std::vector<VersionCheck::RepositoryFile> &filesToCheck,
const std::string &base_path = SD_PATH,
const std::string &suffix_old = UPDATE_OLD_SUFFIX);
bool RemoveTempFiles(const std::vector<VersionCheck::RepositoryFile> &filesToCheck,
const std::string &base_path = SD_PATH,
const std::string &suffix_temp = UPDATE_TEMP_SUFFIX);
bool CheckTempFilesValid(const std::vector<VersionCheck::RepositoryFile> &filesToCheck, const std::string &base_path, const std::string &suffix) {
bool allValid = true;
// Make sure the downloaded files have all the correct hash.
for (auto &file : filesToCheck) {
auto pathOnSDCardTemp = string_format("%s%s%s", base_path.c_str(), file.getPath().c_str(), suffix.c_str());
auto hashOfFileOnSDCard = hashFile(pathOnSDCardTemp);
if (hashOfFileOnSDCard.has_value()) {
if (hashOfFileOnSDCard != file.getSha1()) {
DEBUG_FUNCTION_LINE_WARN("File %s has a unexpected hash", pathOnSDCardTemp.c_str());
allValid = false;
break;
} else {
DEBUG_FUNCTION_LINE("File %s is valid", pathOnSDCardTemp.c_str());
}
} else {
DEBUG_FUNCTION_LINE_WARN("File %s doesn't exist", pathOnSDCardTemp.c_str());
allValid = false;
break;
}
}
return allValid;
}
bool CopyFilesFinal(const std::vector<VersionCheck::RepositoryFile> &filesToCheck, const std::string &base_path, const std::string &suffix_temp, const std::string &suffix_old) {
for (auto &file : filesToCheck) {
auto pathOnSDCard = string_format("%s%s", base_path.c_str(), file.getPath().c_str());
auto pathOnSDCardTemp = string_format("%s%s%s", base_path.c_str(), file.getPath().c_str(), suffix_temp.c_str());
auto pathOnSDCardOld = string_format("%s%s%s", base_path.c_str(), file.getPath().c_str(), suffix_old.c_str());
struct stat stBuf = {};
// Remove existing files. (Shouldn't happen)
if (stat(pathOnSDCard.c_str(), &stBuf) >= 0 && S_ISDIR(stBuf.st_mode)) {
DEBUG_FUNCTION_LINE("Remove %s", pathOnSDCard.c_str());
if (remove(pathOnSDCard.c_str()) < 0) {
DEBUG_FUNCTION_LINE_ERR("(Should not happen) Failed to remove %s", pathOnSDCard.c_str());
}
}
DEBUG_FUNCTION_LINE("Rename %s to %s", pathOnSDCardTemp.c_str(), pathOnSDCard.c_str());
if (rename(pathOnSDCardTemp.c_str(), pathOnSDCard.c_str()) < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to rename %s to %s", pathOnSDCardTemp.c_str(), pathOnSDCard.c_str());
return false;
}
if (file.getStatus() != VersionCheck::FileStatus::Missing) {
DEBUG_FUNCTION_LINE("Remove %s", pathOnSDCardOld.c_str());
if (remove(pathOnSDCardOld.c_str()) < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to remove %s", pathOnSDCardOld.c_str());
}
}
}
return true;
}
bool RenameCurrentToOld(const std::vector<VersionCheck::RepositoryFile> &filesToCheck, const std::string &base_path, const std::string &suffix_old) {
// Rename the target files to .update.old if it exists.
bool allSuccessful = true;
for (auto &file : filesToCheck) {
auto pathOnSDCard = string_format("%s%s", base_path.c_str(), file.getPath().c_str());
auto pathOnSDCardOld = string_format("%s%s%s", base_path.c_str(), file.getPath().c_str(), suffix_old.c_str());
// backup the files that actually exist.
if (file.getStatus() != VersionCheck::FileStatus::Missing) {
struct stat stBuf = {};
// Remove any old ".temp.old" files
if (stat(pathOnSDCardOld.c_str(), &stBuf) >= 0 && S_ISREG(stBuf.st_mode)) {
DEBUG_FUNCTION_LINE("Remove %s", pathOnSDCardOld.c_str());
if (remove(pathOnSDCardOld.c_str()) < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to remove %s", pathOnSDCardOld.c_str());
}
}
// rename file to ".temp.old"
DEBUG_FUNCTION_LINE("Rename %s to %s", pathOnSDCard.c_str(), pathOnSDCardOld.c_str());
if (rename(pathOnSDCard.c_str(), pathOnSDCardOld.c_str()) < 0) {
allSuccessful = false;
break;
}
}
}
return allSuccessful;
}
bool RestoreOldToCurrent(const std::vector<VersionCheck::RepositoryFile> &filesToCheck, const std::string &base_path, const std::string &suffix_old) {
DEBUG_FUNCTION_LINE("Try to restore files");
bool allSuccess = true;
// If renaming existing files to ".temp.old" failed, try to restore
for (auto &file : filesToCheck) {
if (file.getStatus() != VersionCheck::FileStatus::Missing) {
auto pathOnSDCard = string_format("%s%s", base_path.c_str(), file.getPath().c_str());
auto pathOnSDCardOld = string_format("%s%s%s", base_path.c_str(), file.getPath().c_str(), suffix_old.c_str());
struct stat stBuf = {};
if (stat(pathOnSDCardOld.c_str(), &stBuf) >= 0 && S_ISREG(stBuf.st_mode) && stat(pathOnSDCard.c_str(), &stBuf) < 0) {
DEBUG_FUNCTION_LINE("Try to restore %s", pathOnSDCard.c_str());
// rename file from ".temp.old"
DEBUG_FUNCTION_LINE("Rename %s to %s", pathOnSDCardOld.c_str(), pathOnSDCard.c_str());
if (rename(pathOnSDCardOld.c_str(), pathOnSDCard.c_str()) < 0) {
allSuccess = false;
DEBUG_FUNCTION_LINE_ERR("Failed to rename %s to %s", pathOnSDCardOld.c_str(), pathOnSDCard.c_str());
}
}
}
}
return allSuccess;
}
bool RemoveTempFiles(const std::vector<VersionCheck::RepositoryFile> &filesToCheck, const std::string &base_path, const std::string &suffix_temp) {
bool allSuccess = true;
// remove all temp files on error.
for (auto &file : filesToCheck) {
auto pathOnSDCardTemp = string_format("%s%s%s", base_path.c_str(), file.getPath().c_str(), suffix_temp.c_str());
DEBUG_FUNCTION_LINE("Remove %s", pathOnSDCardTemp.c_str());
if (remove(pathOnSDCardTemp.c_str()) < 0) {
DEBUG_FUNCTION_LINE_WARN("Failed to remove %s", pathOnSDCardTemp.c_str());
allSuccess = false;
}
}
return allSuccess;
}
ApplicationState::eSubState UpdaterState::UpdateDownloadFilesFinished(Input *pInput) {
if (!CheckTempFilesValid(mFilesToUpdateConfirmed)) {
RemoveTempFiles(mFilesToUpdateConfirmed);
setError(ERROR_DOWNLOADED_FILES_INVALID);
return SUBSTATE_RUNNING;
}
if (!RenameCurrentToOld(mFilesToUpdateConfirmed)) {
RestoreOldToCurrent(mFilesToUpdateConfirmed);
RemoveTempFiles(mFilesToUpdateConfirmed);
setError(ERROR_FAILED_COPY_FILES);
return SUBSTATE_RUNNING;
}
if (!CopyFilesFinal(mFilesToUpdateConfirmed)) {
RestoreOldToCurrent(mFilesToUpdateConfirmed);
RemoveTempFiles(mFilesToUpdateConfirmed);
setError(ERROR_FAILED_COPY_FILES);
return SUBSTATE_RUNNING;
}
mState = STATE_UPDATE_SUCCESS;
return SUBSTATE_RUNNING;
}

View File

@ -0,0 +1,163 @@
#include "UpdaterState.h"
#include "utils/UpdateUtils.h"
#include "utils/utils.h"
ApplicationState::eSubState UpdaterState::UpdateShowVersionsMenu(Input *input) {
auto oldX = selectedOptionX;
proccessMenuNavigationX(input, (int32_t) mVersionInfo.size());
if (selectedOptionX != oldX) {
selectedOptionY = 0;
} else {
proccessMenuNavigationY(input, mTotalPackageCount);
}
int32_t offset = 0;
bool stop = false;
if (entrySelected(input)) {
for (auto &base : mVersionInfo) {
if (stop) { break; }
for (auto &cat : base.getMutableCategory()) {
if (stop) { break; }
for (auto &package : cat.getMutablePackages()) {
if (!package.getRequired() && mOnlyRequired) {
continue;
}
if (offset == selectedOptionY) {
package.toggleSelect();
stop = true;
break;
}
offset++;
}
}
}
}
if (buttonPressed(input, Input::BUTTON_PLUS)) {
uint32_t countValid = 0;
for (auto &base : this->mVersionInfo) {
for (auto &cat : base.getCategory()) {
for (auto &package : cat.getPackages()) {
if (package.getRequired() || package.getIsSelected()) {
if (package.getStatus() != VersionCheck::PackageStatus::Latest) {
countValid++;
break;
}
}
}
}
}
if (countValid > 0) {
mState = STATE_CONFIRM_PACKAGES;
} else {
mState = STATE_SELECTED_PACKAGES_EMPTY;
}
}
return SUBSTATE_RUNNING;
}
void UpdaterState::RenderShowVersions() {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::setFontSize(20);
uint32_t x;
uint32_t y = 100;
DrawUtils::print(16, 70, "Please select the packages you want to update/install:");
DrawUtils::print(SCREEN_WIDTH - 16, y, "Last update:", true);
auto pageText = string_format("Page %d/%d", selectedOptionX + 1, mVersionInfo.size());
DrawUtils::print(SCREEN_WIDTH / 2 - DrawUtils::getTextWidth(pageText.c_str()) / 2, y, pageText.c_str());
y = 120;
DrawUtils::setFontSize(20);
bool isSelectedHint = false;
bool isRequiredHint = false;
int packageI = 0;
auto &curPage = mVersionInfo[selectedOptionX];
for (auto &category : curPage.getCategory()) {
x = 40;
if (category.getPackagesCount(mOnlyRequired) == 0) {
continue;
}
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::printf(x, y, false, "%s:", category.getName().c_str());
y += 25;
x += 25;
for (auto &package : category.getPackages()) {
if (!package.getRequired() && mOnlyRequired) {
continue;
}
if (packageI == selectedOptionY) {
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::print(17, y - 2, "\ue090");
isSelectedHint = package.getIsSelected();
isRequiredHint = package.getRequired();
}
uint32_t boxsize = 16;
uint32_t boxborder = 2;
DrawUtils::drawRect(40, y - boxsize, boxsize, boxsize, boxborder, COLOR_WHITE);
if (package.getRequired() || package.getIsSelected()) {
DrawUtils::drawRectFilled(40 + (boxborder * 2), y - boxsize + (boxborder * 2), boxsize - boxborder * 4, boxsize - boxborder * 4, package.getRequired() ? COLOR_GRAY : COLOR_WHITE);
}
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::printf(x, y, false, "%s", package.getName().c_str());
if (package.getStatus() == VersionCheck::PackageStatus::Latest) {
DrawUtils::setFontColor(COLOR_GREEN);
} else {
DrawUtils::setFontColor(COLOR_YELLOW);
}
DrawUtils::printf(x + DrawUtils::getTextWidth(package.getName().c_str()) + (package.getRequired() ? DrawUtils::getTextWidth("*") : 0) + 5,
y,
false,
"[%s]",
UpdateUtils::StatusToString(package.getStatus()));
if (package.getRequired()) {
DrawUtils::setFontColor(COLOR_RED);
DrawUtils::print(x + DrawUtils::getTextWidth(package.getName().c_str()), y, "*");
}
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::printf(SCREEN_WIDTH - 16, y, true, "%s", package.getLastUpdateDate().substr(0, 10).c_str());
y += 20;
packageI++;
}
y += 20;
}
DrawUtils::setFontSize(18);
DrawUtils::setFontColor(COLOR_RED);
DrawUtils::print(16, SCREEN_HEIGHT - 50, "*");
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::print(16 + DrawUtils::getTextWidth("*"), SCREEN_HEIGHT - 50, "This package is required");
DrawUtils::setFontColor(COLOR_WHITE);
DrawUtils::print(16, SCREEN_HEIGHT - 14, "\ue07d Navigate packages / \ue083\ue084 Change pages");
if (!isRequiredHint) {
DrawUtils::printf(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, true, "\ue000 %s", isSelectedHint ? "Unselect" : "Select");
} else {
DrawUtils::printf(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 14, true, "(This package is required)");
}
const char *updateHint = "Press \ue045 to update";
DrawUtils::print(SCREEN_WIDTH - 16, SCREEN_HEIGHT - 50, updateHint, true);
}

13
source/common.h Normal file
View File

@ -0,0 +1,13 @@
#pragma once
#define BACKGROUND_COLOR COLOR_BLACK
#define AROMA_DOWNLOAD_URL "https://aroma.foryour.cafe/"
#define UPDATE_SERVER_URL "https://aroma.foryour.cafe"
#define CERT_FILE_LOCATION "fs:/vol/content/cacert.pem"
#define SD_PATH "fs:/vol/external01/"
#define UPDATE_OLD_SUFFIX ".update.old"
#define UPDATE_TEMP_SUFFIX ".update.temp"
#define UPDATER_VERSION "v0.1"
#define UPDATER_VERSION_FULL UPDATER_VERSION UPDATER_VERSION_EXTRA

View File

@ -0,0 +1,20 @@
#pragma once
#include "Input.h"
class CombinedInput : public Input {
public:
void combine(const Input &b) {
data.buttons_h |= b.data.buttons_h;
}
void process() {
data.buttons_d |= (data.buttons_h & (~lastData.buttons_h));
data.buttons_r |= (lastData.buttons_h & (~data.buttons_h));
lastData.buttons_h = data.buttons_h;
}
void reset() {
data.buttons_h = 0;
data.buttons_d = 0;
data.buttons_r = 0;
}
};

60
source/input/Input.h Normal file
View File

@ -0,0 +1,60 @@
#pragma once
#include <cstdint>
#include <cstring>
class Input {
public:
//!Constructor
Input() = default;
//!Destructor
virtual ~Input() = default;
enum eButtons {
BUTTON_NONE = 0x0000,
VPAD_TOUCH = 0x80000000,
BUTTON_Z = 0x20000,
BUTTON_C = 0x10000,
BUTTON_A = 0x8000,
BUTTON_B = 0x4000,
BUTTON_X = 0x2000,
BUTTON_Y = 0x1000,
BUTTON_1 = BUTTON_Y,
BUTTON_2 = BUTTON_X,
BUTTON_LEFT = 0x0800,
BUTTON_RIGHT = 0x0400,
BUTTON_UP = 0x0200,
BUTTON_DOWN = 0x0100,
BUTTON_ZL = 0x0080,
BUTTON_ZR = 0x0040,
BUTTON_L = 0x0020,
BUTTON_R = 0x0010,
BUTTON_PLUS = 0x0008,
BUTTON_MINUS = 0x0004,
BUTTON_HOME = 0x0002,
BUTTON_SYNC = 0x0001,
STICK_R_LEFT = 0x04000000,
STICK_R_RIGHT = 0x02000000,
STICK_R_UP = 0x01000000,
STICK_R_DOWN = 0x00800000,
STICK_L_LEFT = 0x40000000,
STICK_L_RIGHT = 0x20000000,
STICK_L_UP = 0x10000000,
STICK_L_DOWN = 0x08000000
};
typedef struct {
uint32_t buttons_h;
uint32_t buttons_d;
uint32_t buttons_r;
bool validPointer;
bool touched;
float pointerAngle;
int32_t x;
int32_t y;
} PadData;
PadData data{};
PadData lastData{};
};

61
source/input/VPADInput.h Normal file
View File

@ -0,0 +1,61 @@
#pragma once
/****************************************************************************
* Copyright (C) 2015 Dimok
*
* 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 <http://www.gnu.org/licenses/>.
****************************************************************************/
#include "Input.h"
#include <vpad/input.h>
class VPadInput : public Input {
public:
//!Constructor
VPadInput() {
memset(&vpad, 0, sizeof(vpad));
}
//!Destructor
~VPadInput() override = default;
bool update(int32_t width, int32_t height) {
lastData = data;
VPADReadError vpadError = VPAD_READ_NO_SAMPLES;
VPADRead(VPAD_CHAN_0, &vpad, 1, &vpadError);
if (vpadError == VPAD_READ_SUCCESS) {
data.buttons_r = vpad.release;
data.buttons_h = vpad.hold;
data.buttons_d = vpad.trigger;
data.validPointer = !vpad.tpNormal.validity;
data.touched = vpad.tpNormal.touched;
VPADGetTPCalibratedPoint(VPAD_CHAN_0, &tpCalib, &vpad.tpFiltered1);
//! calculate the screen offsets
data.x = -(width >> 1) + (int32_t) (((float) tpCalib.x / 1280.0f) * (float) width);
data.y = -(height >> 1) + (int32_t) (float) height - (((float) tpCalib.y / 720.0f) * (float) height);
return true;
} else {
data.buttons_h = 0;
}
return false;
}
private:
VPADStatus vpad{};
VPADTouchData tpCalib{};
};

177
source/input/WPADInput.h Normal file
View File

@ -0,0 +1,177 @@
#pragma once
/****************************************************************************
* Copyright (C) 2015 Dimok
*
* 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 <http://www.gnu.org/licenses/>.
****************************************************************************/
#include "Input.h"
#include <padscore/kpad.h>
#include <padscore/wpad.h>
class WPADInput : public Input {
public:
WPADInput(KPADChan channel) {
this->channel = channel;
}
~WPADInput() override {}
uint32_t remapWiiMoteButtons(uint32_t buttons) {
uint32_t conv_buttons = 0;
if (buttons & WPAD_BUTTON_LEFT)
conv_buttons |= Input::BUTTON_LEFT;
if (buttons & WPAD_BUTTON_RIGHT)
conv_buttons |= Input::BUTTON_RIGHT;
if (buttons & WPAD_BUTTON_DOWN)
conv_buttons |= Input::BUTTON_DOWN;
if (buttons & WPAD_BUTTON_UP)
conv_buttons |= Input::BUTTON_UP;
if (buttons & WPAD_BUTTON_PLUS)
conv_buttons |= Input::BUTTON_PLUS;
if (buttons & WPAD_BUTTON_2)
conv_buttons |= Input::BUTTON_2;
if (buttons & WPAD_BUTTON_1)
conv_buttons |= Input::BUTTON_1;
if (buttons & WPAD_BUTTON_B)
conv_buttons |= Input::BUTTON_B;
if (buttons & WPAD_BUTTON_A)
conv_buttons |= Input::BUTTON_A;
if (buttons & WPAD_BUTTON_MINUS)
conv_buttons |= Input::BUTTON_MINUS;
if (buttons & WPAD_BUTTON_Z)
conv_buttons |= Input::BUTTON_Z;
if (buttons & WPAD_BUTTON_C)
conv_buttons |= Input::BUTTON_C;
if (buttons & WPAD_BUTTON_HOME)
conv_buttons |= Input::BUTTON_HOME;
return conv_buttons;
}
uint32_t remapClassicButtons(uint32_t buttons) {
uint32_t conv_buttons = 0;
if (buttons & WPAD_CLASSIC_BUTTON_LEFT)
conv_buttons |= Input::BUTTON_LEFT;
if (buttons & WPAD_CLASSIC_BUTTON_RIGHT)
conv_buttons |= Input::BUTTON_RIGHT;
if (buttons & WPAD_CLASSIC_BUTTON_DOWN)
conv_buttons |= Input::BUTTON_DOWN;
if (buttons & WPAD_CLASSIC_BUTTON_UP)
conv_buttons |= Input::BUTTON_UP;
if (buttons & WPAD_CLASSIC_BUTTON_PLUS)
conv_buttons |= Input::BUTTON_PLUS;
if (buttons & WPAD_CLASSIC_BUTTON_X)
conv_buttons |= Input::BUTTON_X;
if (buttons & WPAD_CLASSIC_BUTTON_Y)
conv_buttons |= Input::BUTTON_Y;
if (buttons & WPAD_CLASSIC_BUTTON_B)
conv_buttons |= Input::BUTTON_B;
if (buttons & WPAD_CLASSIC_BUTTON_A)
conv_buttons |= Input::BUTTON_A;
if (buttons & WPAD_CLASSIC_BUTTON_MINUS)
conv_buttons |= Input::BUTTON_MINUS;
if (buttons & WPAD_CLASSIC_BUTTON_HOME)
conv_buttons |= Input::BUTTON_HOME;
if (buttons & WPAD_CLASSIC_BUTTON_ZR)
conv_buttons |= Input::BUTTON_ZR;
if (buttons & WPAD_CLASSIC_BUTTON_ZL)
conv_buttons |= Input::BUTTON_ZL;
if (buttons & WPAD_CLASSIC_BUTTON_R)
conv_buttons |= Input::BUTTON_R;
if (buttons & WPAD_CLASSIC_BUTTON_L)
conv_buttons |= Input::BUTTON_L;
return conv_buttons;
}
bool update(int32_t width, int32_t height) {
lastData = data;
WPADExtensionType type;
if (WPADProbe(channel, &type) != 0) {
data.buttons_h = 0;
return false;
}
KPADRead(channel, &kpad, 1);
if (kpad.extensionType == WPAD_EXT_CORE || kpad.extensionType == WPAD_EXT_NUNCHUK) {
data.buttons_r = remapWiiMoteButtons(kpad.release);
data.buttons_h = remapWiiMoteButtons(kpad.hold);
data.buttons_d = remapWiiMoteButtons(kpad.trigger);
} else {
data.buttons_r = remapClassicButtons(kpad.classic.release);
data.buttons_h = remapClassicButtons(kpad.classic.hold);
data.buttons_d = remapClassicButtons(kpad.classic.trigger);
}
data.validPointer = (kpad.posValid == 1 || kpad.posValid == 2) &&
(kpad.pos.x >= -1.0f && kpad.pos.x <= 1.0f) &&
(kpad.pos.y >= -1.0f && kpad.pos.y <= 1.0f);
//! calculate the screen offsets if pointer is valid else leave old value
if (data.validPointer) {
data.x = (width >> 1) * kpad.pos.x;
data.y = (height >> 1) * (-kpad.pos.y);
if (kpad.angle.y > 0.0f) {
data.pointerAngle = (-kpad.angle.x + 1.0f) * 0.5f * 180.0f;
} else {
data.pointerAngle = (kpad.angle.x + 1.0f) * 0.5f * 180.0f - 180.0f;
}
}
return true;
}
static void init() {
KPADInit();
WPADEnableURCC(1);
}
static void close() {
}
private:
KPADStatus kpad{};
KPADChan channel;
};

82
source/main.cpp Normal file
View File

@ -0,0 +1,82 @@
#include "MainApplicationState.h"
#include "input/CombinedInput.h"
#include "input/VPADInput.h"
#include "input/WPADInput.h"
#include "utils/DownloadUtils.h"
#include "utils/DrawUtils.h"
#include "utils/logger.h"
#include <coreinit/energysaver.h>
#include <filesystem>
#include <sndcore2/core.h>
#include <whb/proc.h>
void main_loop() {
DEBUG_FUNCTION_LINE_VERBOSE("Creating state");
std::unique_ptr<MainApplicationState> state = std::make_unique<MainApplicationState>();
CombinedInput baseInput;
VPadInput vpadInput;
WPADInput wpadInputs[4] = {
WPAD_CHAN_0,
WPAD_CHAN_1,
WPAD_CHAN_2,
WPAD_CHAN_3};
DEBUG_FUNCTION_LINE_VERBOSE("Entering main loop");
while (WHBProcIsRunning()) {
baseInput.reset();
if (vpadInput.update(1280, 720)) {
baseInput.combine(vpadInput);
}
for (auto &wpadInput : wpadInputs) {
if (wpadInput.update(1280, 720)) {
baseInput.combine(wpadInput);
}
}
baseInput.process();
state->update(&baseInput);
state->render();
}
}
int main() {
initLogging();
WHBProcInit();
if (!DrawUtils::Init()) {
OSFatal("Failed to init DrawUtils");
}
AXInit();
WPADInput::init();
if (!DownloadUtils::Init()) {
DEBUG_FUNCTION_LINE_ERR("Failed to init DownloadUtils");
OSFatal("Failed to init DownloadUtils");
}
uint32_t isAPDEnabled;
IMIsAPDEnabled(&isAPDEnabled);
if (isAPDEnabled) {
DEBUG_FUNCTION_LINE_VERBOSE("Disable auto shutdown");
IMDisableAPD();
}
main_loop();
if (isAPDEnabled) {
DEBUG_FUNCTION_LINE_VERBOSE("Enable auto shutdown");
IMEnableAPD();
}
DownloadUtils::Deinit();
WPADInput::close();
DrawUtils::DeInit();
AXQuit();
deinitLogging();
return 0;
}

View File

@ -0,0 +1,147 @@
#include "DownloadUtils.h"
#include "../common.h"
#include "FSUtils.h"
#include "logger.h"
#include <coreinit/cache.h>
#include <curl/curl.h>
#define IO_BUFSIZE (128 * 1024) // 128 KB
bool DownloadUtils::libInitDone = false;
uint8_t *DownloadUtils::cacert_pem = nullptr;
uint32_t DownloadUtils::cacert_pem_size = 0;
static int initSocket(void *ptr, curl_socket_t socket, curlsocktype type) {
int o = 1;
// Activate WinScale
int r = setsockopt(socket, SOL_SOCKET, SO_WINSCALE, &o, sizeof(o));
if (r != 0) {
DEBUG_FUNCTION_LINE_ERR("initSocket: Error setting WinScale: %d", r);
return CURL_SOCKOPT_ERROR;
}
o = IO_BUFSIZE;
// Set receive buffersize
r = setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &o, sizeof(o));
if (r != 0) {
DEBUG_FUNCTION_LINE_ERR("initSocket: Error setting RBS: %d", r);
return CURL_SOCKOPT_ERROR;
}
return CURL_SOCKOPT_OK;
}
size_t writeCallback(char *buf, size_t size, size_t nmemb, void *up) {
auto *data = (std::string *) up;
data->append(buf, size * nmemb);
return size * nmemb; //tell curl how many bytes we handled
}
int progress_callback(void *clientp,
curl_off_t dltotal,
curl_off_t dlnow,
curl_off_t ultotal,
curl_off_t ulnow) {
if (clientp != nullptr) {
auto *progress = (float *) clientp;
if (dltotal > 0 && dlnow > 0) {
*progress = (float) dlnow / (float) dltotal;
} else {
*progress = 0.0f;
}
OSMemoryBarrier();
}
return 0;
}
bool DownloadUtils::Init() {
if (libInitDone) {
return true;
}
CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
if (res != CURLE_OK) {
return false;
}
if (LoadFileToMem(CERT_FILE_LOCATION, &cacert_pem, &cacert_pem_size) < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to load cert");
cacert_pem = nullptr;
cacert_pem_size = 0;
}
libInitDone = true;
return true;
}
void DownloadUtils::Deinit() {
if (!libInitDone) {
return;
}
free(cacert_pem);
cacert_pem = nullptr;
cacert_pem_size = 0;
curl_global_cleanup();
libInitDone = false;
}
int DownloadUtils::DownloadFileToBuffer(const char *url, std::string &outBuffer, int &responseCodeOut, float *progress) {
if (!libInitDone) {
return -1;
}
// Start a curl session
CURL *curl = curl_easy_init();
if (!curl) {
curl_global_cleanup();
return -1;
}
if (cacert_pem != nullptr) {
struct curl_blob blob {};
blob.data = (void *) cacert_pem;
blob.len = cacert_pem_size;
blob.flags = CURL_BLOB_COPY;
// Use the certificate bundle in the data
curl_easy_setopt(curl, CURLOPT_CAINFO_BLOB, &blob);
} else {
DEBUG_FUNCTION_LINE_ERR("Warning, missing certificate.");
return -4;
}
// Enable optimizations
curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, initSocket);
// Follow redirects
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
// Set the download URL
curl_easy_setopt(curl, CURLOPT_URL, url);
if (progress != nullptr) {
/* pass struct to callback */
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, progress);
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, progress_callback);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
}
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) &outBuffer);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &writeCallback);
if (curl_easy_perform(curl) != CURLE_OK) {
curl_easy_cleanup(curl);
curl_global_cleanup();
return -1;
}
int32_t response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
responseCodeOut = response_code;
curl_easy_cleanup(curl);
return 0;
}

View File

@ -0,0 +1,14 @@
#pragma once
#include <string>
class DownloadUtils {
public:
static bool Init();
static void Deinit();
static int DownloadFileToBuffer(const char *url, std::string &outBuffer, int &responseCodeOut, float *progress);
private:
static bool libInitDone;
static uint8_t *cacert_pem;
static uint32_t cacert_pem_size;
};

451
source/utils/DrawUtils.cpp Normal file
View File

@ -0,0 +1,451 @@
#include "DrawUtils.h"
#include "logger.h"
#include "utils.h"
#include <coreinit/cache.h>
#include <coreinit/memfrmheap.h>
#include <coreinit/memheap.h>
#include <coreinit/memory.h>
#include <coreinit/screen.h>
#include <cstdarg>
#include <cstdlib>
#include <malloc.h>
#include <png.h>
#include <proc_ui/procui.h>
// buffer width
#define TV_WIDTH 0x500
#define DRC_WIDTH 0x380
bool DrawUtils::isBackBuffer;
uint8_t *DrawUtils::tvBuffer = nullptr;
uint32_t DrawUtils::tvSize = 0;
uint8_t *DrawUtils::drcBuffer = nullptr;
uint32_t DrawUtils::drcSize = 0;
bool DrawUtils::hasForeground = false;
static SFT pFont = {};
uint32_t DrawUtils::fontSize = {};
std::map<uint32_t, std::map<uint32_t, SFT_Image>> DrawUtils::glyphCache;
static Color font_col(0xFFFFFFFF);
#define CONSOLE_FRAME_HEAP_TAG (0x000DECAF)
uint32_t DrawUtils::ProcCallbackAcquired([[maybe_unused]] void *context) {
MEMHeapHandle heap = MEMGetBaseHeapHandle(MEM_BASE_HEAP_MEM1);
if (DrawUtils::tvSize) {
DrawUtils::tvBuffer = static_cast<uint8_t *>(MEMAllocFromFrmHeapEx(heap, DrawUtils::tvSize, 0x100));
}
if (DrawUtils::drcSize) {
DrawUtils::drcBuffer = static_cast<uint8_t *>(MEMAllocFromFrmHeapEx(heap, DrawUtils::drcSize, 0x100));
}
DrawUtils::hasForeground = true;
OSScreenSetBufferEx(SCREEN_TV, DrawUtils::tvBuffer);
OSScreenSetBufferEx(SCREEN_DRC, DrawUtils::drcBuffer);
return 0;
}
uint32_t DrawUtils::ProcCallbackReleased([[maybe_unused]] void *context) {
MEMHeapHandle heap = MEMGetBaseHeapHandle(MEM_BASE_HEAP_MEM1);
MEMFreeByStateToFrmHeap(heap, CONSOLE_FRAME_HEAP_TAG);
DrawUtils::hasForeground = FALSE;
return 0;
}
bool DrawUtils::Init() {
if (!DrawUtils::initFont()) {
return false;
}
OSScreenInit();
DrawUtils::tvSize = OSScreenGetBufferSizeEx(SCREEN_TV);
DrawUtils::drcSize = OSScreenGetBufferSizeEx(SCREEN_DRC);
DrawUtils::ProcCallbackAcquired(nullptr);
OSScreenEnableEx(SCREEN_TV, TRUE);
OSScreenEnableEx(SCREEN_DRC, TRUE);
ProcUIRegisterCallback(PROCUI_CALLBACK_ACQUIRE, DrawUtils::ProcCallbackAcquired, nullptr, 100);
ProcUIRegisterCallback(PROCUI_CALLBACK_RELEASE, DrawUtils::ProcCallbackReleased, nullptr, 100);
clear(COLOR_BLACK);
return true;
}
void DrawUtils::DeInit() {
if (DrawUtils::hasForeground) {
OSScreenShutdown();
DrawUtils::ProcCallbackReleased(nullptr);
}
for (auto &fontSizeMap : glyphCache) {
for (auto &cachedGlyph : fontSizeMap.second) {
free(cachedGlyph.second.pixels);
}
}
glyphCache.clear();
}
void DrawUtils::beginDraw() {
uint32_t pixel = *(uint32_t *) tvBuffer;
// check which buffer is currently used
OSScreenPutPixelEx(SCREEN_TV, 0, 0, 0xABCDEF90);
if (*(uint32_t *) tvBuffer == 0xABCDEF90) {
isBackBuffer = false;
} else {
isBackBuffer = true;
}
// restore the pixel we used for checking
*(uint32_t *) tvBuffer = pixel;
}
void DrawUtils::endDraw() {
// OSScreenFlipBuffersEx already flushes the cache?
// DCFlushRange(tvBuffer, tvSize);
// DCFlushRange(drcBuffer, drcSize);
OSScreenFlipBuffersEx(SCREEN_DRC);
OSScreenFlipBuffersEx(SCREEN_TV);
}
void DrawUtils::clear(Color col) {
OSScreenClearBufferEx(SCREEN_TV, col.color);
OSScreenClearBufferEx(SCREEN_DRC, col.color);
}
void DrawUtils::drawPixel(uint32_t x, uint32_t y, uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
float opacity = a / 255.0f;
// put pixel in the drc buffer
uint32_t i = (x + y * DRC_WIDTH) * 4;
if (i + 3 < drcSize / 2) {
if (isBackBuffer) {
i += drcSize / 2;
}
if (a == 0xFF) {
drcBuffer[i] = r;
drcBuffer[i + 1] = g;
drcBuffer[i + 2] = b;
} else {
drcBuffer[i] = r * opacity + drcBuffer[i] * (1 - opacity);
drcBuffer[i + 1] = g * opacity + drcBuffer[i + 1] * (1 - opacity);
drcBuffer[i + 2] = b * opacity + drcBuffer[i + 2] * (1 - opacity);
}
}
uint32_t USED_TV_WIDTH = TV_WIDTH;
float scale = 1.5f;
if (DrawUtils::tvSize == 0x00FD2000) {
USED_TV_WIDTH = 1920;
scale = 2.25f;
}
// scale and put pixel in the tv buffer
for (uint32_t yy = (y * scale); yy < ((y * scale) + (uint32_t) scale); yy++) {
for (uint32_t xx = (x * scale); xx < ((x * scale) + (uint32_t) scale); xx++) {
uint32_t i = (xx + yy * USED_TV_WIDTH) * 4;
if (i + 3 < tvSize / 2) {
if (isBackBuffer) {
i += tvSize / 2;
}
if (a == 0xFF) {
tvBuffer[i] = r;
tvBuffer[i + 1] = g;
tvBuffer[i + 2] = b;
} else {
tvBuffer[i] = r * opacity + tvBuffer[i] * (1 - opacity);
tvBuffer[i + 1] = g * opacity + tvBuffer[i + 1] * (1 - opacity);
tvBuffer[i + 2] = b * opacity + tvBuffer[i + 2] * (1 - opacity);
}
}
}
}
}
void DrawUtils::drawRectFilled(uint32_t x, uint32_t y, uint32_t w, uint32_t h, Color col) {
for (uint32_t yy = y; yy < y + h; yy++) {
for (uint32_t xx = x; xx < x + w; xx++) {
drawPixel(xx, yy, col);
}
}
}
void DrawUtils::drawRect(uint32_t x, uint32_t y, uint32_t w, uint32_t h, uint32_t borderSize, Color col) {
drawRectFilled(x, y, w, borderSize, col);
drawRectFilled(x, y + h - borderSize, w, borderSize, col);
drawRectFilled(x, y, borderSize, h, col);
drawRectFilled(x + w - borderSize, y, borderSize, h, col);
}
void DrawUtils::drawBitmap(uint32_t x, uint32_t y, uint32_t target_width, uint32_t target_height, const uint8_t *data) {
if (data[0] != 'B' || data[1] != 'M') {
// invalid header
return;
}
uint32_t dataPos = __builtin_bswap32(*(uint32_t *) &(data[0x0A]));
uint32_t width = __builtin_bswap32(*(uint32_t *) &(data[0x12]));
uint32_t height = __builtin_bswap32(*(uint32_t *) &(data[0x16]));
if (dataPos == 0) {
dataPos = 54;
}
data += dataPos;
// TODO flip image since bitmaps are stored upside down
for (uint32_t yy = y; yy < y + target_height; yy++) {
for (uint32_t xx = x; xx < x + target_width; xx++) {
uint32_t i = (((xx - x) * width / target_width) + ((yy - y) * height / target_height) * width) * 3;
drawPixel(xx, yy, data[i + 2], data[i + 1], data[i], 0xFF);
}
}
}
static void png_read_data(png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead) {
void **data = (void **) png_get_io_ptr(png_ptr);
memcpy(outBytes, *data, byteCountToRead);
*((uint8_t **) data) += byteCountToRead;
}
void DrawUtils::drawPNG(uint32_t x, uint32_t y, const uint8_t *data) {
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
if (png_ptr == nullptr) {
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == nullptr) {
png_destroy_read_struct(&png_ptr, nullptr, nullptr);
return;
}
png_set_read_fn(png_ptr, (void *) &data, png_read_data);
png_read_info(png_ptr, info_ptr);
uint32_t width = 0;
uint32_t height = 0;
int bitDepth = 0;
int colorType = -1;
uint32_t retval = png_get_IHDR(png_ptr, info_ptr, &width, &height, &bitDepth, &colorType, nullptr, nullptr, nullptr);
if (retval != 1) {
return;
}
uint32_t bytesPerRow = png_get_rowbytes(png_ptr, info_ptr);
auto *rowData = new uint8_t[bytesPerRow];
for (uint32_t yy = y; yy < y + height; yy++) {
png_read_row(png_ptr, (png_bytep) rowData, nullptr);
for (uint32_t xx = x; xx < x + width; xx++) {
if (colorType == PNG_COLOR_TYPE_RGB_ALPHA) {
uint32_t i = (xx - x) * 4;
drawPixel(xx, yy, rowData[i], rowData[i + 1], rowData[i + 2], rowData[i + 3]);
} else if (colorType == PNG_COLOR_TYPE_RGB) {
uint32_t i = (xx - x) * 3;
drawPixel(xx, yy, rowData[i], rowData[i + 1], rowData[i + 2], 0xFF);
}
}
}
delete[] rowData;
png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
}
bool DrawUtils::initFont() {
void *font = nullptr;
uint32_t size = 0;
OSGetSharedData(OS_SHAREDDATATYPE_FONT_STANDARD, 0, &font, &size);
if (font && size) {
fontSize = 20;
pFont.xScale = 20;
pFont.yScale = 20,
pFont.flags = SFT_DOWNWARD_Y;
pFont.font = sft_loadmem(font, size);
if (!pFont.font) {
return false;
}
OSMemoryBarrier();
return true;
}
return false;
}
void DrawUtils::deinitFont() {
sft_freefont(pFont.font);
pFont.font = nullptr;
pFont = {};
}
void DrawUtils::setFontSize(uint32_t size) {
fontSize = size;
pFont.xScale = size;
pFont.yScale = size;
SFT_LMetrics metrics;
sft_lmetrics(&pFont, &metrics);
}
void DrawUtils::setFontColor(Color col) {
font_col = col;
}
static void draw_freetype_bitmap(SFT_Image *bmp, int32_t x, int32_t y) {
int32_t i, j, p, q;
int32_t x_max = x + bmp->width;
int32_t y_max = y + bmp->height;
auto *src = (uint8_t *) bmp->pixels;
for (i = x, p = 0; i < x_max; i++, p++) {
for (j = y, q = 0; j < y_max; j++, q++) {
if (i < 0 || j < 0 || i >= SCREEN_WIDTH || j >= SCREEN_HEIGHT) {
continue;
}
float opacity = src[q * bmp->width + p] / 255.0f;
DrawUtils::drawPixel(i, j, font_col.r, font_col.g, font_col.b, font_col.a * opacity);
}
}
}
void DrawUtils::printf(uint32_t x, uint32_t y, bool alignRight, const char *fmt, ...) {
char *buf = (char *) malloc(4096);
va_list va;
if (!buf) {
return;
}
va_start(va, fmt);
vsnprintf(buf, 4096, reinterpret_cast<const char *>(fmt), va);
DrawUtils::print(x, y, buf, alignRight);
free(buf);
va_end(va);
}
void DrawUtils::print(uint32_t x, uint32_t y, const char *string, bool alignRight) {
auto *buffer = new wchar_t[strlen(string) + 1];
size_t num = mbstowcs(buffer, string, strlen(string));
if (num > 0) {
buffer[num] = 0;
} else {
wchar_t *tmp = buffer;
while ((*tmp++ = *string++))
;
}
print(x, y, buffer, alignRight);
delete[] buffer;
}
void DrawUtils::print(uint32_t x, uint32_t y, const wchar_t *string, bool alignRight) {
auto penX = (int32_t) x;
auto penY = (int32_t) y;
if (alignRight) {
penX -= getTextWidth(string);
}
uint16_t textureWidth = 0, textureHeight = 0;
for (; *string; string++) {
SFT_Glyph gid; // unsigned long gid;
if (sft_lookup(&pFont, *string, &gid) >= 0) {
SFT_GMetrics mtx;
if (sft_gmetrics(&pFont, gid, &mtx) < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to get glyph metrics");
return;
}
if (*string == '\n') {
penY += mtx.minHeight;
penX = x;
continue;
}
if (!glyphCache[fontSize].contains(gid)) {
textureWidth = (mtx.minWidth + 3) & ~3;
textureHeight = mtx.minHeight;
SFT_Image img = {
.pixels = nullptr,
.width = textureWidth,
.height = textureHeight,
};
if (textureWidth == 0) {
textureWidth = 4;
}
if (textureHeight == 0) {
textureHeight = 4;
}
auto buffer = malloc(img.width * img.height);
if (!buffer) {
DEBUG_FUNCTION_LINE_ERR("Failed to allocate memory for glyph");
return;
}
img.pixels = buffer;
if (sft_render(&pFont, gid, img) < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to render glyph");
return;
} else {
glyphCache[fontSize][gid] = img;
}
}
auto img = glyphCache.at(fontSize).at(gid);
draw_freetype_bitmap(&img, (int32_t) (penX + mtx.leftSideBearing), (int32_t) (penY + mtx.yOffset));
penX += (int32_t) mtx.advanceWidth;
}
}
}
uint32_t DrawUtils::getTextWidth(const char *string) {
auto *buffer = new wchar_t[strlen(string) + 1];
size_t num = mbstowcs(buffer, string, strlen(string));
if (num > 0) {
buffer[num] = 0;
} else {
wchar_t *tmp = buffer;
while ((*tmp++ = *string++))
;
}
uint32_t width = getTextWidth(buffer);
delete[] buffer;
return width;
}
uint32_t DrawUtils::getTextWidth(const wchar_t *string) {
uint32_t width = 0;
for (; *string; string++) {
SFT_Glyph gid; // unsigned long gid;
if (sft_lookup(&pFont, *string, &gid) >= 0) {
SFT_GMetrics mtx;
if (sft_gmetrics(&pFont, gid, &mtx) < 0) {
DEBUG_FUNCTION_LINE_ERR("bad glyph metrics");
}
width += (int32_t) mtx.advanceWidth;
}
}
return (uint32_t) width;
}

97
source/utils/DrawUtils.h Normal file
View File

@ -0,0 +1,97 @@
#pragma once
#include "schrift.h"
#include <cstdint>
#include <map>
// visible screen sizes
#define SCREEN_WIDTH 854
#define SCREEN_HEIGHT 480
union Color {
explicit Color(uint32_t color) {
this->color = color;
}
Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a) {
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
uint32_t color{};
struct {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
};
#define COLOR_GRAY Color(128, 128, 128, 255)
#define COLOR_WHITE Color(255, 255, 255, 255)
#define COLOR_BLACK Color(0, 0, 0, 255)
#define COLOR_YELLOW Color(255, 255, 0, 255)
#define COLOR_GREEN Color(128, 255, 0, 255)
#define COLOR_RED Color(255, 0, 0, 255)
#define COLOR_BLUE Color(0, 0, 170, 255)
class DrawUtils {
public:
static uint32_t ProcCallbackAcquired([[maybe_unused]] void *context);
static uint32_t ProcCallbackReleased([[maybe_unused]] void *context);
static bool Init();
static void DeInit();
static void beginDraw();
static void endDraw();
static void clear(Color col);
static void drawPixel(uint32_t x, uint32_t y, Color col) { drawPixel(x, y, col.r, col.g, col.b, col.a); }
static void drawPixel(uint32_t x, uint32_t y, uint8_t r, uint8_t g, uint8_t b, uint8_t a);
static void drawRectFilled(uint32_t x, uint32_t y, uint32_t w, uint32_t h, Color col);
static void drawRect(uint32_t x, uint32_t y, uint32_t w, uint32_t h, uint32_t borderSize, Color col);
static void drawBitmap(uint32_t x, uint32_t y, uint32_t target_width, uint32_t target_height, const uint8_t *data);
static void drawPNG(uint32_t x, uint32_t y, const uint8_t *data);
static bool initFont();
static void deinitFont();
static void setFontSize(uint32_t size);
static void setFontColor(Color col);
static void printf(uint32_t x, uint32_t y, bool alignRight, const char *fmt, ...);
static void print(uint32_t x, uint32_t y, const char *string, bool alignRight = false);
static void print(uint32_t x, uint32_t y, const wchar_t *string, bool alignRight = false);
static uint32_t getTextWidth(const char *string);
static uint32_t getTextWidth(const wchar_t *string);
private:
static bool isBackBuffer;
static uint8_t *tvBuffer;
static uint32_t tvSize;
static uint8_t *drcBuffer;
static uint32_t drcSize;
static bool hasForeground;
static uint32_t fontSize;
static std::map<uint32_t, std::map<uint32_t, SFT_Image>> glyphCache;
};

164
source/utils/FSUtils.cpp Normal file
View File

@ -0,0 +1,164 @@
#include "FSUtils.h"
#include "logger.h"
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <malloc.h>
#include <sys/fcntl.h>
#include <sys/unistd.h>
#include <whb/log.h>
#define ROUNDDOWN(val, align) ((val) & ~(align - 1))
#define ROUNDUP(val, align) ROUNDDOWN(((val) + (align - 1)), align)
int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size) {
//! always initialze input
*inbuffer = nullptr;
if (size) {
*size = 0;
}
int32_t iFd = open(filepath, O_RDONLY);
if (iFd < 0) {
return -1;
}
uint32_t filesize = lseek(iFd, 0, SEEK_END);
lseek(iFd, 0, SEEK_SET);
auto *buffer = (uint8_t *) memalign(0x40, ROUNDUP(filesize, 0x40));
if (buffer == nullptr) {
close(iFd);
return -2;
}
uint32_t blocksize = 0x20000;
uint32_t done = 0;
int32_t readBytes = 0;
while (done < filesize) {
if (done + blocksize > filesize) {
blocksize = filesize - done;
}
readBytes = read(iFd, buffer + done, blocksize);
if (readBytes <= 0) {
break;
}
done += readBytes;
}
close(iFd);
if (done != filesize) {
free(buffer);
buffer = nullptr;
return -3;
}
*inbuffer = buffer;
//! size is optional input
if (size) {
*size = filesize;
}
return filesize;
}
int32_t CheckFile(const char *filepath) {
if (!filepath)
return 0;
struct stat filestat {};
char dirnoslash[strlen(filepath) + 2];
snprintf(dirnoslash, sizeof(dirnoslash), "%s", filepath);
while (dirnoslash[strlen(dirnoslash) - 1] == '/')
dirnoslash[strlen(dirnoslash) - 1] = '\0';
char *notRoot = strrchr(dirnoslash, '/');
if (!notRoot) {
strcat(dirnoslash, "/");
}
if (stat(dirnoslash, &filestat) == 0)
return 1;
return 0;
}
int32_t CreateSubfolder(const char *fullpath) {
if (!fullpath)
return 0;
int32_t result = 0;
char dirnoslash[strlen(fullpath) + 1];
strcpy(dirnoslash, fullpath);
int32_t pos = strlen(dirnoslash) - 1;
while (dirnoslash[pos] == '/') {
dirnoslash[pos] = '\0';
pos--;
}
if (CheckFile(dirnoslash)) {
return 1;
} else {
char parentpath[strlen(dirnoslash) + 2];
strcpy(parentpath, dirnoslash);
char *ptr = strrchr(parentpath, '/');
if (!ptr) {
//!Device root directory (must be with '/')
strcat(parentpath, "/");
struct stat filestat;
if (stat(parentpath, &filestat) == 0)
return 1;
return 0;
}
ptr++;
ptr[0] = '\0';
result = CreateSubfolder(parentpath);
}
if (!result)
return 0;
if (mkdir(dirnoslash, 0777) == -1) {
return 0;
}
return 1;
}
int32_t saveBufferToFile(const char *path, void *buffer, uint32_t size) {
int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY);
if (fd < 0) {
DEBUG_FUNCTION_LINE_ERR("Failed to open %s", path);
return -1;
}
auto sizeToWrite = size;
auto *ptr = buffer;
int32_t curResult;
int64_t totalSize = 0;
while (sizeToWrite > 0) {
curResult = write(fd, ptr, sizeToWrite);
if (curResult < 0) {
close(fd);
return curResult;
}
if (curResult == 0) {
break;
}
ptr = (void *) (((uint32_t) ptr) + curResult);
totalSize += curResult;
sizeToWrite -= curResult;
}
close(fd);
return totalSize;
}

7
source/utils/FSUtils.h Normal file
View File

@ -0,0 +1,7 @@
#pragma once
#include <cstdint>
int32_t LoadFileToMem(const char *filepath, uint8_t **inbuffer, uint32_t *size);
int32_t CreateSubfolder(const char *fullpath);
int32_t saveBufferToFile(const char *path, void *buffer, uint32_t size);

209
source/utils/TinySHA1.hpp Normal file
View File

@ -0,0 +1,209 @@
// clang-format off
/*
*
* TinySHA1 - a header only implementation of the SHA1 algorithm in C++. Based
* on the implementation in boost::uuid::details.
*
* SHA1 Wikipedia Page: http://en.wikipedia.org/wiki/SHA-1
*
* Copyright (c) 2012-22 SAURAV MOHAPATRA <mohaps@gmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef _TINY_SHA1_HPP_
#define _TINY_SHA1_HPP_
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdint.h>
namespace sha1 {
class SHA1 {
public:
typedef uint32_t digest32_t[5];
typedef uint8_t digest8_t[20];
inline static uint32_t LeftRotate(uint32_t value, size_t count) {
return (value << count) ^ (value >> (32 - count));
}
SHA1() { reset(); }
virtual ~SHA1() {}
SHA1(const SHA1 &s) { *this = s; }
const SHA1 &operator=(const SHA1 &s) {
memcpy(m_digest, s.m_digest, 5 * sizeof(uint32_t));
memcpy(m_block, s.m_block, 64);
m_blockByteIndex = s.m_blockByteIndex;
m_byteCount = s.m_byteCount;
return *this;
}
SHA1 &reset() {
m_digest[0] = 0x67452301;
m_digest[1] = 0xEFCDAB89;
m_digest[2] = 0x98BADCFE;
m_digest[3] = 0x10325476;
m_digest[4] = 0xC3D2E1F0;
m_blockByteIndex = 0;
m_byteCount = 0;
return *this;
}
SHA1 &processByte(uint8_t octet) {
this->m_block[this->m_blockByteIndex++] = octet;
++this->m_byteCount;
if (m_blockByteIndex == 64) {
this->m_blockByteIndex = 0;
processBlock();
}
return *this;
}
SHA1 &processBlock(const void *const start, const void *const end) {
const uint8_t *begin = static_cast<const uint8_t *>(start);
const uint8_t *finish = static_cast<const uint8_t *>(end);
while (begin != finish) {
processByte(*begin);
begin++;
}
return *this;
}
SHA1 &processBytes(const void *const data, size_t len) {
const uint8_t *block = static_cast<const uint8_t *>(data);
processBlock(block, block + len);
return *this;
}
const uint32_t *getDigest(digest32_t digest) {
size_t bitCount = this->m_byteCount * 8;
processByte(0x80);
if (this->m_blockByteIndex > 56) {
while (m_blockByteIndex != 0) {
processByte(0);
}
while (m_blockByteIndex < 56) {
processByte(0);
}
} else {
while (m_blockByteIndex < 56) {
processByte(0);
}
}
processByte(0);
processByte(0);
processByte(0);
processByte(0);
processByte(static_cast<unsigned char>((bitCount >> 24) & 0xFF));
processByte(static_cast<unsigned char>((bitCount >> 16) & 0xFF));
processByte(static_cast<unsigned char>((bitCount >> 8) & 0xFF));
processByte(static_cast<unsigned char>((bitCount) & 0xFF));
memcpy(digest, m_digest, 5 * sizeof(uint32_t));
return digest;
}
const uint8_t *getDigestBytes(digest8_t digest) {
digest32_t d32;
getDigest(d32);
size_t di = 0;
digest[di++] = ((d32[0] >> 24) & 0xFF);
digest[di++] = ((d32[0] >> 16) & 0xFF);
digest[di++] = ((d32[0] >> 8) & 0xFF);
digest[di++] = ((d32[0]) & 0xFF);
digest[di++] = ((d32[1] >> 24) & 0xFF);
digest[di++] = ((d32[1] >> 16) & 0xFF);
digest[di++] = ((d32[1] >> 8) & 0xFF);
digest[di++] = ((d32[1]) & 0xFF);
digest[di++] = ((d32[2] >> 24) & 0xFF);
digest[di++] = ((d32[2] >> 16) & 0xFF);
digest[di++] = ((d32[2] >> 8) & 0xFF);
digest[di++] = ((d32[2]) & 0xFF);
digest[di++] = ((d32[3] >> 24) & 0xFF);
digest[di++] = ((d32[3] >> 16) & 0xFF);
digest[di++] = ((d32[3] >> 8) & 0xFF);
digest[di++] = ((d32[3]) & 0xFF);
digest[di++] = ((d32[4] >> 24) & 0xFF);
digest[di++] = ((d32[4] >> 16) & 0xFF);
digest[di++] = ((d32[4] >> 8) & 0xFF);
digest[di++] = ((d32[4]) & 0xFF);
return digest;
}
protected:
void processBlock() {
uint32_t w[80];
for (size_t i = 0; i < 16; i++) {
w[i] = (m_block[i * 4 + 0] << 24);
w[i] |= (m_block[i * 4 + 1] << 16);
w[i] |= (m_block[i * 4 + 2] << 8);
w[i] |= (m_block[i * 4 + 3]);
}
for (size_t i = 16; i < 80; i++) {
w[i] = LeftRotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]), 1);
}
uint32_t a = m_digest[0];
uint32_t b = m_digest[1];
uint32_t c = m_digest[2];
uint32_t d = m_digest[3];
uint32_t e = m_digest[4];
for (std::size_t i = 0; i < 80; ++i) {
uint32_t f = 0;
uint32_t k = 0;
if (i < 20) {
f = (b & c) | (~b & d);
k = 0x5A827999;
} else if (i < 40) {
f = b ^ c ^ d;
k = 0x6ED9EBA1;
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
} else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
uint32_t temp = LeftRotate(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = LeftRotate(b, 30);
b = a;
a = temp;
}
m_digest[0] += a;
m_digest[1] += b;
m_digest[2] += c;
m_digest[3] += d;
m_digest[4] += e;
}
private:
digest32_t m_digest;
uint8_t m_block[64];
size_t m_blockByteIndex;
size_t m_byteCount;
};
}
#endif

View File

@ -0,0 +1,147 @@
#include "UpdateUtils.h"
#include "DownloadUtils.h"
#include "VersionByHash.h"
#include "logger.h"
#include "utils.h"
#include <coreinit/cache.h>
void UpdateUtils::CheckFilesOfVersionInfo(VersionCheck::VersionInfo &versionInfo, bool onlyRequired, float *progress, const std::string &sdBase, const std::string &serverURL) {
if (progress) {
*progress = 0.0f;
}
uint32_t totalFiles = 0;
uint32_t curFileProcessed = 0;
for (auto &baseCategory : versionInfo) {
totalFiles += baseCategory.getFilesCount(onlyRequired);
}
for (auto &baseCategory : versionInfo) {
for (auto &category : baseCategory.getMutableCategory()) {
for (auto &package : category.getMutablePackages()) {
if (!package.getRequired() && onlyRequired) {
continue;
}
std::string packageDate = "2000-01-01T01:01:01Z";
for (auto &repo : package.getMutableRepositories()) {
std::string repoDate = "2000-01-01T01:01:01Z";
for (auto &file : repo.getMutableFiles()) {
if (progress) {
*progress = (float) curFileProcessed / (float) totalFiles;
OSMemoryBarrier();
}
if (file.getRelease().getPublishedAt() > repoDate) {
repoDate = file.getRelease().getPublishedAt();
}
auto pathOnSDCard = string_format("%s%s", sdBase.c_str(), file.getPath().c_str());
auto hashOfFileOnSDCard = hashFile(pathOnSDCard);
if (hashOfFileOnSDCard) {
if (hashOfFileOnSDCard == file.getSha1()) {
file.setStatus(VersionCheck::FileStatus::Latest);
} else {
std::string outBuffer2;
int responseCode;
std::string url = string_format("%s/api/check_versions?hash=%s", serverURL.c_str(), hashOfFileOnSDCard->c_str());
DEBUG_FUNCTION_LINE("Check version of file with hash %s", hashOfFileOnSDCard->c_str());
if (DownloadUtils::DownloadFileToBuffer(url.c_str(), outBuffer2, responseCode, nullptr) < 0 &&
responseCode == 200) {
DEBUG_FUNCTION_LINE("Failed to get information for the file");
file.setStatus(VersionCheck::FileStatus::Error);
curFileProcessed++;
continue;
}
if (outBuffer2 == "not found") {
DEBUG_FUNCTION_LINE("File with this hash not found");
file.setStatus(VersionCheck::FileStatus::UnknownFile);
curFileProcessed++;
continue;
}
try {
VersionByHash::VersionInfo versionInfoSingle = nlohmann::json::parse(outBuffer2.c_str());
DEBUG_FUNCTION_LINE("File with this hash found!");
if (versionInfoSingle.getRelease().getPublishedAt() < file.getRelease().getPublishedAt()) {
DEBUG_FUNCTION_LINE("And it's older than expected");
file.setStatus(VersionCheck::FileStatus::Outdated);
} else {
DEBUG_FUNCTION_LINE("But it's newer than expected");
file.setStatus(VersionCheck::FileStatus::Newer);
}
} catch (std::exception &e) {
DEBUG_FUNCTION_LINE_WARN("Failed to parse VersionByHash::VersionInfo");
file.setStatus(VersionCheck::FileStatus::Error);
}
}
} else {
DEBUG_FUNCTION_LINE("File %s was not found on the sd card", file.getPath().c_str());
file.setStatus(VersionCheck::FileStatus::Missing);
}
curFileProcessed++;
}
if (progress) {
*progress = (float) curFileProcessed / (float) totalFiles;
OSMemoryBarrier();
}
bool allMissing = true;
for (auto &file : repo.getFiles()) {
if (file.getStatus() != VersionCheck::FileStatus::Missing) {
allMissing = false;
}
if (file.getStatus() != VersionCheck::FileStatus::Latest) {
repo.setStatus(VersionCheck::RepoStatus::Dirty);
}
}
if (allMissing) {
repo.setStatus(VersionCheck::RepoStatus::Missing);
}
if (repoDate > packageDate) {
packageDate = repoDate;
}
}
bool allMissing = true;
for (auto &repo : package.getRepositories()) {
if (repo.getStatus() != VersionCheck::RepoStatus::Missing) {
allMissing = false;
}
if (repo.getStatus() != VersionCheck::RepoStatus::Latest) {
package.setStatus(VersionCheck::PackageStatus::Dirty);
package.setSelected(true);
}
}
if (allMissing) {
package.setStatus(VersionCheck::PackageStatus::Missing);
package.setSelected(false);
}
package.setLastUpdateDate(packageDate);
}
}
}
}
std::vector<VersionCheck::RepositoryFile> UpdateUtils::GetNonLatestFilesFromVersionInfo(const VersionCheck::VersionInfo &versionInfo, bool onlyRequired) {
std::vector<VersionCheck::RepositoryFile> result;
for (auto &baseCategory : versionInfo) {
for (auto &category : baseCategory.getCategory()) {
for (auto &package : category.getPackages()) {
if (!package.getIsSelected() && !package.getRequired()) {
continue;
}
if (!package.getRequired() && onlyRequired) {
continue;
}
for (auto &repo : package.getRepositories()) {
for (auto &file : repo.getFiles()) {
if (file.getStatus() != VersionCheck::FileStatus::Latest) {
result.push_back(file);
}
}
}
}
}
}
return result;
}

View File

@ -0,0 +1,59 @@
#pragma once
#include "../common.h"
#include "VersionCheck.h"
#include <string>
#include <vector>
class UpdateUtils {
public:
static void CheckFilesOfVersionInfo(VersionCheck::VersionInfo &versionInfo,
bool onlyRequired,
float *progress,
const std::string &sdBase = SD_PATH,
const std::string &serverURL = UPDATE_SERVER_URL);
static std::vector<VersionCheck::RepositoryFile> GetNonLatestFilesFromVersionInfo(const VersionCheck::VersionInfo &versionInfo, bool onlyRequired);
static const char *StatusToString(VersionCheck::RepoStatus e) {
switch (e) {
case VersionCheck::RepoStatus::Latest:
return "Latest";
case VersionCheck::RepoStatus::Dirty:
return "Dirty";
case VersionCheck::RepoStatus::Missing:
return "Missing";
}
return "Out of Range";
}
static const char *StatusToString(VersionCheck::FileStatus e) {
switch (e) {
case VersionCheck::FileStatus::Latest:
return "Latest";
case VersionCheck::FileStatus::Missing:
return "Missing";
case VersionCheck::FileStatus::Outdated:
return "Outdated";
case VersionCheck::FileStatus::UnknownFile:
return "UnknownFile";
case VersionCheck::FileStatus::Error:
return "Error";
case VersionCheck::FileStatus::Newer:
return "Newer";
}
return "Out of Range";
}
static const char *StatusToString(VersionCheck::PackageStatus e) {
switch (e) {
case VersionCheck::PackageStatus::Latest:
return "Up to date";
case VersionCheck::PackageStatus::Dirty:
return "Has update";
case VersionCheck::PackageStatus::Missing:
return "Not installed";
}
return "Out of Range";
}
};

View File

@ -0,0 +1,270 @@
// clang-format off
// To parse this JSON data, first install
//
// json.hpp https://github.com/nlohmann/json
//
// Then include this file, and then do
//
// VersionInfo data = nlohmann::json::parse(jsonString);
#pragma once
#include "json.hpp"
#include <optional>
#include <stdexcept>
#include <regex>
namespace VersionByHash {
using nlohmann::json;
inline json get_untyped(const json & j, const char * property) {
if (j.find(property) != j.end()) {
return j.at(property).get<json>();
}
return json();
}
inline json get_untyped(const json & j, std::string property) {
return get_untyped(j, property.data());
}
class File {
public:
File() = default;
virtual ~File() = default;
private:
std::string path;
std::string sha1;
public:
const std::string & getPath() const { return path; }
std::string & getMutablePath() { return path; }
void setPath(const std::string & value) { this->path = value; }
const std::string & getSha1() const { return sha1; }
std::string & getMutableSha1() { return sha1; }
void setSha1(const std::string & value) { this->sha1 = value; }
};
class Assets {
public:
Assets() = default;
virtual ~Assets() = default;
private:
int64_t id;
std::string nodeId;
std::string name;
std::string contentType;
std::string url;
int64_t size;
std::string createdAt;
std::string updatedAt;
std::string browserDownloadUrl;
std::vector<File> files;
public:
const int64_t & getId() const { return id; }
int64_t & getMutableId() { return id; }
void setId(const int64_t & value) { this->id = value; }
const std::string & getNodeId() const { return nodeId; }
std::string & getMutableNodeId() { return nodeId; }
void setNodeId(const std::string & value) { this->nodeId = value; }
const std::string & getName() const { return name; }
std::string & getMutableName() { return name; }
void setName(const std::string & value) { this->name = value; }
const std::string & getContentType() const { return contentType; }
std::string & getMutableContentType() { return contentType; }
void setContentType(const std::string & value) { this->contentType = value; }
const std::string & getUrl() const { return url; }
std::string & getMutableUrl() { return url; }
void setUrl(const std::string & value) { this->url = value; }
const int64_t & getSize() const { return size; }
int64_t & getMutableSize() { return size; }
void setSize(const int64_t & value) { this->size = value; }
const std::string & getCreatedAt() const { return createdAt; }
std::string & getMutableCreatedAt() { return createdAt; }
void setCreatedAt(const std::string & value) { this->createdAt = value; }
const std::string & getUpdatedAt() const { return updatedAt; }
std::string & getMutableUpdatedAt() { return updatedAt; }
void setUpdatedAt(const std::string & value) { this->updatedAt = value; }
const std::string & getBrowserDownloadUrl() const { return browserDownloadUrl; }
std::string & getMutableBrowserDownloadUrl() { return browserDownloadUrl; }
void setBrowserDownloadUrl(const std::string & value) { this->browserDownloadUrl = value; }
const std::vector<File> & getFiles() const { return files; }
std::vector<File> & getMutableFiles() { return files; }
void setFiles(const std::vector<File> & value) { this->files = value; }
};
class Release {
public:
Release() = default;
virtual ~Release() = default;
private:
int64_t id;
std::string nodeId;
std::string name;
std::string tagName;
bool prerelease;
std::string targetCommitish;
std::string createdAt;
std::string publishedAt;
public:
const int64_t & getId() const { return id; }
int64_t & getMutableId() { return id; }
void setId(const int64_t & value) { this->id = value; }
const std::string & getNodeId() const { return nodeId; }
std::string & getMutableNodeId() { return nodeId; }
void setNodeId(const std::string & value) { this->nodeId = value; }
const std::string & getName() const { return name; }
std::string & getMutableName() { return name; }
void setName(const std::string & value) { this->name = value; }
const std::string & getTagName() const { return tagName; }
std::string & getMutableTagName() { return tagName; }
void setTagName(const std::string & value) { this->tagName = value; }
const bool & getPrerelease() const { return prerelease; }
bool & getMutablePrerelease() { return prerelease; }
void setPrerelease(const bool & value) { this->prerelease = value; }
const std::string & getTargetCommitish() const { return targetCommitish; }
std::string & getMutableTargetCommitish() { return targetCommitish; }
void setTargetCommitish(const std::string & value) { this->targetCommitish = value; }
const std::string & getCreatedAt() const { return createdAt; }
std::string & getMutableCreatedAt() { return createdAt; }
void setCreatedAt(const std::string & value) { this->createdAt = value; }
const std::string & getPublishedAt() const { return publishedAt; }
std::string & getMutablePublishedAt() { return publishedAt; }
void setPublishedAt(const std::string & value) { this->publishedAt = value; }
};
class VersionInfo {
public:
VersionInfo() = default;
virtual ~VersionInfo() = default;
private:
std::string repo;
Assets assets;
Release release;
public:
const std::string & getRepo() const { return repo; }
std::string & getMutableRepo() { return repo; }
void setRepo(const std::string & value) { this->repo = value; }
const Assets & getAssets() const { return assets; }
Assets & getMutableAssets() { return assets; }
void setAssets(const Assets & value) { this->assets = value; }
const Release & getRelease() const { return release; }
Release & getMutableRelease() { return release; }
void setRelease(const Release & value) { this->release = value; }
};
}
namespace nlohmann {
void from_json(const json & j, VersionByHash::File & x);
void to_json(json & j, const VersionByHash::File & x);
void from_json(const json & j, VersionByHash::Assets & x);
void to_json(json & j, const VersionByHash::Assets & x);
void from_json(const json & j, VersionByHash::Release & x);
void to_json(json & j, const VersionByHash::Release & x);
void from_json(const json & j, VersionByHash::VersionInfo & x);
void to_json(json & j, const VersionByHash::VersionInfo & x);
inline void from_json(const json & j, VersionByHash::File& x) {
x.setPath(j.at("path").get<std::string>());
x.setSha1(j.at("sha1").get<std::string>());
}
inline void to_json(json & j, const VersionByHash::File & x) {
j = json::object();
j["path"] = x.getPath();
j["sha1"] = x.getSha1();
}
inline void from_json(const json & j, VersionByHash::Assets& x) {
x.setId(j.at("id").get<int64_t>());
x.setNodeId(j.at("node_id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setContentType(j.at("content_type").get<std::string>());
x.setUrl(j.at("url").get<std::string>());
x.setSize(j.at("size").get<int64_t>());
x.setCreatedAt(j.at("created_at").get<std::string>());
x.setUpdatedAt(j.at("updated_at").get<std::string>());
x.setBrowserDownloadUrl(j.at("browser_download_url").get<std::string>());
x.setFiles(j.at("files").get<std::vector<VersionByHash::File>>());
}
inline void to_json(json & j, const VersionByHash::Assets & x) {
j = json::object();
j["id"] = x.getId();
j["node_id"] = x.getNodeId();
j["name"] = x.getName();
j["content_type"] = x.getContentType();
j["url"] = x.getUrl();
j["size"] = x.getSize();
j["created_at"] = x.getCreatedAt();
j["updated_at"] = x.getUpdatedAt();
j["browser_download_url"] = x.getBrowserDownloadUrl();
j["files"] = x.getFiles();
}
inline void from_json(const json & j, VersionByHash::Release& x) {
x.setId(j.at("id").get<int64_t>());
x.setNodeId(j.at("node_id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setTagName(j.at("tag_name").get<std::string>());
x.setPrerelease(j.at("prerelease").get<bool>());
x.setTargetCommitish(j.at("target_commitish").get<std::string>());
x.setCreatedAt(j.at("created_at").get<std::string>());
x.setPublishedAt(j.at("published_at").get<std::string>());
}
inline void to_json(json & j, const VersionByHash::Release & x) {
j = json::object();
j["id"] = x.getId();
j["node_id"] = x.getNodeId();
j["name"] = x.getName();
j["tag_name"] = x.getTagName();
j["prerelease"] = x.getPrerelease();
j["target_commitish"] = x.getTargetCommitish();
j["created_at"] = x.getCreatedAt();
j["published_at"] = x.getPublishedAt();
}
inline void from_json(const json & j, VersionByHash::VersionInfo& x) {
x.setRepo(j.at("repo").get<std::string>());
x.setAssets(j.at("assets").get<VersionByHash::Assets>());
x.setRelease(j.at("release").get<VersionByHash::Release>());
}
inline void to_json(json & j, const VersionByHash::VersionInfo & x) {
j = json::object();
j["repo"] = x.getRepo();
j["assets"] = x.getAssets();
j["release"] = x.getRelease();
}
}

556
source/utils/VersionCheck.h Normal file
View File

@ -0,0 +1,556 @@
// To parse this JSON data, first install
//
// json.hpp https://github.com/nlohmann/json
//
// Then include this file, and then do
//
// BaseCategories data = nlohmann::json::parse(jsonString);
#pragma once
#include "json.hpp"
#include <optional>
#include <regex>
#include <stdexcept>
#ifndef NLOHMANN_OPT_HELPER
#define NLOHMANN_OPT_HELPER
namespace nlohmann {
template<typename T>
struct adl_serializer<std::shared_ptr<T>> {
static void to_json(json &j, const std::shared_ptr<T> &opt) {
if (!opt) j = nullptr;
else
j = *opt;
}
static std::shared_ptr<T> from_json(const json &j) {
if (j.is_null()) return std::unique_ptr<T>();
else
return std::unique_ptr<T>(new T(j.get<T>()));
}
};
} // namespace nlohmann
#endif
namespace VersionCheck {
using nlohmann::json;
#ifndef NLOHMANN_UNTYPED_VersionCheck_HELPERHELPER
#define NLOHMANN_UNTYPED_VersionCheck_HELPERHELPER
inline json get_untyped(const json &j, const char *property) {
if (j.find(property) != j.end()) {
return j.at(property).get<json>();
}
return json();
}
inline json get_untyped(const json &j, std::string property) {
return get_untyped(j, property.data());
}
#endif
#ifndef NLOHMANN_OPTIONAL_VersionCheck_
#define NLOHMANN_OPTIONAL_VersionCheck_
template<typename T>
inline std::shared_ptr<T> get_optional(const json &j, const char *property) {
if (j.find(property) != j.end()) {
return j.at(property).get<std::shared_ptr<T>>();
}
return std::shared_ptr<T>();
}
template<typename T>
inline std::shared_ptr<T> get_optional(const json &j, std::string property) {
return get_optional<T>(j, property.data());
}
#endif
enum class FileStatus : int { Latest,
Missing,
Outdated,
UnknownFile,
Newer,
Error };
enum class RepoStatus : int { Latest,
Dirty,
Missing };
enum class PackageStatus : int { Latest,
Dirty,
Missing };
class AssetFile {
public:
AssetFile() = default;
virtual ~AssetFile() = default;
private:
std::string path;
std::string sha1;
public:
const std::string &getPath() const { return path; }
std::string &getMutablePath() { return path; }
void setPath(const std::string &value) { this->path = value; }
const std::string &getSha1() const { return sha1; }
std::string &getMutableSha1() { return sha1; }
void setSha1(const std::string &value) { this->sha1 = value; }
};
class Asset {
public:
Asset() = default;
virtual ~Asset() = default;
private:
int64_t id;
std::string nodeId;
std::string name;
std::string contentType;
std::string url;
int64_t size;
std::string createdAt;
std::string updatedAt;
std::string browserDownloadUrl;
std::vector<AssetFile> files;
public:
const int64_t &getId() const { return id; }
int64_t &getMutableId() { return id; }
void setId(const int64_t &value) { this->id = value; }
const std::string &getNodeId() const { return nodeId; }
std::string &getMutableNodeId() { return nodeId; }
void setNodeId(const std::string &value) { this->nodeId = value; }
const std::string &getName() const { return name; }
std::string &getMutableName() { return name; }
void setName(const std::string &value) { this->name = value; }
const std::string &getContentType() const { return contentType; }
std::string &getMutableContentType() { return contentType; }
void setContentType(const std::string &value) { this->contentType = value; }
const std::string &getUrl() const { return url; }
std::string &getMutableUrl() { return url; }
void setUrl(const std::string &value) { this->url = value; }
const int64_t &getSize() const { return size; }
int64_t &getMutableSize() { return size; }
void setSize(const int64_t &value) { this->size = value; }
const std::string &getCreatedAt() const { return createdAt; }
std::string &getMutableCreatedAt() { return createdAt; }
void setCreatedAt(const std::string &value) { this->createdAt = value; }
const std::string &getUpdatedAt() const { return updatedAt; }
std::string &getMutableUpdatedAt() { return updatedAt; }
void setUpdatedAt(const std::string &value) { this->updatedAt = value; }
const std::string &getBrowserDownloadUrl() const { return browserDownloadUrl; }
std::string &getMutableBrowserDownloadUrl() { return browserDownloadUrl; }
void setBrowserDownloadUrl(const std::string &value) { this->browserDownloadUrl = value; }
const std::vector<AssetFile> &getFiles() const { return files; }
std::vector<AssetFile> &getMutableFiles() { return files; }
void setFiles(const std::vector<AssetFile> &value) { this->files = value; }
};
class Release {
public:
Release() = default;
virtual ~Release() = default;
private:
int64_t id;
std::string nodeId;
std::string name;
std::string tagName;
bool prerelease;
std::string targetCommitish;
std::string createdAt;
std::string publishedAt;
public:
const int64_t &getId() const { return id; }
int64_t &getMutableId() { return id; }
void setId(const int64_t &value) { this->id = value; }
const std::string &getNodeId() const { return nodeId; }
std::string &getMutableNodeId() { return nodeId; }
void setNodeId(const std::string &value) { this->nodeId = value; }
const std::string &getName() const { return name; }
std::string &getMutableName() { return name; }
void setName(const std::string &value) { this->name = value; }
const std::string &getTagName() const { return tagName; }
std::string &getMutableTagName() { return tagName; }
void setTagName(const std::string &value) { this->tagName = value; }
const bool &getPrerelease() const { return prerelease; }
bool &getMutablePrerelease() { return prerelease; }
void setPrerelease(const bool &value) { this->prerelease = value; }
const std::string &getTargetCommitish() const { return targetCommitish; }
std::string &getMutableTargetCommitish() { return targetCommitish; }
void setTargetCommitish(const std::string &value) { this->targetCommitish = value; }
const std::string &getCreatedAt() const { return createdAt; }
std::string &getMutableCreatedAt() { return createdAt; }
void setCreatedAt(const std::string &value) { this->createdAt = value; }
const std::string &getPublishedAt() const { return publishedAt; }
std::string &getMutablePublishedAt() { return publishedAt; }
void setPublishedAt(const std::string &value) { this->publishedAt = value; }
};
class RepositoryFile {
public:
RepositoryFile() = default;
virtual ~RepositoryFile() = default;
private:
std::string path;
std::string sha1;
Asset asset;
Release release;
FileStatus status;
public:
const std::string &getPath() const { return path; }
std::string &getMutablePath() { return path; }
void setPath(const std::string &value) { this->path = value; }
const std::string &getSha1() const { return sha1; }
std::string &getMutableSha1() { return sha1; }
void setSha1(const std::string &value) { this->sha1 = value; }
const Asset &getAsset() const { return asset; }
Asset &getMutableAsset() { return asset; }
void setAsset(const Asset &value) { this->asset = value; }
const Release &getRelease() const { return release; }
Release &getMutableRelease() { return release; }
void setRelease(const Release &value) { this->release = value; }
const FileStatus &getStatus() const { return status; }
FileStatus &getMutableStatus() { return status; }
void setStatus(const FileStatus &value) { this->status = value; }
};
class Tag {
public:
Tag() = default;
virtual ~Tag() = default;
private:
std::string tagName;
public:
const std::string &getTagName() const { return tagName; }
std::string &getMutableTagName() { return tagName; }
void setTagName(const std::string &value) { this->tagName = value; }
};
class Repo {
public:
Repo() = default;
virtual ~Repo() = default;
private:
std::string owner;
std::string repo;
Tag tag;
std::shared_ptr<bool> forceTag;
public:
const std::string &getOwner() const { return owner; }
std::string &getMutableOwner() { return owner; }
void setOwner(const std::string &value) { this->owner = value; }
const std::string &getRepo() const { return repo; }
std::string &getMutableRepo() { return repo; }
void setRepo(const std::string &value) { this->repo = value; }
const Tag &getTag() const { return tag; }
Tag &getMutableTag() { return tag; }
void setTag(const Tag &value) { this->tag = value; }
std::shared_ptr<bool> getForceTag() const { return forceTag; }
void setForceTag(std::shared_ptr<bool> value) { this->forceTag = value; }
};
class Repository {
public:
Repository() = default;
virtual ~Repository() = default;
private:
Repo repo;
std::vector<RepositoryFile> files;
RepoStatus status;
public:
const Repo &getRepo() const { return repo; }
Repo &getMutableRepo() { return repo; }
void setRepo(const Repo &value) { this->repo = value; }
const std::vector<RepositoryFile> &getFiles() const { return files; }
std::vector<RepositoryFile> &getMutableFiles() { return files; }
void setFiles(const std::vector<RepositoryFile> &value) { this->files = value; }
const RepoStatus &getStatus() const { return status; }
RepoStatus &getMutableStatus() { return status; }
void setStatus(const RepoStatus &value) { this->status = value; }
size_t getFilesCount(bool onlyRequired) const {
return files.size();
}
};
class Package {
public:
Package() = default;
virtual ~Package() = default;
private:
std::string id;
std::string name;
std::string description;
std::vector<Repository> repositories;
bool required;
bool preSelected;
PackageStatus status;
std::string lastUpdateDate;
bool isSelected = false;
public:
const std::string &getId() const { return id; }
std::string &getMutableId() { return id; }
void setId(const std::string &value) { this->id = value; }
const std::string &getName() const { return name; }
std::string &getMutableName() { return name; }
void setName(const std::string &value) { this->name = value; }
const std::string &getDescription() const { return description; }
std::string &getMutableDescription() { return description; }
void setDescription(const std::string &value) { this->description = value; }
const std::vector<Repository> &getRepositories() const { return repositories; }
std::vector<Repository> &getMutableRepositories() { return repositories; }
void setRepositories(const std::vector<Repository> &value) { this->repositories = value; }
const bool &getRequired() const { return required; }
bool &getMutableRequired() { return required; }
void setRequired(const bool &value) { this->required = value; }
const bool &getPreSelected() const { return preSelected; }
bool &getMutablePreSelected() { return preSelected; }
void setPreSelected(const bool &value) { this->preSelected = value; }
const PackageStatus &getStatus() const { return status; }
PackageStatus &getMutableStatus() { return status; }
void setStatus(const PackageStatus &value) { this->status = value; }
const std::string &getLastUpdateDate() const { return lastUpdateDate; }
std::string &getMutableLastUpdateDate() { return lastUpdateDate; }
void setLastUpdateDate(const std::string &value) { this->lastUpdateDate = value; }
const bool &getIsSelected() const { return this->isSelected; }
void toggleSelect() {
if (!required) this->isSelected = !this->isSelected;
}
void setSelected(const bool &value) {
if (!required) this->isSelected = value;
}
size_t getFilesCount(bool onlyRequired) const {
size_t res = 0;
for (auto &repo : getRepositories()) {
res += repo.getFilesCount(onlyRequired);
}
return res;
}
};
class Category {
public:
Category() = default;
virtual ~Category() = default;
private:
std::string id;
std::string name;
std::vector<Package> packages;
public:
const std::string &getId() const { return id; }
std::string &getMutableId() { return id; }
void setId(const std::string &value) { this->id = value; }
const std::string &getName() const { return name; }
std::string &getMutableName() { return name; }
void setName(const std::string &value) { this->name = value; }
const std::vector<Package> &getPackages() const { return packages; }
std::vector<Package> &getMutablePackages() { return packages; }
void setPackages(const std::vector<Package> &value) { this->packages = value; }
size_t getFilesCount(bool onlyRequired) const {
size_t res = 0;
for (auto &package : getPackages()) {
res += package.getFilesCount(onlyRequired);
}
return res;
}
const size_t getPackagesCount(bool required) const {
if (!required) {
return packages.size();
}
size_t result = 0;
for (auto &cur : packages) {
if (cur.getRequired()) {
result++;
}
}
return result;
}
};
class BaseCategory {
public:
BaseCategory() = default;
virtual ~BaseCategory() = default;
private:
std::string id;
std::string name;
std::vector<Category> category;
public:
const std::string &getId() const { return id; }
std::string &getMutableId() { return id; }
void setId(const std::string &value) { this->id = value; }
const std::string &getName() const { return name; }
std::string &getMutableName() { return name; }
void setName(const std::string &value) { this->name = value; }
const std::vector<Category> &getCategory() const { return category; }
std::vector<Category> &getMutableCategory() { return category; }
void setCategory(const std::vector<Category> &value) { this->category = value; }
size_t getFilesCount(bool onlyRequired) const {
size_t res = 0;
for (auto &cat : category) {
res += cat.getFilesCount(onlyRequired);
}
return res;
}
};
using VersionInfo = std::vector<BaseCategory>;
} // namespace VersionCheck
namespace VersionCheck {
void from_json(const json &j, AssetFile &x);
void from_json(const json &j, Asset &x);
void from_json(const json &j, Release &x);
void from_json(const json &j, RepositoryFile &x);
void from_json(const json &j, Tag &x);
void from_json(const json &j, Repo &x);
void from_json(const json &j, Repository &x);
void from_json(const json &j, Package &x);
void from_json(const json &j, Category &x);
void from_json(const json &j, BaseCategory &x);
inline void from_json(const json &j, AssetFile &x) {
x.setPath(j.at("path").get<std::string>());
x.setSha1(j.at("sha1").get<std::string>());
}
inline void from_json(const json &j, Asset &x) {
x.setId(j.at("id").get<int64_t>());
x.setNodeId(j.at("node_id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setContentType(j.at("content_type").get<std::string>());
x.setUrl(j.at("url").get<std::string>());
x.setSize(j.at("size").get<int64_t>());
x.setCreatedAt(j.at("created_at").get<std::string>());
x.setUpdatedAt(j.at("updated_at").get<std::string>());
x.setBrowserDownloadUrl(j.at("browser_download_url").get<std::string>());
x.setFiles(j.at("files").get<std::vector<AssetFile>>());
}
inline void from_json(const json &j, Release &x) {
x.setId(j.at("id").get<int64_t>());
x.setNodeId(j.at("node_id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setTagName(j.at("tag_name").get<std::string>());
x.setPrerelease(j.at("prerelease").get<bool>());
x.setTargetCommitish(j.at("target_commitish").get<std::string>());
x.setCreatedAt(j.at("created_at").get<std::string>());
x.setPublishedAt(j.at("published_at").get<std::string>());
}
inline void from_json(const json &j, RepositoryFile &x) {
x.setPath(j.at("path").get<std::string>());
x.setSha1(j.at("sha1").get<std::string>());
x.setAsset(j.at("asset").get<Asset>());
x.setRelease(j.at("release").get<Release>());
}
inline void from_json(const json &j, Tag &x) {
x.setTagName(j.at("tag_name").get<std::string>());
}
inline void from_json(const json &j, Repo &x) {
x.setOwner(j.at("owner").get<std::string>());
x.setRepo(j.at("repo").get<std::string>());
x.setTag(j.at("tag").get<Tag>());
x.setForceTag(get_optional<bool>(j, "forceTag"));
}
inline void from_json(const json &j, Repository &x) {
x.setRepo(j.at("repo").get<Repo>());
x.setFiles(j.at("files").get<std::vector<RepositoryFile>>());
}
inline void from_json(const json &j, Package &x) {
x.setId(j.at("id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setDescription(j.at("description").get<std::string>());
x.setRepositories(j.at("repositories").get<std::vector<Repository>>());
x.setRequired(j.at("required").get<bool>());
x.setPreSelected(j.at("preSelected").get<bool>());
}
inline void from_json(const json &j, Category &x) {
x.setId(j.at("id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setPackages(j.at("packages").get<std::vector<Package>>());
}
inline void from_json(const json &j, BaseCategory &x) {
x.setId(j.at("id").get<std::string>());
x.setName(j.at("name").get<std::string>());
x.setCategory(j.at("category").get<std::vector<Category>>());
}
} // namespace VersionCheck

24642
source/utils/json.hpp Normal file

File diff suppressed because it is too large Load Diff

178
source/utils/json_fwd.hpp Normal file
View File

@ -0,0 +1,178 @@
/* clang-format off */
// __ _____ _____ _____
// __| | __| | | | JSON for Modern C++
// | | |__ | | | | | | version 3.11.2
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT
#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_
#define INCLUDE_NLOHMANN_JSON_FWD_HPP_
#include <cstdint> // int64_t, uint64_t
#include <map> // map
#include <memory> // allocator
#include <string> // string
#include <vector> // vector
// #include <nlohmann/detail/abi_macros.hpp>
// __ _____ _____ _____
// __| | __| | | | JSON for Modern C++
// | | |__ | | | | | | version 3.11.2
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
//
// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann <https://nlohmann.me>
// SPDX-License-Identifier: MIT
// This file contains all macro definitions affecting or depending on the ABI
#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK
#if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH)
#if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 2
#warning "Already included a different version of the library!"
#endif
#endif
#endif
#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum)
#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum)
#define NLOHMANN_JSON_VERSION_PATCH 2 // NOLINT(modernize-macro-to-enum)
#ifndef JSON_DIAGNOSTICS
#define JSON_DIAGNOSTICS 0
#endif
#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0
#endif
#if JSON_DIAGNOSTICS
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
#else
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS
#endif
#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp
#else
#define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON
#endif
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
#endif
// Construct the namespace ABI tags component
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b)
#define NLOHMANN_JSON_ABI_TAGS \
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \
NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON)
// Construct the namespace version component
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
_v ## major ## _ ## minor ## _ ## patch
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \
NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch)
#if NLOHMANN_JSON_NAMESPACE_NO_VERSION
#define NLOHMANN_JSON_NAMESPACE_VERSION
#else
#define NLOHMANN_JSON_NAMESPACE_VERSION \
NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \
NLOHMANN_JSON_VERSION_MINOR, \
NLOHMANN_JSON_VERSION_PATCH)
#endif
// Combine namespace components
#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b
#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \
NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b)
#ifndef NLOHMANN_JSON_NAMESPACE
#define NLOHMANN_JSON_NAMESPACE \
nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \
NLOHMANN_JSON_ABI_TAGS, \
NLOHMANN_JSON_NAMESPACE_VERSION)
#endif
#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN
#define NLOHMANN_JSON_NAMESPACE_BEGIN \
namespace nlohmann \
{ \
inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \
NLOHMANN_JSON_ABI_TAGS, \
NLOHMANN_JSON_NAMESPACE_VERSION) \
{
#endif
#ifndef NLOHMANN_JSON_NAMESPACE_END
#define NLOHMANN_JSON_NAMESPACE_END \
} /* namespace (inline namespace) NOLINT(readability/namespace) */ \
} // namespace nlohmann
#endif
/*!
@brief namespace for Niels Lohmann
@see https://github.com/nlohmann
@since version 1.0.0
*/
NLOHMANN_JSON_NAMESPACE_BEGIN
/*!
@brief default JSONSerializer template argument
This serializer ignores the template arguments and uses ADL
([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl))
for serialization.
*/
template<typename T = void, typename SFINAE = void>
struct adl_serializer;
/// a class to store JSON values
/// @sa https://json.nlohmann.me/api/basic_json/
template<template<typename U, typename V, typename... Args> class ObjectType =
std::map,
template<typename U, typename... Args> class ArrayType = std::vector,
class StringType = std::string, class BooleanType = bool,
class NumberIntegerType = std::int64_t,
class NumberUnsignedType = std::uint64_t,
class NumberFloatType = double,
template<typename U> class AllocatorType = std::allocator,
template<typename T, typename SFINAE = void> class JSONSerializer =
adl_serializer,
class BinaryType = std::vector<std::uint8_t>, // cppcheck-suppress syntaxError
class CustomBaseClass = void>
class basic_json;
/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document
/// @sa https://json.nlohmann.me/api/json_pointer/
template<typename RefStringType>
class json_pointer;
/*!
@brief default specialization
@sa https://json.nlohmann.me/api/json/
*/
using json = basic_json<>;
/// @brief a minimal map-like container that preserves insertion order
/// @sa https://json.nlohmann.me/api/ordered_map/
template<class Key, class T, class IgnoredLess, class Allocator>
struct ordered_map;
/// @brief specialization that maintains the insertion order of object keys
/// @sa https://json.nlohmann.me/api/ordered_json/
using ordered_json = basic_json<nlohmann::ordered_map>;
NLOHMANN_JSON_NAMESPACE_END
#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_

36
source/utils/logger.c Normal file
View File

@ -0,0 +1,36 @@
#ifdef DEBUG
#include <stdint.h>
#include <whb/log_cafe.h>
#include <whb/log_module.h>
#include <whb/log_udp.h>
uint32_t moduleLogInit = false;
uint32_t cafeLogInit = false;
uint32_t udpLogInit = false;
#endif // DEBUG
void initLogging() {
#ifdef DEBUG
if (!(moduleLogInit = WHBLogModuleInit())) {
cafeLogInit = WHBLogCafeInit();
udpLogInit = WHBLogUdpInit();
}
#endif // DEBUG
}
void deinitLogging() {
#ifdef DEBUG
if (moduleLogInit) {
WHBLogModuleDeinit();
moduleLogInit = false;
}
if (cafeLogInit) {
WHBLogCafeDeinit();
cafeLogInit = false;
}
if (udpLogInit) {
WHBLogUdpDeinit();
udpLogInit = false;
}
#endif // DEBUG
}

68
source/utils/logger.h Normal file
View File

@ -0,0 +1,68 @@
#pragma once
#include <coreinit/debug.h>
#include <string.h>
#include <whb/log.h>
#ifdef __cplusplus
extern "C" {
#endif
#define LOG_APP_TYPE "A"
#define LOG_APP_NAME "aroma_updater"
#define __FILENAME_X__ (strrchr(__FILE__, '\\') ? strrchr(__FILE__, '\\') + 1 : __FILE__)
#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILENAME_X__)
#define LOG(LOG_FUNC, FMT, ARGS...) LOG_EX_DEFAULT(LOG_FUNC, "", "", FMT, ##ARGS)
#define LOG_EX_DEFAULT(LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) LOG_EX(__FILENAME__, __FUNCTION__, __LINE__, LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ##ARGS)
#define LOG_EX(FILENAME, FUNCTION, LINE, LOG_FUNC, LOG_LEVEL, LINE_END, FMT, ARGS...) \
do { \
LOG_FUNC("[(%s)%18s][%23s]%30s@L%04d: " LOG_LEVEL "" FMT "" LINE_END, LOG_APP_TYPE, LOG_APP_NAME, FILENAME, FUNCTION, LINE, ##ARGS); \
} while (0)
#ifdef DEBUG
#ifdef VERBOSE_DEBUG
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_VERBOSE_EX(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "", "", FMT, ##ARGS);
#else
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_VERBOSE_EX(FMT, ARGS...) while (0)
#endif
#define DEBUG_FUNCTION_LINE(FMT, ARGS...) LOG(WHBLogPrintf, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) LOG(WHBLogWritef, FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(WHBLogPrintf, "##WARN ## ", "", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, WHBLogPrintf, "##ERROR## ", "", FMT, ##ARGS);
#else
#define DEBUG_FUNCTION_LINE_VERBOSE_EX(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_VERBOSE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_WRITE(FMT, ARGS...) while (0)
#define DEBUG_FUNCTION_LINE_ERR(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##ERROR## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_WARN(FMT, ARGS...) LOG_EX_DEFAULT(OSReport, "##WARN ## ", "\n", FMT, ##ARGS)
#define DEBUG_FUNCTION_LINE_ERR_LAMBDA(FILENAME, FUNCTION, LINE, FMT, ARGS...) LOG_EX(FILENAME, FUNCTION, LINE, OSReport, "##ERROR## ", "\n", FMT, ##ARGS);
#endif
void initLogging();
void deinitLogging();
#ifdef __cplusplus
}
#endif

1460
source/utils/schrift.c Normal file

File diff suppressed because it is too large Load Diff

88
source/utils/schrift.h Normal file
View File

@ -0,0 +1,88 @@
/* This file is part of libschrift.
*
* © 2019-2022 Thomas Oltmann and contributors
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#ifndef SCHRIFT_H
#define SCHRIFT_H 1
#include <stddef.h> /* size_t */
#include <stdint.h> /* uint_fast32_t, uint_least32_t */
#ifdef __cplusplus
extern "C" {
#endif
#define SFT_DOWNWARD_Y 0x01
typedef struct SFT SFT;
typedef struct SFT_Font SFT_Font;
typedef uint_least32_t SFT_UChar; /* Guaranteed to be compatible with char32_t. */
typedef uint_fast32_t SFT_Glyph;
typedef struct SFT_LMetrics SFT_LMetrics;
typedef struct SFT_GMetrics SFT_GMetrics;
typedef struct SFT_Kerning SFT_Kerning;
typedef struct SFT_Image SFT_Image;
struct SFT {
SFT_Font *font;
double xScale;
double yScale;
double xOffset;
double yOffset;
int flags;
};
struct SFT_LMetrics {
double ascender;
double descender;
double lineGap;
};
struct SFT_GMetrics {
double advanceWidth;
double leftSideBearing;
int yOffset;
int minWidth;
int minHeight;
};
struct SFT_Kerning {
double xShift;
double yShift;
};
struct SFT_Image {
void *pixels;
int width;
int height;
};
const char *sft_version(void);
SFT_Font *sft_loadmem(const void *mem, size_t size);
void sft_freefont(SFT_Font *font);
int sft_lmetrics(const SFT *sft, SFT_LMetrics *metrics);
int sft_lookup(const SFT *sft, SFT_UChar codepoint, SFT_Glyph *glyph);
int sft_gmetrics(const SFT *sft, SFT_Glyph glyph, SFT_GMetrics *metrics);
int sft_kerning(const SFT *sft, SFT_Glyph leftGlyph, SFT_Glyph rightGlyph,
SFT_Kerning *kerning);
int sft_render(const SFT *sft, SFT_Glyph glyph, SFT_Image image);
#ifdef __cplusplus
}
#endif
#endif

25
source/utils/utils.cpp Normal file
View File

@ -0,0 +1,25 @@
#include "FSUtils.h"
#include "TinySHA1.hpp"
#include <optional>
#include <string>
std::string calculateSHA1(const char *buffer, size_t size) {
sha1::SHA1 s;
s.processBytes(buffer, size);
uint32_t digest[5];
s.getDigest(digest);
char tmp[48];
snprintf(tmp, 45, "%08x%08x%08x%08x%08x", digest[0], digest[1], digest[2], digest[3], digest[4]);
return tmp;
}
std::optional<std::string> hashFile(const std::string &path) {
uint8_t *data = nullptr;
uint32_t size = 0;
if (LoadFileToMem(path.c_str(), &data, &size) < 0 || data == nullptr) {
return {};
}
std::string result = calculateSHA1(reinterpret_cast<const char *>(data), size);
free(data);
return result;
}

35
source/utils/utils.h Normal file
View File

@ -0,0 +1,35 @@
#pragma once
#include <memory>
#include <mutex>
#include <optional>
#include <vector>
template<class T, class... Args>
std::unique_ptr<T> make_unique_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::unique_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
template<typename T>
inline typename std::unique_ptr<T> make_unique_nothrow(size_t num) noexcept {
return std::unique_ptr<T>(new (std::nothrow) std::remove_extent_t<T>[num]());
}
template<class T, class... Args>
std::shared_ptr<T> make_shared_nothrow(Args &&...args) noexcept(noexcept(T(std::forward<Args>(args)...))) {
return std::shared_ptr<T>(new (std::nothrow) T(std::forward<Args>(args)...));
}
template<typename... Args>
std::string string_format(const std::string &format, Args... args) {
int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
auto size = static_cast<size_t>(size_s);
auto buf = make_unique_nothrow<char[]>(size);
if (!buf) {
return std::string("");
}
std::snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
}
std::optional<std::string> hashFile(const std::string &path);

5713
source/utils/zip_file.hpp Normal file

File diff suppressed because it is too large Load Diff

2
source/version.h Normal file
View File

@ -0,0 +1,2 @@
#pragma once
#define UPDATER_VERSION_EXTRA ""