1
0
Fork 0
This commit is contained in:
LordMZTE 2023-11-26 14:01:22 +01:00
commit 4705b42515
Signed by: LordMZTE
GPG Key ID: B64802DC33A64FF6
39 changed files with 2854 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/zig-*

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

69
README.md Normal file
View File

@ -0,0 +1,69 @@
![Logo](assets/logo.svg)
# Zenolith
Zenolith is my attempt at a retained-mode, platform-agnostic, zig-native GUI engine.
Warning: Zenolith is in an extremely early stage! Many important features such as text editing
are not yet implemented. Expect breaking changes!
## Attention GitHub users!
Zenolith is mirrored on GitHub to make it easier to discover, however, this mirror is read-only!
Do not open issues or pull requests on GitHub!
All development happens on [MZTE Git](https://git.mzte.de/zenolith/zenolith).
## Contributing
Pull requests are always welcome! If you'd like to fix a bug, improve documentation or implement
a feature on the TODO list below, go ahead!
If you'd like to suggest a new feature or design change, please open an issue first to discuss it!
**All commits must follow [Conventional Commits](https://www.conventionalcommits.org/)!**
## TODO
- [x] Painter API
- [x] Rectangles
- [x] Textures
- [x] Text
- [ ] Multi-Color chunks
- [ ] Multi-Font chunks
- [ ] Triangles
- [ ] Matrix Transformations?
- [ ] Drawing of partial widgets
- [ ] stencils?
- [x] Widgets
- [x] Box (FlowBox-like algorithm)
- [x] Button
- [x] Label
- [ ] Word Wrapping
- [ ] Character Wrapping
- [ ] Ellipsization
- [ ] Text Edit
- [ ] Tabbed Pane
- [ ] Split Pane
- [ ] Scrolled Pane
- [ ] Focus Stack
- [x] Theming
- [ ] Built-in themes
- [ ] Layout overflow handling
- [ ] Logo
- [x] Treevents (Tree-Bound, downwards events)
- [x] Backevents (Tree-Bound, upwards events)
- [ ] Platform events (Platform event loop events)
- [ ] Wrap Backevents
- [x] Attreebutes (Tree-Bound, inhereted widget properties)
- [ ] Documentation
- [x] In-Code
- [ ] Book
- [ ] Examples
- [ ] CI/CD
- [x] [SDL2 Backend](https://git.mzte.de/zenolith/zenolith-sdl2)
- [ ] Mach Backend
- [ ] TUI Backend
- [ ] WASM Backend
## Gallery
![Early Test GUI](assets/early-test-gui.png)

BIN
assets/early-test-gui.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

252
assets/logo-inkscape.svg Normal file
View File

@ -0,0 +1,252 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="1001.0335"
height="308.078"
viewBox="0 0 264.85678 81.512305"
version="1.1"
id="svg1"
inkscape:version="1.3.1 (91b66b0783, 2023-11-16, custom)"
sodipodi:docname="logo-inkscape.svg"
inkscape:export-filename="logo.png"
inkscape:export-xdpi="96"
inkscape:export-ydpi="96"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<sodipodi:namedview
id="namedview1"
pagecolor="#505050"
bordercolor="#ffffff"
borderopacity="1"
inkscape:showpageshadow="0"
inkscape:pageopacity="0"
inkscape:pagecheckerboard="1"
inkscape:deskcolor="#505050"
inkscape:document-units="mm"
inkscape:zoom="0.70710678"
inkscape:cx="647.70981"
inkscape:cy="273.65032"
inkscape:window-width="1876"
inkscape:window-height="998"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="layer1"
showgrid="true">
<inkscape:grid
id="grid12"
units="mm"
originx="-47.851528"
originy="7.7685909"
spacingx="0.26458333"
spacingy="0.26458334"
empcolor="#0099e5"
empopacity="0.30196078"
color="#0099e5"
opacity="0.14901961"
empspacing="4"
dotted="false"
gridanglex="30"
gridanglez="30"
visible="true" />
</sodipodi:namedview>
<defs
id="defs1">
<inkscape:path-effect
effect="mirror_symmetry"
start_point="31.834537,32.818143"
end_point="31.834537,36.648513"
center_point="31.834537,34.733328"
id="path-effect12"
is_visible="true"
lpeversion="1.2"
lpesatellites=""
mode="free"
discard_orig_path="false"
fuse_paths="false"
oposite_fuse="false"
split_items="false"
split_open="false"
link_styles="false" />
<inkscape:path-effect
effect="mirror_symmetry"
start_point="36.98,32.09"
end_point="37.082139,36.92"
center_point="37.03107,34.505"
id="path-effect11"
is_visible="true"
lpeversion="1.2"
lpesatellites=""
mode="free"
discard_orig_path="false"
fuse_paths="false"
oposite_fuse="false"
split_items="false"
split_open="false"
link_styles="false" />
<inkscape:path-effect
effect="perspective-envelope"
up_left_point="33.01,32.34706"
up_right_point="37.076535,33.624727"
down_left_point="33.012395,36.92"
down_right_point="37.087757,36.92"
id="path-effect10"
is_visible="true"
lpeversion="1"
deform_type="perspective"
horizontal_mirror="false"
vertical_mirror="false"
overflow_perspective="false" />
<inkscape:path-effect
effect="perspective-envelope"
up_left_point="33.01,32.34706"
up_right_point="37.076535,33.624727"
down_left_point="33.012395,36.92"
down_right_point="37.087757,36.92"
id="path-effect8"
is_visible="true"
lpeversion="1"
deform_type="perspective"
horizontal_mirror="false"
vertical_mirror="false"
overflow_perspective="false" />
<inkscape:path-effect
effect="construct_grid"
id="path-effect7"
is_visible="true"
lpeversion="1"
nr_x="5"
nr_y="5" />
<inkscape:path-effect
effect="perspective-envelope"
up_left_point="6.4239554,57.746712"
up_right_point="8.6499964,55.943269"
down_left_point="7.178544,61.91306"
down_right_point="10.335708,61.658464"
id="path-effect6"
is_visible="false"
lpeversion="1"
deform_type="envelope_deformation"
horizontal_mirror="false"
vertical_mirror="false"
overflow_perspective="false" />
<inkscape:path-effect
effect="perspective-envelope"
up_left_point="6.4239554,57.746712"
up_right_point="10.335708,57.746712"
down_left_point="6.4239554,61.658464"
down_right_point="10.335708,61.658464"
id="path-effect5"
is_visible="true"
lpeversion="1"
deform_type="perspective"
horizontal_mirror="false"
vertical_mirror="false"
overflow_perspective="false" />
<inkscape:path-effect
effect="mirror_symmetry"
start_point="31.463,21.717299"
end_point="31.463,61.46"
center_point="31.463,41.58865"
id="path-effect1"
is_visible="true"
lpeversion="1.2"
lpesatellites=""
mode="free"
discard_orig_path="false"
fuse_paths="false"
oposite_fuse="false"
split_items="false"
split_open="false"
link_styles="false" />
</defs>
<g
inkscape:label="Layer 1"
inkscape:groupmode="layer"
id="layer1"
transform="translate(-47.85153,7.7685908)">
<g
id="g17"
transform="matrix(1.137038,0,0,1.137038,184.3175,-14.988782)">
<g
id="g12"
transform="matrix(1.2911442,0,0,1.2911442,-8.9794231,-6.3756026)">
<path
style="fill:#1e1e2e;fill-opacity:1;stroke:none;stroke-width:1;stroke-opacity:1"
d="M 22.174415,57.832922 25.59976,30.911456 31.463,21.717299 V 61.46 Z m 18.57717,0 L 37.32624,30.911456 31.463,21.717299 V 61.46 Z"
id="path1"
sodipodi:nodetypes="ccccc"
inkscape:path-effect="#path-effect1"
inkscape:original-d="M 22.174415,57.832922 25.59976,30.911456 31.463,21.717299 V 61.46 Z" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="m 25.59976,30.911456 -3.425345,26.921465 9.288586,3.627077 9.288584,-3.627077 -3.425346,-26.921465 -5.863238,-9.194157 z"
id="path2"
sodipodi:nodetypes="ccccccc" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="m 25.59976,30.911456 5.863241,-2.224956 5.863238,2.224956"
id="path3" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="M 31.463001,21.717299 V 28.6865"
id="path4" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="M 31.463001,28.6865 V 61.459998"
id="path5" />
<path
id="path8"
d="M 33.011196,34.629828 35.381861,36.92 37.082139,35.270442 35.373436,33.089629 Z m -2.353318,0 -2.370665,2.290172 -1.700278,-1.649558 1.708703,-2.180813 z"
style="fill:#ffffff;fill-opacity:1;stroke:#7f849c;stroke-width:0.221004;stroke-dasharray:none;stroke-opacity:1"
sodipodi:nodetypes="ccccc"
inkscape:path-effect="#path-effect10;#path-effect12"
inkscape:original-d="m 33.012395,34.384741 2.037682,2.03768 2.03768,-2.03768 -2.037681,-2.037681 z"
transform="matrix(-1,0,0,1,63.297537,-0.65813929)" />
</g>
<path
id="rect12"
style="fill:#ffffff;stroke:#11111b;stroke-width:0.1;stroke-dasharray:none;stroke-opacity:1"
d="m 31.643848,6.3499999 c 0,4.0993831 2.732922,6.8323051 6.832305,6.8323051 -4.099383,0 -6.832305,2.732921 -6.832305,6.832304 0,-4.099383 -2.732922,-6.832304 -6.832304,-6.832304 4.099382,0 6.832304,-2.732922 6.832304,-6.8323051 z"
sodipodi:nodetypes="ccccc" />
</g>
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="M 52.916665,28.575001 H 66.674998 L 48.683332,62.441669 h 23.283333 l 3.174999,-3.175 -3.174999,-3.175001 h -12.7 L 76.034252,22.225001 H 52.750919 l -3.009254,3.175 z"
id="path13"
sodipodi:nodetypes="ccccccccccc" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 81.907671,22.225002 v 3.175 37.041668 H 99.89934 l 3.17499,-3.175 -3.17499,-3.175 H 87.199336 V 42.333336 H 99.89934 l 3.17499,-3.175002 -3.17499,-3.175 H 87.199336 l 10e-7,-7.408332 H 99.89934 l 3.17499,-3.175 -3.17499,-3.175 H 85.082671 Z"
id="path14"
sodipodi:nodetypes="cccccccccccccccccc" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="M 108.84938,67.733335 V 15.875 l 23.28334,39.158335 V 15.875 l 4.23333,4.233332 v 51.858336 l -23.28333,-38.1 v 38.1 z"
id="path15"
sodipodi:nodetypes="ccccccccc" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 142.0047,41.275001 11.66369,22.225001 2.64583,-4.233333 2.64584,4.233333 12.20007,-22.225001 -12.70004,-21.166667 v 11.641667 l 6.35,9.525 -8.46666,13.758334 -7.40834,-13.758334 5.29167,-9.525 -2e-5,-11.641667 z"
id="path16"
sodipodi:nodetypes="ccccccccccccc" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 183.15452,22.224999 v 33.866669 l 14.81666,1e-6 3.175,3.175 -3.175,3.175 -21.16666,-10e-7 V 22.224999 l 3.175,-4.233333 z"
id="path17"
sodipodi:nodetypes="ccccccccc" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 239.6038,20.108335 h 35.98333 l -4.23333,7.408333 h -10.58334 l 0.26459,39.158334 -3.175,-4.233333 -3.175,4.233333 -0.26459,-39.158334 h -10.58333 z"
id="path18"
sodipodi:nodetypes="cccccccccc" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 281.51666,20.108336 v 45.508335 l 3.175,-3.175 3.17499,3.175 1e-5,-23.283336 h 17.99166 v 23.283336 l 3.175,-3.175 3.175,3.175 V 20.108336 l -3.175,-3.175 -3.175,3.175 V 37.041669 H 287.86666 V 20.108336 l -3.175,-3.175 z"
id="path19"
sodipodi:nodetypes="ccccccccccccccccc" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 10 KiB

BIN
assets/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

83
assets/logo.svg Normal file
View File

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="1001.0335"
height="308.078"
viewBox="0 0 264.85678 81.512305"
version="1.1"
id="svg1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1" />
<g
id="layer1"
transform="translate(-47.85153,7.7685908)">
<g
id="g17"
transform="matrix(1.137038,0,0,1.137038,184.3175,-14.988782)">
<g
id="g12"
transform="matrix(1.2911442,0,0,1.2911442,-8.9794231,-6.3756026)">
<path
style="fill:#1e1e2e;fill-opacity:1;stroke:none;stroke-width:1;stroke-opacity:1"
d="M 22.174415,57.832922 25.59976,30.911456 31.463,21.717299 V 61.46 Z m 18.57717,0 L 37.32624,30.911456 31.463,21.717299 V 61.46 Z"
id="path1" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="m 25.59976,30.911456 -3.425345,26.921465 9.288586,3.627077 9.288584,-3.627077 -3.425346,-26.921465 -5.863238,-9.194157 z"
id="path2" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="m 25.59976,30.911456 5.863241,-2.224956 5.863238,2.224956"
id="path3" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="M 31.463001,21.717299 V 28.6865"
id="path4" />
<path
style="fill:none;fill-opacity:1;stroke:#eba0ac;stroke-width:0.3;stroke-dasharray:none;stroke-opacity:1"
d="M 31.463001,28.6865 V 61.459998"
id="path5" />
<path
id="path8"
d="M 33.011196,34.629828 35.381861,36.92 37.082139,35.270442 35.373436,33.089629 Z m -2.353318,0 -2.370665,2.290172 -1.700278,-1.649558 1.708703,-2.180813 z"
style="fill:#ffffff;fill-opacity:1;stroke:#7f849c;stroke-width:0.221004;stroke-dasharray:none;stroke-opacity:1"
transform="matrix(-1,0,0,1,63.297537,-0.65813929)" />
</g>
<path
id="rect12"
style="fill:#ffffff;stroke:#11111b;stroke-width:0.1;stroke-dasharray:none;stroke-opacity:1"
d="m 31.643848,6.3499999 c 0,4.0993831 2.732922,6.8323051 6.832305,6.8323051 -4.099383,0 -6.832305,2.732921 -6.832305,6.832304 0,-4.099383 -2.732922,-6.832304 -6.832304,-6.832304 4.099382,0 6.832304,-2.732922 6.832304,-6.8323051 z" />
</g>
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="M 52.916665,28.575001 H 66.674998 L 48.683332,62.441669 h 23.283333 l 3.174999,-3.175 -3.174999,-3.175001 h -12.7 L 76.034252,22.225001 H 52.750919 l -3.009254,3.175 z"
id="path13" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 81.907671,22.225002 v 3.175 37.041668 H 99.89934 l 3.17499,-3.175 -3.17499,-3.175 H 87.199336 V 42.333336 H 99.89934 l 3.17499,-3.175002 -3.17499,-3.175 H 87.199336 l 10e-7,-7.408332 H 99.89934 l 3.17499,-3.175 -3.17499,-3.175 H 85.082671 Z"
id="path14" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="M 108.84938,67.733335 V 15.875 l 23.28334,39.158335 V 15.875 l 4.23333,4.233332 v 51.858336 l -23.28333,-38.1 v 38.1 z"
id="path15" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 142.0047,41.275001 11.66369,22.225001 2.64583,-4.233333 2.64584,4.233333 12.20007,-22.225001 -12.70004,-21.166667 v 11.641667 l 6.35,9.525 -8.46666,13.758334 -7.40834,-13.758334 5.29167,-9.525 -2e-5,-11.641667 z"
id="path16" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 183.15452,22.224999 v 33.866669 l 14.81666,1e-6 3.175,3.175 -3.175,3.175 -21.16666,-10e-7 V 22.224999 l 3.175,-4.233333 z"
id="path17" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 239.6038,20.108335 h 35.98333 l -4.23333,7.408333 h -10.58334 l 0.26459,39.158334 -3.175,-4.233333 -3.175,4.233333 -0.26459,-39.158334 h -10.58333 z"
id="path18" />
<path
style="fill:#11111b;fill-opacity:1;stroke:#f38ba8;stroke-width:1;stroke-dasharray:none;stroke-opacity:1"
d="m 281.51666,20.108336 v 45.508335 l 3.175,-3.175 3.17499,3.175 1e-5,-23.283336 h 17.99166 v 23.283336 l 3.175,-3.175 3.175,3.175 V 20.108336 l -3.175,-3.175 -3.175,3.175 V 37.041669 H 287.86666 V 20.108336 l -3.175,-3.175 z"
id="path19" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 4.8 KiB

31
build.zig Normal file
View File

@ -0,0 +1,31 @@
const std = @import("std");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
const statspatch_dep = b.dependency("statspatch", .{ .target = target, .optimize = optimize });
_ = b.addModule("zenolith", .{
.source_file = .{ .path = "src/main.zig" },
.dependencies = &.{
.{
.name = "statspatch",
.module = statspatch_dep.module("statspatch"),
},
},
});
const main_tests = b.addTest(.{
.root_source_file = .{ .path = "src/main.zig" },
.target = target,
.optimize = optimize,
});
main_tests.addModule("statspatch", statspatch_dep.module("statspatch"));
const run_main_tests = b.addRunArtifact(main_tests);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&run_main_tests.step);
}

16
build.zig.zon Normal file
View File

@ -0,0 +1,16 @@
.{
.name = "zenolith",
// The version number here currently serves little purpose and is also not retrievable from
// the build script. For this reason, it's set to 0.0.0 here and the actual version
// number is declared in build.zig.
.version = "0.0.0",
.paths = .{""},
.dependencies = .{
.statspatch = .{
.url = "https://git.mzte.de/LordMZTE/statspatch/archive/231e3ce529efa9a084fb095ff570dfd985ca9a7d.tar.gz",
.hash = "1220685f1c039a53076ef169ef2e2959aeb054c86d4eda5aac736885daa0bf2f6910",
},
},
}

56
src/Color.zig Normal file
View File

@ -0,0 +1,56 @@
//! An 8-bit RGBA color
const std = @import("std");
r: u8,
g: u8,
b: u8,
a: u8,
const Color = @This();
pub fn black(alpha: u8) Color {
return gray(0, alpha);
}
pub fn white(alpha: u8) Color {
return gray(0xff, alpha);
}
pub fn gray(c: u8, alpha: u8) Color {
return .{ .r = c, .g = c, .b = c, .a = alpha };
}
pub fn toArray(self: Color) [4]u8 {
return .{ self.r, self.g, self.b, self.a };
}
pub fn fromArray(arr: [4]u8) Color {
return .{ .r = arr[0], .g = arr[1], .b = arr[2], .a = arr[3] };
}
pub fn toInt(self: Color) u32 {
return @as(u32, self.r) << 24 |
@as(u24, self.g) << 16 |
@as(u16, self.b) << 8 |
self.a;
}
pub fn fromInt(i: u32) Color {
return .{
.r = @truncate(i >> 24),
.g = @truncate(i >> 16),
.b = @truncate(i >> 8),
.a = @truncate(i),
};
}
test "integer conversion" {
try std.testing.expectEqual(
@as(u32, 0xf00dbabe),
toInt(.{ .r = 0xf0, .g = 0x0d, .b = 0xba, .a = 0xbe }),
);
try std.testing.expectEqual(
Color{ .r = 0xf0, .g = 0x0d, .b = 0xba, .a = 0xbe },
fromInt(0xf00dbabe),
);
}

168
src/attreebute.zig Normal file
View File

@ -0,0 +1,168 @@
/// This is a type-indexed map used for storing attreebutes
/// (inherited attributes in the widget tree).
///
/// Each widget may store an AttreebuteMap which will take precedence over it's parent's map
/// when a child widget is getting an attreebute. When resolving an attreebute, the widget tree
/// is walked toward the root node starting at the widget the attreebute is to be retrieved for,
/// checking all AttreebuteMaps until one containing the requested attreebute is found, otherwise
/// the attreebute is considered to be null.
///
/// Attreebutes which require a destructor should be avoided, and if necessary be removed manually
/// using remove prior to deinit. Due to the nature of it's implementation, the map can only call
/// destructors in remove and mod when overriding it, not in deinit.
const std = @import("std");
const util = @import("util.zig");
test {
_ = BoxStyle;
_ = ButtonStyle;
_ = CurrentFont;
}
pub const BoxStyle = @import("attreebutes/BoxStyle.zig");
pub const ButtonStyle = @import("attreebutes/ButtonStyle.zig");
pub const CurrentFont = @import("attreebutes/CurrentFont.zig");
pub const AttreebuteMap = struct {
const Context = struct {
pub fn hash(self: Context, t: u64) u64 {
_ = self;
return t;
}
pub fn eql(self: Context, a: u64, b: u64) bool {
_ = self;
return a == b;
}
};
/// An entry in the underlying map. Contains a slice to the entry's bytes as well as it's
/// alignment to make the allocator happy when freeing with unknown type.
const Entry = struct {
bytes: []u8,
log2_align: u8,
fn of(ptr: anytype) Entry {
return .{
.bytes = std.mem.asBytes(ptr),
.log2_align = std.math.log2_int(usize, @typeInfo(@TypeOf(ptr)).Pointer.alignment),
};
}
fn to(self: Entry, comptime T: type) *T {
std.debug.assert(std.math.log2_int(usize, @alignOf(T)) == self.log2_align);
return @alignCast(std.mem.bytesAsValue(T, self.bytes[0..@sizeOf(T)]));
}
};
// TODO: implement this without tricking a HashMap
const TypeHashMap = std.HashMapUnmanaged(u64, Entry, Context, std.hash_map.default_max_load_percentage);
/// The backing hash map. Be very careful here, if a given invariant is not held up, this will
/// lead to invalid pointer casts!
///
/// The key of this map is the type hash as returned by util.hashType and the value is a slice
/// consisting of a pointer to the data and it's size allocated on the map's allocator.
inner: TypeHashMap,
/// Creates a new AttreebuteMap. Caller owns returned memory and must free it by calling deinit.
pub fn init() AttreebuteMap {
return .{ .inner = TypeHashMap{} };
}
/// Frees all resources owned by this AttreebuteMap.
pub fn deinit(self: *AttreebuteMap, alloc: std.mem.Allocator) void {
var iter = self.inner.valueIterator();
while (iter.next()) |value| {
// We need to invoke rawFree here to keep the alignment consistent.
alloc.rawFree(
value.bytes,
value.log2_align,
@returnAddress(),
);
}
self.inner.deinit(alloc);
self.* = undefined;
}
/// Initialize an attreebute. If the key exists, the data behind it will be freed and it's
/// destructor will be called in accordance to util.deinitGeneric.
/// The returned value will be a pointer to the attreebute stored in the map. It remains valid
/// until removed or util the map is deinitialized.
/// The returned pointer points to uninitialized memory and must be set by the caller.
pub fn mod(self: *AttreebuteMap, alloc: std.mem.Allocator, comptime T: type) !*T {
const valp = try alloc.create(T);
errdefer alloc.destroy(valp);
if (try self.inner.fetchPut(alloc, util.hashType(T), Entry.of(valp))) |old| {
const old_val: *T = old.value.to(T);
util.deinitGeneric(old_val, alloc);
alloc.destroy(old_val);
}
return valp;
}
/// Retrieves the attreebute of the given type from this map, or returns null if not present.
/// The returned pointer remains valid as long as this map, unless the attreebute is removed,
/// in which case it is invalidated. If the attreebute is to be modified, the data behind the
/// return value is mutable.
///
/// The caller should NOT free the returned pointer!
pub fn get(self: AttreebuteMap, comptime T: type) ?*T {
return if (self.inner.get(util.hashType(T))) |val| val.to(T) else null;
}
/// If present, removes the given attreebute type from the map and returns true, otherwise
/// returns false. The allocator is required for deinitializing the attreebute. This will call
/// the attreebute's destructor in accordance with util.deinitGeneric.
pub fn remove(self: *AttreebuteMap, alloc: std.mem.Allocator, comptime T: type) bool {
if (self.inner.fetchRemove(util.hashType(T))) |old| {
const old_val: *T = old.value.to(T);
util.deinitGeneric(old_val, alloc);
alloc.destroy(old_val);
return true;
} else {
return false;
}
}
/// Returns true if the given attreebute type is present within the map, false otherwise.
///
/// If the attreebute value is required, the caller should prefer calling get
/// and handling a null return value instead.
pub fn has(self: AttreebuteMap, comptime T: type) bool {
return self.inner.contains(util.hashType(T));
}
};
test "basic type store" {
var map = AttreebuteMap.init();
defer map.deinit(std.testing.allocator);
var a_state: enum { start, init, deinit } = .start;
const A = struct {
state: *@TypeOf(a_state),
pub fn deinit(self: *@This()) void {
self.state.* = .deinit;
}
};
const a = try map.mod(std.testing.allocator, A);
a.* = .{ .state = &a_state };
map.get(A).?.state.* = .init;
try std.testing.expect(map.has(A));
try std.testing.expect(a.state.* == .init);
try std.testing.expectEqual(a_state, a.state.*);
_ = map.remove(std.testing.allocator, A);
try std.testing.expectEqual(a_state, .deinit);
_ = try map.mod(std.testing.allocator, u32);
}

View File

@ -0,0 +1,5 @@
//! This attreebute specifies how the box widget should look.
const BackgroundStyle = @import("../background_style.zig").BackgroundStyle;
background: BackgroundStyle = .none,

View File

@ -0,0 +1,15 @@
//! Style options for the button widget.
const BackgroundStyle = @import("../background_style.zig").BackgroundStyle;
const Color = @import("../Color.zig");
background: BackgroundStyle,
background_hovered: BackgroundStyle,
/// Spacing between the text and the button's outer bounds.
padding: usize,
/// Font size to use for the label.
font_size: usize,
text_color: Color,

View File

@ -0,0 +1,5 @@
//! This attreebute may be used in a widget that needs to render text to chose a font to pass to the
//! painter. A user should set this if text rendering is required.
const Font = @import("../font.zig").Font;
font: *Font,

36
src/backevent.zig Normal file
View File

@ -0,0 +1,36 @@
//! A Backevent is an event that is headed to the event loop to be handled by the user code. Such an
//! event is either pushed straight to the platform event loop using Platform.pushBackevent or
//! handled by widgets, travelling up the widget tree, where widgets can intercept them or
//! propagate them using the dispatch function. Custom backevents should be declared
//! in zenolith_options.backevents as this is a statspatch type.
const std = @import("std");
const statspatch = @import("statspatch");
test {
_ = ButtonActivated;
}
pub const ButtonActivated = @import("backevents/ButtonActivated.zig");
const zenolith = @import("main.zig");
const Widget = @import("widget.zig").Widget;
fn Prototype(comptime Self: type) type {
std.debug.assert(Self == Backevent);
return struct {
//! Propagates this backevent up the widget tree. If the current (given) Widget has a parent,
//! the event is propagated to it. Otherwise, it is pushed to the platform event loop.
//! Widgets should call this in their backevent handler if they do not wish to modify or
//! intercept the backevent.
pub fn dispatch(self: Self, widget: *Widget) anyerror!void {
if (widget.data.parent) |p| {
try p.backevent(self);
} else {
try widget.data.platform.?.pushBackevent(self);
}
}
};
}
pub const Backevent = statspatch.StatspatchType(Prototype, void, &zenolith.backevents);

View File

@ -0,0 +1,6 @@
//! A backevent that is fired when a button is activated.
//! The GUI code should dispatch on the btn_widget field in this struct.
//! btn_widget will always have a Button as it's implementation.
const Widget = @import("../widget.zig").Widget;
btn_widget: *Widget,

27
src/background_style.zig Normal file
View File

@ -0,0 +1,27 @@
//! This file contains a union to be used by various widgets as a uniform way to determine how
//! their background should look. It also contains a useful function for drawing such a background.
const Color = @import("Color.zig");
const Painter = @import("painter.zig").Painter;
const Rectangle = @import("layout/Rectangle.zig");
pub const BackgroundStyle = union(enum) {
none,
fill: Color,
stroked: struct { stroke: Color, fill: ?Color = null, width: usize },
pub fn drawBackground(self: BackgroundStyle, painter: *Painter, rect: Rectangle) !void {
switch (self) {
.none => {},
.fill => |col| try painter.rect(
rect,
col,
),
.stroked => |opt| try painter.strokeRect(
rect,
opt.width,
opt.stroke,
opt.fill,
),
}
}
};

96
src/font.zig Normal file
View File

@ -0,0 +1,96 @@
const std = @import("std");
const statspatch = @import("statspatch");
const zenolith = @import("main.zig");
const Size = @import("layout/Size.zig");
fn FontPrototype(comptime Self: type) type {
std.debug.assert(Self == Font);
return struct {
/// Performs layout on the given string of UTF-8 encoded text.
/// The wrap parameter controls how text should be wrapped. If set to none, no text wrapping
/// should be done, if set to word or glyph it should wrap whole words or whole glyphs
/// respectively. The size parameter is in px. Platforms where this isn't applicable
/// should try to make the font size match closely.
pub fn layout(
self: *Self,
text: []const u8,
size: usize,
wrap: TextWrap,
) !Chunk {
return try statspatch.implcall(
self,
.ptr,
"layout",
anyerror!Chunk,
.{ text, size, wrap },
);
}
/// Free resources associated with this font.
pub fn deinit(self: Self) void {
statspatch.implcallOptional(self, .self, "deinit", void, .{}) orelse {};
}
};
}
fn ChunkPrototype(comptime Self: type) type {
std.debug.assert(Self == Chunk);
return struct {
/// Returns the total size of the chunk.
/// This is often used for layout to determine the size of text.
pub fn getSize(self: Self) Size {
return statspatch.implcall(self, .self, "getSize", Size, .{});
}
/// Free resources associated with this chunk.
pub fn deinit(self: Self) void {
return statspatch.implcallOptional(self, .self, "deinit", void, .{}) orelse {};
}
};
}
/// Determines how text should be wrapped when doing text layout.
pub const TextWrap = union(enum) {
/// Don't wrap text.
none,
/// Wrap words after the given maximum width.
word: usize,
/// Wrap individual glyphs after the given maximum width.
glyph: usize,
};
pub const font_impls = impls: {
var implementations: []const type = &.{};
for (zenolith.platform_impls) |pi| {
if (@hasDecl(pi, "Font")) {
implementations = implementations ++ &[1]type{pi.Font};
}
}
break :impls implementations;
};
pub const chunk_impls = impls: {
var implementations: [font_impls.len]type = undefined;
for (&implementations, font_impls) |*chunk, font| {
chunk.* = font.Chunk;
}
break :impls &implementations;
};
/// The font type is a backend-specific statspatch type which encapsulates a font.
/// This is used with the painter API to draw text.
/// Platforms should specify their font implementation by declaring a Font declaration.
pub const Font = statspatch.StatspatchType(FontPrototype, void, font_impls);
/// A chunk represents a laid-out piece of text. This is created by the font using the layout
/// function. It typically contains information about the positions of individual glyphs, although
/// this is up to the backend.
/// Fonts should specify their chunk implementation by declaring a Chunk declaration.
pub const Chunk = statspatch.StatspatchType(ChunkPrototype, void, chunk_impls);

11
src/layout.zig Normal file
View File

@ -0,0 +1,11 @@
test {
_ = Constraints;
_ = Position;
_ = Rectangle;
_ = Size;
}
pub const Constraints = @import("layout/Constraints.zig");
pub const Position = @import("layout/Position.zig");
pub const Rectangle = @import("layout/Rectangle.zig");
pub const Size = @import("layout/Size.zig");

View File

@ -0,0 +1,46 @@
//! This struct represents the freedom a Widget gets when determining its size.
//! It's passed to a Box through the LayoutSize treevent and is used to set limits to the size it can have.
const std = @import("std");
const Size = @import("Size.zig");
min: Size,
max: Size,
const Self = @This();
/// Clamps a given size to fit the Constraints
pub fn clamp(self: Self, size: Size) Size {
return .{
.width = std.math.clamp(size.width, self.min.width, self.max.width),
.height = std.math.clamp(size.height, self.min.height, self.max.height),
};
}
/// Asserts that a size is within the constraints.
/// It's good practice to call this on children to verify their size after a LayoutSize event.
pub fn expectFits(self: Self, size: Size) error{ConstraintViolation}!void {
if (!self.fits(size))
return error.ConstraintViolation;
}
/// Checks if a size fits the constraints.
pub fn fits(self: Self, size: Size) bool {
return size.width >= self.min.width and
size.height >= self.min.height and
size.width <= self.max.width and
size.height <= self.max.height;
}
/// Helper for constructing a tight constraint for a given size.
pub fn tight(size: Size) Self {
return .{
.min = size,
.max = size,
};
}
/// Checks if this is a tight constraint.
pub fn isTight(self: Self) bool {
return std.meta.eql(self.min, self.max);
}

38
src/layout/Position.zig Normal file
View File

@ -0,0 +1,38 @@
//! A 2-Dimensional position, typically used to denote where a widget is relative to the top left.
const Size = @import("Size.zig");
x: usize,
y: usize,
const Position = @This();
pub const zero = Position{ .x = 0, .y = 0 };
/// Returns a Position where both components are identical.
pub inline fn two(pos: usize) Position {
return .{ .x = pos, .y = pos };
}
/// Performs a component-wise addition on two Positions.
pub inline fn add(self: Position, other: Position) Position {
return .{
.x = self.x + other.x,
.y = self.y + other.y,
};
}
/// Performs a component-wise addition on two Positions.
pub inline fn sub(self: Position, other: Position) Position {
return .{
.x = self.x - other.x,
.y = self.y - other.y,
};
}
/// Converts this Position to a Size.
pub inline fn size(self: Position) Size {
return .{
.width = self.x,
.height = self.y,
};
}

25
src/layout/Rectangle.zig Normal file
View File

@ -0,0 +1,25 @@
//! A simple type describing a rectangle in the GUI. The position is relative to the top left.
const Position = @import("Position.zig");
const Size = @import("Size.zig");
pos: Position,
size: Size,
const Rectangle = @This();
pub const zero = Rectangle{
.pos = Position.zero,
.size = Size.zero,
};
/// Returns the area of this Rectangle.
pub inline fn area(self: Rectangle) usize {
return self.size.area();
}
pub inline fn contains(self: Rectangle, pos: Position) bool {
return pos.x >= self.pos.x and
pos.y >= self.pos.y and
pos.x <= self.pos.x + self.size.width and
pos.y <= self.pos.y + self.size.height;
}

40
src/layout/Size.zig Normal file
View File

@ -0,0 +1,40 @@
//! A size, usually used for widget sizes.
const Position = @import("Position.zig");
width: usize,
height: usize,
const Size = @This();
pub const zero = Size{ .width = 0, .height = 0 };
/// Returns a Size where both components are identical.
pub inline fn two(size: usize) Size {
return .{ .width = size, .height = size };
}
/// Returns the area of this size.
pub inline fn area(self: Size) usize {
return self.width * self.height;
}
/// Performs a component-wise addition on two Sizes.
pub inline fn add(self: Size, other: Size) Size {
return .{
.width = self.width + other.width,
.height = self.height + other.height,
};
}
/// Performs a component-wise addition on two Sizes.
pub inline fn sub(self: Size, other: Size) Size {
return .{
.width = self.width - other.width,
.height = self.height - other.height,
};
}
/// Converts this Size to a Position.
pub inline fn position(self: Size) Position {
return .{ .x = self.width, .y = self.height };
}

90
src/main.zig Normal file
View File

@ -0,0 +1,90 @@
const std = @import("std");
const root = @import("root");
test {
_ = attreebute;
_ = backevent;
_ = font;
_ = layout;
_ = painter;
_ = platform;
_ = texture;
_ = treevent;
_ = util;
_ = widget;
_ = Color;
}
pub const attreebute = @import("attreebute.zig");
pub const backevent = @import("backevent.zig");
pub const font = @import("font.zig");
pub const layout = @import("layout.zig");
pub const painter = @import("painter.zig");
pub const platform = @import("platform.zig");
pub const texture = @import("texture.zig");
pub const treevent = @import("treevent.zig");
pub const util = @import("util.zig");
pub const widget = @import("widget.zig");
pub const Color = @import("Color.zig");
/// List of the default widget implementations included with Zenolith.
/// If you set zenolith_options.widget_impls, include this if you want to use Zenolith's widgets.
pub const default_widget_impls = [_]type{
widget.Box,
widget.Button,
widget.Label,
};
/// The default painter implementations bundled with Zenolith.
pub const default_painter_impls = [_]type{};
/// The default platform implementations included with Zenolith. This is likely to remain empty.
pub const default_platform_impls = [_]type{};
/// The default backevents in Zenolith. Remember that these may be required by widgets.
pub const default_backevents = [_]type{
backevent.ButtonActivated,
};
const root_options = if (@hasDecl(root, "zenolith_options")) root.zenolith_options else struct {};
comptime {
const backevent_info = @typeInfo(@TypeOf(backevents));
if (backevent_info != .Array or backevent_info.Array.child != type)
@compileError("backevents must be a [_]type!");
const widget_impl_info = @typeInfo(@TypeOf(widget_impls));
if (widget_impl_info != .Array or widget_impl_info.Array.child != type)
@compileError("widget_impls must be a [_]type!");
const painter_impl_info = @typeInfo(@TypeOf(painter_impls));
if (painter_impl_info != .Array or painter_impl_info.Array.child != type)
@compileError("painter_impls must be a [_]type!");
const platform_impl_info = @typeInfo(@TypeOf(platform_impls));
if (platform_impl_info != .Array or platform_impl_info.Array.child != type)
@compileError("platform_impls must be a [_]type!");
}
pub const backevents = if (@hasDecl(root_options, "backevents"))
root_options.backevents
else
default_backevents;
pub const widget_impls = if (@hasDecl(root_options, "widget_impls"))
root_options.widget_impls
else
default_widget_impls;
pub const painter_impls = if (@hasDecl(root_options, "painter_impls"))
root_options.painter_impls
else
default_painter_impls;
pub const platform_impls = if (@hasDecl(root_options, "platform_impls"))
root_options.platform_impls
else
default_platform_impls;

161
src/painter.zig Normal file
View File

@ -0,0 +1,161 @@
//! The painter is a statspatch-based type which represents Zenolith's primary backend-agnostic
//! graphics abstraction. It is designed with minimalism in mind and is not supposed to provide
//! a feature-complete and flexible API, rather being designed to contain universal primitives
//! for drawing a basic GUI. For more complicated uses, backends should offer their own facilities.
//! Due to the nature of the painter as a statspatch type, it can be downcast, offering
//! access to implementation-specific APIs to widgets.
//!
//! This type intentionally doesn't work like textures do in the sense that implementations must be
//! explicitly declared, as users should be given the option of using their own custom painters,
//! for example for performing graphical modifications on subtrees.
const std = @import("std");
const statspatch = @import("statspatch");
const zenolith = @import("main.zig");
const font = @import("font.zig");
const Color = @import("Color.zig");
const Position = @import("layout/Position.zig");
const Rectangle = @import("layout/Rectangle.zig");
const Size = @import("layout/Size.zig");
const Texture = @import("texture.zig").Texture;
fn Prototype(comptime Self: type) type {
std.debug.assert(Self == Painter);
return struct {
/// Draws a rectangle in the given color.
/// The coordinates are absolute and not relative to a widget.
/// Thus, widgets must account for their own position.
pub fn rect(
self: *Self,
rectangle: Rectangle,
color: Color,
) !void {
try statspatch.implcall(
self,
.ptr,
"rect",
anyerror!void,
.{ rectangle, color },
);
}
/// Draws an outlined rectangle.
/// line_width specifies the width of the outline. stroke_color can be used to optionall
/// fill the rectangle in a given color.
///
/// Caller asserts that
/// rectangle.size.width >= 2 * line_width and rectangle.size.height >= 2 * line_width
pub fn strokeRect(
self: *Self,
rectangle: Rectangle,
line_width: usize,
stroke_color: Color,
fill_color: ?Color,
) !void {
std.debug.assert(rectangle.size.width >= 2 * line_width and
rectangle.size.height >= 2 * line_width);
if (statspatch.implcallOptional(
self,
.self,
"strokeRect",
anyerror!void,
.{ rectangle, line_width, stroke_color, fill_color },
)) |ret| try ret else {
// TODO: draw as 2 rects if fill_color is set
const ud_size = Size{
.width = rectangle.size.width,
.height = line_width,
};
const lr_size = Size{
.width = line_width,
.height = rectangle.size.height,
};
// top
try self.rect(.{
.pos = rectangle.pos,
.size = ud_size,
}, stroke_color);
// left
try self.rect(.{
.pos = rectangle.pos,
.size = lr_size,
}, stroke_color);
// bottom
try self.rect(.{
.pos = .{
.x = rectangle.pos.x,
.y = rectangle.pos.y + rectangle.size.height - line_width,
},
.size = ud_size,
}, stroke_color);
// right
try self.rect(.{
.pos = .{
.x = rectangle.pos.x + rectangle.size.width - line_width,
.y = rectangle.pos.y,
},
.size = lr_size,
}, stroke_color);
// fill
if (fill_color) |fc| {
if (rectangle.area() > 0) {
try self.rect(.{
.pos = rectangle.pos.add(Position.two(line_width)),
.size = rectangle.size.sub(Size.two(line_width * 2)),
}, fc);
}
}
}
}
/// Copies the region of texture identified by src to the screen at dest. If the dimensions
/// of the two rectangles differ, the painter should stretch the texture accordingly.
/// The caller asserts that the texture is one that has been obtained on the same platform
/// that this painter is rendering on.
/// The coordinates are absolute and not relative to a widget.
/// Thus, widgets must account for their own position.
pub fn texturedRect(
self: *Self,
src: Rectangle,
dest: Rectangle,
texture: *Texture,
) !void {
return statspatch.implcall(
self,
.ptr,
"texturedRect",
anyerror!void,
.{ src, dest, texture },
);
}
/// Draw a given Chunk of laid-out text, typically obtained through the font at the given
/// position. The caller asserts that the given chunk is compatible with this painter's
/// underlying platform.
pub fn text(
self: *Self,
pos: Position,
chunk: font.Chunk,
color: Color,
) !void {
return statspatch.implcall(
self,
.ptr,
"text",
anyerror!void,
.{ pos, chunk, color },
);
}
};
}
pub const Painter = statspatch.StatspatchType(Prototype, void, &zenolith.painter_impls);

23
src/platform.zig Normal file
View File

@ -0,0 +1,23 @@
//! The platform is the main interface to be implemnted by backends. It's responsible for driving
//! the GUI by sending treevents, handling system events and rendering the GUI.
const std = @import("std");
const statspatch = @import("statspatch");
const zenolith = @import("main.zig");
const Backevent = @import("backevent.zig").Backevent;
fn Prototype(comptime Self: type) type {
std.debug.assert(Self == Platform);
return struct {
//! Pushes a backevent to the platform's event loop.
//! These should make their way back to the user code, how exactly depende on the Platform's
//! API. This function must be threadsafe!
pub fn pushBackevent(self: *Self, ev: Backevent) !void {
try statspatch.implcall(self, .ptr, "pushBackevent", anyerror!void, .{ev});
}
};
}
pub const Platform = statspatch.StatspatchType(Prototype, void, &zenolith.platform_impls);

36
src/texture.zig Normal file
View File

@ -0,0 +1,36 @@
//! This data structure is a statspatch type allowing interfacing between zenolith and a platform's
//! rendering system for drawing textures.
//! Unlike other statspatch types in Zenolith, there is no root option for declaring implementations.
//! Instead, declared platform implementations should have a declaration called Texture containing
//! their texture implementation type.
const std = @import("std");
const statspatch = @import("statspatch");
const zenolith = @import("main.zig");
const Size = @import("layout/Size.zig");
fn Prototype(comptime Self: type) type {
std.debug.assert(Self == Texture);
return struct {
/// Gets this textures size in pixels.
pub fn getSize(self: Self) Size {
return statspatch.implcall(self, .self, "getSize", Size, .{});
}
};
}
pub const impls = impls: {
var implementations: []const type = &.{};
for (zenolith.platform_impls) |pi| {
if (@hasDecl(pi, "Texture")) {
implementations = implementations ++ &[1]type{pi.Texture};
}
}
break :impls implementations;
};
pub const Texture = statspatch.StatspatchType(Prototype, void, impls);

40
src/treevent.zig Normal file
View File

@ -0,0 +1,40 @@
//! A treevent is an event which is propagated through the tree.
//! To fire a treevent, the treevent function is called on the respective widget.
//! This function may call a treevent's dispatch function (which must be present in all treevents!)
//! and handle a treevent accordingly. It may also choose not to call dispatch on the treevent, or
//! to conditionally dispatch it.
//!
//! Treevents are encouraged to have a fire function, taking a self parameter and a widget.
//! This function can be used by code firing a treevent and can, for example, contain code
//! to to things after the treevent has been fully dispatched or to only conditionally fire it.
const std = @import("std");
const Widget = @import("widget.zig").Widget;
test {
_ = Click;
_ = Draw;
_ = LayoutPosition;
_ = LayoutSize;
_ = Link;
_ = MouseMove;
}
pub const Click = @import("treevents/Click.zig");
pub const Draw = @import("treevents/Draw.zig");
pub const LayoutPosition = @import("treevents/LayoutPosition.zig");
pub const LayoutSize = @import("treevents/LayoutSize.zig");
pub const Link = @import("treevents/Link.zig");
pub const MouseMove = @import("treevents/MouseMove.zig");
pub fn fire(widget: *Widget, tv: anytype) !void {
const Tv = @TypeOf(tv);
var tvv = tv;
if (std.meta.hasFn(Tv, "preFire")) {
try tvv.preFire();
}
try widget.treevent(tv);
if (std.meta.hasFn(Tv, "postFire")) {
try tvv.postFire();
}
}

48
src/treevents/Click.zig Normal file
View File

@ -0,0 +1,48 @@
//! This treevent is fired on a mouse click. The default dispatcher dispatches it to all Widgets.
//! Widgets that wish to handle being clicked on must ensure the click has occured on them.
//! The isOnWidget function allows this. This approach allows for widgets like sliders to detect
//! mouse up events anywhere in the UI.
const Position = @import("../layout/Position.zig");
const Rectangle = @import("../layout/Rectangle.zig");
const Widget = @import("../widget.zig").Widget;
/// A mouse button. For scroll_* buttons, only the click action is permitted.
pub const MouseButton = enum {
left,
middle,
right,
scroll_up,
scroll_down,
scroll_left,
scroll_right,
};
pub const Action = enum {
/// The mouse button has been pressed.
down,
/// The mouse button has been released.
up,
/// The mouse button has been pressed. This should indicate a single interaction with the GUI.
/// Widgets should use this to handle a single mouse input, this is what a button reacts to
/// for example. Platforms often fire this at the same time as a down event.
click,
};
pos: Position,
button: MouseButton,
action: Action,
const Click = @This();
pub fn dispatch(self: Click, widget: *Widget) !void {
for (widget.children()) |child| {
try child.treevent(self);
}
}
pub fn isOnWidget(self: Click, widget: Widget) bool {
const bb = Rectangle{ .pos = widget.data.position, .size = widget.data.size };
return bb.contains(self.pos);
}

13
src/treevents/Draw.zig Normal file
View File

@ -0,0 +1,13 @@
//! This event signals widgets that they should be drawn using the given painter.
const Painter = @import("../painter.zig").Painter;
const Widget = @import("../widget.zig").Widget;
painter: *Painter,
const Draw = @This();
pub fn dispatch(self: Draw, widget: *Widget) !void {
for (widget.children()) |child| {
try child.treevent(self);
}
}

View File

@ -0,0 +1,21 @@
//! This treevent is fired after LayoutSize. Widgets should use this to calculate and set their
//! positions relative to the treevent's position field.
//! The dispatch function will plainly dispatch the treevent to all children keeping the position
//! the same and setting this widget's position, but this should be overriden unless the widget
//! does not have any children or is a simple wrapper and does not affect the children's position
//! in any way.
const std = @import("std");
const Position = @import("../layout/Position.zig");
const Widget = @import("../widget.zig").Widget;
position: Position,
const LayoutPosition = @This();
pub fn dispatch(self: LayoutPosition, widget: *Widget) !void {
widget.data.position = self.position;
for (widget.children()) |w| {
try w.treevent(self);
}
}

View File

@ -0,0 +1,32 @@
//! This treevent is fired first when doing a layout pass on a widget (before LayoutPosition).
//! In the handler, widgets should calculate their own size and set the size field in their data.
//! This event needs to be propagated to children so they can set their size.
const std = @import("std");
// TODO: handle error.Overflow in fire function and set flag to disable draw event for subtree.
const Constraints = @import("../layout/Constraints.zig");
const Widget = @import("../widget.zig").Widget;
/// This is set to true if this is the final layout pass being done on a widget.
/// Widgets should only propagate this to children if this is true.
///
/// This exists so that widgets that need to do multiple layout passes don't recursively layout
/// the whole sub tree on a non-final layout pass, reducing performance overhead.
///
/// Widgets should propagate this event with final = true to their children exactly once.
final: bool,
/// These represent constraints the widget laid out must adhere to.
constraints: Constraints,
const LayoutSize = @This();
/// There is no sensible default implementation for this, thus referencing the default dispatcher
/// for this treevent is always a compile error. This is one of a few treevents that are
/// mandatory to handle.
pub fn dispatch(self: LayoutSize, widget: *Widget) !void {
_ = widget;
_ = self;
@compileError("Must handle LayoutSize treevent!");
}

26
src/treevents/Link.zig Normal file
View File

@ -0,0 +1,26 @@
//! This treevent must always be fired on a subtree after it's children have been modified.
//! It sets the parent of each widget while being propagated.
const Platform = @import("../platform.zig").Platform;
const Widget = @import("../widget.zig").Widget;
/// The parent of the widget the event is currently being handled on.
/// If this is null, the widget's parent will remain unchanged.
parent: ?*Widget,
/// The current platform. Will be applied to all widgets.
/// Unlike the parent widget, the treevent will set this to null if the value is null here.
platform: ?*Platform,
const Link = @This();
/// Dispatches the Link treevent to all children, setting their parent widget to this one.
pub fn dispatch(self: Link, widget: *Widget) !void {
if (self.parent) |p|
widget.data.parent = p;
widget.data.platform = self.platform;
for (widget.children()) |child| {
try child.treevent(Link{ .parent = widget, .platform = self.platform });
}
}

View File

@ -0,0 +1,22 @@
//! This treevent is fired when the mouse cursor moves. It contains the new mouse cursor position
//! as well as the relative movement of the cursor.
const Position = @import("../layout/Position.zig");
const Rectangle = @import("../layout/Rectangle.zig");
const Widget = @import("../widget.zig").Widget;
pos: Position,
dx: isize,
dy: isize,
const MouseMove = @This();
pub fn dispatch(self: MouseMove, widget: *Widget) !void {
for (widget.children()) |child| {
try child.treevent(self);
}
}
pub fn isOnWidget(self: MouseMove, widget: Widget) bool {
const bb = Rectangle{ .pos = widget.data.position, .size = widget.data.size };
return bb.contains(self.pos);
}

57
src/util.zig Normal file
View File

@ -0,0 +1,57 @@
//! This module contains general-purpose utilities.
const std = @import("std");
/// A generic deinit function which should do a decent job at deinitializing any given type.
/// If you want your type to be picked up here, you must provide an accessible `deinit` function,
/// taking a `self` parameter and optionally an allocator as a second parameter.
pub fn deinitGeneric(x: anytype, alloc: std.mem.Allocator) void {
const BaseT = @TypeOf(x);
const T = switch (@typeInfo(BaseT)) {
.Pointer => |pointer_info| pointer_info.child,
else => BaseT,
};
switch (@typeInfo(T)) {
.Struct, .Enum, .Union, .Opaque => {},
else => return, // type cannot have functions
}
if (@hasDecl(T, "deinit") and @typeInfo(@TypeOf(T.deinit)) == .Fn) {
const params = @typeInfo(@TypeOf(T.deinit)).Fn.params;
if (params.len == 1) {
x.deinit();
} else if (params.len == 2 and params[1].type == std.mem.Allocator) {
x.deinit(alloc);
}
}
}
/// Computes a hash for a given type. This is guaranteed to be unique per-type given (at least
/// that's what this is supposed to do, further testing required).
pub fn hashType(comptime T: type) u64 {
return comptime std.hash_map.hashString(@typeName(T));
}
test "deinitGeneric" {
var type_with_plain_deinit = std.ArrayList(u64).init(std.testing.allocator);
// ensure we get a memory leak if deinitGeneric doesn't work
try type_with_plain_deinit.append(0xdeadbeef);
// alloc shouldn't be used here
deinitGeneric(&type_with_plain_deinit, std.testing.failing_allocator);
var type_with_alloc_deinit = std.ArrayListUnmanaged(u64){};
try type_with_alloc_deinit.append(std.testing.allocator, 0xb00b135);
deinitGeneric(&type_with_alloc_deinit, std.testing.allocator);
}
test "hashType" {
const A = struct {};
const B = A;
try std.testing.expectEqual(hashType(A), hashType(B));
}

181
src/widget.zig Normal file
View File

@ -0,0 +1,181 @@
//! The main Widget type.
//! This is based on the Statspatch library.
const std = @import("std");
const statspatch = @import("statspatch");
const zenolith = @import("main.zig");
const layout = @import("layout.zig");
const treev = @import("treevent.zig");
const AttreebuteMap = @import("attreebute.zig").AttreebuteMap;
const Backevent = @import("backevent.zig").Backevent;
const Platform = @import("platform.zig").Platform;
test {
_ = Box;
_ = Button;
_ = Label;
}
pub const Box = @import("widgets/Box.zig");
pub const Button = @import("widgets/Button.zig");
pub const Label = @import("widgets/Label.zig");
// TODO: avoid anyerror here
fn Prototype(comptime Self: type) type {
std.debug.assert(Self == Widget);
return struct {
/// Initialize a widget. This will create it's data and optionally call it's
/// initialize funciton. The returned pointer is allocated on the given allocator.
/// This is mostly to make the API nicer, performance overhead should be minimal.
/// The returned pointer is freed by deinit.
pub fn init(alloc: std.mem.Allocator, impl: anytype) !*Self {
const self = try alloc.create(Self);
errdefer alloc.destroy(self);
self.* = Self.create(impl, .{
.allocator = alloc,
.attreebutes = null,
.parent = null,
.platform = null,
.position = .{ .x = 0, .y = 0 },
.size = .{ .width = 0, .height = 0 },
});
// Possibly call an initialize function. The widget can do any necessary
// initialization of it's data here.
_ = try (statspatch.implcallOptional(self, .ptr, "initialize", anyerror!void, .{self}) orelse {});
return self;
}
/// Free the widget's resources. Will call an implementation's deinit
/// and deinit on all children.
pub fn deinit(self: *Self) void {
for (self.children()) |child| {
// TODO: call child.deinit() here
// see: https://github.com/ziglang/zig/issues/17872
deinit(child);
}
_ = statspatch.implcallOptional(self, .ptr, "deinit", void, .{self});
if (self.data.attreebutes) |*map| map.deinit(self.data.allocator);
self.data.allocator.destroy(self);
}
/// Retrieve a given attreebute. Will try this widget's map or ask it's
/// parent if not present.
pub fn getAttreebute(self: *Self, comptime T: type) ?*T {
// `zig fmt` seems to be drunk here
return (if (self.data.attreebutes) |map|
map.get(T)
else
null) orelse
if (self.data.parent) |p|
p.getAttreebute(T)
else
null;
}
/// Called to dispatch a treevent.
pub fn treevent(self: *Self, tv: anytype) !void {
try statspatch.implcall(self, .ptr, "treevent", anyerror!void, .{ self, tv });
}
pub fn backevent(self: *Self, ev: Backevent) !void {
try (statspatch.implcallOptional(
self,
.ptr,
"backevent",
anyerror!void,
.{ self, ev },
) orelse ev.dispatch(self));
}
/// Returns the widget's children.
/// The resulting slice must point to memory owned by the widget!
pub fn children(self: *Self) []const *Self {
return statspatch.implcallOptional(
self,
.ptr,
"children",
[]const *Self,
.{self},
) orelse &.{};
}
/// Returns the widget's flex expand factor, or 0 if it should not be expanded.
/// Simple wrappers should delegate this to their child.
/// Used by widgets such as Box to determine the size of their children.
pub fn getFlexExpand(self: Self) usize {
return statspatch.implcallOptional(
self,
.self,
"getFlexExpand",
usize,
.{self},
) orelse 0;
}
/// Appends a child to the end of this widget's children if position is null, otherwise
/// it is inserted before the element at position.
/// The caller must ensure that position is less than children().len,
/// otherwise, undefined behaviour is invoked.
/// Returns error.Unsupported if the widget does not support such functionality.
pub fn addChild(self: *Self, position: ?usize, child: *Widget) !void {
return statspatch.implcallOptional(
self,
.ptr,
"addChild",
anyerror!void,
.{ self, position, child },
) orelse error.Unsupported;
}
/// Removes the child at position or the last child if position is null.
/// The function then returns the removed child.
/// The caller must ensure that position is less than children().len and children() is not
/// empty, otherwise, undefined behaviour is invoked.
/// Returns error.Unsupported if the widget does not support such functionality.
pub fn removeChild(self: *Self, position: usize) !*Widget {
return statspatch.implcallOptional(
self,
.ptr,
"removeChild",
anyerror!void,
.{ self, position },
) orelse error.Unsupported;
}
};
}
/// Common data shared among all widgets.
pub const WidgetData = struct {
allocator: std.mem.Allocator,
/// A map of this widget's attreebutes.
attreebutes: ?AttreebuteMap,
/// The widget's parent or null if it's at the root of the widget tree.
parent: ?*Widget,
/// The platform the widget is running under. This is typically set by the Link treevent.
platform: ?*Platform,
/// The widget's position starting from the top left.
position: layout.Position,
/// The widget's size.
size: layout.Size,
};
pub const Widget = statspatch.StatspatchType(Prototype, WidgetData, &zenolith.widget_impls);
test "widget" {
var widget = try Box.init(std.testing.allocator, .vertical);
defer widget.deinit();
try widget.treevent(treev.Link{ .parent = null, .platform = null });
try widget.treevent(treev.LayoutSize{
.constraints = layout.Constraints.tight(.{ .width = 10, .height = 10 }),
.final = true,
});
widget.data.attreebutes = AttreebuteMap.init();
_ = try widget.data.attreebutes.?.put(std.testing.allocator, u32, 42);
try std.testing.expectEqual(@as(u32, 42), widget.getAttreebute(u32).?.*);
}

264
src/widgets/Box.zig Normal file
View File

@ -0,0 +1,264 @@
//! A widget which lays out it's children using a FlowBox-like algorithm in a given direction.
const std = @import("std");
const attreebute = @import("../attreebute.zig");
const treev = @import("../treevent.zig");
const layout = @import("../layout.zig");
const Widget = @import("../widget.zig").Widget;
pub const Direction = enum {
vertical,
horizontal,
};
/// Specifies how children should be aligned on the secondary axis.
/// In horizontal mode, left means top and right means bottom.
pub const ChildPositioning = enum {
left,
center,
right,
};
pub const Child = struct {
widget: *Widget,
/// Offset from the start of the box. Used for positioning.
offset: usize = 0,
pos: ChildPositioning,
};
/// Direction to lay out children in.
/// - vertical/column
/// - horizontal/row
direction: Direction,
children: std.MultiArrayList(Child),
/// If set to true, the box will expand in the direction orthogonal to the direction field
/// to fill the constraints.
orth_expand: bool = false,
const Box = @This();
pub fn init(alloc: std.mem.Allocator, direction: Direction) !*Widget {
const self = Box{
.direction = direction,
.children = std.MultiArrayList(Child){},
};
return try Widget.init(alloc, self);
}
pub fn deinit(self: *Box, selfw: *Widget) void {
self.children.deinit(selfw.data.allocator);
}
pub fn treevent(self: *Box, selfw: *Widget, tv: anytype) anyerror!void {
switch (@TypeOf(tv)) {
treev.LayoutSize => {
const slice = self.children.slice();
// The maximum size of the children in the direction orthogonal to that of the Box.
var max_orth_size: usize = if (self.orth_expand) switch (self.direction) {
.vertical => tv.constraints.max.width,
.horizontal => tv.constraints.max.height,
} else 0;
var cur_pos: usize = 0;
// first pass, initial sizes
{
for (slice.items(.widget)) |child| {
var child_cons = tv.constraints;
switch (self.direction) {
.vertical => {
child_cons.max.height -|= cur_pos;
child_cons.min.height -|= cur_pos;
},
.horizontal => {
child_cons.max.width -|= cur_pos;
child_cons.min.width -|= cur_pos;
},
}
try child.treevent(treev.LayoutSize{
.constraints = child_cons,
// we only do a second pass on this child if it's flex
.final = child.getFlexExpand() == 0,
});
try child_cons.expectFits(child.data.size);
cur_pos += switch (self.direction) {
.vertical => child.data.size.height,
.horizontal => child.data.size.width,
};
max_orth_size = @max(max_orth_size, switch (self.direction) {
.vertical => child.data.size.width,
.horizontal => child.data.size.height,
});
}
}
// second pass, flex widgets
{
const remaining_space = switch (self.direction) {
.vertical => tv.constraints.max.height,
.horizontal => tv.constraints.max.width,
} - cur_pos;
cur_pos = 0;
const flex_extra_space = try selfw.data.allocator.alloc(?f64, self.children.len);
defer selfw.data.allocator.free(flex_extra_space);
@memset(flex_extra_space, null);
var flex_sum: f64 = 0;
for (slice.items(.widget)) |child| {
flex_sum += @floatFromInt(child.getFlexExpand());
}
// calculate the height/width the flex children will get.
for (flex_extra_space, slice.items(.widget)) |*fes, child| {
if (child.getFlexExpand() > 0) {
fes.* = @as(f64, @floatFromInt(child.getFlexExpand())) / flex_sum;
fes.*.? *= @floatFromInt(remaining_space);
}
}
for (
slice.items(.widget),
slice.items(.offset),
flex_extra_space,
) |child, *offset, maybe_fes| {
if (maybe_fes) |fes| {
const child_cons = switch (self.direction) {
.vertical => v: {
const child_height = @as(usize, @intFromFloat(fes)) +
child.data.size.height;
break :v layout.Constraints.tight(.{
.width = child.data.size.width,
.height = child_height,
});
},
.horizontal => h: {
const child_width = @as(usize, @intFromFloat(fes)) +
child.data.size.width;
break :h layout.Constraints.tight(.{
.width = child_width,
.height = child.data.size.height,
});
},
};
try child.treevent(treev.LayoutSize{
.constraints = child_cons,
.final = true,
});
try child_cons.expectFits(child.data.size);
}
offset.* = cur_pos;
cur_pos += switch (self.direction) {
.vertical => child.data.size.height,
.horizontal => child.data.size.width,
};
}
}
selfw.data.size = switch (self.direction) {
.vertical => .{
.height = cur_pos,
.width = max_orth_size,
},
.horizontal => .{
.width = max_orth_size,
.height = cur_pos,
},
};
},
treev.LayoutPosition => {
const slice = self.children.slice();
selfw.data.position = tv.position;
for (
slice.items(.widget),
slice.items(.offset),
slice.items(.pos),
) |child, offset, positioning| {
const child_pos = switch (self.direction) {
.vertical => switch (positioning) {
.left => .{ .x = tv.position.x, .y = tv.position.y + offset },
.center => .{
.x = tv.position.x +
@divTrunc(selfw.data.size.width, 2) - @divTrunc(child.data.size.width, 2),
.y = tv.position.y + offset,
},
.right => .{
.x = tv.position.x + selfw.data.size.width - child.data.size.width,
.y = tv.position.y + offset,
},
},
.horizontal => switch (positioning) {
.left => .{ .x = tv.position.x + offset, .y = tv.position.y },
.center => .{
.x = tv.position.x + offset,
.y = tv.position.y +
@divTrunc(selfw.data.size.height, 2) - @divTrunc(child.data.size.height, 2),
},
.right => .{
.x = tv.position.x + offset,
.y = tv.position.y + selfw.data.size.height - child.data.size.height,
},
},
};
try child.treevent(treev.LayoutPosition{ .position = child_pos });
}
},
treev.Draw => {
const style: *const attreebute.BoxStyle = selfw.getAttreebute(attreebute.BoxStyle) orelse &.{};
try style.background.drawBackground(
tv.painter,
.{ .pos = selfw.data.position, .size = selfw.data.size },
);
try tv.dispatch(selfw);
},
else => try tv.dispatch(selfw),
}
}
pub fn children(self: *Box, _: *Widget) []const *Widget {
return self.children.items(.widget);
}
pub fn addChild(self: *Box, selfw: *Widget, position: ?usize, child: *Widget) !void {
try self.addChildPositioned(selfw, position, child, .left);
}
/// Same as the normal Widget.addChild function, except a positioning for the child is set.
pub fn addChildPositioned(
self: *Box,
selfw: *Widget,
idx: ?usize,
child: *Widget,
positioning: ChildPositioning,
) !void {
if (idx) |i| {
try self.children.insert(selfw.data.allocator, i, .{ .widget = child, .pos = positioning });
} else {
try self.children.append(selfw.data.allocator, .{ .widget = child, .pos = positioning });
}
}
pub fn removeChild(self: *Box, selfw: *Widget, position: ?usize) void {
_ = selfw;
if (position) |pos| {
const old = self.children.get(pos).widget;
self.children.orderedRemove(pos);
return old;
} else {
return self.children.pop().widget;
}
}

86
src/widgets/Button.zig Normal file
View File

@ -0,0 +1,86 @@
//! A simple button widget. This will emit an ButtonActivated backevent when clicked on.
//! This widget requries the ButtonStyle attreebute to be set!
const std = @import("std");
const attreebute = @import("../attreebute.zig");
const backevent = @import("../backevent.zig");
const font = @import("../font.zig");
const treev = @import("../treevent.zig");
const layout = @import("../layout.zig");
const Color = @import("../Color.zig");
const Widget = @import("../widget.zig").Widget;
label_str: []const u8,
chunk: ?font.Chunk,
hovered: bool,
const Button = @This();
pub fn init(alloc: std.mem.Allocator, label: []const u8) !*Widget {
const self = Button{
.label_str = label,
.chunk = null,
.hovered = false,
};
return try Widget.init(alloc, self);
}
pub fn deinit(self: *Button, selfw: *Widget) void {
_ = selfw;
if (self.chunk) |chunk|
chunk.deinit();
}
pub fn treevent(self: *Button, selfw: *Widget, tv: anytype) !void {
switch (@TypeOf(tv)) {
treev.LayoutSize => {
const style = selfw.getAttreebute(attreebute.ButtonStyle) orelse
@panic("The Button widget must have the ButtonStyle attreebute set!");
if (self.chunk == null) {
const curfont = (selfw.getAttreebute(attreebute.CurrentFont) orelse
@panic("The Button widget must have the CurrentFont attreebute set!")).font;
self.chunk = try curfont.layout(self.label_str, style.font_size, .none);
}
selfw.data.size = self.chunk.?.getSize().add(layout.Size.two(style.padding * 2));
},
treev.Draw => {
const style = selfw.getAttreebute(attreebute.ButtonStyle) orelse
@panic("The Button widget must have the ButtonStyle attreebute set!");
if (self.chunk == null) {
const curfont = (selfw.getAttreebute(attreebute.CurrentFont) orelse
@panic("The Button widget must have the CurrentFont attreebute set!")).font;
self.chunk = try curfont.layout(self.label_str, style.font_size, .none);
}
try (if (self.hovered) style.background_hovered else style.background).drawBackground(
tv.painter,
.{ .pos = selfw.data.position, .size = selfw.data.size },
);
try tv.painter.text(
selfw.data.position.add(layout.Position.two(style.padding)),
self.chunk.?,
style.text_color,
);
},
treev.Click => {
if (tv.button == .left and tv.action == .click and tv.isOnWidget(selfw.*)) {
try selfw.backevent(backevent.Backevent.create(
backevent.ButtonActivated{ .btn_widget = selfw },
{},
));
}
},
treev.MouseMove => {
self.hovered = tv.isOnWidget(selfw.*);
},
else => try tv.dispatch(selfw),
}
}

67
src/widgets/Label.zig Normal file
View File

@ -0,0 +1,67 @@
//! A simple text label with a given color and size.
// TODO: use CurrentFont
// TODO: free self.chunk
const std = @import("std");
const font = @import("../font.zig");
const treev = @import("../treevent.zig");
const layout = @import("../layout.zig");
const Color = @import("../Color.zig");
const Widget = @import("../widget.zig").Widget;
font: *font.Font,
chunk: font.Chunk,
color: Color,
size: usize,
const Label = @This();
pub const LabelOptions = struct {
alloc: std.mem.Allocator,
font: *font.Font,
text: []const u8,
size: usize = 32,
color: Color = Color.white(0xff),
};
pub const UpdateOptions = struct {
text: []const u8,
font: ?*font.Font = null,
size: ?usize = null,
color: ?Color = null,
};
pub fn init(opts: LabelOptions) !*Widget {
const self = Label{
.font = opts.font,
.chunk = try opts.font.layout(opts.text, opts.size, .none),
.color = opts.color,
.size = opts.size,
};
errdefer self.chunk.deinit();
return try Widget.init(opts.alloc, self);
}
pub fn update(self: *Label, opts: UpdateOptions) !void {
if (opts.font) |f| self.font = f;
if (opts.size) |s| self.size = s;
if (opts.color) |col| self.color = col;
const oldchunk = self.chunk;
self.chunk = try self.font.layout(opts.text, self.size, .none);
defer oldchunk.deinit();
}
pub fn treevent(self: *Label, selfw: *Widget, tv: anytype) !void {
switch (@TypeOf(tv)) {
treev.LayoutSize => {
selfw.data.size = tv.constraints.clamp(self.chunk.getSize());
},
treev.Draw => {
try tv.painter.text(selfw.data.position, self.chunk, self.color);
},
else => try tv.dispatch(selfw),
}
}