Compare commits

..

17 Commits

44 changed files with 2419 additions and 118 deletions

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>.

10
README.md Normal file
View File

@ -0,0 +1,10 @@
# SIMD
*The code powering [simd.jaytux.com](https://simd.jaytux.com)*
This service provides a RESTful API for C/C++ intrinsics, with a slight focus on SIMD intrinsics. The data is currently sourced from [Intel](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#), but I'd like to incorporate AMD performance data, as well as intrinsics from ARM and/or PowerPC.
## Project Structure
- `/api/`: the code powering the API itself (using Ktor in Kotlin);
- `/frontend/`: the code powering the desktop and web frontends (using Compose Multiplatform).
See the respective directories for details on setup/dependencies/building/running.

2
api/.gitignore vendored
View File

@ -43,4 +43,4 @@ bin/
.env .env
intrinsics.sqlite intrinsics.sqlite
com.jaytux.simd.api.tar.gz *.tar.gz

View File

@ -25,6 +25,8 @@
5. At this point, you are ready to load the data into the database using the application. Run `./gradlew run -reload /path/to/post-processed/data.js /path/to/post-processed/perf2.js` 5. At this point, you are ready to load the data into the database using the application. Run `./gradlew run -reload /path/to/post-processed/data.js /path/to/post-processed/perf2.js`
6. Finally, you can start the application using `./gradlew run` 6. Finally, you can start the application using `./gradlew run`
You can also use the `./package.sh` script to build a standalone executable (with bundled JVM).You can also use the `./package.sh` script to build a standalone executable (with bundled JVM). It uses the Gradle `shadowJar` target together with `jpackage`.
## Running ## Running
By default, the application runs on port `42024`. You can start it using `./gradlew run`. By default, the application runs on port `42024`. You can start it using `./gradlew run`.
@ -76,12 +78,14 @@ Gets a (paginated) list of all C/C++(-like) types used by the intrinsics. The ty
Searches the database using the given filters. The filters are passed as query parameters, and can be combined. All filters are optional. The following filters are available: Searches the database using the given filters. The filters are passed as query parameters, and can be combined. All filters are optional. The following filters are available:
- `name=[string]`: searches based on the name of the intrinsic; employs fuzzy-search (using `LIKE %it%`) - `name=[string]`: searches based on the name of the intrinsic; employs fuzzy-search (using `LIKE %it%`)
- `return=[string]`: searches based on the return type of the intrinsic; exact search only - `return=[string]`: searches based on the return type of the intrinsic; exact search only
- `cpuid=[string]`: searches based on the CPUID of the intrinsic; exact search only - `cpuid=[*]`: searches based on the CPUID of the intrinsic; exact search only
- `tech=[string]`: searches based on the technology of the intrinsic; exact search only - `tech=[*]`: searches based on the technology of the intrinsic; exact search only
- `category=[string]`: searches based on the category of the intrinsic; exact search only - `category=[*]`: searches based on the category of the intrinsic; exact search only
- `desc=[string]`: searches based on the description of the intrinsic; employs fuzzy-search (using `LIKE %it%`) - `desc=[string]`: searches based on the description of the intrinsic; employs fuzzy-search (using `LIKE %it%`)
- `page=[int]`: specifies the page number to return (default is 0) - `page=[int]`: specifies the page number to return (default is 0)
Parameters marked by `[*]` are JSON-lists (so you should pass them as `cpuid=["PREFETCHI", "SSE2"]`). They are considered to be OR-ed together (i.e. the results will contain a mix of all intrinsics matching either of the CPUIDs (from the example)).
Passing no filters is equivalent to using `GET /all`, and data is returned in the same format: Passing no filters is equivalent to using `GET /all`, and data is returned in the same format:
```json ```json
{ {
@ -131,3 +135,13 @@ Gets the details for a single, specific intrinsic. The following data is returne
] ]
} }
``` ```
### `GET /version`
Gets version information for the data. The following data is returned:
```json
{
"intelVersion": "M.m.p (Major.minor.patch version as reported by Intel)",
"intelUpdate": "yyyy-MM-dd (date of Intel's last update prior to scraping)",
"scrapeDate": "yyyy-MM-dd (date of last update)"
}
```

View File

@ -1,13 +1,52 @@
#!/usr/bin/env sh #!/usr/bin/env sh
echo ""
echo "+-----------------+"
echo "| ./gradlew clean |"
echo "+-----------------+"
echo ""
./gradlew clean ./gradlew clean
echo ""
echo "+---------------------+"
echo "| ./gradlew shadowJar |"
echo "+---------------------+"
echo ""
./gradlew shadowJar ./gradlew shadowJar
echo ""
echo "+-----------------------------+"
echo "| cp build/libs/api-all.jar . |"
echo "+-----------------------------+"
echo ""
cp build/libs/api-all.jar . cp build/libs/api-all.jar .
rm -fr build/dist/ com.jaytux.simd.api.tar.gz echo ""
echo "+----------------------------------------+"
echo "| rm -fr build/dist/ simd-api@jvm.tar.gz |"
echo "+----------------------------------------+"
echo ""
rm -fr build/dist/ simd-api@jvm.tar.gz
echo ""
echo "+-----------------------------------------------------------------------------------------------+"
echo "| jpackage --type app-image --input build/libs/ --dest build/dist/ --name com.jaytux.simd.api \\ |"
echo "| --main-jar ./api-all.jar --main-class com.jaytux.simd.MainKt |"
echo "+-----------------------------------------------------------------------------------------------+"
echo ""
jpackage --type app-image --input build/libs/ --dest build/dist/ --name com.jaytux.simd.api \ jpackage --type app-image --input build/libs/ --dest build/dist/ --name com.jaytux.simd.api \
--main-jar ./api-all.jar --main-class com.jaytux.simd.MainKt --main-jar ./api-all.jar --main-class com.jaytux.simd.MainKt
echo ""
echo "+----------------+"
echo "| rm api-all.jar |"
echo "+----------------+"
echo ""
rm api-all.jar rm api-all.jar
tar -czf com.jaytux.simd.api.tar.gz -C build/dist com.jaytux.simd.api
echo ""
echo "+----------------------------------------------------------------+"
echo "| tar -czf simd-api@jvm.tar.gz -C build/dist com.jaytux.simd.api |"
echo "+----------------------------------------------------------------+"
echo ""
tar -czf simd-api@jvm.tar.gz -C build/dist com.jaytux.simd.api

View File

