Mondrian (empty) → 0.1.0.0
raw patch · 16 files changed
+2392/−0 lines, 16 filesdep +JuicyPixelsdep +Mondriandep +basesetup-changed
Dependencies added: JuicyPixels, Mondrian, base, bytestring, colour, css-syntax, gl, linear, mtl, scientific, sdl2, stylist-traits, text, typograffiti, unordered-containers, vector
Files
- CHANGELOG.md +5/−0
- LICENSE +674/−0
- Mondrian.cabal +67/−0
- Setup.hs +2/−0
- app/Convert.hs +29/−0
- app/Main.hs +90/−0
- lib/Graphics/Rendering/Rect.hs +50/−0
- lib/Graphics/Rendering/Rect/Backgrounds.hs +276/−0
- lib/Graphics/Rendering/Rect/Border.hs +99/−0
- lib/Graphics/Rendering/Rect/CSS.hs +42/−0
- lib/Graphics/Rendering/Rect/CSS/Backgrounds.hs +333/−0
- lib/Graphics/Rendering/Rect/CSS/Border.hs +169/−0
- lib/Graphics/Rendering/Rect/CSS/Colour.hs +310/−0
- lib/Graphics/Rendering/Rect/Image.hs +100/−0
- lib/Graphics/Rendering/Rect/Types.hs +142/−0
- test/MyLibTest.hs +4/−0
+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for Mondrian++## 0.1.0.0 -- YYYY-mm-dd++* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The GNU General Public License is a free, copyleft license for+software and other kinds of works.++ The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+the GNU General Public License is intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users. We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors. You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++ To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights. Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received. You must make sure that they, too, receive+or can get the source code. And you must show them these terms so they+know their rights.++ Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++ For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software. For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++ Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so. This is fundamentally incompatible with the aim of+protecting users' freedom to change the software. The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable. Therefore, we+have designed this version of the GPL to prohibit the practice for those+products. If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++ Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary. To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++ The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++ 0. Definitions.++ "This License" refers to version 3 of the GNU General Public License.++ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++ A "covered work" means either the unmodified Program or a work based+on the Program.++ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++ 1. Source Code.++ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++ The Corresponding Source for a work in source code form is that+same work.++ 2. Basic Permissions.++ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++ 13. Use with the GNU Affero General Public License.++ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU Affero General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++ 14. Revised Versions of this License.++ The Free Software Foundation may publish revised and/or new versions of+the GNU General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU General Public License, you may choose any version ever published+by the Free Software Foundation.++ If the Program specifies that a proxy can decide which future+versions of the GNU General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++ 15. Disclaimer of Warranty.++ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++ 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++ If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++ <program> Copyright (C) <year> <name of author>+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU GPL, see+<http://www.gnu.org/licenses/>.++ The GNU General Public License does not permit incorporating your program+into proprietary programs. If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library. If this is what you want to do, use the GNU Lesser General+Public License instead of this License. But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ Mondrian.cabal view
@@ -0,0 +1,67 @@+cabal-version: >=1.10+-- Initial package description 'Mondrian.cabal' generated by 'cabal init'.+-- For further documentation, see http://haskell.org/cabal/users-guide/++name: Mondrian+version: 0.1.0.0+synopsis: Renders backgrounds & borders+-- description:+homepage: https://argonaut-constellation.org/+-- bug-reports:+license: GPL-3+license-file: LICENSE+author: Adrian Cochrane+maintainer: ~alcinnz/Mondrian@todo.argonaut-constellation.org+-- copyright:+category: Graphics+build-type: Simple+extra-source-files: CHANGELOG.md++library+ exposed-modules: Graphics.Rendering.Rect,+ Graphics.Rendering.Rect.Backgrounds,+ Graphics.Rendering.Rect.Border,+ Graphics.Rendering.Rect.Image,+ Graphics.Rendering.Rect.CSS,+ Graphics.Rendering.Rect.CSS.Colour,+ Graphics.Rendering.Rect.CSS.Backgrounds,+ Graphics.Rendering.Rect.CSS.Border+ other-modules: Graphics.Rendering.Rect.Types+ -- other-extensions:+ build-depends: base >=4.13 && <5, stylist-traits >= 0.1.3.1 && < 1,+ css-syntax, colour >= 2.3.6 && < 3, scientific, text,+ bytestring, typograffiti >=0.2 && <0.4, linear,+ gl, vector, mtl,+ unordered-containers>=0.2 && <1, JuicyPixels >=3.0 && <4+ hs-source-dirs: lib+ default-language: Haskell2010++ ghc-options: -Wall++executable Mondrian+ main-is: Main.hs+ -- other-modules:+ -- other-extensions:+ build-depends: base >=4.13 && <5, Mondrian, sdl2 >= 2.5.4, gl, linear,+ stylist-traits, text, css-syntax, JuicyPixels+ hs-source-dirs: app+ default-language: Haskell2010++ ghc-options: -Wall++executable Convert+ main-is: Convert.hs+ build-depends: base >= 4.13 && <5, JuicyPixels+ hs-source-dirs: app+ default-language: Haskell2010++ ghc-options: -Wall++test-suite Mondrian-test+ default-language: Haskell2010+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: MyLibTest.hs+ build-depends: base >=4.13 && <5++ ghc-options: -Wall
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ app/Convert.hs view
@@ -0,0 +1,29 @@+module Main where++import Codec.Picture (readImage, savePngImage, DynamicImage(..), Image, PixelF)+import Codec.Picture.Types (promoteImage, convertImage, pixelMap)+import System.Environment (getArgs)++main :: IO ()+main = do+ [path] <- getArgs+ Right img <- readImage path+ savePngImage "out.png" $ convertDyn img++-- Convert pixels to some flavour of RGBA+convertDyn :: DynamicImage -> DynamicImage+convertDyn (ImageY8 img) = ImageRGBA8 $ promoteImage img+convertDyn (ImageY16 img) = ImageRGBA16 $ promoteImage img+convertDyn (ImageY32 img) =+ ImageRGBF $ promoteImage (pixelMap fromIntegral img :: Image PixelF)+convertDyn (ImageYF img) = ImageRGBF $ promoteImage img+convertDyn (ImageYA8 img) = ImageRGBA8 $ promoteImage img+convertDyn (ImageYA16 img) = ImageRGBA16 $ promoteImage img+convertDyn (ImageRGB8 img) = ImageRGB8 img+convertDyn (ImageRGB16 img) = ImageRGB16 img+convertDyn (ImageRGBF img) = ImageRGBF img+convertDyn (ImageRGBA8 img) = ImageRGBA8 img+convertDyn (ImageRGBA16 img) = ImageRGBA16 img+convertDyn (ImageYCbCr8 img) = ImageRGB8 $ convertImage img+convertDyn (ImageCMYK8 img) = ImageRGB8 $ convertImage img+convertDyn (ImageCMYK16 img) = ImageRGB16 $ convertImage img
+ app/Main.hs view
@@ -0,0 +1,90 @@+{-# LANGUAGE OverloadedStrings #-}+module Main where++import Graphics.Rendering.Rect+import Stylist.Parse (parseProperties')+import Stylist (PropertyParser(..))+import Data.Text (Text, pack, unpack)+import Data.CSS.Syntax.Tokens (tokenize, serialize, Token(Whitespace))++import SDL hiding (trace)+import Graphics.GL.Core32+import System.Environment (getArgs)++import Data.Function (fix)+import Control.Monad (unless)+import Control.Monad.IO.Class (MonadIO (..))++import Codec.Picture (DynamicImage(..), PixelRGBA8(..),+ readImage, generateImage)++import Debug.Trace (trace) -- To warn about invalid args++parseStyle :: PropertyParser p => String -> p+parseStyle syn+ | (ret, []) <- parseProperties' toks = apply ret+ | (ret, rest) <- parseProperties' toks =+ trace ("Extraneous chars: " ++ unpack (serialize rest)) $ apply ret+ where+ toks = tokenize $ pack syn+ apply ((key, val):props)+ | Just self' <- longhand self self key val' = self'+ | props'@(_:_) <- shorthand self key val' = apply (props' ++ props)+ | otherwise = trace ("Unsupported property " ++ unpack key) self+ where+ self = apply props+ val' = filter (/= Whitespace) val+ apply [] = temp++orthoProjection :: (Fractional a1, Integral a2) => V2 a2 -> M44 a1+orthoProjection (V2 ww wh) =+ let (hw,hh) = (fromIntegral ww, fromIntegral wh)+ in ortho 0 hw hh 0 0 1++main :: IO ()+main = do+ SDL.initializeAll+ args <- getArgs+ let style :: RectStyle Text+ style = case args of+ [] -> trace "Using blank styles, should see blank screen!" temp+ [arg] -> parseStyle arg+ (arg:_) -> trace "Extraneous commandline args!" $ parseStyle arg++ let openGL = defaultOpenGL { glProfile = Core Debug 3 3 }+ wcfg = defaultWindow {+ windowInitialSize = V2 640 480,+ windowGraphicsContext = OpenGLContext openGL,+ windowResizable = True+ }+ w <- createWindow "Mondrian" wcfg+ _ <- glCreateContext w++ atlas <- atlasFromStyles loadImage [style]+ let style' = styleResolveImages atlas style++ render <- renderRects+ fix $ \loop -> do+ events <- fmap eventPayload <$> pollEvents+ liftIO $ glClearColor 1 1 1 1+ liftIO $ glClear GL_COLOR_BUFFER_BIT++ sz@(V2 dw dh) <- liftIO $ glGetDrawableSize w+ liftIO $ glViewport 0 0 (fromIntegral dw) (fromIntegral dh)++ let rect = Rect 0 0 (fromIntegral dw) (fromIntegral dh)+ rects = Rects (shrink1 rect 150) (shrink1 rect 100) (shrink1 rect 50) rect++ render style' rects $ orthoProjection sz++ liftIO $ glSwapWindow w+ unless (QuitEvent `elem` events) loop++loadImage :: Text -> IO DynamicImage+loadImage path = do+ ret <- readImage $ unpack path+ return $ case ret of+ Right x -> x+ Left _ -> ImageRGBA8 $ generateImage transparent 1 1+transparent :: p1 -> p2 -> PixelRGBA8+transparent _ _ = PixelRGBA8 0 0 0 0
+ lib/Graphics/Rendering/Rect.hs view
@@ -0,0 +1,50 @@+module Graphics.Rendering.Rect(Rect(..), Rects(..), shrink, shrink1, renderRects,+ RectStyle(..), colour, border,+ Backgrounds(..), Pattern(..), Resize(..), Length(..), RadialShape(..),+ Border(..), BorderStyle(..), topColour, rightColour, bottomColour, leftColour,+ Atlas, buildAtlas, atlasFromStyles, Texture, styleResolveImages) where++import Graphics.Rendering.Rect.CSS+import Graphics.Rendering.Rect.Backgrounds+import Graphics.Rendering.Rect.Types+import Graphics.Rendering.Rect.Image+import Graphics.Rendering.Rect.Border++import Linear (M44)+import Control.Monad.IO.Class (MonadIO)++import Codec.Picture (DynamicImage)+import Data.Text (Text)+import Data.List (nub)++shrink :: Rect -> Float -> Float -> Float -> Float -> Rect+shrink self dLeft dTop dRight dBottom =+ Rect (left self + dLeft) (top self + dTop)+ (right self - dRight) (bottom self - dBottom)+shrink1 :: Rect -> Float -> Rect+shrink1 self d = shrink self d d d d++renderRects :: (MonadIO m, MonadIO n) =>+ n (RectStyle Texture -> Rects -> M44 Float -> m ())+renderRects = do+ bg <- renderBackgrounds+ frame <- renderBorder+ return $ \style rects mat -> do+ bg (backgrounds style) rects mat+ frame (border style) rects mat++styleResolveImages :: Atlas -> RectStyle Text -> RectStyle Texture+styleResolveImages atlas self =+ let textures = map atlasLookup' $ image $ backgrounds self+ in self { backgrounds = (backgrounds self) { image = textures } }+ where+ atlasLookup' None = None+ atlasLookup' (Img path) = Img $ atlasLookup path atlas+ atlasLookup' (Linear a b) = Linear a b+ atlasLookup' (Radial a b cc d) = Radial a b cc d+ atlasLookup' (Conical a b cc) = Conical a b cc++atlasFromStyles :: MonadIO m =>+ (Text -> IO DynamicImage) -> [RectStyle Text] -> m Atlas+atlasFromStyles cb styles =+ buildAtlas cb $ nub [path | s <- styles, Img path <- image $ backgrounds s]
+ lib/Graphics/Rendering/Rect/Backgrounds.hs view
@@ -0,0 +1,276 @@+module Graphics.Rendering.Rect.Backgrounds(Backgrounds(..), Pattern(..),+ RadialShape(..), Resize(..), Length(..), Extent(..),+ resolveSize, renderBackgrounds) where++import Graphics.Rendering.Rect.CSS.Backgrounds+import Graphics.Rendering.Rect.Types+import Graphics.Rendering.Rect.Image (Texture(texSize), textureSetRepeat)+import qualified Data.ByteString.Char8 as B8+import Linear (M44, V2(..))++import Control.Monad.IO.Class (MonadIO(..))+import Data.Maybe (fromMaybe, listToMaybe)+import Control.Monad (forM)++baseFragmentShader :: B8.ByteString+baseFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "out vec4 fcolour;",+ "uniform vec4 colour;",+ "void main() { fcolour = colour; }"+ ]++imageFragmentShader :: B8.ByteString+imageFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "in vec2 coord;",+ "out vec4 fcolour;",+ "uniform vec2 pos;",+ "uniform sampler2D image;",+ "uniform vec2 size;",+ "void main() { fcolour = texture(image, coord/size - pos/size); }"+ ]++linearFragmentShader :: B8.ByteString+linearFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "in vec2 coord;",+ "out vec4 fcolour;",+ "uniform vec2 size;",+ "uniform vec4 stops[10];",+ "uniform float stopPoints[10];",+ "uniform int nStops;",+ "uniform float angle;",+ "",+ "void main() {",+ " vec2 pos = coord/size;", -- Range 0..1+ " pos -= 0.5; pos *= 2;", -- Range -1..1+ " float a = pos.x*sin(angle) + pos.y*-cos(angle);", -- Range -1..1+ " a /= 2; a += 0.5;", -- Range 0..1+ "",+ " int i = 0;",+ -- Workaround for buggy GPU drivers on test machine.+ " if (1 < nStops - 1 && a > stopPoints[1]) i = 1;",+ " if (2 < nStops - 1 && a > stopPoints[2]) i = 2;",+ " if (3 < nStops - 1 && a > stopPoints[3]) i = 3;",+ " if (4 < nStops - 1 && a > stopPoints[4]) i = 4;",+ " if (5 < nStops - 1 && a > stopPoints[5]) i = 5;",+ " if (6 < nStops - 1 && a > stopPoints[6]) i = 6;",+ " if (7 < nStops - 1 && a > stopPoints[7]) i = 7;",+ " if (8 < nStops - 1 && a > stopPoints[8]) i = 8;",+ "",+ " a = smoothstep(stopPoints[i], stopPoints[i+1], a);",+ " fcolour = mix(stops[i], stops[i+1], a);",+ "}"+ ]++radialFragmentShader :: B8.ByteString+radialFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "in vec2 coord;",+ "out vec4 fcolour;",+ "uniform vec2 size;",+ "uniform vec2 extent;",+ "uniform vec2 center;",+ "uniform vec4 stops[10];",+ "uniform float stopPoints[10];",+ "uniform int nStops;",+ "",+ "void main() {",+ " float a = distance(coord/extent, center/size) * 2;",+ "",+ " int i = 0;",+ -- Workaround for buggy GPU drivers on test machine.+ " if (1 < nStops - 1 && a > stopPoints[1]) i = 1;",+ " if (2 < nStops - 1 && a > stopPoints[2]) i = 2;",+ " if (3 < nStops - 1 && a > stopPoints[3]) i = 3;",+ " if (4 < nStops - 1 && a > stopPoints[4]) i = 4;",+ " if (5 < nStops - 1 && a > stopPoints[5]) i = 5;",+ " if (6 < nStops - 1 && a > stopPoints[6]) i = 6;",+ " if (7 < nStops - 1 && a > stopPoints[7]) i = 7;",+ " if (8 < nStops - 1 && a > stopPoints[8]) i = 8;",+ "",+ " a = smoothstep(stopPoints[i], stopPoints[i+1], a);",+ " fcolour = mix(stops[i], stops[i+1], a);",+ "}"+ ]+circleFragmentShader :: B8.ByteString+circleFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "in vec2 coord;",+ "out vec4 fcolour;",+ "uniform vec2 center;",+ "uniform float radius;",+ "uniform vec4 stops[10];",+ "uniform float stopPoints[10];",+ "uniform int nStops;",+ "",+ "void main() {",+ " float a = distance(coord, center)/radius;",+ "",+ " int i = 0;",+ -- Workaround for buggy GPU drivers on test machine.+ " if (1 < nStops - 1 && a > stopPoints[1]) i = 1;",+ " if (2 < nStops - 1 && a > stopPoints[2]) i = 2;",+ " if (3 < nStops - 1 && a > stopPoints[3]) i = 3;",+ " if (4 < nStops - 1 && a > stopPoints[4]) i = 4;",+ " if (5 < nStops - 1 && a > stopPoints[5]) i = 5;",+ " if (6 < nStops - 1 && a > stopPoints[6]) i = 6;",+ " if (7 < nStops - 1 && a > stopPoints[7]) i = 7;",+ " if (8 < nStops - 1 && a > stopPoints[8]) i = 8;",+ "",+ " a = smoothstep(stopPoints[i], stopPoints[i+1], a);",+ " fcolour = mix(stops[i], stops[i+1], a);",+ "}"+ ]++conicFragmentShader :: B8.ByteString+conicFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "in vec2 coord;",+ "out vec4 fcolour;",+ "uniform vec2 center;",+ "uniform float angle;",+ "uniform vec4 stops[10];",+ "uniform float stopPoints[10];",+ "uniform int nStops;",+ "",+ "void main() {",+ " vec2 v = coord - center;",+ " float a = atan(v.x, -v.y) - angle;",+ " float turn = 2*radians(180);",+ " a = fract(a/turn);",+ "",+ " int i = 0;",+ -- Workaround for buggy GPU drivers on test machine.+ " if (1 < nStops - 1 && a > stopPoints[1]) i = 1;",+ " if (2 < nStops - 1 && a > stopPoints[2]) i = 2;",+ " if (3 < nStops - 1 && a > stopPoints[3]) i = 3;",+ " if (4 < nStops - 1 && a > stopPoints[4]) i = 4;",+ " if (5 < nStops - 1 && a > stopPoints[5]) i = 5;",+ " if (6 < nStops - 1 && a > stopPoints[6]) i = 6;",+ " if (7 < nStops - 1 && a > stopPoints[7]) i = 7;",+ " if (8 < nStops - 1 && a > stopPoints[8]) i = 8;",+ "",+ " a = smoothstep(stopPoints[i], stopPoints[i+1], a);",+ " fcolour = mix(stops[i], stops[i+1], a);",+ "}"+ ]++renderBackgrounds :: (MonadIO m, MonadIO n) =>+ n (Backgrounds Texture -> Rects -> M44 Float -> m ())+renderBackgrounds = do+ base <- renderRectWith baseFragmentShader ["colour"]+ layer <- renderRectWith imageFragmentShader ["size", "pos"]+ linear <- renderRectWith linearFragmentShader ["size", "angle",+ "stops", "stopPoints", "nStops"]+ ellipse <- renderRectWith radialFragmentShader ["size", "extent", "center",+ "stops", "stopPoints", "nStops"]+ circle <- renderRectWith circleFragmentShader ["center", "radius",+ "stops", "stopPoints", "nStops"]+ conic <- renderRectWith conicFragmentShader ["center", "angle",+ "stops", "stopPoints", "nStops"]+ return $ \self a b -> do+ base [] [c $ background self] (headDef borderBox $ clip self)+ (headDef paddingBox $ origin self) a b+ let layers = image self `zip` (clip self ++ repeat borderBox)+ `zip` (bgSize self ++ repeat (Size Auto Auto))+ `zip` (origin self ++ repeat paddingBox)+ `zip` (bgPos self ++ repeat (Absolute 0, Absolute 0))+ `zip` (bgRepeat self ++ repeat (True, True))+ _<-forM layers $ \(((((pat0, clip0), size0), origin0), pos0), repeat0) ->+ case pat0 of+ None -> return ()+ Img img0 -> do+ let sz = resolveSize (size $ clip0 a) (texSize img0) size0+ let pos' = (v2$l2f' pos0$size$clip0 a) - (v2$l2f' pos0 sz)+ textureSetRepeat img0 repeat0+ layer [img0] [u $ v2 sz, u pos'] clip0 origin0 a b+ Linear angle stops -> let size' = size $ clip0 a in linear [] [+ u $ v2 $ size', u angle, cs 10 $ map fst stops,+ us $ ls2fs size' $ map snd $ take 10 stops, u $ length stops+ ] clip0 origin0 a b+ -- FIXME: Incorporate resolveEllipseExtent without messing up center+ Radial Ellipse ext org stops -> let sz@(_,h) = size $ clip0 a in+ let (org', ext') = resolveEllipseExtent sz org ext in ellipse [] [+ u $ v2 sz, u $ v2 ext', u $ v2 org', cs 10 $ map fst stops,+ us $ ls2fs (0,h/2) $ map snd $ take 10 stops, u $ length stops+ ] clip0 origin0 a b+ Radial Circle ext org stops -> let sz@(w,h) = size $ clip0 a+ in let (org', r) = resolveCircleExtent sz org ext in circle [] [+ u $ v2 org', u r, cs 10 $ map fst stops,+ us $ ls2fs (0,min w h/2) $ map snd $ take 10 stops,+ u $ length stops+ ] clip0 origin0 a b+ Conical angle org stops -> let sz = size $ clip0 a in conic [] [+ u $ v2 $ l2f' org sz, u angle, cs 10 $ map fst stops,+ us $ ls2fs (0,2*pi) $ map snd $ take 10 stops, u $ length stops+ ] clip0 origin0 a b+ return ()++headDef :: c -> [c] -> c+headDef def = fromMaybe def . listToMaybe+v2 :: (a, a) -> V2 a+v2 = uncurry V2+-- Easier to express this algorithm on CPU-side...+ls2fs :: (Float, Float) -> [Length] -> [Float]+ls2fs (_,h) ls = resolveAutos 0 $ inner True 0 ls+ where+ -- https://drafts.csswg.org/css-images/#color-stop-fixup Step 1.+ inner True _ (Auto:ls') = Scale 0:inner False 0 ls'+ inner _ _ [Auto] = [Scale 1]+ -- Step 2+ inner _ prev (Scale x:ls') | x < prev = Scale prev:inner False prev ls'+ inner _ prev (Absolute x:ls') | x/h < prev = Scale prev:inner False prev ls'+ inner _ _ (Scale x:ls') = Scale x:inner False x ls'+ inner _ _ (Absolute x:ls') = Absolute x:inner False (x/h) ls'+ inner _ prev (Auto:ls') = Auto:inner False prev ls'+ inner _ _ [] = []+ -- Step 3+ resolveAutos :: Float -> [Length] -> [Float]+ resolveAutos _ (Scale x:ls') = x:resolveAutos x ls'+ resolveAutos _ (Absolute x:ls') = (x/h):resolveAutos (x/h) ls'+ resolveAutos _ [] = []+ resolveAutos prev ls0 = [prev + succ i*grad | i <- [0..n - 1]] ++ fs+ where+ (autos, ls') = span (==Auto) ls0+ n = toEnum $ length autos+ fs = resolveAutos 0 ls' -- Doesn't matter if prev's in another branch...+ next | (x:_) <- fs = x+ | otherwise = 1 -- Step 1 should've taken care of this...+ grad = (next - prev)/(n + 1)++l2f :: Length -> Float -> Float+l2f Auto x = x/2+l2f (Scale x) y = x*y+l2f (Absolute x) _ = x+l2f' :: (Length, Length) -> (Float, Float) -> (Float, Float)+l2f' (x,y) (w,h) = (l2f x w, l2f y h)++resolveEllipseExtent :: (Float, Float) -> (Length, Length) -> Extent ->+ ((Float, Float), (Float, Float))+resolveEllipseExtent sz@(x',y') pos ext = ((x, y), inner ext)+ where+ (x,y) = l2f' pos sz+ horiz = [x, x' - x]+ vert = [y, y' - y]+ inner (Extent s t) = (l2f s x, l2f t y)+ -- FIXME: How to calculate closest/farthest-corner?+ -- Spec just says keep this aspect ratio.+ inner ClosestCorner = (minimum horiz * 2, minimum vert * 2)+ inner ClosestSide = (minimum horiz * 2, minimum vert * 2)+ inner FarthestCorner = (maximum horiz * 2, maximum vert * 2)+ inner FarthestSide = (maximum horiz * 2, maximum vert * 2)+resolveCircleExtent :: (Float, Float) -> (Length, Length) -> Extent ->+ ((Float, Float), Float)+resolveCircleExtent sz@(x',y') pos ext = ((x, y), inner ext)+ where+ (x,y) = l2f' pos sz+ sides = [x, x' - x, y, y' - y]+ corners = [hypot x y, hypot x $ y'-y, hypot y $ x'-x, hypot (x'-x) (y'-y)]+ hypot a b = sqrt $ a*a + b*b+ inner (Extent a _) = l2f a y -- Should be absolute...+ inner ClosestCorner = minimum corners+ inner ClosestSide = minimum sides+ inner FarthestCorner = maximum corners+ inner FarthestSide = maximum sides
+ lib/Graphics/Rendering/Rect/Border.hs view
@@ -0,0 +1,99 @@+module Graphics.Rendering.Rect.Border(renderBorder, Border(..), BorderStyle(..),+ topColour, rightColour, bottomColour, leftColour) where++import Graphics.Rendering.Rect.CSS.Border+import Graphics.Rendering.Rect.Types+import qualified Data.ByteString.Char8 as B8+import Control.Monad.IO.Class (MonadIO(..))+import Linear (M44)++borderFragmentShader :: B8.ByteString+borderFragmentShader = B8.pack $ unlines [+ "#version 330 core",+ "uniform float widths[4];",+ "uniform vec4 colours[4];",+ "uniform int styles[5];",+ "uniform vec2 boxSize;",+ "in vec2 coord;",+ "out vec4 fcolour;",+ "",+ "const int TOP = 0;",+ "const int RIGHT = 1;",+ "const int BOTTOM = 2;",+ "const int LEFT = 3;",+ "const int NONE = 4;",+ "",+ "const int NOBORDER = 0;",+ "const int SOLID = 1;",+ "const int DASHED = 2;",+ "const int DOTTED = 3;",+ "const int DOUBLE = 4;",+ "const int GROOVE = 5;",+ "const int RIDGE = 6;",+ "const int INSET = 7;",+ "const int OUTSET = 8;",+ "",+ "bool inTrap(float x, float y, float width, int height, int left, int right) {",+ " float a = y/widths[height];",+ " return a*widths[left] <= x && x <= width - widths[right]*a;",+ "}",+ "",+ "void main() {",+ " int side = NONE;",+ " if (coord.y < abs(widths[TOP]) &&",+ " inTrap(coord.x, coord.y, boxSize.x, TOP, LEFT, RIGHT))",+ " side = TOP;",+ " else if (coord.x < abs(widths[LEFT]) &&",+ " inTrap(coord.y, coord.x, boxSize.y, LEFT, TOP, BOTTOM))",+ " side = LEFT;",+ " else if (boxSize.x - coord.x < abs(widths[RIGHT]) &&",+ " inTrap(coord.y, boxSize.x-coord.x, boxSize.y, RIGHT,TOP,BOTTOM))",+ " side = RIGHT;",+ " else if (boxSize.y - coord.y < abs(widths[BOTTOM])) side = BOTTOM;",+ "",+ " vec2 pos = coord;",+ " if (side == RIGHT || side == BOTTOM) pos = boxSize - coord;",+ " if (side == LEFT || side == RIGHT) pos = pos.yx;",+ "",+ " int segment = int(floor(pos.x/widths[side]/2));",+ " float width = widths[side];",+ " vec2 dotCenter = vec2(segment*width*2 + width, width/2);",+ " int stroke3 = int(floor(3*pos.y/widths[side]));",+ " int stroke = int(floor(2*pos.y/widths[side]));",+ " bool topleft = side == TOP || side == LEFT;",+ " if (!topleft) stroke = abs(1 - stroke);",+ " if (styles[side] == SOLID) fcolour = colours[side];",+ " else if (styles[side] == DASHED)",+ " fcolour = segment % 2 == 0 ? colours[side] : vec4(0);",+ " else if (styles[side] == DOTTED)",+ " fcolour = distance(pos, dotCenter) < widths[side]/2 ?",+ " colours[side] : vec4(0);",+ " else if (styles[side] == DOUBLE && stroke3 != 1) fcolour = colours[side];",+ " else if (styles[side] == GROOVE)",+ " fcolour = colours[side] + vec4(stroke == 0 ? -0.1 : +0.1);",+ " else if (styles[side] == RIDGE)",+ " fcolour = colours[side] + vec4(stroke == 0 ? +0.1 : -0.1);",+ " else if (styles[side] == INSET)",+ " fcolour = colours[side] + vec4(topleft ? -0.2 : +0.2);",+ " else if (styles[side] == OUTSET)",+ " fcolour = colours[side] + vec4(topleft ? +0.2 : -0.2);",+ " else fcolour = vec4(0.0);",+ "}"+ ]++renderBorder :: (MonadIO m, MonadIO n) => n (Border -> Rects -> M44 Float -> m ())+renderBorder = do+ inner <- renderRectWith borderFragmentShader [+ "widths[0]", "widths[1]", "widths[2]", "widths[3]",+ "colours[0]", "colours[1]", "colours[2]", "colours[3]",+ "styles[0]", "styles[1]", "styles[2]", "styles[3]", "styles[4]"]+ return $ \self rects -> let (b, p) = (borderBox rects, paddingBox rects)+ in inner [] [+ u $ top p - top b, u $ right b - right p,+ u $ bottom b - bottom p, u $ left p - left b,+ c $ topColour self, c $ rightColour self,+ c $ bottomColour self, c $ leftColour self,+ u $ fromEnum $ topStyle self, u $ fromEnum $ rightStyle self,+ u $ fromEnum $ bottomStyle self, u $ fromEnum $ leftStyle self,+ u (0 :: Int)+ ] borderBox borderBox rects
+ lib/Graphics/Rendering/Rect/CSS.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE OverloadedStrings, RecordWildCards, FlexibleInstances #-}+module Graphics.Rendering.Rect.CSS(RectStyle(..), colour, border) where++import Stylist (PropertyParser(..))+import Graphics.Rendering.Rect.CSS.Colour (ColourPallet(foreground))+import Graphics.Rendering.Rect.CSS.Backgrounds (Backgrounds(..))+import Graphics.Rendering.Rect.CSS.Border (Border(..))+import Data.Text (Text)+import Data.Colour(AlphaColour)++data RectStyle img = RectStyle {+ colours :: ColourPallet,+ backgrounds :: Backgrounds img,+ border' :: Border+} deriving (Eq, Show, Read)+colour :: RectStyle img -> AlphaColour Float+colour = foreground . colours+border :: RectStyle img -> Border+border self = (border' self) { borderPallet = colours self }++instance PropertyParser (RectStyle Text) where+ temp = RectStyle { colours = temp, backgrounds = temp, border' = temp }+ inherit RectStyle {..} = RectStyle {+ colours = inherit colours, backgrounds = temp, border' = temp+ }+ priority RectStyle {..} =+ priority colours ++ priority backgrounds ++ priority border'++ shorthand self key value+ | ret@(_:_) <- shorthand (backgrounds self) key value = ret+ | ret@(_:_) <- shorthand (border self) key value = ret+ | Just _ <- longhand self self key value = [(key, value)]+ | otherwise = []+ longhand parent self key value+ | Just ret <- longhand (backgrounds parent) { pallet = colours self }+ (backgrounds self) { pallet = colours self } key value =+ Just self { backgrounds = ret }+ | Just ret <- longhand (colours parent) (colours self) key value =+ Just self { colours = ret }+ | Just ret <- longhand (border parent) (border self) key value =+ Just self { border' = ret }+ | otherwise = Nothing
+ lib/Graphics/Rendering/Rect/CSS/Backgrounds.hs view
@@ -0,0 +1,333 @@+{-# LANGUAGE OverloadedStrings, FlexibleInstances #-}+module Graphics.Rendering.Rect.CSS.Backgrounds (Backgrounds(..),+ Pattern(..), RadialShape(..), Extent(..),+ Resize(..), Length(..), resolveSize) where++import Stylist (PropertyParser(..), parseUnorderedShorthand, parseOperands)+import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..))+import Data.Maybe (isJust, catMaybes)+import Data.Text (Text)+import Data.Scientific (scientific, toRealFloat)++import Graphics.Rendering.Rect.CSS.Colour (ColourPallet, parseColour)+import Data.Colour (AlphaColour, transparent)+import Graphics.Rendering.Rect.Types (Rects(..), Rect(..))++data Backgrounds img = Backgrounds {+ pallet :: ColourPallet,+ background :: C,+ clip :: [Rects -> Rect],+ origin :: [Rects -> Rect],+ image :: [Pattern img],+ bgPos :: [(Length, Length)],+ bgSize :: [Resize],+ bgRepeat :: [(Bool, Bool)]+} deriving (Eq, Show, Read)++type C = AlphaColour Float++data Pattern img = None | Img img | Linear Float [(C, Length)]+ | Radial RadialShape Extent (Length, Length) [(C, Length)]+ | Conical Float (Length, Length) [(C, Length)]+ deriving (Eq, Show, Read)+data RadialShape = Circle | Ellipse deriving (Eq, Show, Read)+data Extent = Extent Length Length | ClosestCorner+ | ClosestSide | FarthestCorner | FarthestSide deriving (Eq, Show, Read)++-- We need to resolve images before we can compute the actual lengths!+data Resize = Cover | Contain | Size Length Length deriving (Eq, Show, Read)+data Length = Absolute Float | Scale Float | Auto deriving (Eq, Show, Read)++instance PropertyParser (Backgrounds Text) where+ temp = Backgrounds {+ pallet = temp, background = transparent, clip = [borderBox],+ image = [None], bgSize = [Size Auto Auto], origin = [paddingBox],+ bgPos = [(Absolute 0, Absolute 0)], bgRepeat = [(True, True)]+ }+ inherit _ = temp+ priority _ = []++ longhand _ self@Backgrounds{ pallet = c } "background-color" toks+ | Just ([], val) <- parseColour c toks = Just self { background = val }+ longhand _ self "background-clip" t | val@(_:_) <- parseCSSList box t =+ Just self { clip = reverse val }+ longhand _ self@Backgrounds { pallet = pp } "background-image" t+ | val@(_:_) <- parseCSSList inner t = Just self { image = reverse val }+ where+ inner [Ident "none"] = Just None+ inner [Ident "initial"] = Just None+ inner [Url ret] = Just $ Img ret+ inner [Function "url", String ret, RightParen] = Just $ Img ret+ inner (Function "linear-gradient":toks)+ | Just cs@(_:_:_)<-colourStops pp (Comma:toks) = Just $ Linear pi cs+ inner (Function "linear-gradient":Dimension _ x unit:toks)+ | Just s <- lookup unit angularUnits,+ Just cs@(_:_:_) <- colourStops pp toks = Just $ Linear (f x*s) cs+ inner (Function "linear-gradient":Ident "to":Ident a:Ident b:toks)+ | Just angle<-corner a b, Just stops@(_:_:_)<-colourStops pp toks =+ Just $ Linear angle stops+ | Just angle<-corner b a, Just stops@(_:_:_)<-colourStops pp toks =+ Just $ Linear angle stops+ where+ corner "top" "right" = Just $ 0.25*pi+ corner "bottom" "right" = Just $ 0.75*pi+ corner "bottom" "left" = Just $ 1.25*pi+ corner "top" "left" = Just $ 1.75*pi+ corner _ _ = Nothing+ inner (Function "linear-gradient":Ident "to":Ident side:toks)+ | Just angle <- lookup side [+ ("top", 0), ("right", pi/2), ("bottom", pi), ("left", pi*1.5)],+ Just cs@(_:_:_) <- colourStops pp toks = Just $ Linear angle cs+ inner (Function "radial-gradient":toks)+ | Just cs@(_:_:_) <- colourStops pp (Comma:toks) =+ Just $ Radial Ellipse FarthestCorner center cs+ | (shp, org, ext, ts) <- radArgs toks,+ Just cs@(_:_:_) <- colourStops pp ts = Just $ Radial shp ext org cs+ where+ radArgs (Ident s:Ident "at":ts) | Just shape <- radShape s,+ Just (org, ts') <- position ts =+ (shape, org, FarthestCorner, ts')+ radArgs (Ident "at":ts) | Just (org, ts') <- position ts =+ (Ellipse, org, FarthestCorner, ts')+ radArgs (Ident "circle":Ident "at":ts)+ | Just (org, ts') <- position ts = (Circle,org,FarthestCorner,ts')+ radArgs (Ident "circle":ts)+ | Just (_, Ident "at":ts') <- circleExt ts,+ Just (org, stops) <- position ts' =+ (Circle, org, FarthestCorner, stops)+ | Just (_,ts')<-circleExt ts=(Circle,center,FarthestCorner,ts')+ | otherwise = (Circle, center, FarthestCorner, ts)+ radArgs (Ident "ellipse":Ident "at":ts)+ | Just (org,ts')<-position ts=(Ellipse,org,FarthestCorner,ts')+ radArgs (Ident "ellipse":ts)+ | Just (_, Ident "at":ts') <- ellipseExt ts,+ Just (org, stops) <- position ts' =+ (Ellipse, org, FarthestCorner, stops)+ | Just (_,ts')<-ellipseExt ts=(Ellipse,center,FarthestCorner,ts')+ | otherwise = (Ellipse, center, FarthestCorner, ts)+ radArgs ts | Just (_, Ident "at":ts') <- ellipseExt ts,+ Just (org, stops) <- position ts' =+ (Ellipse, org, FarthestCorner, stops)+ | Just (_, Ident "ellipse":Ident "at":ts') <- ellipseExt ts,+ Just (org, stops) <- position ts' =+ (Ellipse, org, FarthestCorner, stops)+ | Just (_, Ident "ellipse":ts') <- ellipseExt ts =+ (Ellipse, center, FarthestCorner, ts')+ | Just (_, Ident "circle":Ident "at":ts') <- circleExt ts,+ Just (org, stops) <- position ts' =+ (Circle, org, FarthestCorner, stops)+ | Just (_, Ident "circle":ts') <- circleExt ts =+ (Circle, center, FarthestCorner, ts')+ | otherwise = (Ellipse, center, FarthestCorner, ts)+ radShape "circle" = Just Circle+ radShape "ellipse" = Just Ellipse+ radShape _ = Nothing+ radExt (Ident "closest-corner":ts) = Just (ClosestCorner, ts)+ radExt (Ident "closest-side":ts) = Just (ClosestSide, ts)+ radExt (Ident "farthest-corner":ts) = Just (FarthestCorner, ts)+ radExt (Ident "farthest-side":ts) = Just (FarthestSide, ts)+ radExt _ = Nothing+ ellipseExt ts | Just ret <- radExt ts = Just ret+ ellipseExt (Percentage _ x:Percentage _ y:ts) =+ Just (p' x `Extent` p' y, ts)+ ellipseExt (Percentage _ x:Dimension _ y "px":ts) =+ Just (p' x `Extent` f' y, ts)+ ellipseExt (Dimension _ x "px":Percentage _ y:ts) =+ Just (f' x `Extent` p' y, ts)+ ellipseExt (Dimension _ x "px":Dimension _ y "px":ts) =+ Just (f' x `Extent` p' y, ts)+ ellipseExt _ = Nothing+ circleExt (Dimension _ x "px":ts) = Just (f' x `Extent` f' x, ts)+ circleExt ts = radExt ts+ -- NOTE: Not implementing colourspaces yet...+ inner (Function "conic-gradient":Ident "from":Dimension _ x unit:+ Ident "at":ts)+ | Just (org, ts') <- position ts, Just s <- lookup unit angularUnits,+ Just stops@(_:_:_) <- colourStops pp ts' =+ Just $ Conical (f x*s) org stops+ inner (Function "conic-gradient":Ident "from":Dimension _ x unit:ts)+ | Just s <- lookup unit angularUnits,+ Just stops@(_:_:_) <- colourStops pp ts =+ Just $ Conical (f x*s) center stops+ inner (Function "conic-gradient":Ident "at":ts)+ | Just (org, ts') <- position ts,+ Just cs@(_:_:_) <- colourStops pp ts' = Just $ Conical 0 org cs+ inner (Function "conic-gradient":ts)+ | Just stops@(_:_:_) <- colourStops pp (Comma:ts) =+ Just $ Conical 0 center stops+ inner _ = Nothing++ angularUnits = [("deg",pi/180),("grad",pi/200),("rad",1),("turn",2*pi)]+ center = (Scale 0.5, Scale 0.5)+ longhand _ self "background-origin" t | val@(_:_) <- parseCSSList box t =+ Just self { origin = reverse val }+ longhand _ self "background-position" t | val@(_:_) <- parseCSSList position t,+ all (null . snd) val = Just self { bgPos = reverse $ map fst val }+ longhand _ self "background-repeat" t | val@(_:_) <- parseCSSList inner t =+ Just self { bgRepeat = reverse val }+ where+ inner [Ident "initial"] = Just (True, True)+ inner [Ident "repeat-x"] = Just (True, False)+ inner [Ident "repeat-y"] = Just (False, True)+ inner [x] | Just y <- inner' x = Just (y, y)+ inner [x, y] | Just x' <- inner' x, Just y' <- inner' y = Just (x', y')+ inner _ = Nothing+ inner' (Ident "repeat") = Just True+ inner' (Ident "no-repeat") = Just False+ inner' _ = Nothing+ longhand _ self "background-size" t | val@(_:_) <- parseCSSList inner t =+ Just self { bgSize = reverse val }+ where -- TODO: Add shorthand support, after background-position.+ inner [x, y] | Just a <- l x, Just b <- l y = Just $ Size a b+ inner [Ident "contain"] = Just Contain+ inner [Ident "cover"] = Just Cover+ inner [Ident "auto"] = Just $ Size Auto Auto+ inner [Ident "initial"] = Just $ Size Auto Auto+ inner _ = Nothing+ -- NOTE: Leave lowering other units to CatTrap.+ l (Ident "auto") = Just Auto+ l (Dimension _ x "px") = Just $ Absolute $ f x+ l (Percentage _ x) = Just $ Scale $ p x+ l _ = Nothing+ longhand _ _ _ _ = Nothing++ -- The multi-layered shorthand is one source of parsing complexity.+ shorthand self "background" t = catProps $ reverse $ parseCSSList inner t+ where+ catProps [] = []+ catProps (props:pss)+ | Just [Ident "initial"] <- "background-color" `lookup` catProps pss =+ map (catProp $ catProps pss) props+ | otherwise = [] -- Only allow background-color in bottommost layer.+ catProp _ ret@("background-color", _) = ret+ catProp bases (key, val)+ | Just base <- key `lookup` bases = (key, base ++ Comma:val)+ -- Shouldn't happen, `inner` expands all props at least to "initial"!+ | otherwise = (key, val)+ inner toks | ret@(_:_) <- parseUnorderedShorthand self [+ "background-color", "background-clip", "background-image",+ "background-origin", "background-position"+ ] toks = Just ret+ | otherwise = Nothing+ shorthand self key val | Just _ <- longhand self self key val = [(key, val)]+ | otherwise = []++box :: [Token] -> Maybe (Rects -> Rect)+box [Ident "content-box"] = Just contentBox+box [Ident "padding-box"] = Just paddingBox+box [Ident "border-box"] = Just borderBox+box [Ident "initial"] = Just borderBox -- To aid shorthand implementation.+box _ = Nothing++position :: [Token] -> Maybe ((Length, Length), [Token])+position (x:y:ts) = position' x y ts <* position' y x ts <* position' x x (y:ts)+position [x] = position' x x []+position _ = Nothing+position' :: Token -> Token -> [Token] -> Maybe ((Length, Length), [Token])+position' x y ts = case ((case x of+ Ident "left" -> Scale 0+ Ident "center" -> Scale 0.5+ Ident "right" -> Scale 1+ Percentage _ a -> p' a+ Dimension _ a "px" -> f' a+ _ -> Auto,+ case y of+ Ident "top" -> Scale 0+ Ident "center" -> Scale 0.5+ Ident "bottom" -> Scale 1+ Percentage _ a -> p' a+ Dimension _ a "px" -> f' a+ _ -> Auto),+ ts) of+ ((Auto, _), _) -> Nothing+ ((_, Auto), _) -> Nothing+ ret -> Just ret++colourStops :: ColourPallet+ -> [Token] -> Maybe [(AlphaColour Float, Length)]+colourStops _ [RightParen] = Just []+colourStops cs (Comma:toks)+ | Just (Percentage _ x:toks', c) <- parseColour cs toks,+ Just ret <- colourStops cs toks' = Just $ (c, Scale $ p x):ret+ | Just (Dimension _ x "px":toks', c) <- parseColour cs toks,+ Just ret <- colourStops cs toks' = Just $ (c, Absolute $ f x):ret+ | Just (toks', c) <- parseColour cs toks,+ Just ret <- colourStops cs toks' = Just $ (c, Auto):ret+colourStops cs (Comma:Percentage _ x:toks)+ | Just (toks', c) <- parseColour cs toks,+ Just ret <- colourStops cs toks' = Just $ (c, Scale $ p x):ret+colourStops cs (Comma:Dimension _ x "px":toks)+ | Just (toks', c) <- parseColour cs toks,+ Just ret <- colourStops cs toks' = Just $ (c, Absolute $ f x):ret+colourStops _ _ = Nothing++parseCSSList :: ([Token] -> Maybe a) -> [Token] -> [a]+parseCSSList cb toks | all isJust ret = catMaybes ret+ | otherwise = []+ where ret = map cb $ map concat $ splitList [Comma] $ parseOperands toks++f :: NumericValue -> Float+f (NVInteger x) = fromInteger x+f (NVNumber x) = toRealFloat x+p :: NumericValue -> Float+p (NVInteger x) = fromInteger x / 100+-- Do the division while we're in base-10!+p (NVNumber x) = toRealFloat (x/scientific 1 2)+p' :: NumericValue -> Length+p' = Scale . p+f' :: NumericValue -> Length+f' = Absolute . f++------+--- Utils taken from HappStack+------++-- | Repeadly splits a list by the provided separator and collects the results+splitList :: Eq a => a -> [a] -> [[a]]+splitList _ [] = []+splitList sep list = h:splitList sep t+ where (h,t)=split (==sep) list++-- | Split is like break, but the matching element is dropped.+split :: (a -> Bool) -> [a] -> ([a], [a])+split filt s = (x,y)+ where+ (x,y')=break filt s+ y = if null y' then [] else tail y'++------+--- Dynamically-computed properties+------++resolveSize :: (Float, Float) -> (Float, Float) -> Resize -> (Float, Float)+resolveSize (owidth, oheight) (width, height) Contain+ | width > owidth, height*sw > oheight, height > width = (width*sh, height*sh)+ | width > owidth = (width*sw, height*sw)+ | height > oheight = (width*sh, height*sh)+ | height > width = (width*sw, height*sw)+ | otherwise = (width*sh, height*sh)+ where+ sh = oheight/height+ sw = owidth/width+resolveSize (owidth, oheight) (width, height) Cover+ | owidth > width, oheight > height*sw = (width*sh, height*sh)+ | oheight > height, owidth > width*sh = (width*sw, height*sw)+ | owidth > width = (width*sw, height*sw)+ | oheight > height = (width*sh, height*sh)+ | oheight > height*sw = (width*sh, height*sh)+ | owidth > width*sh = (width*sw, height*sw)+ | height > width = (width*sw, height*sw)+ | otherwise = (width*sh, height*sh)+ where+ sh = oheight/height+ sw = owidth/width+resolveSize _ ret (Size Auto Auto) = ret+resolveSize _ (width, height) (Size x y) = (x', y')+ where+ x' | Absolute ret <- x = ret+ | Scale s <- x = width*s+ | Auto <- x = y' * width/height+ y' | Absolute ret <- y = ret+ | Scale s <- y = height*s+ -- NOTE: If Auto,Auto case wasn't handled above this'd be an infinite loop.+ | Auto <- y = x' * height/width
+ lib/Graphics/Rendering/Rect/CSS/Border.hs view
@@ -0,0 +1,169 @@+{-# LANGUAGE OverloadedStrings #-}+module Graphics.Rendering.Rect.CSS.Border(Border(..), BorderStyle(..),+ topColour, rightColour, bottomColour, leftColour) where++import Stylist (PropertyParser(..), parseUnorderedShorthand, parseOperands)+import Data.CSS.Syntax.Tokens (Token(..))+import Graphics.Rendering.Rect.CSS.Colour (ColourPallet(foreground), parseColour)+import Data.Colour (AlphaColour)+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)++data Border = Border {+ borderPallet :: ColourPallet,+ topStyle :: BorderStyle,+ topColour' :: Maybe (AlphaColour Float),+ rightStyle :: BorderStyle,+ rightColour' :: Maybe (AlphaColour Float),+ bottomStyle :: BorderStyle,+ bottomColour' :: Maybe (AlphaColour Float),+ leftStyle :: BorderStyle,+ leftColour' :: Maybe (AlphaColour Float)+} deriving (Eq, Show, Read)++resolveColour :: Border -> Maybe (AlphaColour Float) -> AlphaColour Float+resolveColour self = fromMaybe $ foreground $ borderPallet self+topColour, rightColour, bottomColour, leftColour :: Border -> AlphaColour Float+topColour self = resolveColour self $ topColour' self+rightColour self = resolveColour self $ rightColour' self+bottomColour self = resolveColour self $ bottomColour' self+leftColour self = resolveColour self $ leftColour' self++data BorderStyle = NoBorder | Solid | Dashed | Dotted | Double+ | Groove | Ridge | Inset | Outset deriving (Eq, Show, Read, Enum)++style :: Token -> Maybe BorderStyle+style (Ident "initial") = Just NoBorder+style (Ident "none") = Just NoBorder+style (Ident "hidden") = Just NoBorder+style (Ident "solid") = Just Solid+style (Ident "dashed") = Just Dashed+style (Ident "dotted") = Just Dotted+style (Ident "double") = Just Double+style (Ident "groove") = Just Groove+style (Ident "ridge") = Just Ridge+style (Ident "inset") = Just Inset+style (Ident "outset") = Just Outset+style _ = Nothing++instance PropertyParser Border where+ temp = Border {+ borderPallet = temp,+ topStyle = NoBorder,+ topColour' = Nothing,+ rightStyle = NoBorder,+ rightColour' = Nothing,+ bottomStyle = NoBorder,+ bottomColour' = Nothing,+ leftStyle = NoBorder,+ leftColour' = Nothing+ }+ inherit = const temp+ priority = const []++ longhand _ s "border-top-style" [t] | Just v <- style t = Just s {topStyle=v}+ longhand _ s "border-right-style" [t] | Just v<-style t=Just s {rightStyle=v}+ longhand _ s "border-bottom-style" [t]|Just v<-style t=Just s {bottomStyle=v}+ longhand _ s "border-left-style" [t] | Just v<-style t = Just s {leftStyle=v}+ longhand _ self@Border { borderPallet = cc } "border-top-color" ts+ | Just ([], v) <- parseColour cc ts = Just self { topColour' = Just v }+ longhand _ self@Border { borderPallet = cc } "border-right-color" ts+ | Just ([], v) <- parseColour cc ts = Just self { rightColour' = Just v }+ longhand _ self@Border { borderPallet = cc } "border-bottom-color" ts+ | Just ([], v) <- parseColour cc ts = Just self { bottomColour' = Just v }+ longhand _ self@Border { borderPallet = cc } "border-left-color" ts+ | Just ([], v) <- parseColour cc ts = Just self { leftColour' = Just v }++ -- Should be handled by caller, but for the sake of shorthands...+ longhand _ self "border-top-width" [Dimension _ _ "px"] = Just self+ longhand _ self "border-right-width" [Dimension _ _ "px"] = Just self+ longhand _ self "border-bottom-width" [Dimension _ _ "px"] = Just self+ longhand _ self "border-left-width" [Dimension _ _ "px"] = Just self+ longhand _ _ _ _ = Nothing++ shorthand self "border-width" toks+ | length x > 0 && length x <= 4, (top:right:bottom:left:_) <- cycle x,+ all (validProp self "border-top-width") x =+ [("border-top-width", top), ("border-right-width", right),+ ("border-bottom-width", bottom), ("border-left-width", left)]+ where x = parseOperands toks+ -- Define other border shorthands here to properly handle border-widths+ shorthand self "border" toks = parseUnorderedShorthand self [+ "border-color", "border-style", "border-width"] toks+ shorthand self "border-top" toks = parseUnorderedShorthand self [+ "border-top-color", "border-top-style", "border-top-width"] toks+ shorthand self "border-right" toks = parseUnorderedShorthand self [+ "border-right-color", "border-right-style", "border-right-width"] toks+ shorthand self "border-bottom" toks = parseUnorderedShorthand self [+ "border-bottom-color", "border-bottom-style", "border-bottom-width"] toks+ shorthand self "border-left" toks = parseUnorderedShorthand self [+ "border-left-color", "border-left-style", "border-left-width"] toks+ shorthand self "border-inline" toks = parseUnorderedShorthand self [+ "border-inline-color", "border-inline-style", "border-inline-width"] toks+ shorthand self "border-inline-start" toks = parseUnorderedShorthand self [+ "border-inline-start-color", "border-inline-start-style",+ "border-inline-start-width"] toks+ shorthand self "border-inline-end" toks = parseUnorderedShorthand self [+ "border-inline-end-color", "border-inline-end-style",+ "border-inline-end-width"] toks+ shorthand self "border-block" toks = parseUnorderedShorthand self [+ "border-block-color", "border-block-style", "border-block-width"] toks+ shorthand self "border-block-start" toks = parseUnorderedShorthand self [+ "border-block-start-color", "border-block-start-style",+ "border-block-start-width"] toks+ shorthand self "border-block-end" toks = parseUnorderedShorthand self [+ "border-block-end-color", "border-block-end-style",+ "border-block-end-width"] toks+ shorthand self "border-color" toks+ | length x > 0 && length x <= 4, (top:right:bottom:left:_) <- cycle x,+ all (validProp self "border-top-color") x =+ [("border-top-color", top), ("border-right-color", right),+ ("border-bottom-color", bottom), ("border-left-color", left)]+ where x = parseOperands toks+ shorthand self "border-style" toks+ | length x > 0 && length x <= 4, (top:right:bottom:left:_) <- cycle x,+ all (validProp self "border-top-style") x =+ [("border-top-style", top), ("border-right-style", right),+ ("border-bottom-style", bottom), ("border-left-style", left)]+ where x = parseOperands toks+ shorthand self "border-width" toks+ | length x > 0 && length x <= 4, (top:right:bottom:left:_) <- cycle x,+ all (validProp self "border-top-width") x =+ [("border-top-width", top), ("border-right-width", right),+ ("border-bottom-width", bottom), ("border-left-width", left)]+ where x = parseOperands toks+ shorthand self "border-inline-color" toks+ | length x > 0 && length x <= 2, (s:e:_) <- cycle x,+ all (validProp self "border-inline-start-color") x =+ [("border-inline-start-color", s), ("border-inline-end-color", e)]+ where x = parseOperands toks+ shorthand self "border-inline-style" toks+ | length x > 0 && length x <= 2, (s:e:_) <- cycle x,+ all (validProp self "border-inline-start-style") x =+ [("border-inline-start-style", s), ("border-inline-end-style", e)]+ where x = parseOperands toks+ shorthand self "border-inline-width" toks+ | length x > 0 && length x <= 2, (s:e:_) <- cycle x,+ all (validProp self "border-inline-start-width") x =+ [("border-inline-start-width", s), ("border-inline-end-style", e)]+ where x = parseOperands toks+ shorthand self "border-block-color" toks+ | length x > 0 && length x <= 2, (s:e:_) <- cycle x,+ all (validProp self "border-block-start-color") x =+ [("border-block-start-color", s), ("border-block-end-color", e)]+ where x = parseOperands toks+ shorthand self "border-block-style" toks+ | length x > 0 && length x <= 2, (s:e:_) <- cycle x,+ all (validProp self "border-block-start-style") x =+ [("border-block-start-style", s), ("border-block-end-style", e)]+ where x = parseOperands toks+ shorthand self "border-block-width" toks+ | length x > 0 && length x <= 2, (s:e:_) <- cycle x,+ all (validProp self "border-block-start-width") x =+ [("border-block-start-width", s), ("border-block-end-width", e)]+ where x = parseOperands toks+ shorthand self k v | Just _ <- longhand self self k v = [(k, v)]+ | otherwise = []++validProp :: PropertyParser a => a -> Text -> [Token] -> Bool+validProp self key value = isJust $ longhand self self key value
+ lib/Graphics/Rendering/Rect/CSS/Colour.hs view
@@ -0,0 +1,310 @@+{-# LANGUAGE OverloadedStrings, PatternSynonyms, ViewPatterns #-}+module Graphics.Rendering.Rect.CSS.Colour(ColourPallet(..), parseColour) where++import Data.Colour (Colour, AlphaColour, withOpacity, opaque, transparent)+import Data.Colour.SRGB (sRGB, sRGB24)+import Data.Colour.Names+import Data.Colour.RGBSpace.HSL (hsl)+import Data.Colour.RGBSpace (uncurryRGB)+import Data.Colour.SRGB.Linear (rgb)++import Data.CSS.Syntax.Tokens (Token(..), NumericValue(..))+import Data.Scientific (toRealFloat)+import qualified Data.Text as Txt++import Data.Word (Word8)+import Data.Char (isHexDigit, toLower)+import Data.List (elemIndex)+import Debug.Trace (trace) -- For warning messages.++import Stylist (PropertyParser(..))++hsl' :: RealFrac a => a -> a -> a -> Colour a+hsl' hue s l = uncurryRGB rgb $ hsl hue s l++data ColourPallet = ColourPallet {+ foreground :: AlphaColour Float,+ accent :: AlphaColour Float+} deriving (Read, Show, Eq)++instance PropertyParser ColourPallet where+ temp = ColourPallet { foreground = opaque black, accent = opaque blue }+ inherit = id+ priority _ = ["color", "accent"]++ longhand _ self "color" [Ident "initial"]=Just self {foreground=opaque black}+ longhand _ self "color" toks | Just ([], val) <- parseColour self toks =+ Just self { foreground = val }+ longhand _ self "accent-color" [Ident kw]+ | kw `elem` ["initial", "auto"] = Just self {accent = opaque blue}+ longhand _ self "accent-color" t | Just ([], val) <- parseColour self t =+ Just self { accent = val }+ longhand _ _ _ _ = Nothing+ shorthand self key val | Just _ <- longhand self self key val = [(key, val)]+ | otherwise = []++parseColour :: ColourPallet -> [Token] -> Maybe ([Token], AlphaColour Float)+parseColour _ (Function "rgb":Percentage _ r:Comma:+ Percentage _ g:Comma:Percentage _ b:RightParen:toks) =+ Just (toks, opaque $ sRGB (pc r) (pc g) (pc b))+parseColour _ (Function "rgba":Percentage _ r:Comma:+ Percentage _ g:Comma:Percentage _ b:Comma:a':RightParen:toks)+ | a' /= Ident "none", Just a <- f' a' =+ Just (toks, sRGB (pc r) (pc g) (pc b) `withOpacity` a)+parseColour _ (Function "rgb":Number _ (NVInteger r):Comma:+ Number _ (NVInteger g):Comma:Number _ (NVInteger b):RightParen:toks) =+ Just (toks, opaque $ sRGB24 (w r) (w g) (w b))+parseColour _ (Function "rgba":Number _ (NVInteger r):Comma:+ Number _ (NVInteger g):Comma:Number _ (NVInteger b):Comma:+ a':RightParen:toks) | a' /= Ident "none", Just a <- f' a' =+ Just (toks, sRGB24 (w r) (w g) (w b) `withOpacity` a)++parseColour _ (Function "rgb":r':g':b':RightParen:toks)+ | Just r <- w' r', Just g <- w' g', Just b <- w' b' =+ Just (toks, opaque $ sRGB24 r g b)+parseColour _ (Function "rgb":r':g':b':Delim '/':a':RightParen:toks)+ | Just r <- w' r', Just g <- w' g', Just b <- w' b', Just a <- f' a' =+ Just (toks, sRGB24 r g b `withOpacity` a)+parseColour _ (Hash _ v@(r0 :. r1 :. g0 :. g1 :. b0 :. b1 :. ""):toks)+ | Txt.all isHexDigit v = Just (toks, opaque $ sRGBhex r0 r1 g0 g1 b0 b1)+parseColour _ (Hash _ v@(r0 :. r1 :. g0 :. g1 :. b0 :. b1 :. a0 :. a1 :. ""):toks)+ | Txt.all isHexDigit v =+ Just (toks, sRGBhex r0 r1 g0 g1 b0 b1 `withOpacity` h' a0 a1)+parseColour _ (Hash _ v@(r:.g:.b:.""):toks) | Txt.all isHexDigit v =+ Just (toks, opaque $ sRGBhex r r g g b b)+parseColour _ (Hash _ v@(r:.g:.b:.a:.""):toks) | Txt.all isHexDigit v =+ Just (toks, sRGBhex r r g g b b `withOpacity` h' a a)++parseColour _ (Ident x:toks) | Just x' <- inner $ Txt.toLower x =+ Just (toks, opaque x')+ where+ -- NOTE: Some of these colour names are inconsistant or even offensive.+ -- There are historical reasons for this labelling.+ -- https://www.youtube.com/watch?v=HmStJQzclHc+ inner "aliceblue" = Just aliceblue+ inner "antiquewhite" = Just antiquewhite+ inner "aqua" = Just aqua+ inner "aquamarine" = Just aquamarine+ inner "azure" = Just azure+ inner "beige" = Just beige+ inner "bisque" = Just bisque+ inner "black" = Just black+ inner "blanchedalmond" = Just blanchedalmond+ inner "blue" = Just blue+ inner "blueviolet" = Just blueviolet+ inner "brown" = Just brown+ inner "burlywood" = Just burlywood+ inner "cadetblue" = Just cadetblue+ inner "chartreuse" = Just chartreuse+ inner "chocolate" = Just chocolate+ inner "coral" = Just coral+ inner "cornflowerblue" = Just cornflowerblue+ inner "cornsilk" = Just cornsilk+ inner "crimson" = Just crimson+ inner "cyan" = Just cyan+ inner "darkblue" = Just darkblue+ inner "darkcyan" = Just darkcyan+ inner "darkgoldenrod" = Just darkgoldenrod+ inner "darkgray" = Just darkgray+ inner "darkgrey" = Just darkgrey+ inner "darkgreen" = Just darkgreen+ inner "darkkhaki" = Just darkkhaki+ inner "darkmagenta" = Just darkmagenta+ inner "darkolivegreen" = Just darkolivegreen+ inner "darkorange" = Just darkorange+ inner "darkorchid" = Just darkorchid+ inner "darkred" = Just darkred+ inner "darksalmon" = Just darksalmon+ inner "darkseagreen" = Just darkseagreen+ inner "darkslateblue" = Just darkslateblue+ inner "darkslategray" = Just darkslategray+ inner "darkslategrey" = Just darkslategrey+ inner "darkturquoise" = Just darkturquoise+ inner "darkviolet" = Just darkviolet+ inner "deeppink" = Just deeppink+ inner "deepskyblue" = Just deepskyblue+ inner "dimgray" = Just dimgray+ inner "dimgrey" = Just dimgrey+ inner "dodgerblue" = Just dodgerblue+ inner "firebrick" = Just firebrick+ inner "floralwhite" = Just floralwhite+ inner "forestgreen" = Just forestgreen+ inner "fuchsia" = Just fuchsia+ inner "gainsboro" = Just gainsboro+ inner "ghostwhite" = Just ghostwhite+ inner "gold" = Just gold+ inner "goldenrod" = Just goldenrod+ inner "gray" = Just gray+ inner "grey" = Just grey+ inner "green" = Just green+ inner "greenyellow" = Just greenyellow+ inner "honeydew" = Just honeydew+ inner "hotpink" = Just hotpink+ inner "indianred" = Just indianred+ inner "indigo" = Just indigo+ inner "ivory" = Just ivory+ inner "khaki" = Just khaki+ inner "lavender" = Just lavender+ inner "lavenderblush" = Just lavenderblush+ inner "lawngreen" = Just lawngreen+ inner "lemonchiffon" = Just lemonchiffon+ inner "lightblue" = Just lightblue+ inner "lightcoral" = Just lightcoral+ inner "lightcyan" = Just lightcyan+ inner "lightgoldenrodyellow" = Just lightgoldenrodyellow+ inner "lightgray" = Just lightgray+ inner "lightgrey" = Just lightgrey+ inner "lightgreen" = Just lightgreen+ inner "lightpink" = Just lightpink+ inner "lightsalmon" = Just lightsalmon+ inner "lightseagreen" = Just lightseagreen+ inner "lightskyblue" = Just lightskyblue+ inner "lightslategray" = Just lightslategray+ inner "lightslategrey" = Just lightslategrey+ inner "lightsteelblue" = Just lightsteelblue+ inner "lightyellow" = Just lightyellow+ inner "lime" = Just lime+ inner "limegreen" = Just limegreen+ inner "linen" = Just linen+ inner "magenta" = Just magenta+ inner "maroon" = Just maroon+ inner "mediumaquamarine" = Just mediumaquamarine+ inner "mediumblue" = Just mediumblue+ inner "mediumorchid" = Just mediumorchid+ inner "mediumpurple" = Just mediumpurple+ inner "mediumseagreen" = Just mediumseagreen+ inner "mediumslateblue" = Just mediumslateblue+ inner "mediumspringgreen" = Just mediumspringgreen+ inner "mediumturquoise" = Just mediumturquoise+ inner "mediumvioletred" = Just mediumvioletred+ inner "midnightblue" = Just midnightblue+ inner "mintcream" = Just mintcream+ inner "mistyrose" = Just mistyrose+ inner "moccasin" = Just moccasin+ inner "navajowhite" = Just navajowhite+ inner "navy" = Just navy+ inner "oldlace" = Just oldlace+ inner "olive" = Just olive+ inner "olivedrab" = Just olivedrab+ inner "orange" = Just orange+ inner "orangered" = Just orangered+ inner "orchid" = Just orchid+ inner "palegoldenrod" = Just palegoldenrod+ inner "palegreen" = Just palegreen+ inner "paleturquoise" = Just paleturquoise+ inner "palevioletred" = Just palevioletred+ inner "papayawhip" = Just papayawhip+ inner "peachpuff" = Just peachpuff+ inner "peru" = Just peru+ inner "pink" = Just pink+ inner "plum" = Just plum+ inner "powderblue" = Just powderblue+ inner "purple" = Just purple+ -- Named after CSS pioneer Eric Meyer's late daughter+ inner "rebeccapurple" = Just $ sRGB 102 51 153+ inner "red" = Just red+ inner "rosybrown" = Just rosybrown+ inner "royalblue" = Just royalblue+ inner "saddlebrown" = Just saddlebrown+ inner "salmon" = Just salmon+ inner "sandybrown" = Just sandybrown+ inner "seagreen" = Just seagreen+ inner "seashell" = Just seashell+ inner "sienna" = Just sienna+ inner "silver" = Just silver+ inner "skyblue" = Just skyblue+ inner "slateblue" = Just slateblue+ inner "slategray" = Just slategray+ inner "slategrey" = Just slategrey+ inner "snow" = Just snow+ inner "springgreen" = Just springgreen+ inner "steelblue" = Just steelblue+ inner "tan" = Just Data.Colour.Names.tan+ inner "teal" = Just teal+ inner "thistle" = Just thistle+ inner "tomato" = Just tomato+ inner "turquoise" = Just turquoise+ inner "violet" = Just violet+ inner "wheat" = Just wheat+ inner "white" = Just white+ inner "whitesmoke" = Just whitesmoke+ inner "yellow" = Just yellow+ inner "yellowgreen" = Just yellowgreen+ inner _ = Nothing+parseColour _ (Ident x:toks) | Txt.toLower x == "transparent" =+ Just (toks, transparent)+-- FIXME: Add infrastructure to prioritize resolving `color`+parseColour self@ColourPallet { foreground = colour} (Ident x:toks)+ | Txt.toLower x `elem` ["currentcolor", "initial"] = Just (toks, colour)+ | Txt.toLower x == "accentcolor" = Just (toks, accent self)++parseColour _ (Function "hsl":hue':Comma:Percentage _ s:Comma:Percentage _ l:+ RightParen:toks)+ | Just hue <- d hue' = Just (toks, opaque $ hsl' hue (pc s) (pc l))+parseColour _ (Function "hsl":hue':Comma:Percentage _ s:Comma:Percentage _ l:+ Comma:a':RightParen:toks) | Just hue <- d hue', Just a <- f' a' =+ Just (toks, hsl' hue (pc s) (pc l) `withOpacity` a)+parseColour _ (Function "hsla":hue':Comma:Percentage _ s:Comma:Percentage _ l:+ Comma:a':RightParen:toks) | Just hue <- d hue', Just a <- f' a' =+ Just (toks, hsl' hue (pc s) (pc l) `withOpacity` a)+parseColour _ (Function "hsl":hue':s':l':RightParen:toks)+ | Just hue <- d' hue', Just s <- pc' s', Just l <- pc' l' =+ Just (toks, opaque $ hsl' hue s l)+parseColour _ (Function "hsl":hue':s':l':Delim '/':a':RightParen:toks)+ | Just hue <- d' hue', Just s <- pc' s', Just l <- pc' l', Just a <- f' a' =+ Just (toks, hsl' hue s l `withOpacity` a)++parseColour _ _ = Nothing++sRGBhex :: Char -> Char -> Char -> Char -> Char -> Char -> Colour Float+sRGBhex r0 r1 g0 g1 b0 b1 = sRGB24 (h r0 r1) (h g0 g1) (h b0 b1)++h :: Char -> Char -> Word8+h a b+ | Just a' <- toLower a `elemIndex` digits,+ Just b' <- toLower b `elemIndex` digits = toEnum a'*16 + toEnum b'+ | otherwise = trace (a:b:" Invalid hexcode!") 0 -- Should already be checked!+ where+ digits = "0123456789abcdef"+h' :: Char -> Char -> Float+h' a b = fromIntegral (h a b) / 255++pc :: NumericValue -> Float+pc x = f x / 100+pc' :: Token -> Maybe Float+pc' (Ident "none") = Just 0+pc' (Percentage _ x) = Just $ pc x+pc' _ = Nothing++f :: NumericValue -> Float+f (NVInteger x) = fromIntegral x+f (NVNumber x) = toRealFloat x+f' :: Token -> Maybe Float+f' (Ident "none") = Just 0+f' (Percentage _ x) = Just $ pc x+f' (Number _ x) = Just $ f x+f' _ = Nothing++w :: Integer -> Word8+w = fromInteger+w' :: Token -> Maybe Word8+w' (Ident "none") = Just 0+w' (Number _ (NVInteger x)) | x >= 0 && x <= 255 = Just $ fromIntegral $ w x+w' (Percentage _ x) = Just $ toEnum $ fromEnum (pc x * 255)+w' _ = Nothing++d', d :: Token -> Maybe Float+d (Dimension _ x "deg") = Just $ f x+d (Dimension _ x "grad") = Just $ f x / 400 * 360+d (Dimension _ x "rad") = Just $ f x / pi * 180+d (Dimension _ x "turn") = Just $ f x * 360+d (Number _ x) = Just $ f x+d _ = Nothing+d' (Ident "none") = Just 0+d' x = d x++-- Copied from css-syntax.+pattern (:.) :: Char -> Txt.Text -> Txt.Text+pattern x :. xs <- (Txt.uncons -> Just (x, xs))++infixr 5 :.
+ lib/Graphics/Rendering/Rect/Image.hs view
@@ -0,0 +1,100 @@+{-# LANGUAGE OverloadedStrings #-}+module Graphics.Rendering.Rect.Image(+ Atlas, buildAtlas, Texture(..), atlasLookup, textureSetRepeat) where++import qualified Data.HashMap.Lazy as HM+import Data.Text (Text)+import Codec.Picture (DynamicImage(..), Image(..), PixelF, pixelMap)+import Codec.Picture.Types (promoteImage, dynamicMap, convertImage)++import Control.Monad.IO.Class (MonadIO(..))+import Control.Monad (forM)+import Data.Maybe (fromMaybe)++import Graphics.GL.Core32+import Graphics.GL.Types+import Graphics.GL.Ext.EXT.Cmyka+import Graphics.GL.Ext.SGIX.Ycrcb+import Graphics.GL.Compatibility32++import Data.Vector.Storable (unsafeWith, unsafeCast, Vector)+import Foreign.Ptr (castPtr)+import Foreign.Marshal.Array (allocaArray, peekArray)++data Atlas = Atlas { unAtlas :: HM.HashMap Text Texture }++buildAtlas :: MonadIO m => (Text -> IO DynamicImage) -> [Text] -> m Atlas+buildAtlas _ [] = return $ Atlas HM.empty+buildAtlas cb srcs = do+ -- TODO Merge textures into an actual atlas.+ let len = length srcs+ textures <- liftIO $ allocaArray (toEnum len) $ \ptr -> do+ glGenTextures (toEnum len) ptr+ peekArray len ptr+ imgs <- liftIO $ forM srcs cb++ sizes <- forM (zip textures imgs) $ \(texture, dyn) -> do+ -- NOTE: `unsafe` crashes with a divide-by-zero given a `Vector ()`+ let dyn' = convertDyn dyn+ let img = dynamicMap (unsafeCast . imageData) dyn' :: Vector Word+ let (format, word) = glFormat dyn'+ liftIO $ glBindTexture GL_TEXTURE_2D texture+ liftIO $ unsafeWith img $ glTexImage2D GL_TEXTURE_2D 0 GL_RGBA+ (toEnum $ dynamicMap imageWidth dyn')+ (toEnum $ dynamicMap imageHeight dyn')+ 0 format word . castPtr+ liftIO $ glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MIN_FILTER GL_LINEAR+ liftIO $ glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAG_FILTER GL_LINEAR++ return (toEnum $ dynamicMap imageWidth dyn',+ toEnum $ dynamicMap imageHeight dyn')++ let textures' = map (uncurry Texture) $ zip textures sizes+ return $ Atlas $ HM.fromList $ zip srcs textures'++data Texture = Texture { unTexture :: GLuint, texSize :: (Float, Float) }+nilTexture :: Texture+nilTexture = Texture 0 (0, 0)+atlasLookup :: Text -> Atlas -> Texture+atlasLookup key = fromMaybe nilTexture . HM.lookup key . unAtlas+textureSetRepeat :: MonadIO m => Texture -> (Bool, Bool) -> m ()+textureSetRepeat tex (repeatX, repeatY) = do+ liftIO $ glBindTexture GL_TEXTURE_2D $ unTexture tex+ liftIO $ glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_S $+ if repeatX then GL_REPEAT else GL_CLAMP_TO_BORDER+ liftIO $ glTexParameteri GL_TEXTURE_2D GL_TEXTURE_WRAP_T $+ if repeatY then GL_REPEAT else GL_CLAMP_TO_BORDER++-- Convert pixels to some flavour of RGBA+convertDyn :: DynamicImage -> DynamicImage+convertDyn (ImageY8 img) = ImageRGBA8 $ promoteImage img+convertDyn (ImageY16 img) = ImageRGBA16 $ promoteImage img+convertDyn (ImageY32 img) =+ ImageRGBF $ promoteImage (pixelMap fromIntegral img :: Image PixelF)+convertDyn (ImageYF img) = ImageRGBF $ promoteImage img+convertDyn (ImageYA8 img) = ImageRGBA8 $ promoteImage img+convertDyn (ImageYA16 img) = ImageRGBA16 $ promoteImage img+convertDyn (ImageRGB8 img) = ImageRGB8 img+convertDyn (ImageRGB16 img) = ImageRGB16 img+convertDyn (ImageRGBF img) = ImageRGBF img+convertDyn (ImageRGBA8 img) = ImageRGBA8 img+convertDyn (ImageRGBA16 img) = ImageRGBA16 img+convertDyn (ImageYCbCr8 img) = ImageRGB8 $ convertImage img+convertDyn (ImageCMYK8 img) = ImageRGB8 $ convertImage img+convertDyn (ImageCMYK16 img) = ImageRGB16 $ convertImage img++glFormat :: DynamicImage -> (GLenum, GLenum)+glFormat (ImageY8 _) = (GL_LUMINANCE, GL_UNSIGNED_BYTE)+glFormat (ImageY16 _) = (GL_LUMINANCE, GL_UNSIGNED_SHORT)+glFormat (ImageY32 _) = (GL_LUMINANCE, GL_UNSIGNED_INT)+glFormat (ImageYF _) = (GL_LUMINANCE, GL_FLOAT)+glFormat (ImageYA8 _) = (GL_LUMINANCE_ALPHA, GL_BYTE)+glFormat (ImageYA16 _) = (GL_LUMINANCE_ALPHA, GL_UNSIGNED_SHORT)+glFormat (ImageRGB8 _) = (GL_RGB, GL_UNSIGNED_BYTE)+glFormat (ImageRGB16 _) = (GL_RGB, GL_UNSIGNED_SHORT)+glFormat (ImageRGBF _) = (GL_RGB, GL_FLOAT)+glFormat (ImageRGBA8 _) = (GL_RGBA, GL_UNSIGNED_BYTE)+glFormat (ImageRGBA16 _) = (GL_RGBA, GL_UNSIGNED_BYTE)+glFormat (ImageYCbCr8 _) = (GL_YCRCB_444_SGIX, GL_UNSIGNED_BYTE)+glFormat (ImageCMYK8 _) = (GL_CMYK_EXT, GL_UNSIGNED_BYTE)+glFormat (ImageCMYK16 _) = (GL_CMYK_EXT, GL_UNSIGNED_SHORT)
+ lib/Graphics/Rendering/Rect/Types.hs view
@@ -0,0 +1,142 @@+{-# LANGUAGE RecordWildCards #-}+-- So getters can implement typeclasses+{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}+module Graphics.Rendering.Rect.Types(Rect(..), size, Rects(..), BoxSelector,+ Uniform, u, us, c, cs, renderRectWith, liftGL) where++import Linear (M44, V2(..), V4(..))+import qualified Data.ByteString.Char8 as B8+import Data.ByteString (ByteString)+import qualified Data.Vector.Unboxed as UV++import Typograffiti.GL+import Graphics.GL.Core32+import Graphics.GL.Types+import Foreign.Marshal.Array (withArray, withArrayLen)+import Foreign.Ptr (castPtr)++import Control.Monad.IO.Class (MonadIO(..))+import Control.Monad (forM)+import System.Exit (die)++import Data.Colour (AlphaColour, over, alphaChannel)+import Data.Colour.SRGB (RGB(..), toSRGB)+import Data.Colour.Names (black)+import Graphics.Rendering.Rect.Image (Texture(..))++data Rect = Rect {+ left :: Float, top :: Float,+ right :: Float, bottom :: Float+} deriving (Read, Show, Eq, Ord)+rect2geom :: Rect -> UV.Vector (V2 Float)+rect2geom Rect{..} = UV.fromList+ [V2 left top, V2 right top, V2 left bottom, V2 right bottom]+size :: Rect -> (Float, Float)+size Rect {..} = (right - left, bottom - top)++data Rects = Rects {+ contentBox :: Rect,+ paddingBox :: Rect,+ borderBox :: Rect,+ marginBox :: Rect+} deriving (Read, Show, Eq, Ord)+rect :: Float -> Rect+rect x = Rect x x x x++type BoxSelector = Rects -> Rect+instance Eq BoxSelector where+ a == b = a rects == b rects+ where rects = Rects (rect 0) (rect 1) (rect 2) (rect 3)+instance Show BoxSelector where+ show a | a rects == rect 0 = "contentBox"+ | a rects == rect 1 = "paddingBox"+ | a rects == rect 2 = "borderBox"+ | a rects == rect 3 = "marginBox"+ | otherwise = "?"+ where rects = Rects (rect 0) (rect 1) (rect 2) (rect 3)+instance Read BoxSelector where+ readsPrec _ ('c':'o':'n':'t':'e':'n':'t':'B':'o':'x':t) = [(contentBox, t)]+ readsPrec _ ('p':'a':'d':'d':'i':'n':'g':'B':'o':'x':t) = [(paddingBox, t)]+ readsPrec _ ('b':'o':'r':'d':'e':'r':'B':'o':'x':t) = [(borderBox, t)]+ readsPrec _ ('m':'a':'r':'g':'i':'n':'B':'o':'x':t) = [(marginBox, t)]+ readsPrec _ _ = []++vertexShader :: ByteString+vertexShader = B8.pack $ unlines [+ "#version 330 core",+ "uniform mat4 transform;",+ "uniform vec2 origin;",+ "in vec2 pos;",+ "out vec2 coord;",+ "void main() {",+ " gl_Position = vec4(pos, 0, 1) * transform;",+ " coord = pos - origin;",+ "}"+ ]++type Uniform m = GLuint -> GLint -> m ()+u :: (MonadIO m, UniformValue a) => a -> Uniform m+u val prog slot = liftIO $ updateUniform prog slot val+us :: MonadIO m => [Float] -> Uniform m+us vals prog slot = do+ liftIO $ withArrayLen vals $ \len -> glUniform1fv slot (toEnum len)+ clearUniformUpdateError prog slot vals++c :: MonadIO m => AlphaColour Float -> Uniform m+c rgba = u $ c' rgba+c' :: AlphaColour Float -> V4 Float+c' rgba = V4 r g b a+ where+ a = alphaChannel rgba+ -- Workaround for missing APIs in "colour" hackage.+ RGB r g b = toSRGB $ over rgba black+cs :: MonadIO m => Int -> [AlphaColour Float] -> Uniform m+cs mlen rgba prog slot = do+ let val = map c' $ take mlen rgba+ liftIO $ withArrayLen val $ \len -> glUniform4fv slot (toEnum len) . castPtr+ clearUniformUpdateError prog slot val++renderRectWith :: (MonadIO m, MonadIO n) => ByteString -> [String] ->+ n ([Texture] -> [Uniform m] -> (a -> Rect) -> (a -> Rect) -> a+ -> M44 Float -> m ())+renderRectWith fragmentShader uniformNames = do+ vs <- liftGL $ compileOGLShader vertexShader GL_VERTEX_SHADER+ fs <- liftGL $ compileOGLShader fragmentShader GL_FRAGMENT_SHADER+ prog <- liftGL $ compileOGLProgram [("pos", 0)] [vs, fs]+ uniformIDs <- forM uniformNames $ getUniformLocation prog+ matID <- getUniformLocation prog "transform"+ originID <- getUniformLocation prog "origin"+ szID <- getUniformLocation prog "boxSize"+ glUseProgram prog+ glEnable GL_BLEND+ glBlendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA+ return $ \textures uniforms clip' origin' rects mat -> do+ vao <- liftIO $ newBoundVAO+ pbuf <- newBuffer+ bufferGeometry 0 pbuf $ rect2geom $ clip' rects++ glUseProgram prog+ liftIO $ updateUniform prog matID $ mflip mat+ let r = origin' rects+ liftIO $ updateUniform prog originID $ V2 (left r) (top r)+ liftIO $ updateUniform prog szID $ V2 (right r - left r) (bottom r - top r)+ _ <- forM (zip uniformIDs uniforms) $ \(slot, cb) -> cb prog slot++ withBoundTextures (map unTexture textures) $ do+ glBindVertexArray vao+ drawVAO prog vao GL_TRIANGLE_STRIP 4+ glBindVertexArray 0++ liftIO $ withArray [pbuf] $ glDeleteBuffers 1+ liftIO $ withArray [vao] $ glDeleteVertexArrays 1++liftGL :: MonadIO m => IO (Either String a) -> m a+liftGL n = do+ ret <- liftIO n+ case ret of+ Left err -> liftIO $ die err+ Right x -> return x++mflip :: V4 (V4 a) -> V4 (V4 a)+mflip (V4 (V4 a b cc d) (V4 e f g h) (V4 i j k l) (V4 m n o p)) =+ V4 (V4 a e i m) (V4 b f j n) (V4 cc g k o) (V4 d h l p)
+ test/MyLibTest.hs view
@@ -0,0 +1,4 @@+module Main (main) where++main :: IO ()+main = putStrLn "Test suite not yet implemented."