@ -11,8 +11,6 @@ import io.ktor.server.netty.*
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) { fun main(args: Array<String>) {
println("Arguments (${args.size}): [${args.joinToString(", ")}]")
if(args.size >= 3 && args[0] == "-reload") { if(args.size >= 3 && args[0] == "-reload") {
val xmlFile = args[1] val xmlFile = args[1]
val jsonFile = args[2] val jsonFile = args[2]
@ -39,8 +37,9 @@ fun dbSetup(xmlFile: String, jsonFile: String, force: Boolean = false) {
if(force || (xml.version.version isNewerThan current.version)) { if(force || (xml.version.version isNewerThan current.version)) {
Database.reset() Database.reset()
Loader.importToDb(xml, perf) Loader.importToDb(xml, perf)
println("Database reset/reloaded!")
} }
if(!(xml.version.version isNewerThan current.version)) { else if(!(xml.version.version isNewerThan current.version)) {
System.err.println("The XML file (${xml.version}) is not more up-to-date than the database ($current). Use -force to force importing.") System.err.println("The XML file (${xml.version}) is not more up-to-date than the database ($current). Use -force to force importing.")
} }
} }

View File

@ -1,6 +1,7 @@
package com.jaytux.simd.data package com.jaytux.simd.data
import com.fleeksoft.ksoup.Ksoup import com.fleeksoft.ksoup.Ksoup
import com.fleeksoft.ksoup.parser.Parser
import com.jaytux.simd.data.IntrinsicInstructions.xed import com.jaytux.simd.data.IntrinsicInstructions.xed
import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.coroutineScope
import kotlinx.datetime.* import kotlinx.datetime.*
@ -84,6 +85,7 @@ object Loader {
suspend fun loadXml(xmlFile: String): XmlData = coroutineScope { suspend fun loadXml(xmlFile: String): XmlData = coroutineScope {
val xml = Ksoup.parseXml(File(xmlFile).readText(Charsets.UTF_8)) val xml = Ksoup.parseXml(File(xmlFile).readText(Charsets.UTF_8))
Parser.xmlParser()
val cppTypes = mutableSetOf<String>() val cppTypes = mutableSetOf<String>()
val techs = mutableSetOf<String>() val techs = mutableSetOf<String>()
@ -158,13 +160,13 @@ object Loader {
args += argName to type args += argName to type
} }
val desc = it.getElementsByTag("description").firstOrNull()?.text() val desc = it.getElementsByTag("description").firstOrNull()?.wholeText()?.trim()
if(desc == null) { if(desc == null) {
errors += "Missing description element for intrinsic $name" errors += "Missing description element for intrinsic $name"
return@forEachIndexed return@forEachIndexed
} }
val op = it.getElementsByTag("operation").firstOrNull()?.text() val op = it.getElementsByTag("operation").firstOrNull()?.wholeText()?.trim()
val insn = mutableListOf<Triple<String, String, String?>>() val insn = mutableListOf<Triple<String, String, String?>>()
it.getElementsByTag("instruction").forEachIndexed { i, ins -> it.getElementsByTag("instruction").forEachIndexed { i, ins ->

View File

@ -4,13 +4,17 @@ import com.jaytux.simd.data.*
import com.jaytux.simd.server.RouteCache.register import com.jaytux.simd.server.RouteCache.register
import io.ktor.http.* import io.ktor.http.*
import io.ktor.http.content.* import io.ktor.http.content.*
import io.ktor.server.request.*
import io.ktor.server.response.* import io.ktor.server.response.*
import io.ktor.server.routing.* import io.ktor.server.routing.*
import kotlinx.datetime.LocalDate import kotlinx.datetime.LocalDate
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import org.jetbrains.exposed.dao.UUIDEntity
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.SqlExpressionBuilder.like import org.jetbrains.exposed.sql.SqlExpressionBuilder.like
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction import org.jetbrains.exposed.sql.transactions.transaction
import java.util.* import java.util.*
@ -60,32 +64,46 @@ fun Routing.installGetAll() {
fun Routing.installSearch() { fun Routing.installSearch() {
getPagedRequest("/search", "Search for intrinsics matching certain filters", { 100 }, { IntrinsicSummary(it[Intrinsics.id].value, it[Intrinsics.mnemonic]) }) { getPagedRequest("/search", "Search for intrinsics matching certain filters", { 100 }, { IntrinsicSummary(it[Intrinsics.id].value, it[Intrinsics.mnemonic]) }) {
fun <T : UUIDEntity> resolveAny(key: String, finder: (String) -> SizedIterable<T>): List<EntityID<UUID>>? {
return call.request.queryParameters[key]?.let {
try {
val list = Json.decodeFromString<List<String>>(it)
list.map {
finder(it).firstOrNull()?.id
?: throw HttpError("Unknown $key: ${list.joinToString(", ")}")
}
}
catch(e: HttpError) {
throw e
}
catch(e: Exception) {
throw HttpError("Malformed $key parameter: $it")
}
}
}
val name = call.request.queryParameters["name"] val name = call.request.queryParameters["name"]
val returnType = call.request.queryParameters["return"]?.let { val returnType = call.request.queryParameters["return"]?.let {
CppType.find { CppTypes.name eq it }.firstOrNull() CppType.find { CppTypes.name eq it }.firstOrNull()
?: throw HttpError("Unknown return type: $it") ?: throw HttpError("Unknown return type: $it")
} }
val cpuid = call.request.queryParameters["cpuid"]?.let { val anyCpuid = resolveAny("cpuid") { CPUID.find { CPUIDs.name eq it } }
CPUID.find { CPUIDs.name eq it }.firstOrNull() val anyTech = resolveAny("tech") { Tech.find { Techs.name eq it } }
?: throw HttpError("Unknown CPUID: $it") val anyCat = resolveAny("category") { Category.find { Categories.name eq it } }
}
val tech = call.request.queryParameters["tech"]?.let {
Tech.find { Techs.name eq it }.firstOrNull()
?: throw HttpError("Unknown tech: $it")
}
val category = call.request.queryParameters["category"]?.let {
Category.find { Categories.name eq it }.firstOrNull()
?: throw HttpError("Unknown category: $it")
}
val desc = call.request.queryParameters["desc"] val desc = call.request.queryParameters["desc"]
var results = Intrinsics.selectAll() var results = Intrinsics.selectAll().where {
name?.let { results = results.where { Intrinsics.mnemonic like "%$it%" } } val build = listOf(
returnType?.let { results = results.where { Intrinsics.returnType eq it.id } } name?.let { Intrinsics.mnemonic like "%$it%" },
cpuid?.let { results = results.where { Intrinsics.cpuid eq it.id } } returnType?.let { Intrinsics.returnType eq it.id },
tech?.let { results = results.where { Intrinsics.tech eq it.id } } anyCpuid?.let { Intrinsics.cpuid inList it },
category?.let { results = results.where { Intrinsics.category eq it.id } } anyTech?.let { Intrinsics.tech inList it },
desc?.let { results = results.where { Intrinsics.description like "%$it%" } } anyCat?.let { Intrinsics.category inList it },
desc?.let { Intrinsics.description like "%$it%" }
).filterNotNull()
build.fold(Op.TRUE as Op<Boolean>, { acc, op -> op and acc })
}
results.orderAsc(Intrinsics.mnemonic) results.orderAsc(Intrinsics.mnemonic)
} }

View File

@ -8,7 +8,7 @@
<logger name="io.netty" level="warn" /> <logger name="io.netty" level="warn" />
<logger name="ch.qos.logback" level="warn" /> <logger name="ch.qos.logback" level="warn" />
<root level="trace"> <root level="warn">
<appender-ref ref="APPENDER"/> <appender-ref ref="APPENDER"/>
</root> </root>
</configuration> </configuration>

View File

@ -1,19 +0,0 @@
// Project generated by Kotlin Multiplatform Wizard
{
"spec": {
"template_id": "kmt",
"targets": {
"desktop": {
"ui": [
"compose"
]
},
"web": {
"ui": [
"compose"
]
}
}
},
"timestamp": "2025-04-25T08:32:22.469968407Z"
}

3
frontend/.gitignore vendored
View File

@ -16,3 +16,6 @@ captures
!*.xcodeproj/project.xcworkspace/ !*.xcodeproj/project.xcworkspace/
!*.xcworkspace/contents.xcworkspacedata !*.xcworkspace/contents.xcworkspacedata
**/xcshareddata/WorkspaceSettings.xcsettings **/xcshareddata/WorkspaceSettings.xcsettings
**/.env
*.tar.gz

View File

@ -1,18 +1,20 @@
This is a Kotlin Multiplatform project targeting Web, Desktop. # Intrinsics UI
*The UI powering [https://simd.jaytux.com](https://simd.jaytux.com)*
* `/composeApp` is for code that will be shared across your Compose Multiplatform applications. ## Running
It contains several subfolders: The Gradle wrapper (`./gradlew`) in the repository can be used to run the project.
- `commonMain` is for code thats common for all targets. Currently, two targets are available:
- Other folders are for Kotlin code that will be compiled for only the platform indicated in the folder name. - **Web**: The web application uses Kotlin's WASM/JS target and is "optimized" for landscape mode. I am planning to add a portrait mode in the future (together with an Android/iOS version). There are three important Gradle tasks:
For example, if you want to use Apples CoreCrypto for the iOS part of your Kotlin app, - `wasmJsBrowserRun`: runs the web application (mostly used for development);
`iosMain` would be the right folder for such calls. - `wasmJsBrowserDistribution`: builds a distribution of the web application, which can be statically served;
- `wasmJsBrowserProductionWebpack`: builds a production-ready web application, which can be statically served (this target takes a lot longer to build, but should be more performant/smaller in code size).
- **Desktop/JVM**: The desktop application uses Kotlin's JVM target. It has a few important Gradle tasks:
- `desktopRun`: runs the desktop application (mostly used for development);
- `packageAppImage`, `packageDeb`, `packageDmg`, `packageMsi`: packages the desktop application for distribution on various platforms (Linux, MacOS, Windows).
The web distribution can be found in `composeApp/build/dist/wasmJs`, and the desktop distribution in `composeApp/build/compose/binaries/main/app`.
Learn more about [Kotlin Multiplatform](https://www.jetbrains.com/help/kotlin-multiplatform-dev/get-started.html), You can also use the `./package.sh` script to build both (for Desktop, the AppImage will be built). This script also generates a compressed archive (`.tar.gz`) for both.
[Compose Multiplatform](https://github.com/JetBrains/compose-multiplatform/#compose-multiplatform),
[Kotlin/Wasm](https://kotl.in/wasm/)…
We would appreciate your feedback on Compose/Web and Kotlin/Wasm in the public Slack channel [#compose-web](https://slack-chats.kotlinlang.org/c/compose-web). ## Configuring
If you face any issues, please report them on [GitHub](https://github.com/JetBrains/compose-multiplatform/issues). The only configuration is the backend URL. At the moment, it is set explicitly in the code, but I might change that. To change it, change the value `com.jaytux.simd.frontend.client.Client.baseUrl` in `/composeApp/src/commonMain/kotlin/com/jaytux/simd/frontend/client/Client.kt`.
You can open the web application by running the `:composeApp:wasmJsBrowserDevelopmentRun` Gradle task.

View File

@ -47,12 +47,14 @@ kotlin {
implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.lifecycle.runtime.compose)
implementation(libs.ktor.client.core) implementation(libs.ktor.client.core)
implementation(libs.ktor.client.logging) implementation(libs.ktor.client.logging)
implementation(libs.ktor.client.content.negotiation)
implementation(libs.ktor.serialization.kotlinx.json) implementation(libs.ktor.serialization.kotlinx.json)
implementation(libs.dotenv)
implementation(libs.json) implementation(libs.json)
implementation(libs.kotlinx.datetime) implementation(libs.kotlinx.datetime)
implementation(libs.kotlinx.serialization.json) implementation(libs.kotlinx.serialization.json)
implementation(libs.logback.classic) implementation(libs.logback.classic)
implementation(libs.material3)
implementation(libs.lucide)
} }
desktopMain.dependencies { desktopMain.dependencies {
implementation(compose.desktop.currentOs) implementation(compose.desktop.currentOs)
@ -65,15 +67,25 @@ kotlin {
} }
} }
compose.desktop { compose.desktop {
application { application {
mainClass = "com.jaytux.simd.frontend.MainKt" mainClass = "com.jaytux.simd.frontend.MainKt"
nativeDistributions { nativeDistributions {
targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb) targetFormats(TargetFormat.Dmg, TargetFormat.Msi, TargetFormat.Deb, TargetFormat.AppImage)
packageName = "com.jaytux.simd.frontend" packageName = "com.jaytux.simd.frontend"
packageVersion = "1.0.0" packageVersion = "1.0.0"
} }
} }
} }
compose.resources {
//
}
tasks.withType<Jar> {
duplicatesStrategy = DuplicatesStrategy.INCLUDE
manifest {
attributes["Main-Class"] = "com.jaytux.simd.frontend.MainKt"
}
}

View File

@ -1,36 +1,32 @@
package com.jaytux.simd.frontend package com.jaytux.simd.frontend
import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.Image import androidx.compose.material3.*
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.* import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import org.jetbrains.compose.resources.painterResource import com.jaytux.simd.frontend.theme.SimdTheme
import com.jaytux.simd.frontend.ui.DataState
import com.jaytux.simd.frontend.ui.ErrorSnackBar
import com.jaytux.simd.frontend.ui.topBar
import org.jetbrains.compose.ui.tooling.preview.Preview import org.jetbrains.compose.ui.tooling.preview.Preview
import frontend.composeapp.generated.resources.Res
import frontend.composeapp.generated.resources.compose_multiplatform
@Composable @Composable
@Preview @Preview
fun App() { fun App() {
MaterialTheme { SimdTheme {
var showContent by remember { mutableStateOf(false) } val scope = rememberCoroutineScope()
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { val snackState = remember { SnackbarHostState() }
Button(onClick = { showContent = !showContent }) { val data = DataState(scope, {
Text("Click me!") println(it)
} snackState.showSnackbar(it, duration = SnackbarDuration.Short)
AnimatedVisibility(showContent) { })
val greeting = remember { Greeting().greet() }
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Scaffold(
Image(painterResource(Res.drawable.compose_multiplatform), null) topBar = { topBar(data) },
Text("Compose: $greeting") snackbarHost = { SnackbarHost(snackState) { ErrorSnackBar(it) } }
} ) {
Surface(Modifier.padding(top = it.calculateTopPadding())) {
mainView(data)
} }
} }
} }

View File

@ -1,9 +0,0 @@
package com.jaytux.simd.frontend
class Greeting {
private val platform = getPlatform()
fun greet(): String {
return "Hello, ${platform.name}!"
}
}

View File

@ -0,0 +1,34 @@
package com.jaytux.simd.frontend
import androidx.compose.runtime.Composable
sealed class Either<out L, out R> {
class Left<L>(val value: L) : Either<L, Nothing>()
class Right<R>(val value: R) : Either<Nothing, R>()
fun <T> fold(onLeft: (L) -> T, onRight: (R) -> T): T = when(this) {
is Left -> onLeft(value)
is Right -> onRight(value)
}
suspend fun <T> foldSuspend(onLeft: suspend (L) -> T, onRight: suspend (R) -> T): T = when(this) {
is Left -> onLeft(value)
is Right -> onRight(value)
}
@Composable
fun <T> foldCompose(onLeft: @Composable (L) -> T, onRight: @Composable (R) -> T): T = when(this) {
is Left -> onLeft(value)
is Right -> onRight(value)
}
}
fun <T> T.left() = Either.Left(this)
fun <T> T.right() = Either.Right(this)
fun <L, R, X> Either<L, R>.map(f: (R) -> X): Either<L, X> = when(this) {
is Either.Left -> this
is Either.Right -> Either.Right(f(value))
}
typealias OrError<T> = Either<String, T>

View File

@ -1,7 +1,10 @@
package com.jaytux.simd.frontend package com.jaytux.simd.frontend
interface Platform { import androidx.compose.runtime.Composable
val name: String import com.jaytux.simd.frontend.ui.DataState
} import io.ktor.client.*
expect fun getPlatform(): Platform expect fun getKtorClient(builder: HttpClientConfig<*>.() -> Unit): HttpClient
@Composable
expect fun mainView(data: DataState): Unit

View File

@ -0,0 +1,6 @@
package com.jaytux.simd.frontend
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
fun <T> MutableState<T>.immutable(): State<T> = this

View File

@ -0,0 +1,188 @@
package com.jaytux.simd.frontend.client
import com.jaytux.simd.frontend.*
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.coroutines.delay
import kotlinx.datetime.LocalDate
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.Json
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid
@OptIn(ExperimentalUuidApi::class)
object Client {
val httpClient: HttpClient by lazy { getKtorClient{ install(ContentNegotiation) { json() } } }
val baseUrl = "https://simd.jaytux.com/api"
object UUIDSerializer : KSerializer<Uuid> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("UUID", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): Uuid = try {
Uuid.parse(decoder.decodeString())
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Invalid UUID format")
}
override fun serialize(encoder: Encoder, value: Uuid) = encoder.encodeString(value.toString())
}
@Serializable
data class IntrinsicSummary constructor(@Serializable(with = UUIDSerializer::class) val id: Uuid, val name: String)
@Serializable
data class Param(val name: String, val type: String)
@Serializable
data class Instruction(val mnemonic: String, val xed: String, val form: String?)
@Serializable
data class PlatformPerformance(val platform: String, val latency: Float?, val throughput: Float?)
@Serializable
data class IntrinsicDetails(
@Serializable(with = UUIDSerializer::class) val id: Uuid,
val name: String,
val returnType: String,
val returnVar: String?,
val description: String,
val operations: String?,
val category: String,
val cpuid: String?,
val tech: String,
val params: List<Param>,
val instructions: List<Instruction>?,
val performance: List<PlatformPerformance>?
)
@Serializable
data class Versioning(
val intelVersion: String, val intelUpdate: LocalDate, val scrapeDate: LocalDate
)
@Serializable data class Paginated<T>(val page: Long, val totalPages: Long, val items: List<T>)
interface PaginatedResponse<T> {
fun currentPage(): Long
fun totalPages(): Long
fun currentItems(): List<T>
fun hasNextPage(): Boolean
suspend fun loadNextPage(): OrError<Unit>
}
private inline suspend fun <reified T> throttle(millis: Long, crossinline block: suspend () -> T): T {
delay(millis)
return block()
}
private suspend inline fun <reified T> makeBasicRequest(url: String, crossinline builder: URLBuilder.() -> Unit = {}): OrError<T> = try {
val resp = httpClient.get(url) {
header("Accept", "application/json")
expectSuccess = true
url { builder() }
}
resp.body<T>().right()
} catch (e: Exception) {
"Failed to load $url: ${e.message ?: "Unknown error"}".left()
}
private suspend inline fun <reified T> getPaginated(url: String): OrError<PaginatedResponse<T>> {
val loader: suspend (Long?) -> OrError<Paginated<T>> = { page: Long? ->
makeBasicRequest<Paginated<T>>(url + (if (page != null) "/$page" else ""))
}
return loader(null).map { p0 ->
object : PaginatedResponse<T> {
var page = p0.page
val total = p0.totalPages
var current = p0.items
override fun currentItems(): List<T> = current
override fun hasNextPage(): Boolean = page < total
override fun currentPage(): Long = page
override fun totalPages(): Long = total
override suspend fun loadNextPage(): OrError<Unit> {
if(hasNextPage()) {
return loader(page + 1).map {
page = it.page
current = it.items
}
}
else {
return "No more pages (for URL ${url})".left()
}
}
}
}
}
private suspend inline fun <reified T> getPaginatedQuery(url: String, crossinline addParams: URLBuilder.() -> Unit = {}): OrError<PaginatedResponse<T>> {
val loader: suspend (Long?) -> OrError<Paginated<T>> = { page: Long? ->
makeBasicRequest<Paginated<T>>(url) {
addParams()
if(page != null) parameters.append("page", "$page")
}
}
return loader(null).map { p0 ->
object : PaginatedResponse<T> {
var page = p0.page
val total = p0.totalPages
var current = p0.items
override fun currentItems(): List<T> = current
override fun hasNextPage(): Boolean = page < total
override fun currentPage(): Long = page
override fun totalPages(): Long = total
override suspend fun loadNextPage(): OrError<Unit> {
if(hasNextPage()) {
return loader(page + 1).map {
page = it.page
current = it.items
}
}
else {
return "No more pages (for URL ${url})".left()
}
}
}
}
}
suspend fun getAll(): OrError<PaginatedResponse<IntrinsicSummary>> = getPaginated<IntrinsicSummary>("$baseUrl/all")
suspend fun getCpuid(): OrError<PaginatedResponse<String>> = getPaginated<String>("$baseUrl/cpuid")
suspend fun getTech(): OrError<PaginatedResponse<String>> = getPaginated<String>("$baseUrl/tech")
suspend fun getCategory(): OrError<PaginatedResponse<String>> = getPaginated<String>("$baseUrl/category")
suspend fun getTypes(): OrError<PaginatedResponse<String>> = getPaginated<String>("$baseUrl/types")
suspend fun getSearch(
name: String? = null, returnT: String? = null, cpuid: List<String> = listOf(),
tech: List<String> = listOf(), category: List<String> = listOf(), desc: String? = null
): OrError<PaginatedResponse<IntrinsicSummary>> = getPaginatedQuery("$baseUrl/search") {
if(name != null) parameters.append("name", name)
if(returnT != null) parameters.append("returnT", returnT)
if(cpuid.isNotEmpty()) parameters.append("cpuid", Json.encodeToString(cpuid))
if(tech.isNotEmpty()) parameters.append("tech", Json.encodeToString(tech))
if(category.isNotEmpty()) parameters.append("category", Json.encodeToString(category))
if(desc != null) parameters.append("desc", desc)
}
suspend fun getDetails(id: Uuid): OrError<IntrinsicDetails> = makeBasicRequest("$baseUrl/details/$id")
suspend fun getVersion(): OrError<Versioning> = makeBasicRequest("$baseUrl/version")
}

View File

@ -0,0 +1,53 @@
package com.jaytux.simd.frontend.client
import androidx.compose.runtime.mutableStateOf
import com.jaytux.simd.frontend.OrError
import com.jaytux.simd.frontend.immutable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
object Loader {
val progressInit = "Initializing..."
val progressFailed = "Finished (failed)"
val progressFinished = "Finished"
fun <T> CoroutineScope.loadAll(
client: suspend () -> OrError<Client.PaginatedResponse<T>>,
onError: suspend (String) -> Unit,
onFinishSuccess: suspend (List<T>) -> Unit,
onStatusChange: suspend (String) -> Unit,
onProgress: suspend (List<T>) -> Unit = {},
throttleBefore: Long = 0,
) = launch {
delay(throttleBefore) // in case of UI-driven loading
onStatusChange(progressInit)
client().foldSuspend({
onStatusChange(progressFailed)
onError(it)
}) { pg ->
onStatusChange("Loading ${pg.currentPage() + 1}/${pg.totalPages()}")
val res = pg.currentItems().toMutableList()
var anyError = false
while (pg.hasNextPage() && !anyError) {
pg.loadNextPage().foldSuspend({
onStatusChange(progressFailed)
onError(it)
anyError = true
}) {
onStatusChange("Loading ${pg.currentPage() + 1}/${pg.totalPages()}")
res.addAll(pg.currentItems())
onProgress(res)
}
}
if (!anyError) {
onStatusChange(progressFinished)
onFinishSuccess(res)
}
}
}
}

View File

@ -0,0 +1,225 @@
package com.jaytux.simd.frontend.theme
import androidx.compose.ui.graphics.Color
val primaryLight = Color(0xFF005CB9)
val onPrimaryLight = Color(0xFFFFFFFF)
val primaryContainerLight = Color(0xFF5B9BFF)
val onPrimaryContainerLight = Color(0xFF00326A)
val secondaryLight = Color(0xFF176648)
val onSecondaryLight = Color(0xFFFFFFFF)
val secondaryContainerLight = Color(0xFF367F5F)
val onSecondaryContainerLight = Color(0xFFE3FFED)
val tertiaryLight = Color(0xFF8C3D9B)
val onTertiaryLight = Color(0xFFFFFFFF)
val tertiaryContainerLight = Color(0xFFD07BDE)
val onTertiaryContainerLight = Color(0xFF5A036C)
val errorLight = Color(0xFFBA1A1A)
val onErrorLight = Color(0xFFFFFFFF)
val errorContainerLight = Color(0xFFFFDAD6)
val onErrorContainerLight = Color(0xFF93000A)
val backgroundLight = Color(0xFFF9F9FF)
val onBackgroundLight = Color(0xFF191C22)
val surfaceLight = Color(0xFFF9F9FF)
val onSurfaceLight = Color(0xFF191C22)
val surfaceVariantLight = Color(0xFFDEE2F1)
val onSurfaceVariantLight = Color(0xFF424752)
val outlineLight = Color(0xFF727784)
val outlineVariantLight = Color(0xFFC2C6D4)
val scrimLight = Color(0xFF000000)
val inverseSurfaceLight = Color(0xFF2E3037)
val inverseOnSurfaceLight = Color(0xFFEFF0F9)
val inversePrimaryLight = Color(0xFFAAC7FF)
val surfaceDimLight = Color(0xFFD8D9E2)
val surfaceBrightLight = Color(0xFFF9F9FF)
val surfaceContainerLowestLight = Color(0xFFFFFFFF)
val surfaceContainerLowLight = Color(0xFFF2F3FC)
val surfaceContainerLight = Color(0xFFECEDF6)
val surfaceContainerHighLight = Color(0xFFE7E8F0)
val surfaceContainerHighestLight = Color(0xFFE1E2EB)
val primaryLightMediumContrast = Color(0xFF00356F)
val onPrimaryLightMediumContrast = Color(0xFFFFFFFF)
val primaryContainerLightMediumContrast = Color(0xFF1D6BCC)
val onPrimaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val secondaryLightMediumContrast = Color(0xFF003F29)
val onSecondaryLightMediumContrast = Color(0xFFFFFFFF)
val secondaryContainerLightMediumContrast = Color(0xFF307A5A)
val onSecondaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val tertiaryLightMediumContrast = Color(0xFF5D096F)
val onTertiaryLightMediumContrast = Color(0xFFFFFFFF)
val tertiaryContainerLightMediumContrast = Color(0xFF9C4CAC)
val onTertiaryContainerLightMediumContrast = Color(0xFFFFFFFF)
val errorLightMediumContrast = Color(0xFF740006)
val onErrorLightMediumContrast = Color(0xFFFFFFFF)
val errorContainerLightMediumContrast = Color(0xFFCF2C27)
val onErrorContainerLightMediumContrast = Color(0xFFFFFFFF)
val backgroundLightMediumContrast = Color(0xFFF9F9FF)
val onBackgroundLightMediumContrast = Color(0xFF191C22)
val surfaceLightMediumContrast = Color(0xFFF9F9FF)
val onSurfaceLightMediumContrast = Color(0xFF0E1117)
val surfaceVariantLightMediumContrast = Color(0xFFDEE2F1)
val onSurfaceVariantLightMediumContrast = Color(0xFF313641)
val outlineLightMediumContrast = Color(0xFF4D525E)
val outlineVariantLightMediumContrast = Color(0xFF686D7A)
val scrimLightMediumContrast = Color(0xFF000000)
val inverseSurfaceLightMediumContrast = Color(0xFF2E3037)
val inverseOnSurfaceLightMediumContrast = Color(0xFFEFF0F9)
val inversePrimaryLightMediumContrast = Color(0xFFAAC7FF)
val surfaceDimLightMediumContrast = Color(0xFFC5C6CE)
val surfaceBrightLightMediumContrast = Color(0xFFF9F9FF)
val surfaceContainerLowestLightMediumContrast = Color(0xFFFFFFFF)
val surfaceContainerLowLightMediumContrast = Color(0xFFF2F3FC)
val surfaceContainerLightMediumContrast = Color(0xFFE7E8F0)
val surfaceContainerHighLightMediumContrast = Color(0xFFDBDCE5)
val surfaceContainerHighestLightMediumContrast = Color(0xFFD0D1DA)
val primaryLightHighContrast = Color(0xFF002B5D)
val onPrimaryLightHighContrast = Color(0xFFFFFFFF)
val primaryContainerLightHighContrast = Color(0xFF004892)
val onPrimaryContainerLightHighContrast = Color(0xFFFFFFFF)
val secondaryLightHighContrast = Color(0xFF003321)
val onSecondaryLightHighContrast = Color(0xFFFFFFFF)
val secondaryContainerLightHighContrast = Color(0xFF005439)
val onSecondaryContainerLightHighContrast = Color(0xFFFFFFFF)
val tertiaryLightHighContrast = Color(0xFF4F0060)
val onTertiaryLightHighContrast = Color(0xFFFFFFFF)
val tertiaryContainerLightHighContrast = Color(0xFF732584)
val onTertiaryContainerLightHighContrast = Color(0xFFFFFFFF)
val errorLightHighContrast = Color(0xFF600004)
val onErrorLightHighContrast = Color(0xFFFFFFFF)
val errorContainerLightHighContrast = Color(0xFF98000A)
val onErrorContainerLightHighContrast = Color(0xFFFFFFFF)
val backgroundLightHighContrast = Color(0xFFF9F9FF)
val onBackgroundLightHighContrast = Color(0xFF191C22)
val surfaceLightHighContrast = Color(0xFFF9F9FF)
val onSurfaceLightHighContrast = Color(0xFF000000)
val surfaceVariantLightHighContrast = Color(0xFFDEE2F1)
val onSurfaceVariantLightHighContrast = Color(0xFF000000)
val outlineLightHighContrast = Color(0xFF272C37)
val outlineVariantLightHighContrast = Color(0xFF444955)
val scrimLightHighContrast = Color(0xFF000000)
val inverseSurfaceLightHighContrast = Color(0xFF2E3037)
val inverseOnSurfaceLightHighContrast = Color(0xFFFFFFFF)
val inversePrimaryLightHighContrast = Color(0xFFAAC7FF)
val surfaceDimLightHighContrast = Color(0xFFB7B8C1)
val surfaceBrightLightHighContrast = Color(0xFFF9F9FF)
val surfaceContainerLowestLightHighContrast = Color(0xFFFFFFFF)
val surfaceContainerLowLightHighContrast = Color(0xFFEFF0F9)
val surfaceContainerLightHighContrast = Color(0xFFE1E2EB)
val surfaceContainerHighLightHighContrast = Color(0xFFD3D4DC)
val surfaceContainerHighestLightHighContrast = Color(0xFFC5C6CE)
val primaryDark = Color(0xFFAAC7FF)
val onPrimaryDark = Color(0xFF002F65)
val primaryContainerDark = Color(0xFF5B9BFF)
val onPrimaryContainerDark = Color(0xFF00326A)
val secondaryDark = Color(0xFF8CD6B0)
val onSecondaryDark = Color(0xFF003825)
val secondaryContainerDark = Color(0xFF367F5F)
val onSecondaryContainerDark = Color(0xFFE3FFED)
val tertiaryDark = Color(0xFFF6ADFF)
val onTertiaryDark = Color(0xFF560068)
val tertiaryContainerDark = Color(0xFFD07BDE)
val onTertiaryContainerDark = Color(0xFF5A036C)
val errorDark = Color(0xFFFFB4AB)
val onErrorDark = Color(0xFF690005)
val errorContainerDark = Color(0xFF93000A)
val onErrorContainerDark = Color(0xFFFFDAD6)
val backgroundDark = Color(0xFF111319)
val onBackgroundDark = Color(0xFFE1E2EB)
val surfaceDark = Color(0xFF111319)
val onSurfaceDark = Color(0xFFE1E2EB)
val surfaceVariantDark = Color(0xFF424752)
val onSurfaceVariantDark = Color(0xFFC2C6D4)
val outlineDark = Color(0xFF8C919E)
val outlineVariantDark = Color(0xFF424752)
val scrimDark = Color(0xFF000000)
val inverseSurfaceDark = Color(0xFFE1E2EB)
val inverseOnSurfaceDark = Color(0xFF2E3037)
val inversePrimaryDark = Color(0xFF005CB9)
val surfaceDimDark = Color(0xFF111319)
val surfaceBrightDark = Color(0xFF363940)
val surfaceContainerLowestDark = Color(0xFF0B0E14)
val surfaceContainerLowDark = Color(0xFF191C22)
val surfaceContainerDark = Color(0xFF1D2026)
val surfaceContainerHighDark = Color(0xFF272A30)
val surfaceContainerHighestDark = Color(0xFF32353B)
val primaryDarkMediumContrast = Color(0xFFCDDDFF)
val onPrimaryDarkMediumContrast = Color(0xFF002551)
val primaryContainerDarkMediumContrast = Color(0xFF5B9BFF)
val onPrimaryContainerDarkMediumContrast = Color(0xFF000C22)
val secondaryDarkMediumContrast = Color(0xFFA1ECC5)
val onSecondaryDarkMediumContrast = Color(0xFF002C1C)
val secondaryContainerDarkMediumContrast = Color(0xFF569F7C)
val onSecondaryContainerDarkMediumContrast = Color(0xFF000000)
val tertiaryDarkMediumContrast = Color(0xFFFDCDFF)
val onTertiaryDarkMediumContrast = Color(0xFF450054)
val tertiaryContainerDarkMediumContrast = Color(0xFFD07BDE)
val onTertiaryContainerDarkMediumContrast = Color(0xFF1C0023)
val errorDarkMediumContrast = Color(0xFFFFD2CC)
val onErrorDarkMediumContrast = Color(0xFF540003)
val errorContainerDarkMediumContrast = Color(0xFFFF5449)
val onErrorContainerDarkMediumContrast = Color(0xFF000000)
val backgroundDarkMediumContrast = Color(0xFF111319)
val onBackgroundDarkMediumContrast = Color(0xFFE1E2EB)
val surfaceDarkMediumContrast = Color(0xFF111319)
val onSurfaceDarkMediumContrast = Color(0xFFFFFFFF)
val surfaceVariantDarkMediumContrast = Color(0xFF424752)
val onSurfaceVariantDarkMediumContrast = Color(0xFFD8DCEB)
val outlineDarkMediumContrast = Color(0xFFADB2C0)
val outlineVariantDarkMediumContrast = Color(0xFF8B909D)
val scrimDarkMediumContrast = Color(0xFF000000)
val inverseSurfaceDarkMediumContrast = Color(0xFFE1E2EB)
val inverseOnSurfaceDarkMediumContrast = Color(0xFF272A30)
val inversePrimaryDarkMediumContrast = Color(0xFF004690)
val surfaceDimDarkMediumContrast = Color(0xFF111319)
val surfaceBrightDarkMediumContrast = Color(0xFF42444B)
val surfaceContainerLowestDarkMediumContrast = Color(0xFF05070D)
val surfaceContainerLowDarkMediumContrast = Color(0xFF1B1E24)
val surfaceContainerDarkMediumContrast = Color(0xFF25282E)
val surfaceContainerHighDarkMediumContrast = Color(0xFF303339)
val surfaceContainerHighestDarkMediumContrast = Color(0xFF3B3E44)
val primaryDarkHighContrast = Color(0xFFEBF0FF)
val onPrimaryDarkHighContrast = Color(0xFF000000)
val primaryContainerDarkHighContrast = Color(0xFFA4C3FF)
val onPrimaryContainerDarkHighContrast = Color(0xFF000B20)
val secondaryDarkHighContrast = Color(0xFFBAFFDA)
val onSecondaryDarkHighContrast = Color(0xFF000000)
val secondaryContainerDarkHighContrast = Color(0xFF88D2AD)
val onSecondaryContainerDarkHighContrast = Color(0xFF000E07)
val tertiaryDarkHighContrast = Color(0xFFFFEAFC)
val onTertiaryDarkHighContrast = Color(0xFF000000)
val tertiaryContainerDarkHighContrast = Color(0xFFF5A7FF)
val onTertiaryContainerDarkHighContrast = Color(0xFF1A0022)
val errorDarkHighContrast = Color(0xFFFFECE9)
val onErrorDarkHighContrast = Color(0xFF000000)
val errorContainerDarkHighContrast = Color(0xFFFFAEA4)
val onErrorContainerDarkHighContrast = Color(0xFF220001)
val backgroundDarkHighContrast = Color(0xFF111319)
val onBackgroundDarkHighContrast = Color(0xFFE1E2EB)
val surfaceDarkHighContrast = Color(0xFF111319)
val onSurfaceDarkHighContrast = Color(0xFFFFFFFF)
val surfaceVariantDarkHighContrast = Color(0xFF424752)
val onSurfaceVariantDarkHighContrast = Color(0xFFFFFFFF)
val outlineDarkHighContrast = Color(0xFFEBF0FF)
val outlineVariantDarkHighContrast = Color(0xFFBEC2D1)
val scrimDarkHighContrast = Color(0xFF000000)
val inverseSurfaceDarkHighContrast = Color(0xFFE1E2EB)
val inverseOnSurfaceDarkHighContrast = Color(0xFF000000)
val inversePrimaryDarkHighContrast = Color(0xFF004690)
val surfaceDimDarkHighContrast = Color(0xFF111319)
val surfaceBrightDarkHighContrast = Color(0xFF4D5057)
val surfaceContainerLowestDarkHighContrast = Color(0xFF000000)
val surfaceContainerLowDarkHighContrast = Color(0xFF1D2026)
val surfaceContainerDarkHighContrast = Color(0xFF2E3037)
val surfaceContainerHighDarkHighContrast = Color(0xFF393B42)
val surfaceContainerHighestDarkHighContrast = Color(0xFF44474E)

View File

@ -0,0 +1,259 @@
package com.jaytux.simd.frontend.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
private val lightScheme = lightColorScheme(
primary = primaryLight,
onPrimary = onPrimaryLight,
primaryContainer = primaryContainerLight,
onPrimaryContainer = onPrimaryContainerLight,
secondary = secondaryLight,
onSecondary = onSecondaryLight,
secondaryContainer = secondaryContainerLight,
onSecondaryContainer = onSecondaryContainerLight,
tertiary = tertiaryLight,
onTertiary = onTertiaryLight,
tertiaryContainer = tertiaryContainerLight,
onTertiaryContainer = onTertiaryContainerLight,
error = errorLight,
onError = onErrorLight,
errorContainer = errorContainerLight,
onErrorContainer = onErrorContainerLight,
background = backgroundLight,
onBackground = onBackgroundLight,
surface = surfaceLight,
onSurface = onSurfaceLight,
surfaceVariant = surfaceVariantLight,
onSurfaceVariant = onSurfaceVariantLight,
outline = outlineLight,
outlineVariant = outlineVariantLight,
scrim = scrimLight,
inverseSurface = inverseSurfaceLight,
inverseOnSurface = inverseOnSurfaceLight,
inversePrimary = inversePrimaryLight,
surfaceDim = surfaceDimLight,
surfaceBright = surfaceBrightLight,
surfaceContainerLowest = surfaceContainerLowestLight,
surfaceContainerLow = surfaceContainerLowLight,
surfaceContainer = surfaceContainerLight,
surfaceContainerHigh = surfaceContainerHighLight,
surfaceContainerHighest = surfaceContainerHighestLight,
)
private val darkScheme = darkColorScheme(
primary = primaryDark,
onPrimary = onPrimaryDark,
primaryContainer = primaryContainerDark,
onPrimaryContainer = onPrimaryContainerDark,
secondary = secondaryDark,
onSecondary = onSecondaryDark,
secondaryContainer = secondaryContainerDark,
onSecondaryContainer = onSecondaryContainerDark,
tertiary = tertiaryDark,
onTertiary = onTertiaryDark,
tertiaryContainer = tertiaryContainerDark,
onTertiaryContainer = onTertiaryContainerDark,
error = errorDark,
onError = onErrorDark,
errorContainer = errorContainerDark,
onErrorContainer = onErrorContainerDark,
background = backgroundDark,
onBackground = onBackgroundDark,
surface = surfaceDark,
onSurface = onSurfaceDark,
surfaceVariant = surfaceVariantDark,
onSurfaceVariant = onSurfaceVariantDark,
outline = outlineDark,
outlineVariant = outlineVariantDark,
scrim = scrimDark,
inverseSurface = inverseSurfaceDark,
inverseOnSurface = inverseOnSurfaceDark,
inversePrimary = inversePrimaryDark,
surfaceDim = surfaceDimDark,
surfaceBright = surfaceBrightDark,
surfaceContainerLowest = surfaceContainerLowestDark,
surfaceContainerLow = surfaceContainerLowDark,
surfaceContainer = surfaceContainerDark,
surfaceContainerHigh = surfaceContainerHighDark,
surfaceContainerHighest = surfaceContainerHighestDark,
)
private val mediumContrastLightColorScheme = lightColorScheme(
primary = primaryLightMediumContrast,
onPrimary = onPrimaryLightMediumContrast,
primaryContainer = primaryContainerLightMediumContrast,
onPrimaryContainer = onPrimaryContainerLightMediumContrast,
secondary = secondaryLightMediumContrast,
onSecondary = onSecondaryLightMediumContrast,
secondaryContainer = secondaryContainerLightMediumContrast,
onSecondaryContainer = onSecondaryContainerLightMediumContrast,
tertiary = tertiaryLightMediumContrast,
onTertiary = onTertiaryLightMediumContrast,
tertiaryContainer = tertiaryContainerLightMediumContrast,
onTertiaryContainer = onTertiaryContainerLightMediumContrast,
error = errorLightMediumContrast,
onError = onErrorLightMediumContrast,
errorContainer = errorContainerLightMediumContrast,
onErrorContainer = onErrorContainerLightMediumContrast,
background = backgroundLightMediumContrast,
onBackground = onBackgroundLightMediumContrast,
surface = surfaceLightMediumContrast,
onSurface = onSurfaceLightMediumContrast,
surfaceVariant = surfaceVariantLightMediumContrast,
onSurfaceVariant = onSurfaceVariantLightMediumContrast,
outline = outlineLightMediumContrast,
outlineVariant = outlineVariantLightMediumContrast,
scrim = scrimLightMediumContrast,
inverseSurface = inverseSurfaceLightMediumContrast,
inverseOnSurface = inverseOnSurfaceLightMediumContrast,
inversePrimary = inversePrimaryLightMediumContrast,
surfaceDim = surfaceDimLightMediumContrast,
surfaceBright = surfaceBrightLightMediumContrast,
surfaceContainerLowest = surfaceContainerLowestLightMediumContrast,
surfaceContainerLow = surfaceContainerLowLightMediumContrast,
surfaceContainer = surfaceContainerLightMediumContrast,
surfaceContainerHigh = surfaceContainerHighLightMediumContrast,
surfaceContainerHighest = surfaceContainerHighestLightMediumContrast,
)
private val highContrastLightColorScheme = lightColorScheme(
primary = primaryLightHighContrast,
onPrimary = onPrimaryLightHighContrast,
primaryContainer = primaryContainerLightHighContrast,
onPrimaryContainer = onPrimaryContainerLightHighContrast,
secondary = secondaryLightHighContrast,
onSecondary = onSecondaryLightHighContrast,
secondaryContainer = secondaryContainerLightHighContrast,
onSecondaryContainer = onSecondaryContainerLightHighContrast,
tertiary = tertiaryLightHighContrast,
onTertiary = onTertiaryLightHighContrast,
tertiaryContainer = tertiaryContainerLightHighContrast,
onTertiaryContainer = onTertiaryContainerLightHighContrast,
error = errorLightHighContrast,
onError = onErrorLightHighContrast,
errorContainer = errorContainerLightHighContrast,
onErrorContainer = onErrorContainerLightHighContrast,
background = backgroundLightHighContrast,
onBackground = onBackgroundLightHighContrast,
surface = surfaceLightHighContrast,
onSurface = onSurfaceLightHighContrast,
surfaceVariant = surfaceVariantLightHighContrast,
onSurfaceVariant = onSurfaceVariantLightHighContrast,
outline = outlineLightHighContrast,
outlineVariant = outlineVariantLightHighContrast,
scrim = scrimLightHighContrast,
inverseSurface = inverseSurfaceLightHighContrast,
inverseOnSurface = inverseOnSurfaceLightHighContrast,
inversePrimary = inversePrimaryLightHighContrast,
surfaceDim = surfaceDimLightHighContrast,
surfaceBright = surfaceBrightLightHighContrast,
surfaceContainerLowest = surfaceContainerLowestLightHighContrast,
surfaceContainerLow = surfaceContainerLowLightHighContrast,
surfaceContainer = surfaceContainerLightHighContrast,
surfaceContainerHigh = surfaceContainerHighLightHighContrast,
surfaceContainerHighest = surfaceContainerHighestLightHighContrast,
)
private val mediumContrastDarkColorScheme = darkColorScheme(
primary = primaryDarkMediumContrast,
onPrimary = onPrimaryDarkMediumContrast,
primaryContainer = primaryContainerDarkMediumContrast,
onPrimaryContainer = onPrimaryContainerDarkMediumContrast,
secondary = secondaryDarkMediumContrast,
onSecondary = onSecondaryDarkMediumContrast,
secondaryContainer = secondaryContainerDarkMediumContrast,
onSecondaryContainer = onSecondaryContainerDarkMediumContrast,
tertiary = tertiaryDarkMediumContrast,
onTertiary = onTertiaryDarkMediumContrast,
tertiaryContainer = tertiaryContainerDarkMediumContrast,
onTertiaryContainer = onTertiaryContainerDarkMediumContrast,
error = errorDarkMediumContrast,
onError = onErrorDarkMediumContrast,
errorContainer = errorContainerDarkMediumContrast,
onErrorContainer = onErrorContainerDarkMediumContrast,
background = backgroundDarkMediumContrast,
onBackground = onBackgroundDarkMediumContrast,
surface = surfaceDarkMediumContrast,
onSurface = onSurfaceDarkMediumContrast,
surfaceVariant = surfaceVariantDarkMediumContrast,
onSurfaceVariant = onSurfaceVariantDarkMediumContrast,
outline = outlineDarkMediumContrast,
outlineVariant = outlineVariantDarkMediumContrast,
scrim = scrimDarkMediumContrast,
inverseSurface = inverseSurfaceDarkMediumContrast,
inverseOnSurface = inverseOnSurfaceDarkMediumContrast,
inversePrimary = inversePrimaryDarkMediumContrast,
surfaceDim = surfaceDimDarkMediumContrast,
surfaceBright = surfaceBrightDarkMediumContrast,
surfaceContainerLowest = surfaceContainerLowestDarkMediumContrast,
surfaceContainerLow = surfaceContainerLowDarkMediumContrast,
surfaceContainer = surfaceContainerDarkMediumContrast,
surfaceContainerHigh = surfaceContainerHighDarkMediumContrast,
surfaceContainerHighest = surfaceContainerHighestDarkMediumContrast,
)
private val highContrastDarkColorScheme = darkColorScheme(
primary = primaryDarkHighContrast,
onPrimary = onPrimaryDarkHighContrast,
primaryContainer = primaryContainerDarkHighContrast,
onPrimaryContainer = onPrimaryContainerDarkHighContrast,
secondary = secondaryDarkHighContrast,
onSecondary = onSecondaryDarkHighContrast,
secondaryContainer = secondaryContainerDarkHighContrast,
onSecondaryContainer = onSecondaryContainerDarkHighContrast,
tertiary = tertiaryDarkHighContrast,
onTertiary = onTertiaryDarkHighContrast,
tertiaryContainer = tertiaryContainerDarkHighContrast,
onTertiaryContainer = onTertiaryContainerDarkHighContrast,
error = errorDarkHighContrast,
onError = onErrorDarkHighContrast,
errorContainer = errorContainerDarkHighContrast,
onErrorContainer = onErrorContainerDarkHighContrast,
background = backgroundDarkHighContrast,
onBackground = onBackgroundDarkHighContrast,
surface = surfaceDarkHighContrast,
onSurface = onSurfaceDarkHighContrast,
surfaceVariant = surfaceVariantDarkHighContrast,
onSurfaceVariant = onSurfaceVariantDarkHighContrast,
outline = outlineDarkHighContrast,
outlineVariant = outlineVariantDarkHighContrast,
scrim = scrimDarkHighContrast,
inverseSurface = inverseSurfaceDarkHighContrast,
inverseOnSurface = inverseOnSurfaceDarkHighContrast,
inversePrimary = inversePrimaryDarkHighContrast,
surfaceDim = surfaceDimDarkHighContrast,
surfaceBright = surfaceBrightDarkHighContrast,
surfaceContainerLowest = surfaceContainerLowestDarkHighContrast,
surfaceContainerLow = surfaceContainerLowDarkHighContrast,
surfaceContainer = surfaceContainerDarkHighContrast,
surfaceContainerHigh = surfaceContainerHighDarkHighContrast,
surfaceContainerHighest = surfaceContainerHighestDarkHighContrast,
)
@Immutable
data class ColorFamily(
val color: Color,
val onColor: Color,
val colorContainer: Color,
val onColorContainer: Color
)
val unspecified_scheme = ColorFamily(
Color.Unspecified, Color.Unspecified, Color.Unspecified, Color.Unspecified
)
@Composable
fun SimdTheme(
content: @Composable() () -> Unit
) {
MaterialTheme(
colorScheme = darkScheme,
typography = buildTypography(),
content = content
)
}

View File

@ -0,0 +1,50 @@
package com.jaytux.simd.frontend.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Typography
import androidx.compose.runtime.Composable
import androidx.compose.ui.text.font.FontFamily
import com.jaytux.simd.frontend.App
import frontend.composeapp.generated.resources.*
import frontend.composeapp.generated.resources.Res
import org.jetbrains.compose.resources.Font
@Composable
fun Roboto() = FontFamily(
Font(Res.font.RobotoMonoMedium),
Font(Res.font.RobotoMonoItalic),
Font(Res.font.RobotoMonoBold),
)
@Composable
fun Alegreya() = FontFamily(
Font(Res.font.AlegreyaMedium),
Font(Res.font.AlegreyaItalic),
Font(Res.font.AlegreyaBold),
)
@Composable
fun buildTypography(): Typography {
val baseline = MaterialTheme.typography
val displayFontFamily = Alegreya()
val bodyFontFamily = Roboto()
val AppTypography = Typography(
displayLarge = baseline.displayLarge.copy(fontFamily = displayFontFamily),
displayMedium = baseline.displayMedium.copy(fontFamily = displayFontFamily),
displaySmall = baseline.displaySmall.copy(fontFamily = displayFontFamily),
headlineLarge = baseline.headlineLarge.copy(fontFamily = displayFontFamily),
headlineMedium = baseline.headlineMedium.copy(fontFamily = displayFontFamily),
headlineSmall = baseline.headlineSmall.copy(fontFamily = displayFontFamily),
titleLarge = baseline.titleLarge.copy(fontFamily = displayFontFamily),
titleMedium = baseline.titleMedium.copy(fontFamily = displayFontFamily),
titleSmall = baseline.titleSmall.copy(fontFamily = displayFontFamily),
bodyLarge = baseline.bodyLarge.copy(fontFamily = bodyFontFamily),
bodyMedium = baseline.bodyMedium.copy(fontFamily = bodyFontFamily),
bodySmall = baseline.bodySmall.copy(fontFamily = bodyFontFamily),
labelLarge = baseline.labelLarge.copy(fontFamily = bodyFontFamily),
labelMedium = baseline.labelMedium.copy(fontFamily = bodyFontFamily),
labelSmall = baseline.labelSmall.copy(fontFamily = bodyFontFamily),
)
return AppTypography
}

View File

@ -0,0 +1,183 @@
package com.jaytux.simd.frontend.ui
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import com.jaytux.simd.frontend.Either
import com.jaytux.simd.frontend.client.Client
import com.jaytux.simd.frontend.client.Loader
import com.jaytux.simd.frontend.client.Loader.loadAll
import com.jaytux.simd.frontend.immutable
import com.jaytux.simd.frontend.left
import com.jaytux.simd.frontend.right
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.launch
import kotlin.uuid.ExperimentalUuidApi
import kotlin.uuid.Uuid
@OptIn(ExperimentalUuidApi::class)
class DataState(
val scope: CoroutineScope,
val addSnackBar: suspend (message: String) -> Unit,
) {
data class SubState<T>(
val stateMut: MutableState<String> = mutableStateOf(""),
val dataMut: MutableState<List<T>> = mutableStateOf(listOf())
) {
val state = stateMut.immutable()
val data = dataMut.immutable()
}
// --- Intrinsic Summaries ---
private val _summary = SubState<Client.IntrinsicSummary>()
val summaryState = _summary.state
val summaries = _summary.data
// --- CPUIDs ---
private val _cpuid = SubState<String>()
val cpuidState = _cpuid.state
val cpuid = _cpuid.data
private val _selectedCpuids = mutableStateOf(listOf<Int>())
val selectedCpuids = _selectedCpuids.immutable()
// --- Techs ---
private val _techs = SubState<String>()
val techsState = _techs.state
val techs = _techs.data
private val _selectedTechs = mutableStateOf(listOf<Int>())
val selectedTechs = _selectedTechs.immutable()
// --- CppTypes ---
private val _cppTypes = SubState<String>()
val cppTypesState = _cppTypes.state
val cppTypes = _cppTypes.data
private var filterByType: String? = null
// --- Categories ---
private val _categories = SubState<String>()
val categoriesState = _categories.state
val categories = _categories.data
private val _selectedCats = mutableStateOf(listOf<Int>())
val selectedCats = _selectedCats.immutable()
// --- Details ---
private val _intrinsics = mutableMapOf<Uuid, MutableState<Either<String, Client.IntrinsicDetails>?>>()
private val _intrinsicLoaders = mutableMapOf<Uuid, Job>()
// --- Version ---
private val _version = mutableStateOf<Client.Versioning?>(null)
val version = _version.immutable()
// --- Filtering ---
private var _filterJob: Job? = null
private val _filterData = mutableStateOf(listOf<Client.IntrinsicSummary>())
val filterData = _filterData.immutable()
val filterName = mutableStateOf("")
val filterDesc = mutableStateOf("")
init {
_filterJob = scope.loadAll(
client = { Client.getAll() },
onError = addSnackBar,
onFinishSuccess = { /*_summary.dataMut.value = it*/ _filterData.value = it },
onStatusChange = { _summary.stateMut.value = it },
onProgress = { /*_summary.dataMut.value = it*/ _filterData.value = it }
)
scope.loadAll(
client = { Client.getCpuid() },
onError = addSnackBar,
onFinishSuccess = { _cpuid.dataMut.value = it },
onStatusChange = { _cpuid.stateMut.value = it }
)
scope.loadAll(
client = { Client.getTech() },
onError = addSnackBar,
onFinishSuccess = { _techs.dataMut.value = it },
onStatusChange = { _techs.stateMut.value = it }
)
scope.loadAll(
client = { Client.getCategory() },
onError = addSnackBar,
onFinishSuccess = { _categories.dataMut.value = it },
onStatusChange = { _categories.stateMut.value = it }
)
scope.loadAll(
client = { Client.getTypes() },
onError = addSnackBar,
onFinishSuccess = { _cppTypes.dataMut.value = it },
onStatusChange = { _cppTypes.stateMut.value = it }
)
scope.launch {
Client.getVersion().foldSuspend(addSnackBar) {
_version.value = it
}
}
}
operator fun get(uuid: Uuid): State<Either<String, Client.IntrinsicDetails>?> =
_intrinsics.getOrPut(uuid) { mutableStateOf(null) }
fun toggleTech(idx: Int) {
if (idx in _selectedTechs.value) _selectedTechs.value -= idx
else _selectedTechs.value += idx
doFilter()
}
fun toggleCategory(idx: Int) {
if (idx in _selectedCats.value) _selectedCats.value -= idx
else _selectedCats.value += idx
doFilter()
}
fun toggleCpuid(idx: Int) {
if (idx in _selectedCpuids.value) _selectedCpuids.value -= idx
else _selectedCpuids.value += idx
doFilter()
}
fun setReturn(type: String) {
filterByType = if(type !in cppTypes.value) null else type
}
fun loadDetails(uuid: Uuid) {
val current = _intrinsicLoaders[uuid]
if(current != null && !current.isActive) return
_intrinsicLoaders[uuid] = scope.launch {
Client.getDetails(uuid).foldSuspend({
val msg = "Failed to load details for $uuid: $it"
addSnackBar(msg)
_intrinsics.getOrPut(uuid) { mutableStateOf(null) }.value = msg.left()
}) {
_intrinsics.getOrPut(uuid) { mutableStateOf(null) }.value = it.right()
}
}
}
fun doFilter() {
_filterJob?.cancel()
_filterJob = scope.loadAll(
client = {
Client.getSearch(
name = filterName.value.ifBlank { null },
returnT = filterByType,
cpuid = _selectedCpuids.value.map { cpuid.value[it] },
tech = _selectedTechs.value.map { techs.value[it] },
category = _selectedCats.value.map { categories.value[it] },
desc = filterDesc.value.ifBlank { null }
)
},
onError = addSnackBar,
onFinishSuccess = { _filterData.value = it },
onStatusChange = {},
onProgress = { _filterData.value = it },
throttleBefore = 250L
)
}
}

View File

@ -0,0 +1,407 @@
package com.jaytux.simd.frontend.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import com.composables.icons.lucide.*
import com.jaytux.simd.frontend.OrError
import com.jaytux.simd.frontend.client.Client
import com.jaytux.simd.frontend.client.Loader
import com.jaytux.simd.frontend.theme.buildTypography
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlin.uuid.ExperimentalUuidApi
@Composable
fun fontSizeDp(style: TextStyle = LocalTextStyle.current) = with(LocalDensity.current) {
style.fontSize.toDp()
}
@Composable
fun Spinner(text: String, style: TextStyle = LocalTextStyle.current) = Row {
CircularProgressIndicator(Modifier.size(fontSizeDp(style) * 2).scale(0.5f))
Spacer(Modifier.width(5.dp))
Text(text, Modifier.align(Alignment.CenterVertically), style = style)
}
@Composable
fun ErrorSnackBar(data: SnackbarData) {
Snackbar(
containerColor = MaterialTheme.colorScheme.error,
contentColor = MaterialTheme.colorScheme.onError,
) {
Box(Modifier.padding(5.dp)) {
Text(data.visuals.message, modifier = Modifier.align(Alignment.Center))
}
}
}
@Composable
fun MicroHeader(text: String, modifier: Modifier = Modifier) =
Text(text, modifier, style = MaterialTheme.typography.bodyLarge)
@Composable
fun Collapsible(expanded: Boolean, onClick: () -> Unit, content: @Composable () -> Unit) {
Row(Modifier.clickable { onClick() }) {
Icon(if(expanded) Lucide.ChevronDown else Lucide.ChevronRight, "Expand/Collapse")
Spacer(Modifier.width(10.dp))
content()
}
}
@Composable
fun Checkable(checked: Boolean, onClick: () -> Unit, content: @Composable () -> Unit) {
Row(Modifier.clickable { onClick() }) {
Icon(if(checked) Lucide.SquareCheckBig else Lucide.Square, "Check/Uncheck")
Spacer(Modifier.width(10.dp))
content()
}
}
@Composable
fun Indented(steps: Int = 1, content: @Composable ColumnScope.() -> Unit) {
Row(Modifier.padding(start = (steps * 20).dp)) {
Column {
content()
}
}
}
fun <T> LazyListScope.FilterBlock(
title: String,
expanded: Boolean,
status: String,
options: List<T>,
selected: List<Int>,
onToggleExpand: () -> Unit,
onToggleSelect: (Int) -> Unit,
renderT: @Composable (T) -> Unit
) {
item {
Collapsible(expanded, onToggleExpand) {
MicroHeader("$title (${selected.size} selected)")
}
}
if(expanded) {
if(options.isEmpty()) {
item {
Indented {
Spinner(status)
}
}
}
else {
itemsIndexed(options) { i, t ->
Indented {
Checkable(i in selected, { onToggleSelect(i) }) {
renderT(t)
}
}
}
}
}
}
@Composable
fun topBar(data: DataState) = Surface(tonalElevation = 10.dp, shadowElevation = 10.dp, color = MaterialTheme.colorScheme.primaryContainer) {
val version by data.version
Box(Modifier.fillMaxWidth().padding(10.dp)) {
Box(Modifier.align(Alignment.Center)) {
Text(
"C/C++ (SIMD) Intrinsics",
style = MaterialTheme.typography.headlineLarge
)
}
version?.let {
Column(Modifier.align(Alignment.CenterEnd)) {
Row {
Text(
"Intel data: ${it.intelVersion} (last update: ${it.intelUpdate})",
style = MaterialTheme.typography.labelSmall
)
// TODO: add other versioning data (AMD, ARM, ...) when added to DB/backend
}
Text("Last database update: ${it.scrapeDate}", style = MaterialTheme.typography.labelSmall)
}
}
}
}
@Composable
fun ColumnScope.FilterColumn(data: DataState) {
var expandTech by remember { mutableStateOf(false) }
var expandCategory by remember { mutableStateOf(false) }
var expandCpuid by remember { mutableStateOf(false) }
val techs by data.techs; val techMsg by data.techsState; val techSel by data.selectedTechs
val cats by data.categories; val catMsg by data.categoriesState; val catSel by data.selectedCats
val cpuid by data.cpuid; val cpuidMsg by data.cpuidState; val cpuidSel by data.selectedCpuids
Text("Filter intrinsics by:", style = MaterialTheme.typography.headlineSmall)
LazyColumn {
FilterBlock(
"ISA extensions", expandTech, techMsg, techs, techSel,
{ expandTech = !expandTech }, { data.toggleTech(it) }
) { Text(it) }
FilterBlock(
"Categories", expandCategory, catMsg, cats, catSel,
{ expandCategory = !expandCategory }, { data.toggleCategory(it) }
) { Text(it) }
FilterBlock(
"CPUIDs", expandCpuid, cpuidMsg, cpuid, cpuidSel,
{ expandCpuid = !expandCpuid }, { data.toggleCpuid(it) }
) { Text(it) }
}
}
@Composable
fun IntrinsicCard(
summary: Client.IntrinsicSummary,
details: OrError<Client.IntrinsicDetails>?,
requestLoad: suspend (Client.IntrinsicSummary) -> Unit
) {
var expanded by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
Surface(
Modifier.fillMaxWidth().padding(5.dp).clickable {
expanded = !expanded
if(expanded && details == null) scope.launch { requestLoad(summary) }
},
tonalElevation = 2.dp,
shadowElevation = 2.dp,
shape = MaterialTheme.shapes.medium
) {
val style = MaterialTheme.typography.labelMedium
Column(Modifier.padding(10.dp)) {
Text(summary.name, style = MaterialTheme.typography.headlineSmall)
if(expanded) {
Indented {
details?.foldCompose({
Text(it, color = MaterialTheme.colorScheme.error)
}) {
Text("Synopsis")
Indented {
Row {
Text("${it.returnType} ${it.name}(${it.params.joinToString(", ") { p -> "${p.type} ${p.name}" }})")
Text(" [${it.category}]", color = LocalContentColor.current.copy(alpha = 0.4f))
}
it.cpuid?.let { cpuid -> Text("CPUID: $cpuid", style = style) }
}
Spacer(Modifier.height(5.dp))
Text("Description")
Indented {
Text(it.description, style = style)
it.instructions?.let { insn ->
Spacer(Modifier.height(2.dp))
Text("Instruction(s):")
Indented {
insn.forEach { ins ->
Text("${ins.mnemonic} ${ins.form ?: ""}", style = style)
}
}
}
}
it.operations?.let { ops ->
Spacer(Modifier.height(5.dp))
Text("Operations")
Indented {
Surface(Modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.surfaceDim) {
Column {
ops.split("\n").forEach { op ->
val depth = op.takeWhile { it == '\t' }.length
val text = op.drop(depth)
Indented(depth) { Text(text, style = style) }
}
}
}
}
}
it.performance?.let { perf ->
if(perf.isEmpty()) return@let
Spacer(Modifier.height(5.dp))
Text("Performance")
Indented {
Row {
Column {
Text("Architecture")
perf.forEach { p -> Text(p.platform, style = style) }
}
Spacer(Modifier.width(20.dp))
Column {
Text("Latency (cycles)")
perf.forEach { p -> Text(p.latency?.toString() ?: "-", style = style) }
}
Spacer(Modifier.width(20.dp))
Column {
Text("Throughput (CPI)")
perf.forEach { p -> Text(p.throughput?.toString() ?: "-", style = style) }
}
}
}
}
}
if(details == null) Text("Loading details...", style = MaterialTheme.typography.bodySmall)
}
}
}
}
}
@OptIn(ExperimentalUuidApi::class)
@Composable
fun ColumnScope.IntrinsicColumn(data: DataState) {
var nameFilter by data.filterName
var descFilter by data.filterDesc
var retFilter by remember { mutableStateOf<String>("") }
val intrinsicState by data.summaryState
val intrinsicList by data.filterData
val typeOptions by data.cppTypes
val typeMsg by data.cppTypesState
var expandFilter by remember { mutableStateOf(false) }
OutlinedTextField(
nameFilter, { nameFilter = it; data.doFilter() },
Modifier.fillMaxWidth(),
leadingIcon = { Icon(Lucide.SearchCode, "Search") },
label = { Text("Filter by intrinsic name...") }
)
Text(
(if (expandFilter) "Hide" else "Show") + " additional filters",
Modifier.clickable { expandFilter = !expandFilter }.align(Alignment.End),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
textDecoration = TextDecoration.Underline
)
if (expandFilter) {
var showingOptions by remember { mutableStateOf(false) }
OutlinedTextField(
retFilter, { retFilter = it; showingOptions = true },
Modifier.clickable { showingOptions = true }.fillMaxWidth(0.66f).onFocusChanged {
showingOptions = it.isFocused
if(!it.isFocused) data.setReturn(retFilter)
},
trailingIcon = {
Icon(if (showingOptions) Lucide.ChevronUp else Lucide.ChevronDown, "Show options")
},
label = { Text("Filter by return type...") },
isError = retFilter !in typeOptions
)
DropdownMenu(
showingOptions, { showingOptions = false },
properties = PopupProperties()
) {
if (typeOptions.isEmpty()) {
DropdownMenuItem(
{ Spinner(typeMsg) }, { retFilter = "" }
)
} else {
DropdownMenuItem(
{ Text("(none)") }, { retFilter = "" }
)
typeOptions.filter{ retFilter in it }.take(10).forEach { it ->
DropdownMenuItem(
{ Text(it) }, { retFilter = it }
)
}
}
}
OutlinedTextField(
descFilter,
{ descFilter = it; data.doFilter() },
Modifier.fillMaxWidth(),
label = { Text("Filter by description...") })
}
if(intrinsicList.isEmpty()) {
Box(Modifier.fillMaxSize()) {
Column(Modifier.align(Alignment.Center)) {
when(intrinsicState) {
Loader.progressFinished -> Text("No results for your query")
Loader.progressFailed -> {
Text("An error occurred while processing your query")
}
else -> {
Spinner(intrinsicState)
}
}
}
}
}
else {
if(intrinsicState != Loader.progressFinished) {
Spinner(intrinsicState, MaterialTheme.typography.bodySmall)
}
LazyColumn {
items(intrinsicList) { it ->
val details by data[it.id]
IntrinsicCard(it, details) { data.loadDetails(it.id) }
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

View File

@ -0,0 +1,35 @@
package com.jaytux.simd.frontend
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.jaytux.simd.frontend.ui.DataState
import com.jaytux.simd.frontend.ui.FilterColumn
import com.jaytux.simd.frontend.ui.IntrinsicColumn
import com.jaytux.simd.frontend.ui.topBar
@Composable
actual fun mainView(data: DataState) = Row {
Surface(
Modifier.weight(0.25f).fillMaxSize(),
tonalElevation = 3.dp,
shadowElevation = 3.dp,
color = MaterialTheme.colorScheme.primary,
shape = MaterialTheme.shapes.medium.copy(topStart = CornerSize(0.dp), topEnd = CornerSize(0.dp))
) {
Column(Modifier.padding(5.dp)) {
FilterColumn(data)
}
}
Column(Modifier.weight(0.66f).padding(15.dp)) {
IntrinsicColumn(data)
}
}

View File

@ -1,7 +1,10 @@
package com.jaytux.simd.frontend package com.jaytux.simd.frontend
class JVMPlatform: Platform { import io.ktor.client.*
override val name: String = "Java ${System.getProperty("java.version")}" import io.ktor.client.engine.cio.*
} import java.awt.Desktop
import java.net.URI
actual fun getPlatform(): Platform = JVMPlatform() actual fun getKtorClient(builder: HttpClientConfig<*>.() -> Unit): HttpClient = HttpClient(CIO) {
builder()
}

View File

@ -1,12 +1,17 @@
package com.jaytux.simd.frontend package com.jaytux.simd.frontend
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.window.Window import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application import androidx.compose.ui.window.application
import frontend.composeapp.generated.resources.Res
import frontend.composeapp.generated.resources.icon
import org.jetbrains.compose.resources.painterResource
fun main() = application { fun main() = application {
Window( Window(
onCloseRequest = ::exitApplication, onCloseRequest = ::exitApplication,
title = "frontend", title = "Intrinsics Viewer",
icon = painterResource(Res.drawable.icon),
) { ) {
App() App()
} }

View File

@ -0,0 +1,35 @@
package com.jaytux.simd.frontend
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.jaytux.simd.frontend.ui.DataState
import com.jaytux.simd.frontend.ui.FilterColumn
import com.jaytux.simd.frontend.ui.IntrinsicColumn
import com.jaytux.simd.frontend.ui.topBar
@Composable
actual fun mainView(data: DataState) = Row {
Surface(
Modifier.weight(0.25f).fillMaxSize(),
tonalElevation = 3.dp,
shadowElevation = 3.dp,
color = MaterialTheme.colorScheme.primary,
shape = MaterialTheme.shapes.medium.copy(topStart = CornerSize(0.dp), topEnd = CornerSize(0.dp))
) {
Column(Modifier.padding(5.dp)) {
FilterColumn(data)
}
}
Column(Modifier.weight(0.66f).padding(15.dp)) {
IntrinsicColumn(data)
}
}

View File

@ -1,7 +1,10 @@
package com.jaytux.simd.frontend package com.jaytux.simd.frontend
class WasmPlatform: Platform { import androidx.compose.runtime.Composable
override val name: String = "Web with Kotlin/Wasm" import io.ktor.client.*
} import io.ktor.client.engine.js.*
import kotlinx.browser.window
actual fun getPlatform(): Platform = WasmPlatform() actual fun getKtorClient(builder: HttpClientConfig<*>.() -> Unit): HttpClient = HttpClient(Js) {
builder()
}

View File

@ -6,6 +6,7 @@ import kotlinx.browser.document
@OptIn(ExperimentalComposeUiApi::class) @OptIn(ExperimentalComposeUiApi::class)
fun main() { fun main() {
document.getElementById("loading")?.remove()
ComposeViewport(document.body!!) { ComposeViewport(document.body!!) {
App() App()
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

View File

@ -3,10 +3,12 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>frontend</title> <title>Intrinsics Viewer</title>
<link type="text/css" rel="stylesheet" href="styles.css"> <link type="text/css" rel="stylesheet" href="styles.css">
<link rel="icon" href="icon.png">
<script type="application/javascript" src="composeApp.js"></script> <script type="application/javascript" src="composeApp.js"></script>
</head> </head>
<body> <body>
<div id="loading">⏳ UI Loading...</div>
</body> </body>
</html> </html>

View File

@ -5,3 +5,14 @@ html, body {
padding: 0; padding: 0;
overflow: hidden; overflow: hidden;
} }
#loading {
/* perfectly center this div */
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 2em;
color: #000;
text-align: center;
}

View File

@ -9,6 +9,7 @@ dotenv = "6.5.1"
serialization = "1.8.1" serialization = "1.8.1"
logback = "1.5.6" logback = "1.5.6"
json = "20231013" json = "20231013"
ui-text-google-fonts = "1.8.0"
[libraries] [libraries]
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
@ -22,14 +23,17 @@ ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }
ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" } ktor-client-cio = { module = "io.ktor:ktor-client-cio", version.ref = "ktor" }
ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" } ktor-client-js = { module = "io.ktor:ktor-client-js", version.ref = "ktor" }
ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "ktor" } ktor-client-logging = { module = "io.ktor:ktor-client-logging", version.ref = "ktor" }
ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" } ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }
dotenv = { module = "io.github.cdimascio:dotenv-kotlin", version.ref = "dotenv" }
json = { module = "org.json:json", version.ref = "json" } json = { module = "org.json:json", version.ref = "json" }
kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version = "0.6.2" } kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version = "0.6.2" }
kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "serialization" }
logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" }
material3 = { module = "org.jetbrains.compose.material3:material3", version.ref = "compose-multiplatform" }
lucide = { module = "com.composables:icons-lucide", version="1.0.0" }
[plugins] [plugins]
composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "compose-multiplatform" } composeMultiplatform = { id = "org.jetbrains.compose", version.ref = "compose-multiplatform" }
composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } composeCompiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }

View File

@ -52,6 +52,11 @@
"@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/resolve-uri" "^3.1.0"
"@jridgewell/sourcemap-codec" "^1.4.14" "@jridgewell/sourcemap-codec" "^1.4.14"
"@js-joda/core@3.2.0":
version "3.2.0"
resolved "https://registry.yarnpkg.com/@js-joda/core/-/core-3.2.0.tgz#3e61e21b7b2b8a6be746df1335cf91d70db2a273"
integrity sha512-PMqgJ0sw5B7FKb2d5bWYIoxjri+QlW/Pys7+Rw82jSH0QN3rB05jZ/VrrsUdh1w4+i2kw9JOejXGq/KhDOX7Kg==
"@leichtgewicht/ip-codec@^2.0.1": "@leichtgewicht/ip-codec@^2.0.1":
version "2.0.5" version "2.0.5"
resolved "https://registry.yarnpkg.com/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz#4fc56c15c580b9adb7dc3c333a134e540b44bfb1" resolved "https://registry.yarnpkg.com/@leichtgewicht/ip-codec/-/ip-codec-2.0.5.tgz#4fc56c15c580b9adb7dc3c333a134e540b44bfb1"
@ -2837,6 +2842,11 @@ wrappy@1:
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"
integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==
ws@8.18.0:
version "8.18.0"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.0.tgz#0d7505a6eafe2b0e712d232b42279f53bc289bbc"
integrity sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==
ws@^8.13.0: ws@^8.13.0:
version "8.18.1" version "8.18.1"
resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.1.tgz#ea131d3784e1dfdff91adb0a4a116b127515e3cb" resolved "https://registry.yarnpkg.com/ws/-/ws-8.18.1.tgz#ea131d3784e1dfdff91adb0a4a116b127515e3cb"

43
frontend/package.sh Executable file
View File

@ -0,0 +1,43 @@
#!/usr/bin/env sh
echo ""
echo "+-----------------+"
echo "| ./gradlew clean |"
echo "+-----------------+"
echo ""
./gradlew clean
echo ""
echo "+---------------------------+"
echo "| ./gradlew packageAppImage |"
echo "+---------------------------+"
echo ""
./gradlew packageAppImage
echo ""
echo "+------------------------------------------+"
echo "| ./gradlew wasmJsBrowserProductionWebpack |"
echo "+------------------------------------------+"
echo ""
./gradlew wasmJsBrowserProductionWebpack
echo ""
echo "+-------------------------------------+"
echo "| ./gradlew wasmJsBrowserDistribution |"
echo "+-------------------------------------+"
echo ""
./gradlew wasmJsBrowserDistribution
echo ""
echo "+-------------------------------------------------------------------------------------------------------------+"
echo "| tar -czf simd-frontend@linux.tar.gz -C composeApp/build/compose/binaries/main/app/ com.jaytux.simd.frontend |"
echo "+-------------------------------------------------------------------------------------------------------------+"
echo ""
tar -czf simd-frontend@linux.tar.gz -C composeApp/build/compose/binaries/main/app/ com.jaytux.simd.frontend
echo ""
echo "+----------------------------------------------------------------------------------------+"
echo "| tar -czf simd-frontend@web.tar.gz -C composeApp/build/dist/wasmJs productionExecutable |"
echo "+----------------------------------------------------------------------------------------+"
echo ""
tar -czf simd-frontend@web.tar.gz -C composeApp/build/dist/wasmJs productionExecutable